status
stringclasses 1
value | repo_name
stringclasses 31
values | repo_url
stringclasses 31
values | issue_id
int64 1
104k
| title
stringlengths 4
369
| body
stringlengths 0
254k
⌀ | issue_url
stringlengths 37
56
| pull_url
stringlengths 37
54
| before_fix_sha
stringlengths 40
40
| after_fix_sha
stringlengths 40
40
| report_datetime
timestamp[us, tz=UTC] | language
stringclasses 5
values | commit_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 4
188
| file_content
stringlengths 0
5.12M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,484 |
[Bug]: navigator.connection.rtt is always 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.3.1
### What operating system are you using?
Ubuntu
### Operating System Version
20.04.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Executing `navigator.connection.rtt` should return a non-zero value when configured:
```
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
```
### Actual Behavior
when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values.
[Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38484
|
https://github.com/electron/electron/pull/38491
|
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
|
57147d1b8d1352e8f49d6086b9957869d0d1e75a
| 2023-05-30T04:30:26Z |
c++
| 2023-05-31T15:06:25Z |
shell/browser/browser_process_impl.h
|
// Copyright (c) 2012 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.
// This interface is for managing the global services of the application. Each
// service is lazily created when requested the first time. The service getters
// will return NULL if the service is not available, so callers must check for
// this condition.
#ifndef ELECTRON_SHELL_BROWSER_BROWSER_PROCESS_IMPL_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_PROCESS_IMPL_H_
#include <memory>
#include <string>
#include "base/command_line.h"
#include "chrome/browser/browser_process.h"
#include "components/embedder_support/origin_trials/origin_trials_settings_storage.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/value_map_pref_store.h"
#include "printing/buildflags/buildflags.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "shell/browser/net/system_network_context_manager.h"
namespace printing {
class PrintJobManager;
}
// Empty definition for std::unique_ptr, rather than a forward declaration
class BackgroundModeManager {};
// NOT THREAD SAFE, call only from the main thread.
// These functions shouldn't return NULL unless otherwise noted.
class BrowserProcessImpl : public BrowserProcess {
public:
BrowserProcessImpl();
~BrowserProcessImpl() override;
// disable copy
BrowserProcessImpl(const BrowserProcessImpl&) = delete;
BrowserProcessImpl& operator=(const BrowserProcessImpl&) = delete;
static void ApplyProxyModeFromCommandLine(ValueMapPrefStore* pref_store);
BuildState* GetBuildState() override;
void PostEarlyInitialization();
void PreCreateThreads();
void PostDestroyThreads() {}
void PostMainMessageLoopRun();
void SetSystemLocale(const std::string& locale);
const std::string& GetSystemLocale() const;
void EndSession() override {}
void FlushLocalStateAndReply(base::OnceClosure reply) override {}
bool IsShuttingDown() override;
metrics_services_manager::MetricsServicesManager* GetMetricsServicesManager()
override;
metrics::MetricsService* metrics_service() override;
ProfileManager* profile_manager() override;
PrefService* local_state() override;
scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory()
override;
variations::VariationsService* variations_service() override;
BrowserProcessPlatformPart* platform_part() override;
extensions::EventRouterForwarder* extension_event_router_forwarder() override;
NotificationUIManager* notification_ui_manager() override;
NotificationPlatformBridge* notification_platform_bridge() override;
SystemNetworkContextManager* system_network_context_manager() override;
network::NetworkQualityTracker* network_quality_tracker() override;
embedder_support::OriginTrialsSettingsStorage*
GetOriginTrialsSettingsStorage() override;
policy::ChromeBrowserPolicyConnector* browser_policy_connector() override;
policy::PolicyService* policy_service() override;
IconManager* icon_manager() override;
GpuModeManager* gpu_mode_manager() override;
printing::PrintPreviewDialogController* print_preview_dialog_controller()
override;
printing::BackgroundPrintingManager* background_printing_manager() override;
IntranetRedirectDetector* intranet_redirect_detector() override;
DownloadStatusUpdater* download_status_updater() override;
DownloadRequestLimiter* download_request_limiter() override;
BackgroundModeManager* background_mode_manager() override;
StatusTray* status_tray() override;
safe_browsing::SafeBrowsingService* safe_browsing_service() override;
subresource_filter::RulesetService* subresource_filter_ruleset_service()
override;
component_updater::ComponentUpdateService* component_updater() override;
MediaFileSystemRegistry* media_file_system_registry() override;
WebRtcLogUploader* webrtc_log_uploader() override;
network_time::NetworkTimeTracker* network_time_tracker() override;
gcm::GCMDriver* gcm_driver() override;
resource_coordinator::ResourceCoordinatorParts* resource_coordinator_parts()
override;
resource_coordinator::TabManager* GetTabManager() override;
SerialPolicyAllowedPorts* serial_policy_allowed_ports() override;
HidPolicyAllowedDevices* hid_policy_allowed_devices() override;
HidSystemTrayIcon* hid_system_tray_icon() override;
void CreateDevToolsProtocolHandler() override {}
void CreateDevToolsAutoOpener() override {}
void set_background_mode_manager_for_test(
std::unique_ptr<BackgroundModeManager> manager) override {}
#if (BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX))
void StartAutoupdateTimer() override {}
#endif
void SetApplicationLocale(const std::string& locale) override;
const std::string& GetApplicationLocale() override;
printing::PrintJobManager* print_job_manager() override;
StartupData* startup_data() override;
device::GeolocationManager* geolocation_manager() override;
void SetGeolocationManager(
std::unique_ptr<device::GeolocationManager> geolocation_manager) override;
private:
#if BUILDFLAG(ENABLE_PRINTING)
std::unique_ptr<printing::PrintJobManager> print_job_manager_;
#endif
std::unique_ptr<PrefService> local_state_;
std::unique_ptr<device::GeolocationManager> geolocation_manager_;
std::string locale_;
std::string system_locale_;
embedder_support::OriginTrialsSettingsStorage origin_trials_settings_storage_;
};
#endif // ELECTRON_SHELL_BROWSER_BROWSER_PROCESS_IMPL_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,484 |
[Bug]: navigator.connection.rtt is always 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.3.1
### What operating system are you using?
Ubuntu
### Operating System Version
20.04.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Executing `navigator.connection.rtt` should return a non-zero value when configured:
```
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
```
### Actual Behavior
when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values.
[Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38484
|
https://github.com/electron/electron/pull/38491
|
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
|
57147d1b8d1352e8f49d6086b9957869d0d1e75a
| 2023-05-30T04:30:26Z |
c++
| 2023-05-31T15:06:25Z |
shell/browser/electron_browser_main_parts.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_browser_main_parts.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/browser/ui/color/chrome_color_mixers.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/embedder_support/origin_trials/origin_trials_settings_storage.h"
#include "components/os_crypt/sync/key_storage_config_linux.h"
#include "components/os_crypt/sync/os_crypt.h"
#include "content/browser/browser_main_loop.h" // nogncheck
#include "content/public/browser/browser_child_process_host_delegate.h"
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/first_party_sets_handler.h"
#include "content/public/browser/web_ui_controller_factory.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/process_type.h"
#include "content/public/common/result_codes.h"
#include "electron/buildflags/buildflags.h"
#include "electron/fuses.h"
#include "media/base/localized_strings.h"
#include "services/network/public/cpp/features.h"
#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
#include "shell/app/electron_main_delegate.h"
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/browser.h"
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_web_ui_controller_factory.h"
#include "shell/browser/feature_list.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
#include "shell/browser/ui/devtools_manager_delegate.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/logging.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/idle/idle.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_switches.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "base/environment.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#include "electron/electron_gtk_stubs.h"
#include "ui/base/cursor/cursor_factory.h"
#include "ui/base/ime/linux/linux_input_method_context_factory.h"
#include "ui/gfx/color_utils.h"
#include "ui/gtk/gtk_compat.h" // nogncheck
#include "ui/gtk/gtk_util.h" // nogncheck
#include "ui/linux/linux_ui.h"
#include "ui/linux/linux_ui_factory.h"
#include "ui/linux/linux_ui_getter.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/display/win/dpi.h"
#include "ui/gfx/system_fonts_win.h"
#include "ui/strings/grit/app_locale_settings.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "components/os_crypt/sync/keychain_password_mac.h"
#include "shell/browser/ui/cocoa/views_delegate_mac.h"
#else
#include "shell/browser/ui/views/electron_views_delegate.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/browser_context_keyed_service_factories.h"
#include "extensions/common/extension_api.h"
#include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h"
#include "shell/browser/extensions/electron_extensions_browser_client.h"
#include "shell/common/extensions/electron_extensions_client.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#include "shell/common/plugin_info.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
namespace electron {
namespace {
#if BUILDFLAG(IS_LINUX)
class LinuxUiGetterImpl : public ui::LinuxUiGetter {
public:
LinuxUiGetterImpl() = default;
~LinuxUiGetterImpl() override = default;
ui::LinuxUiTheme* GetForWindow(aura::Window* window) override {
return GetForProfile(nullptr);
}
ui::LinuxUiTheme* GetForProfile(Profile* profile) override {
return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk);
}
};
#endif
template <typename T>
void Erase(T* container, typename T::iterator iter) {
container->erase(iter);
}
#if BUILDFLAG(IS_WIN)
// gfx::Font callbacks
void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) {
l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override,
&font_adjustment->font_scale);
font_adjustment->font_scale *= display::win::GetAccessibilityFontScale();
}
int GetMinimumFontSize() {
int min_font_size;
base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
&min_font_size);
return min_font_size;
}
#endif
std::u16string MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return u"Default";
#if BUILDFLAG(IS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return u"Communications";
#endif
default:
return std::u16string();
}
}
#if BUILDFLAG(IS_LINUX)
// GTK does not provide a way to check if current theme is dark, so we compare
// the text and background luminosity to get a result.
// This trick comes from FireFox.
void UpdateDarkThemeSetting() {
float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel"));
float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel"));
bool is_dark = fg > bg;
// Pass it to NativeUi theme, which is used by the nativeTheme module and most
// places in Electron.
ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark);
// Pass it to Web Theme, to make "prefers-color-scheme" media query work.
ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark);
}
#endif
// A fake BrowserProcess object that used to feed the source code from chrome.
class FakeBrowserProcessImpl : public BrowserProcessImpl {
public:
embedder_support::OriginTrialsSettingsStorage*
GetOriginTrialsSettingsStorage() override {
return &origin_trials_settings_storage_;
}
private:
embedder_support::OriginTrialsSettingsStorage origin_trials_settings_storage_;
};
} // namespace
#if BUILDFLAG(IS_LINUX)
class DarkThemeObserver : public ui::NativeThemeObserver {
public:
DarkThemeObserver() = default;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override {
UpdateDarkThemeSetting();
}
};
#endif
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr;
ElectronBrowserMainParts::ElectronBrowserMainParts()
: fake_browser_process_(std::make_unique<BrowserProcessImpl>()),
browser_(std::make_unique<Browser>()),
node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)),
electron_bindings_(
std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {
DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts";
self_ = this;
}
ElectronBrowserMainParts::~ElectronBrowserMainParts() = default;
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::Get() {
DCHECK(self_);
return self_;
}
bool ElectronBrowserMainParts::SetExitCode(int code) {
if (!exit_code_)
return false;
content::BrowserMainLoop::GetInstance()->SetResultCode(code);
*exit_code_ = code;
return true;
}
int ElectronBrowserMainParts::GetExitCode() const {
return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT);
}
int ElectronBrowserMainParts::PreEarlyInitialization() {
field_trial_list_ = std::make_unique<base::FieldTrialList>();
#if BUILDFLAG(IS_POSIX)
HandleSIGCHLD();
#endif
#if BUILDFLAG(IS_LINUX)
DetectOzonePlatform();
ui::OzonePlatform::PreEarlyInitialization();
#endif
#if BUILDFLAG(IS_MAC)
screen_ = std::make_unique<display::ScopedNativeScreen>();
#endif
ui::ColorProviderManager::Get().AppendColorProviderInitializer(
base::BindRepeating(AddChromeColorMixers));
return GetExitCode();
}
void ElectronBrowserMainParts::PostEarlyInitialization() {
// A workaround was previously needed because there was no ThreadTaskRunner
// set. If this check is failing we may need to re-add that workaround
DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault());
// The ProxyResolverV8 has setup a complete V8 environment, in order to
// avoid conflicts we only initialize our V8 environment after that.
js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop());
v8::HandleScope scope(js_env_->isolate());
node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext());
// Create the global environment.
node::Environment* env = node_bindings_->CreateEnvironment(
js_env_->isolate()->GetCurrentContext(), js_env_->platform());
node_env_ = std::make_unique<NodeEnvironment>(env);
env->set_trace_sync_io(env->options()->trace_sync_io);
// We do not want to crash the main process on unhandled rejections.
env->options()->unhandled_rejections = "warn-with-error-code";
// Add Electron extended APIs.
electron_bindings_->BindTo(js_env_->isolate(), env->process_object());
// Create explicit microtasks runner.
js_env_->CreateMicrotasksRunner();
// Wrap the uv loop with global env.
node_bindings_->set_uv_env(env);
// Load everything.
node_bindings_->LoadEnvironment(env);
// We already initialized the feature list in PreEarlyInitialization(), but
// the user JS script would not have had a chance to alter the command-line
// switches at that point. Lets reinitialize it here to pick up the
// command-line changes.
base::FeatureList::ClearInstanceForTesting();
InitializeFeatureList();
// Initialize field trials.
InitializeFieldTrials();
// Reinitialize logging now that the app has had a chance to set the app name
// and/or user data directory.
logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
/* is_preinit = */ false);
// Initialize after user script environment creation.
fake_browser_process_->PostEarlyInitialization();
}
int ElectronBrowserMainParts::PreCreateThreads() {
if (!views::LayoutProvider::Get()) {
layout_provider_ = std::make_unique<views::LayoutProvider>();
}
// Fetch the system locale for Electron.
#if BUILDFLAG(IS_MAC)
fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale());
#else
fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale());
#endif
auto* command_line = base::CommandLine::ForCurrentProcess();
std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
#if BUILDFLAG(IS_MAC)
// The browser process only wants to support the language Cocoa will use,
// so force the app locale to be overridden with that value. This must
// happen before the ResourceBundle is loaded
if (locale.empty())
l10n_util::OverrideLocaleWithCocoaLocale();
#elif BUILDFLAG(IS_LINUX)
// l10n_util::GetApplicationLocaleInternal uses g_get_language_names(),
// which keys off of getenv("LC_ALL").
// We must set this env first to make ui::ResourceBundle accept the custom
// locale.
auto env = base::Environment::Create();
absl::optional<std::string> lc_all;
if (!locale.empty()) {
std::string str;
if (env->GetVar("LC_ALL", &str))
lc_all.emplace(std::move(str));
env->SetVar("LC_ALL", locale.c_str());
}
#endif
// Load resources bundle according to locale.
std::string loaded_locale = LoadResourceBundle(locale);
#if defined(USE_AURA)
// NB: must be called _after_ locale resource bundle is loaded,
// because ui lib makes use of it in X11
if (!display::Screen::GetScreen()) {
screen_ = views::CreateDesktopScreen();
}
#endif
// Initialize the app locale for Electron and Chromium.
std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale);
ElectronBrowserClient::SetApplicationLocale(app_locale);
fake_browser_process_->SetApplicationLocale(app_locale);
#if BUILDFLAG(IS_LINUX)
// Reset to the original LC_ALL since we should not be changing it.
if (!locale.empty()) {
if (lc_all)
env->SetVar("LC_ALL", *lc_all);
else
env->UnSetVar("LC_ALL");
}
#endif
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
#if BUILDFLAG(IS_MAC)
ui::InitIdleMonitor();
Browser::Get()->ApplyForcedRTL();
#endif
fake_browser_process_->PreCreateThreads();
// Notify observers.
Browser::Get()->PreCreateThreads();
return 0;
}
void ElectronBrowserMainParts::PostCreateThreads() {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread));
#if BUILDFLAG(ENABLE_PLUGINS)
// PluginService can only be used on the UI thread
// and ContentClient::AddPlugins gets called for both browser and render
// process where the latter will not have UI thread which leads to DCHECK.
// Separate the WebPluginInfo registration for these processes.
std::vector<content::WebPluginInfo> plugins;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->RefreshPlugins();
GetInternalPlugins(&plugins);
for (const auto& plugin : plugins)
plugin_service->RegisterInternalPlugin(plugin, true);
#endif
}
void ElectronBrowserMainParts::PostDestroyThreads() {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_browser_client_.reset();
extensions::ExtensionsBrowserClient::Set(nullptr);
#endif
#if BUILDFLAG(IS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
fake_browser_process_->PostDestroyThreads();
}
void ElectronBrowserMainParts::ToolkitInitialized() {
#if BUILDFLAG(IS_LINUX)
auto* linux_ui = ui::GetDefaultLinuxUi();
CHECK(linux_ui);
linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>();
// Try loading gtk symbols used by Electron.
electron::InitializeElectron_gtk(gtk::GetLibGtk());
if (!electron::IsElectron_gtkInitialized()) {
electron::UninitializeElectron_gtk();
}
electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf());
CHECK(electron::IsElectron_gdk_pixbufInitialized())
<< "Failed to initialize libgdk_pixbuf-2.0.so.0";
// Chromium does not respect GTK dark theme setting, but they may change
// in future and this code might be no longer needed. Check the Chromium
// issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=998903
UpdateDarkThemeSetting();
// Update the native theme when GTK theme changes. The GetNativeTheme
// here returns a NativeThemeGtk, which monitors GTK settings.
dark_theme_observer_ = std::make_unique<DarkThemeObserver>();
auto* linux_ui_theme = ui::LinuxUiTheme::GetForProfile(nullptr);
CHECK(linux_ui_theme);
linux_ui_theme->GetNativeTheme()->AddObserver(dark_theme_observer_.get());
ui::LinuxUi::SetInstance(linux_ui);
// Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager
// implementation). Start observing them once it's initialized.
ui::CursorFactory::GetInstance()->ObserveThemeChanges();
#endif
#if defined(USE_AURA)
wm_state_ = std::make_unique<wm::WMState>();
#endif
#if BUILDFLAG(IS_WIN)
gfx::win::SetAdjustFontCallback(&AdjustUIFont);
gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize);
#endif
#if BUILDFLAG(IS_MAC)
views_delegate_ = std::make_unique<ViewsDelegateMac>();
#else
views_delegate_ = std::make_unique<ViewsDelegate>();
#endif
}
int ElectronBrowserMainParts::PreMainMessageLoopRun() {
// Run user's main script before most things get initialized, so we can have
// a chance to setup everything.
node_bindings_->PrepareEmbedThread();
node_bindings_->StartPolling();
// url::Add*Scheme are not threadsafe, this helps prevent data races.
url::LockSchemeRegistries();
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_client_ = std::make_unique<ElectronExtensionsClient>();
extensions::ExtensionsClient::Set(extensions_client_.get());
// BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient.
extensions_browser_client_ =
std::make_unique<ElectronExtensionsBrowserClient>();
extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt();
extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt();
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckServiceFactory::GetInstance();
#endif
content::WebUIControllerFactory::RegisterFactory(
ElectronWebUIControllerFactory::GetInstance());
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) {
// --remote-debugging-pipe
auto on_disconnect = base::BindOnce([]() {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); }));
});
content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(
std::move(on_disconnect));
} else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
// --remote-debugging-port
DevToolsManagerDelegate::StartHttpHandler();
}
#if !BUILDFLAG(IS_MAC)
// The corresponding call in macOS is in ElectronApplicationDelegate.
Browser::Get()->WillFinishLaunching();
Browser::Get()->DidFinishLaunching(base::Value::Dict());
#endif
// Notify observers that main thread message loop was initialized.
Browser::Get()->PreMainMessageLoopRun();
return GetExitCode();
}
void ElectronBrowserMainParts::WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) {
exit_code_ = content::RESULT_CODE_NORMAL_EXIT;
Browser::Get()->SetMainMessageLoopQuitClosure(
run_loop->QuitWhenIdleClosure());
}
void ElectronBrowserMainParts::PostCreateMainMessageLoop() {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
std::string app_name = electron::Browser::Get()->GetName();
#endif
#if BUILDFLAG(IS_LINUX)
auto shutdown_cb =
base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop(
std::move(shutdown_cb),
content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput}));
bluez::DBusBluezManagerWrapperLinux::Initialize();
// Set up crypt config. This needs to be done before anything starts the
// network service, as the raw encryption key needs to be shared with the
// network service for encrypted cookie storage.
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::unique_ptr<os_crypt::Config> config =
std::make_unique<os_crypt::Config>();
// Forward to os_crypt the flag to use a specific password store.
config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore);
config->product_name = app_name;
config->application_name = app_name;
config->main_thread_runner =
base::SingleThreadTaskRunner::GetCurrentDefault();
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1
config->should_use_preference =
command_line.HasSwitch(::switches::kEnableEncryptionSelection);
base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path);
OSCrypt::SetConfig(std::move(config));
#endif
#if BUILDFLAG(IS_MAC)
KeychainPassword::GetServiceName() = app_name + " Safe Storage";
KeychainPassword::GetAccountName() = app_name;
#endif
#if BUILDFLAG(IS_POSIX)
// Exit in response to SIGINT, SIGTERM, etc.
InstallShutdownSignalHandlers(
base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())),
content::GetUIThreadTaskRunner({}));
#endif
}
void ElectronBrowserMainParts::PostMainMessageLoopRun() {
#if BUILDFLAG(IS_MAC)
FreeAppDelegate();
#endif
// Shutdown the DownloadManager before destroying Node to prevent
// DownloadItem callbacks from crashing.
for (auto& iter : ElectronBrowserContext::browser_context_map()) {
auto* download_manager = iter.second.get()->GetDownloadManager();
if (download_manager) {
download_manager->Shutdown();
}
}
// Shutdown utility process created with Electron API before
// stopping Node.js so that exit events can be emitted. We don't let
// content layer perform this action since it destroys
// child process only after this step (PostMainMessageLoopRun) via
// BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our
// use case.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108
//
// The following logic is based on
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159
//
// Although content::BrowserChildProcessHostIterator is only to be called from
// IO thread, it is safe to call from PostMainMessageLoopRun because thread
// restrictions have been lifted.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078
for (content::BrowserChildProcessHostIterator it(
content::PROCESS_TYPE_UTILITY);
!it.Done(); ++it) {
if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) {
auto& process = it.GetData().GetProcess();
if (!process.IsValid())
continue;
auto utility_process_wrapper =
api::UtilityProcessWrapper::FromProcessId(process.Pid());
if (utility_process_wrapper)
utility_process_wrapper->Shutdown(0 /* exit_code */);
}
}
// Destroy node platform after all destructors_ are executed, as they may
// invoke Node/V8 APIs inside them.
node_env_->env()->set_trace_sync_io(false);
js_env_->DestroyMicrotasksRunner();
node::Stop(node_env_->env(), node::StopFlags::kDoNotTerminateIsolate);
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();
}
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
| 38,484 |
[Bug]: navigator.connection.rtt is always 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.3.1
### What operating system are you using?
Ubuntu
### Operating System Version
20.04.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Executing `navigator.connection.rtt` should return a non-zero value when configured:
```
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
```
### Actual Behavior
when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values.
[Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38484
|
https://github.com/electron/electron/pull/38491
|
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
|
57147d1b8d1352e8f49d6086b9957869d0d1e75a
| 2023-05-30T04:30:26Z |
c++
| 2023-05-31T15:06:25Z |
spec/chromium-spec.ts
|
import { expect } from 'chai';
import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import * as https from 'https';
import * as http from 'http';
import * as path from 'path';
import * as fs from 'fs';
import * as url from 'url';
import * as ChildProcess from 'child_process';
import { EventEmitter, once } from 'events';
import { promisify } from 'util';
import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
import { PipeTransport } from './pipe-transport';
import * as ws from 'ws';
import { setTimeout } from 'timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
describe('reporting api', () => {
it('sends a report for an intervention', async () => {
const reporting = new EventEmitter();
// The Reporting API only works on https with valid certs. To dodge having
// to set up a trusted certificate, hack the validator.
session.defaultSession.setCertificateVerifyProc((req, cb) => {
cb(0);
});
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options, (req, res) => {
if (req.url?.endsWith('report')) {
let data = '';
req.on('data', (d) => { data += d.toString('utf-8'); });
req.on('end', () => {
reporting.emit('report', JSON.parse(data));
});
}
const { port } = server.address() as any;
res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`);
res.setHeader('Content-Type', 'text/html');
res.end('<script>window.navigator.vibrate(1)</script>');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`);
const [reports] = await reportGenerated;
expect(reports).to.be.an('array').with.lengthOf(1);
const { type, url, body } = reports[0];
expect(type).to.equal('intervention');
expect(url).to.equal(url);
expect(body.id).to.equal('NavigatorVibrate');
expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/);
} finally {
bw.destroy();
server.close();
}
});
});
describe('window.postMessage', () => {
afterEach(async () => {
await closeAllWindows();
});
it('sets the source and origin correctly', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
const [, message] = await once(ipcMain, 'complete');
expect(message.data).to.equal('testing');
expect(message.origin).to.equal('file://');
expect(message.sourceEqualsOpener).to.equal(true);
expect(message.eventOrigin).to.equal('file://');
});
});
describe('focus handling', () => {
let webviewContents: WebContents;
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
contextIsolation: false
}
});
const webviewReady = once(w.webContents, 'did-attach-webview');
await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
const [, wvContents] = await webviewReady;
webviewContents = wvContents;
await once(webviewContents, 'did-finish-load');
w.focus();
});
afterEach(() => {
webviewContents = null as unknown as WebContents;
w.destroy();
w = null as unknown as BrowserWindow;
});
const expectFocusChange = async () => {
const [, focusedElementId] = await once(ipcMain, 'focus-changed');
return focusedElementId;
};
describe('a TAB press', () => {
const tabPressEvent: any = {
type: 'keyDown',
keyCode: 'Tab'
};
it('moves focus to the next focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
});
});
describe('a SHIFT + TAB press', () => {
const shiftTabPressEvent: any = {
type: 'keyDown',
modifiers: ['Shift'],
keyCode: 'Tab'
};
it('moves focus to the previous focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
});
});
});
describe('web security', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('engages CORB when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,<script>
const s = document.createElement('script')
s.src = "${serverUrl}"
// The script will load successfully but its body will be emptied out
// by CORB, so we don't expect a syntax error.
s.onload = () => { require('electron').ipcRenderer.send('success') }
document.documentElement.appendChild(s)
</script>`);
await p;
});
it('bypasses CORB when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,
<script>
window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
</script>
<script src="${serverUrl}"></script>`);
await p;
});
it('engages CORS when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('failed');
});
it('bypasses CORS when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('passed');
});
describe('accessing file://', () => {
async function loadFile (w: BrowserWindow) {
const thisFile = url.format({
pathname: __filename.replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
await w.loadURL(`data:text/html,<script>
function loadFile() {
return new Promise((resolve) => {
fetch('${thisFile}').then(
() => resolve('loaded'),
() => resolve('failed')
)
});
}
</script>`);
return await w.webContents.executeJavaScript('loadFile()');
}
it('is forbidden when web security is enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
const result = await loadFile(w);
expect(result).to.equal('failed');
});
it('is allowed when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
const result = await loadFile(w);
expect(result).to.equal('loaded');
});
});
describe('wasm-eval csp', () => {
async function loadWasm (csp: string) {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
enableBlinkFeatures: 'WebAssemblyCSP'
}
});
await w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
</head>
<script>
function loadWasm() {
const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
return new Promise((resolve) => {
WebAssembly.instantiate(wasmBin).then(() => {
resolve('loaded')
}).catch((error) => {
resolve(error.message)
})
});
}
</script>`);
return await w.webContents.executeJavaScript('loadWasm()');
}
it('wasm codegen is disallowed by default', async () => {
const r = await loadWasm('');
expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"');
});
it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
const r = await loadWasm("'wasm-unsafe-eval'");
expect(r).to.equal('loaded');
});
});
describe('csp', () => {
for (const sandbox of [true, false]) {
describe(`when sandbox: ${sandbox}`, () => {
for (const contextIsolation of [true, false]) {
describe(`when contextIsolation: ${contextIsolation}`, () => {
it('prevents eval from running in an inline script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
</head>
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.match(/Refused to evaluate a string/);
});
it('does not prevent eval from running in an inline script when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.equal('true');
});
it('prevents eval from running in executeJavaScript', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>');
await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected();
});
it('does not prevent eval from running in executeJavaScript when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,');
expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true();
});
});
}
});
}
});
it('does not crash when multiple WebContent are created with web security disabled', () => {
const options = { show: false, webPreferences: { webSecurity: false } };
const w1 = new BrowserWindow(options);
w1.loadURL(serverUrl);
const w2 = new BrowserWindow(options);
w2.loadURL(serverUrl);
});
});
describe('command line switches', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
describe('--lang switch', () => {
const currentLocale = app.getLocale();
const currentSystemLocale = app.getSystemLocale();
const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages());
const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
const appPath = path.join(fixturesPath, 'api', 'locale-check');
const args = [appPath, `--set-lang=${locale}`];
if (printEnv) {
args.push('--print-env');
}
appProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
let stderr = '';
appProcess.stderr.on('data', (data) => { stderr += data; });
const [code, signal] = await once(appProcess, 'exit');
if (code !== 0) {
throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
}
output = output.replace(/(\r\n|\n|\r)/gm, '');
expect(output).to.equal(result);
};
it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`));
const lcAll = String(process.env.LC_ALL);
ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
// The LC_ALL env should not be set to DOM locale string.
expect(lcAll).to.not.equal(app.getLocale());
});
ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
});
describe('--remote-debugging-pipe switch', () => {
it('should expose CDP via pipe', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(message.result.product).to.contain('Chrome');
expect(message.result.userAgent).to.contain('Electron');
});
it('should override --remote-debugging-port switch', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
let stderr = '';
appProcess.stderr.on('data', (data: string) => { stderr += data; });
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(stderr).to.not.include('DevTools listening on');
});
it('should shut down Electron upon Browser.close CDP command', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
await once(appProcess, 'exit');
});
});
describe('--remote-debugging-port switch', () => {
it('should display the discovery page', (done) => {
const electronPath = process.execPath;
let output = '';
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
appProcess.stdout.on('data', (data) => {
console.log(data);
});
appProcess.stderr.on('data', (data) => {
console.log(data);
output += data;
const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
if (m) {
appProcess!.stderr.removeAllListeners('data');
const port = m[1];
http.get(`http://127.0.0.1:${port}`, (res) => {
try {
expect(res.statusCode).to.eql(200);
expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
done();
} catch (e) {
done(e);
} finally {
res.destroy();
}
});
}
});
});
});
});
describe('chromium features', () => {
afterEach(closeAllWindows);
describe('accessing key names also used as Node.js module names', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
});
});
describe('first party sets', () => {
const fps = [
'https://fps-member1.glitch.me',
'https://fps-member2.glitch.me',
'https://fps-member3.glitch.me'
];
it('loads first party sets', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base');
const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
it('loads sets from the command line', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line');
const args = [appPath, `--use-first-party-set=${fps}`];
const fpsProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
});
describe('loading jquery', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
});
});
describe('navigator.languages', () => {
it('should return the system locale only', async () => {
const appLocale = app.getLocale();
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const languages = await w.webContents.executeJavaScript('navigator.languages');
expect(languages.length).to.be.greaterThan(0);
expect(languages).to.contain(appLocale);
});
});
describe('navigator.serviceWorker', () => {
it('should register for file scheme', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for intercepted file scheme', (done) => {
const customSession = session.fromPartition('intercept-file');
customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
const content = fs.readFileSync(path.normalize(file));
const ext = path.extname(file);
let type = 'text/html';
if (ext === '.js') type = 'application/javascript';
callback({ data: content, mimeType: type } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol('file');
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for custom scheme', (done) => {
const customSession = session.fromPartition('custom-scheme');
customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
callback({ path: path.normalize(file) } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
});
it('should not allow nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
partition: 'sw-file-scheme-worker-spec',
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`);
const data = await w.webContents.executeJavaScript(`
navigator.serviceWorker.register('worker-no-node.js', {
scope: './'
}).then(() => navigator.serviceWorker.ready)
new Promise((resolve) => {
navigator.serviceWorker.onmessage = event => resolve(event.data);
});
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
describe('navigator.geolocation', () => {
ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'geolocation-spec',
contextIsolation: false
}
});
const message = once(w.webContents, 'ipc-message');
w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'geolocation') {
callback(false);
} else {
callback(true);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
const [, channel] = await message;
expect(channel).to.equal('success', 'unexpected response from geolocation api');
});
ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'geolocation-spec'
}
});
w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => {
callback(true);
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
x => resolve({coords: x.coords, timestamp: x.timestamp}),
err => reject(new Error(err.message))))`);
expect(position).to.have.property('coords');
expect(position).to.have.property('timestamp');
});
});
describe('web workers', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
appProcess = ChildProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
it('Worker can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
worker.postMessage(message);
eventPromise.then(t => t.data)
`);
expect(data).to.equal('ping');
});
it('Worker has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker_node.js');
new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('Worker has node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/worker.html`);
const [, data] = await once(ipcMain, 'worker-result');
expect(data).to.equal('object function object function');
});
describe('SharedWorker', () => {
it('can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
worker.port.postMessage(message);
eventPromise
`);
expect(data).to.equal('ping');
});
it('has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('does not have node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
});
describe('form submit', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
res.setHeader('Content-Type', 'application/json');
req.on('end', () => {
res.end(`body:${body}`);
});
});
serverUrl = (await listen(server)).url;
});
after(async () => {
server.close();
await closeAllWindows();
});
[true, false].forEach((isSandboxEnabled) =>
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const loadPromise = once(w.webContents, 'did-finish-load');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.submit();
`);
await loadPromise;
const res = await w.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
it('posts data to a new window with target=_blank', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const windowCreatedPromise = once(app, 'browser-window-created');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.target = '_blank';
form.submit();
`);
const [, newWin] = await windowCreatedPromise;
const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
})
);
});
describe('window.open', () => {
for (const show of [true, false]) {
it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
const w = new BrowserWindow({ show });
// toggle visibility
if (show) {
w.hide();
} else {
w.show();
}
defer(() => { w.close(); });
const promise = once(app, 'browser-window-created');
w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
const [, newWindow] = await promise;
expect(newWindow.isVisible()).to.equal(true);
});
}
// FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false')
const e = await message
b.close();
return {
eventData: e.data
}
})()`);
expect(eventData.isProcessGlobalUndefined).to.be.true();
});
it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
// NB. webSecurity is disabled because native window.open() is not
// allowed to load devtools:// URLs.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created');
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
it('can disable node integration when it is enabled on the parent window', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created');
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = require('url').format({
pathname: `${fixturesPath}/pages/window-no-javascript.html`,
protocol: 'file',
slashes: true
});
w.webContents.executeJavaScript(`
{ b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created');
await once(contents, 'did-finish-load');
// Click link on page
contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
const [, window] = await once(app, 'browser-window-created');
const preferences = window.webContents.getLastWebPreferences();
expect(preferences.javascript).to.be.false();
});
it('defines a window.location getter', async () => {
let targetURL: string;
if (process.platform === 'win32') {
targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
} else {
targetURL = `file://${fixturesPath}/pages/base-page.html`;
}
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
const [, window] = await once(app, 'browser-window-created');
await once(window.webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
});
it('defines a window.location setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('defines a window.location.href setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('open a blank page when no URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('open a blank page when an empty URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('does not throw an exception when the frameName is a built-in object property', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
const frameName = await new Promise((resolve) => {
w.webContents.setWindowOpenHandler(details => {
setImmediate(() => resolve(details.frameName));
return { action: 'allow' };
});
});
expect(frameName).to.equal('__proto__');
});
// FIXME(nornagon): I'm not sure this ... ever was correct?
xit('inherit options of parent window', async () => {
const w = new BrowserWindow({ show: false, width: 123, height: 456 });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const url = `file://${fixturesPath}/pages/window-open-size.html`;
const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(url)}, '', 'show=false')
const e = await message
b.close();
const width = outerWidth;
const height = outerHeight;
return {
width,
height,
eventData: e.data
}
})()`);
expect(eventData).to.equal(`size: ${width} ${height}`);
expect(eventData).to.equal('size: 123 456');
});
it('does not override child options', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`;
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData).to.equal('size: 350 450');
});
it('disables the <webview> tag when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData.isWebViewGlobalUndefined).to.be.true();
});
it('throws an exception when the arguments cannot be converted to strings', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', { toString: null })')
).to.eventually.be.rejected();
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })')
).to.eventually.be.rejected();
});
it('does not throw an exception when the features include webPreferences', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null')
).to.eventually.be.fulfilled();
});
});
describe('window.opener', () => {
it('is null for main window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
const [, channel, opener] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('opener');
expect(opener).to.equal(null);
});
it('is not null for window opened by window.open', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener.html`;
const eventData = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data);
`);
expect(eventData).to.equal('object');
});
});
describe('window.opener.postMessage', () => {
it('sets source and origin correctly', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`;
const { sourceIsChild, origin } = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({
sourceIsChild: e.source === b,
origin: e.origin
}));
`);
expect(sourceIsChild).to.be.true();
expect(origin).to.equal('file://');
});
it('supports windows opened from a <webview>', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('about:blank');
const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html'));
childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`);
const message = await w.webContents.executeJavaScript(`
const webview = new WebView();
webview.allowpopups = true;
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = ${JSON.stringify(childWindowUrl)}
const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true}));
document.body.appendChild(webview);
consoleMessage.then(e => e.message)
`);
expect(message).to.equal('message');
});
describe('targetOrigin argument', () => {
let serverURL: string;
let server: any;
beforeEach(async () => {
server = http.createServer((req, res) => {
res.writeHead(200);
const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html');
res.end(fs.readFileSync(filePath, 'utf8'));
});
serverURL = (await listen(server)).url;
});
afterEach(() => {
server.close();
});
it('delivers messages that match the origin', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const data = await w.webContents.executeJavaScript(`
window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data)
`);
expect(data).to.equal('deliver');
});
});
});
describe('navigator.mediaDevices', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can return labels of enumerated devices', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.true();
});
it('does not return labels of enumerated devices when permission denied', async () => {
session.defaultSession.setPermissionCheckHandler(() => false);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.false();
});
it('returns the same device ids across reloads', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
});
it('can return new device id when cookie storage is cleared', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
await ses.clearStorageData({ storages: ['cookies'] });
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
});
it('provides a securityOrigin to the request handler', async () => {
session.defaultSession.setPermissionRequestHandler(
(wc, permission, callback, details) => {
if (details.securityOrigin !== undefined) {
callback(true);
} else {
callback(false);
}
}
);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
video: {
mandatory: {
chromeMediaSource: "desktop",
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream) => stream.getVideoTracks())`);
expect(labels.some((l: any) => l)).to.be.true();
});
it('fails with "not supported" for getDisplayMedia', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true);
expect(ok).to.be.false();
expect(err).to.equal('Not supported');
});
});
describe('window.opener access', () => {
const scheme = 'app';
const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
const httpUrl1 = `${scheme}://origin1`;
const httpUrl2 = `${scheme}://origin2`;
const fileBlank = `file://${fixturesPath}/pages/blank.html`;
const httpBlank = `${scheme}://origin1/blank`;
const table = [
{ parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
{ parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
// {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
// {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
// NB. this is different from Chrome's behavior, which isolates file: urls from each other
{ parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
{ parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
];
const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
if (request.url.includes('blank')) {
callback(`${fixturesPath}/pages/blank.html`);
} else {
callback(`${fixturesPath}/pages/window-opener-location.html`);
}
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
describe('when opened from main window', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
for (const sandboxPopup of [false, true]) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
sandbox: sandboxPopup
}
}
}));
await w.loadURL(parent);
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
window.addEventListener('message', function f(e) {
resolve(e.data)
})
window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
}
});
describe('when opened from <webview>', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
// This test involves three contexts:
// 1. The root BrowserWindow in which the test is run,
// 2. A <webview> belonging to the root window,
// 3. A window opened by calling window.open() from within the <webview>.
// We are testing whether context (3) can access context (2) under various conditions.
// This is context (1), the base window for the test.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
const parentCode = `new Promise((resolve) => {
// This is context (3), a child window of the WebView.
const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
window.addEventListener("message", e => {
resolve(e.data)
})
})`;
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
// This is context (2), a WebView which will call window.open()
const webview = new WebView()
webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
webview.setAttribute('webpreferences', 'contextIsolation=no')
webview.setAttribute('allowpopups', 'on')
webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
webview.addEventListener('dom-ready', async () => {
webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
})
document.body.appendChild(webview)
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
});
});
describe('storage', () => {
describe('custom non standard schemes', () => {
const protocolName = 'storage';
let contents: WebContents;
before(() => {
protocol.registerFileProtocol(protocolName, (request, callback) => {
const parsedUrl = url.parse(request.url);
let filename;
switch (parsedUrl.pathname) {
case '/localStorage' : filename = 'local_storage.html'; break;
case '/sessionStorage' : filename = 'session_storage.html'; break;
case '/WebSQL' : filename = 'web_sql.html'; break;
case '/indexedDB' : filename = 'indexed_db.html'; break;
case '/cookie' : filename = 'cookie.html'; break;
default : filename = '';
}
callback({ path: `${fixturesPath}/pages/storage/${filename}` });
});
});
after(() => {
protocol.unregisterProtocol(protocolName);
});
beforeEach(() => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
});
afterEach(() => {
contents.destroy();
contents = null as any;
});
it('cannot access localStorage', async () => {
const response = once(ipcMain, 'local-storage-response');
contents.loadURL(protocolName + '://host/localStorage');
const [, error] = await response;
expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access sessionStorage', async () => {
const response = once(ipcMain, 'session-storage-response');
contents.loadURL(`${protocolName}://host/sessionStorage`);
const [, error] = await response;
expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access WebSQL database', async () => {
const response = once(ipcMain, 'web-sql-response');
contents.loadURL(`${protocolName}://host/WebSQL`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
});
it('cannot access indexedDB', async () => {
const response = once(ipcMain, 'indexed-db-response');
contents.loadURL(`${protocolName}://host/indexedDB`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
});
it('cannot access cookie', async () => {
const response = once(ipcMain, 'cookie-response');
contents.loadURL(`${protocolName}://host/cookie`);
const [, error] = await response;
expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
});
});
describe('can be accessed', () => {
let server: http.Server;
let serverUrl: string;
let serverCrossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
server = null as any;
});
afterEach(closeAllWindows);
const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
it(testTitle, async () => {
const w = new BrowserWindow({
show: false,
...extraPreferences
});
let redirected = false;
w.webContents.on('render-process-gone', () => {
expect.fail('renderer crashed / was killed');
});
w.webContents.on('did-redirect-navigation', (event, url) => {
expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
redirected = true;
});
await w.loadURL(`${serverUrl}/redirect-cross-site`);
expect(redirected).to.be.true('didnt redirect');
});
};
testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
});
describe('enableWebSQL webpreference', () => {
const origin = `${standardScheme}://fake-host`;
const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
const sqlPartition = 'web-sql-preference-test';
const sqlSession = session.fromPartition(sqlPartition);
const securityError = 'An attempt was made to break through the security policy of the user agent.';
let contents: WebContents, w: BrowserWindow;
before(() => {
sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
callback({ path: filePath });
});
});
after(() => {
sqlSession.protocol.unregisterProtocol(standardScheme);
});
afterEach(async () => {
if (contents) {
contents.destroy();
contents = null as any;
}
await closeAllWindows();
(w as any) = null;
});
it('default value allows websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
});
it('when set to false can disallow websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
});
it('when set to false does not disable indexedDB', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
const dbName = 'random';
const result = await contents.executeJavaScript(`
new Promise((resolve, reject) => {
try {
let req = window.indexedDB.open('${dbName}');
req.onsuccess = (event) => {
let db = req.result;
resolve(db.name);
}
req.onerror = (event) => { resolve(event.target.code); }
} catch (e) {
resolve(e.message);
}
});
`);
expect(result).to.equal(dbName);
});
it('child webContents can override when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents cannot override when the embedder has disallowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableWebSQL: false,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL('data:text/html,<html></html>');
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents can use websql when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.be.null();
});
});
describe('DOM storage quota increase', () => {
['localStorage', 'sessionStorage'].forEach((storageName) => {
it(`allows saving at least 40MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// Although JavaScript strings use UTF-16, the underlying
// storage provider may encode strings differently, muddling the
// translation between character and byte counts. However,
// a string of 40 * 2^20 characters will require at least 40MiB
// and presumably no more than 80MiB, a size guaranteed to
// to exceed the original 10MiB quota yet stay within the
// new 100MiB quota.
// Note that both the key name and value affect the total size.
const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
const length = 40 * Math.pow(2, 20) - testKeyName.length;
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
// Wait at least one turn of the event loop to help avoid false positives
// Although not entirely necessary, the previous version of this test case
// failed to detect a real problem (perhaps related to DOM storage data caching)
// wherein calling `getItem` immediately after `setItem` would appear to work
// but then later (e.g. next tick) it would not.
await setTimeout(1);
try {
const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`);
expect(storedLength).to.equal(length);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
});
it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
await expect((async () => {
const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
const length = 128 * Math.pow(2, 20) - testKeyName.length;
try {
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
})()).to.eventually.be.rejected();
});
});
});
describe('persistent storage', () => {
it('can be requested', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => {
navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
})`);
expect(grantedBytes).to.equal(1048576);
});
});
});
ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
const pdfSource = url.format({
pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
it('successfully loads a PDF file', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
await once(w.webContents, 'did-finish-load');
});
it('opens when loading a pdf resource as top level navigation', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
const [, contents] = await once(app, 'web-contents-created');
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
it('opens when loading a pdf resource in a iframe', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
const [, contents] = await once(app, 'web-contents-created');
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
});
describe('window.history', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// History should have current page by now.
expect((w.webContents as any).length()).to.equal(1);
const waitCommit = once(w.webContents, 'navigation-entry-committed');
w.webContents.executeJavaScript('window.history.pushState({}, "")');
await waitCommit;
// Initial page + pushed state.
expect((w.webContents as any).length()).to.equal(2);
});
});
describe('window.history.back', () => {
it('should not allow sandboxed iframe to modify main frame state', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-frame-navigate'),
once(w.webContents, 'did-navigate')
]);
w.webContents.executeJavaScript('window.history.pushState(1, "")');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-navigate-in-page')
]);
(w.webContents as any).once('navigation-entry-committed', () => {
expect.fail('Unexpected navigation-entry-committed');
});
w.webContents.once('did-navigate-in-page', () => {
expect.fail('Unexpected did-navigate-in-page');
});
await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()');
expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1);
expect((w.webContents as any).getActiveIndex()).to.equal(1);
});
});
});
describe('chrome://media-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://media-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('chrome://webrtc-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://webrtc-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('document.hasFocus', () => {
it('has correct value when multiple windows are opened', async () => {
const w1 = new BrowserWindow({ show: true });
const w2 = new BrowserWindow({ show: true });
const w3 = new BrowserWindow({ show: false });
await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id);
let focus = false;
focus = await w1.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
focus = await w2.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.true();
focus = await w3.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
});
});
describe('navigator.userAgentData', () => {
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
describe('is not empty', () => {
it('by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a session-wide UA override', async () => {
const ses = session.fromPartition(`${Math.random()}`);
ses.setUserAgent('foobar');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setUserAgent('foo');
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override at load time', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl, {
userAgent: 'foo'
});
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
});
describe('brand list', () => {
it('contains chromium', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
expect(brands.map((b: any) => b.brand)).to.include('Chromium');
});
});
});
describe('Badging API', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
await w.webContents.executeJavaScript('navigator.setAppBadge()');
await w.webContents.executeJavaScript('navigator.clearAppBadge()');
});
});
describe('navigator.webkitGetUserMedia', () => {
it('calls its callbacks', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript(`new Promise((resolve) => {
navigator.webkitGetUserMedia({
audio: true,
video: false
}, () => resolve(),
() => resolve());
})`);
});
});
describe('navigator.language', () => {
it('should not be empty', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
});
});
describe('heap snapshot', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
});
});
// This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761
ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => {
it('can be gotten as context in canvas', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
document.createElement('canvas').getContext('webgl') != null;
`);
expect(canWebglContextBeCreated).to.be.true();
});
});
describe('iframe', () => {
it('does not have node integration', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const result = await w.webContents.executeJavaScript(`
const iframe = document.createElement('iframe')
iframe.src = './set-global.html';
document.body.appendChild(iframe);
new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
`);
expect(result).to.equal('undefined undefined undefined');
});
});
describe('websockets', () => {
it('has user agent', async () => {
const server = http.createServer();
const { port } = await listen(server);
const wss = new ws.Server({ server: server });
const finished = new Promise<string | undefined>((resolve, reject) => {
wss.on('error', reject);
wss.on('connection', (ws, upgradeReq) => {
resolve(upgradeReq.headers['user-agent']);
});
});
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
new WebSocket('ws://127.0.0.1:${port}');
`);
expect(await finished).to.include('Electron');
});
});
describe('fetch', () => {
it('does not crash', async () => {
const server = http.createServer((req, res) => {
res.end('test');
});
defer(() => server.close());
const { port } = await listen(server);
const w = new BrowserWindow({ show: false });
w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const x = await w.webContents.executeJavaScript(`
fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
.then((reader) => {
return reader.read().then((r) => {
reader.cancel();
return r.value;
});
})
`);
expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
});
});
describe('Promise', () => {
before(() => {
ipcMain.handle('ping', (e, arg) => arg);
});
after(() => {
ipcMain.removeHandler('ping');
});
itremote('resolves correctly in Node.js calls', async () => {
await new Promise<void>((resolve, reject) => {
class XElement extends HTMLElement {}
customElements.define('x-element', XElement);
setImmediate(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('x-element');
called = true;
});
});
});
itremote('resolves correctly in Electron calls', async () => {
await new Promise<void>((resolve, reject) => {
class YElement extends HTMLElement {}
customElements.define('y-element', YElement);
require('electron').ipcRenderer.invoke('ping').then(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('y-element');
called = true;
});
});
});
});
describe('synchronous prompts', () => {
describe('window.alert(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
window.alert({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
describe('window.confirm(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
(window.confirm as any)({ toString: null }, 'title');
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('window.history', () => {
describe('window.history.go(offset)', () => {
itremote('throws an exception when the argument cannot be converted to a string', () => {
expect(() => {
(window.history.go as any)({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('console functions', () => {
itremote('should exist', () => {
expect(console.log, 'log').to.be.a('function');
expect(console.error, 'error').to.be.a('function');
expect(console.warn, 'warn').to.be.a('function');
expect(console.info, 'info').to.be.a('function');
expect(console.debug, 'debug').to.be.a('function');
expect(console.trace, 'trace').to.be.a('function');
expect(console.time, 'time').to.be.a('function');
expect(console.timeEnd, 'timeEnd').to.be.a('function');
});
});
// FIXME(nornagon): this is broken on CI, it triggers:
// [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
// trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
// (null text in SpeechSynthesisUtterance struct).
describe('SpeechSynthesis', () => {
itremote('should emit lifecycle events', async () => {
const sentence = `long sentence which will take at least a few seconds to
utter so that it's possible to pause and resume before the end`;
const utter = new SpeechSynthesisUtterance(sentence);
// Create a dummy utterance so that speech synthesis state
// is initialized for later calls.
speechSynthesis.speak(new SpeechSynthesisUtterance());
speechSynthesis.cancel();
speechSynthesis.speak(utter);
// paused state after speak()
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onstart = resolve; });
// paused state after start event
expect(speechSynthesis.paused).to.be.false();
speechSynthesis.pause();
// paused state changes async, right before the pause event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onpause = resolve; });
expect(speechSynthesis.paused).to.be.true();
speechSynthesis.resume();
await new Promise((resolve) => { utter.onresume = resolve; });
// paused state after resume event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onend = resolve; });
});
});
});
describe('font fallback', () => {
async function getRenderedFonts (html: string) {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL(`data:text/html,${html}`);
w.webContents.debugger.attach();
const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
await sendCommand('CSS.enable');
const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
return fonts;
} finally {
w.close();
}
}
it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
const html = '<body style="font-family: sans-serif">test</body>';
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') {
expect(fonts[0].familyName).to.equal('Arial');
} else if (process.platform === 'darwin') {
expect(fonts[0].familyName).to.equal('Helvetica');
} else if (process.platform === 'linux') {
expect(fonts[0].familyName).to.equal('DejaVu Sans');
} // I think this depends on the distro? We don't specify a default.
});
ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
const html = `
<html lang="ja-JP">
<head>
<meta charset="utf-8" />
</head>
<body style="font-family: sans-serif">test 智史</body>
</html>
`;
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); }
});
});
describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
const fullscreenChildHtml = promisify(fs.readFile)(
path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
);
let w: BrowserWindow;
let server: http.Server;
let crossSiteUrl: string;
beforeEach(async () => {
server = http.createServer(async (_req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(await fullscreenChildHtml);
res.end();
});
const serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
w = new BrowserWindow({
show: true,
fullscreen: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeAllWindows();
(w as any) = null;
server.close();
});
ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await setTimeout(500);
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await once(w.webContents, 'leave-html-full-screen');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
w.setFullScreen(false);
await once(w, 'leave-full-screen');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
if (process.platform === 'darwin') await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.true();
await w.webContents.executeJavaScript('document.exitFullscreen()');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
});
describe('navigator.serial', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const getPorts: any = () => {
return w.webContents.executeJavaScript(`
navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.';
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.removeAllListeners('select-serial-port');
});
it('does not return a port if select-serial-port event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not return a port when permission denied', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback(portList[0].portId);
});
session.defaultSession.setPermissionCheckHandler(() => false);
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not crash when select-serial-port is called with an invalid port', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback('i-do-not-exist');
});
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('returns a port when select-serial-port event is defined', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
const port = await getPorts();
if (havePorts) {
expect(port).to.equal('[object SerialPort]');
} else {
expect(port).to.equal(notFoundError);
}
});
it('navigator.serial.getPorts() returns values', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts).to.not.be.empty();
}
});
it('supports port.forget()', async () => {
let forgottenPortFromEvent = {};
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
w.webContents.session.on('serial-port-revoked', (event, details) => {
forgottenPortFromEvent = details.port;
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
if (grantedPorts.length > 0) {
const forgottenPort = await w.webContents.executeJavaScript(`
navigator.serial.getPorts().then(async(ports) => {
const portInfo = await ports[0].getInfo();
await ports[0].forget();
if (portInfo.usbVendorId && portInfo.usbProductId) {
return {
vendorId: '' + portInfo.usbVendorId,
productId: '' + portInfo.usbProductId
}
} else {
return {};
}
})
`);
const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length);
if (forgottenPort.vendorId && forgottenPort.productId) {
expect(forgottenPortFromEvent).to.include(forgottenPort);
}
}
}
});
});
describe('window.getScreenDetails', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
const getScreenDetails: any = () => {
return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true);
};
it('returns screens when a PermissionRequestHandler is not defined', async () => {
const screens = await getScreenDetails();
expect(screens).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(false);
} else {
callback(true);
}
});
const screens = await getScreenDetails();
expect(screens).to.equal('Permission denied.');
});
it('returns screens when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(true);
} else {
callback(false);
}
});
const screens = await getScreenDetails();
expect(screens).to.not.equal('Permission denied.');
});
});
describe('navigator.clipboard.read', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const readClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.equal('Read permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
});
describe('navigator.clipboard.write', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const writeClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.writeText('Hello World!').catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.equal('Write permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
});
ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
let w: BrowserWindow;
const expectedBadgeCount = 42;
const fireAppBadgeAction: any = (action: string, value: any) => {
return w.webContents.executeJavaScript(`
navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
};
// For some reason on macOS changing the badge count doesn't happen right away, so wait
// until it changes.
async function waitForBadgeCount (value: number) {
let badgeCount = app.getBadgeCount();
while (badgeCount !== value) {
await setTimeout(10);
badgeCount = app.getBadgeCount();
}
return badgeCount;
}
describe('in the renderer', () => {
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can set a numerical value', async () => {
const result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
});
it('setAppBadge can set an empty(dot) value', async () => {
const result = await fireAppBadgeAction('set');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
it('clearAppBadge can clear a value', async () => {
let result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
result = await fireAppBadgeAction('clear');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
});
describe('in a service worker', () => {
beforeEach(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
});
afterEach(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
});
it('clearAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'setAppBadge') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS clearing app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
});
});
});
describe('navigator.bluetooth', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
enableBlinkFeatures: 'WebBluetooth'
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
it('can request bluetooth devices', async () => {
const bluetooth = await w.webContents.executeJavaScript(`
navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
});
});
describe('navigator.hid', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-hid-device');
});
it('does not return a device if select-hid-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal('');
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal('');
});
it('returns a device when select-hid-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
} else {
expect(device).to.equal('');
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal('');
}
});
it('excludes a device when a exclusionFilter is specified', async () => {
const exclusionFilters = <any>[];
let haveDevices = false;
let checkForExcludedDevice = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
if (checkForExcludedDevice) {
const compareDevice = {
vendorId: device.vendorId,
productId: device.productId
};
expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
} else {
haveDevices = true;
exclusionFilters.push({
vendorId: device.vendorId,
productId: device.productId
});
return true;
}
}
});
}
callback();
});
await requestDevices();
if (haveDevices) {
// We have devices to exclude, so check if exclusionFilters work
checkForExcludedDevice = true;
await w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
`, true);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('hid-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice = await w.webContents.executeJavaScript(`
navigator.hid.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
name: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
describe('navigator.usb', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-usb-device');
});
it('does not return a device if select-usb-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal(notFoundError);
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal(notFoundError);
});
it('returns a device when select-usb-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
} else {
expect(device).to.equal(notFoundError);
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal(notFoundError);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('usb-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(`
navigator.usb.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
productName: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,484 |
[Bug]: navigator.connection.rtt is always 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.3.1
### What operating system are you using?
Ubuntu
### Operating System Version
20.04.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Executing `navigator.connection.rtt` should return a non-zero value when configured:
```
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
```
### Actual Behavior
when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values.
[Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38484
|
https://github.com/electron/electron/pull/38491
|
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
|
57147d1b8d1352e8f49d6086b9957869d0d1e75a
| 2023-05-30T04:30:26Z |
c++
| 2023-05-31T15:06:25Z |
shell/browser/browser_process_impl.cc
|
// Copyright (c) 2012 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/browser_process_impl.h"
#include <memory>
#include <utility>
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/os_crypt/sync/os_crypt.h"
#include "components/prefs/in_memory_pref_store.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/overlay_user_pref_store.h"
#include "components/prefs/pref_registry.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service_factory.h"
#include "components/proxy_config/pref_proxy_config_tracker_impl.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/common/content_switches.h"
#include "electron/fuses.h"
#include "extensions/common/constants.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_config_service.h"
#include "net/proxy_resolution/proxy_config_with_annotation.h"
#include "services/device/public/cpp/geolocation/geolocation_manager.h"
#include "services/network/public/cpp/network_switches.h"
#include "shell/common/electron_paths.h"
#include "shell/common/thread_restrictions.h"
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_job_manager.h"
#endif
BrowserProcessImpl::BrowserProcessImpl() {
g_browser_process = this;
}
BrowserProcessImpl::~BrowserProcessImpl() {
g_browser_process = nullptr;
}
// static
void BrowserProcessImpl::ApplyProxyModeFromCommandLine(
ValueMapPrefStore* pref_store) {
if (!pref_store)
return;
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kNoProxyServer)) {
pref_store->SetValue(proxy_config::prefs::kProxy,
base::Value(ProxyConfigDictionary::CreateDirect()),
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
} else if (command_line->HasSwitch(switches::kProxyPacUrl)) {
std::string pac_script_url =
command_line->GetSwitchValueASCII(switches::kProxyPacUrl);
pref_store->SetValue(proxy_config::prefs::kProxy,
base::Value(ProxyConfigDictionary::CreatePacScript(
pac_script_url, false /* pac_mandatory */)),
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
} else if (command_line->HasSwitch(switches::kProxyAutoDetect)) {
pref_store->SetValue(proxy_config::prefs::kProxy,
base::Value(ProxyConfigDictionary::CreateAutoDetect()),
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
} else if (command_line->HasSwitch(switches::kProxyServer)) {
std::string proxy_server =
command_line->GetSwitchValueASCII(switches::kProxyServer);
std::string bypass_list =
command_line->GetSwitchValueASCII(switches::kProxyBypassList);
pref_store->SetValue(proxy_config::prefs::kProxy,
base::Value(ProxyConfigDictionary::CreateFixedServers(
proxy_server, bypass_list)),
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
}
}
BuildState* BrowserProcessImpl::GetBuildState() {
NOTIMPLEMENTED();
return nullptr;
}
void BrowserProcessImpl::PostEarlyInitialization() {
PrefServiceFactory prefs_factory;
auto pref_registry = base::MakeRefCounted<PrefRegistrySimple>();
PrefProxyConfigTrackerImpl::RegisterPrefs(pref_registry.get());
#if BUILDFLAG(IS_WIN)
OSCrypt::RegisterLocalPrefs(pref_registry.get());
#endif
auto pref_store = base::MakeRefCounted<ValueMapPrefStore>();
ApplyProxyModeFromCommandLine(pref_store.get());
prefs_factory.set_command_line_prefs(std::move(pref_store));
// Only use a persistent prefs store when cookie encryption is enabled as that
// is the only key that needs it
base::FilePath prefs_path;
CHECK(base::PathService::Get(electron::DIR_SESSION_DATA, &prefs_path));
prefs_path = prefs_path.Append(FILE_PATH_LITERAL("Local State"));
electron::ScopedAllowBlockingForElectron allow_blocking;
scoped_refptr<JsonPrefStore> user_pref_store =
base::MakeRefCounted<JsonPrefStore>(prefs_path);
user_pref_store->ReadPrefs();
prefs_factory.set_user_prefs(user_pref_store);
local_state_ = prefs_factory.Create(std::move(pref_registry));
}
void BrowserProcessImpl::PreCreateThreads() {
// chrome-extension:// URLs are safe to request anywhere, but may only
// commit (including in iframes) in extension processes.
content::ChildProcessSecurityPolicy::GetInstance()
->RegisterWebSafeIsolatedScheme(extensions::kExtensionScheme, true);
// Must be created before the IOThread.
// Once IOThread class is no longer needed,
// this can be created on first use.
if (!SystemNetworkContextManager::GetInstance())
SystemNetworkContextManager::CreateInstance(local_state_.get());
}
void BrowserProcessImpl::PostMainMessageLoopRun() {
if (local_state_)
local_state_->CommitPendingWrite();
// This expects to be destroyed before the task scheduler is torn down.
SystemNetworkContextManager::DeleteInstance();
}
bool BrowserProcessImpl::IsShuttingDown() {
return false;
}
metrics_services_manager::MetricsServicesManager*
BrowserProcessImpl::GetMetricsServicesManager() {
return nullptr;
}
metrics::MetricsService* BrowserProcessImpl::metrics_service() {
return nullptr;
}
ProfileManager* BrowserProcessImpl::profile_manager() {
return nullptr;
}
PrefService* BrowserProcessImpl::local_state() {
DCHECK(local_state_.get());
return local_state_.get();
}
scoped_refptr<network::SharedURLLoaderFactory>
BrowserProcessImpl::shared_url_loader_factory() {
return system_network_context_manager()->GetSharedURLLoaderFactory();
}
variations::VariationsService* BrowserProcessImpl::variations_service() {
return nullptr;
}
BrowserProcessPlatformPart* BrowserProcessImpl::platform_part() {
return nullptr;
}
extensions::EventRouterForwarder*
BrowserProcessImpl::extension_event_router_forwarder() {
return nullptr;
}
NotificationUIManager* BrowserProcessImpl::notification_ui_manager() {
return nullptr;
}
NotificationPlatformBridge* BrowserProcessImpl::notification_platform_bridge() {
return nullptr;
}
SystemNetworkContextManager*
BrowserProcessImpl::system_network_context_manager() {
DCHECK(SystemNetworkContextManager::GetInstance());
return SystemNetworkContextManager::GetInstance();
}
network::NetworkQualityTracker* BrowserProcessImpl::network_quality_tracker() {
return nullptr;
}
embedder_support::OriginTrialsSettingsStorage*
BrowserProcessImpl::GetOriginTrialsSettingsStorage() {
return &origin_trials_settings_storage_;
}
policy::ChromeBrowserPolicyConnector*
BrowserProcessImpl::browser_policy_connector() {
return nullptr;
}
policy::PolicyService* BrowserProcessImpl::policy_service() {
return nullptr;
}
IconManager* BrowserProcessImpl::icon_manager() {
return nullptr;
}
GpuModeManager* BrowserProcessImpl::gpu_mode_manager() {
return nullptr;
}
printing::PrintPreviewDialogController*
BrowserProcessImpl::print_preview_dialog_controller() {
return nullptr;
}
printing::BackgroundPrintingManager*
BrowserProcessImpl::background_printing_manager() {
return nullptr;
}
IntranetRedirectDetector* BrowserProcessImpl::intranet_redirect_detector() {
return nullptr;
}
DownloadStatusUpdater* BrowserProcessImpl::download_status_updater() {
return nullptr;
}
DownloadRequestLimiter* BrowserProcessImpl::download_request_limiter() {
return nullptr;
}
BackgroundModeManager* BrowserProcessImpl::background_mode_manager() {
return nullptr;
}
StatusTray* BrowserProcessImpl::status_tray() {
return nullptr;
}
safe_browsing::SafeBrowsingService*
BrowserProcessImpl::safe_browsing_service() {
return nullptr;
}
subresource_filter::RulesetService*
BrowserProcessImpl::subresource_filter_ruleset_service() {
return nullptr;
}
component_updater::ComponentUpdateService*
BrowserProcessImpl::component_updater() {
return nullptr;
}
MediaFileSystemRegistry* BrowserProcessImpl::media_file_system_registry() {
return nullptr;
}
WebRtcLogUploader* BrowserProcessImpl::webrtc_log_uploader() {
return nullptr;
}
network_time::NetworkTimeTracker* BrowserProcessImpl::network_time_tracker() {
return nullptr;
}
gcm::GCMDriver* BrowserProcessImpl::gcm_driver() {
return nullptr;
}
resource_coordinator::ResourceCoordinatorParts*
BrowserProcessImpl::resource_coordinator_parts() {
return nullptr;
}
resource_coordinator::TabManager* BrowserProcessImpl::GetTabManager() {
return nullptr;
}
SerialPolicyAllowedPorts* BrowserProcessImpl::serial_policy_allowed_ports() {
return nullptr;
}
HidPolicyAllowedDevices* BrowserProcessImpl::hid_policy_allowed_devices() {
return nullptr;
}
HidSystemTrayIcon* BrowserProcessImpl::hid_system_tray_icon() {
return nullptr;
}
void BrowserProcessImpl::SetSystemLocale(const std::string& locale) {
system_locale_ = locale;
}
const std::string& BrowserProcessImpl::GetSystemLocale() const {
return system_locale_;
}
void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) {
locale_ = locale;
}
const std::string& BrowserProcessImpl::GetApplicationLocale() {
return locale_;
}
printing::PrintJobManager* BrowserProcessImpl::print_job_manager() {
#if BUILDFLAG(ENABLE_PRINTING)
if (!print_job_manager_)
print_job_manager_ = std::make_unique<printing::PrintJobManager>();
return print_job_manager_.get();
#else
return nullptr;
#endif
}
StartupData* BrowserProcessImpl::startup_data() {
return nullptr;
}
device::GeolocationManager* BrowserProcessImpl::geolocation_manager() {
return geolocation_manager_.get();
}
void BrowserProcessImpl::SetGeolocationManager(
std::unique_ptr<device::GeolocationManager> geolocation_manager) {
geolocation_manager_ = std::move(geolocation_manager);
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,484 |
[Bug]: navigator.connection.rtt is always 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.3.1
### What operating system are you using?
Ubuntu
### Operating System Version
20.04.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Executing `navigator.connection.rtt` should return a non-zero value when configured:
```
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
```
### Actual Behavior
when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values.
[Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38484
|
https://github.com/electron/electron/pull/38491
|
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
|
57147d1b8d1352e8f49d6086b9957869d0d1e75a
| 2023-05-30T04:30:26Z |
c++
| 2023-05-31T15:06:25Z |
shell/browser/browser_process_impl.h
|
// Copyright (c) 2012 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.
// This interface is for managing the global services of the application. Each
// service is lazily created when requested the first time. The service getters
// will return NULL if the service is not available, so callers must check for
// this condition.
#ifndef ELECTRON_SHELL_BROWSER_BROWSER_PROCESS_IMPL_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_PROCESS_IMPL_H_
#include <memory>
#include <string>
#include "base/command_line.h"
#include "chrome/browser/browser_process.h"
#include "components/embedder_support/origin_trials/origin_trials_settings_storage.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/value_map_pref_store.h"
#include "printing/buildflags/buildflags.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "shell/browser/net/system_network_context_manager.h"
namespace printing {
class PrintJobManager;
}
// Empty definition for std::unique_ptr, rather than a forward declaration
class BackgroundModeManager {};
// NOT THREAD SAFE, call only from the main thread.
// These functions shouldn't return NULL unless otherwise noted.
class BrowserProcessImpl : public BrowserProcess {
public:
BrowserProcessImpl();
~BrowserProcessImpl() override;
// disable copy
BrowserProcessImpl(const BrowserProcessImpl&) = delete;
BrowserProcessImpl& operator=(const BrowserProcessImpl&) = delete;
static void ApplyProxyModeFromCommandLine(ValueMapPrefStore* pref_store);
BuildState* GetBuildState() override;
void PostEarlyInitialization();
void PreCreateThreads();
void PostDestroyThreads() {}
void PostMainMessageLoopRun();
void SetSystemLocale(const std::string& locale);
const std::string& GetSystemLocale() const;
void EndSession() override {}
void FlushLocalStateAndReply(base::OnceClosure reply) override {}
bool IsShuttingDown() override;
metrics_services_manager::MetricsServicesManager* GetMetricsServicesManager()
override;
metrics::MetricsService* metrics_service() override;
ProfileManager* profile_manager() override;
PrefService* local_state() override;
scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory()
override;
variations::VariationsService* variations_service() override;
BrowserProcessPlatformPart* platform_part() override;
extensions::EventRouterForwarder* extension_event_router_forwarder() override;
NotificationUIManager* notification_ui_manager() override;
NotificationPlatformBridge* notification_platform_bridge() override;
SystemNetworkContextManager* system_network_context_manager() override;
network::NetworkQualityTracker* network_quality_tracker() override;
embedder_support::OriginTrialsSettingsStorage*
GetOriginTrialsSettingsStorage() override;
policy::ChromeBrowserPolicyConnector* browser_policy_connector() override;
policy::PolicyService* policy_service() override;
IconManager* icon_manager() override;
GpuModeManager* gpu_mode_manager() override;
printing::PrintPreviewDialogController* print_preview_dialog_controller()
override;
printing::BackgroundPrintingManager* background_printing_manager() override;
IntranetRedirectDetector* intranet_redirect_detector() override;
DownloadStatusUpdater* download_status_updater() override;
DownloadRequestLimiter* download_request_limiter() override;
BackgroundModeManager* background_mode_manager() override;
StatusTray* status_tray() override;
safe_browsing::SafeBrowsingService* safe_browsing_service() override;
subresource_filter::RulesetService* subresource_filter_ruleset_service()
override;
component_updater::ComponentUpdateService* component_updater() override;
MediaFileSystemRegistry* media_file_system_registry() override;
WebRtcLogUploader* webrtc_log_uploader() override;
network_time::NetworkTimeTracker* network_time_tracker() override;
gcm::GCMDriver* gcm_driver() override;
resource_coordinator::ResourceCoordinatorParts* resource_coordinator_parts()
override;
resource_coordinator::TabManager* GetTabManager() override;
SerialPolicyAllowedPorts* serial_policy_allowed_ports() override;
HidPolicyAllowedDevices* hid_policy_allowed_devices() override;
HidSystemTrayIcon* hid_system_tray_icon() override;
void CreateDevToolsProtocolHandler() override {}
void CreateDevToolsAutoOpener() override {}
void set_background_mode_manager_for_test(
std::unique_ptr<BackgroundModeManager> manager) override {}
#if (BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX))
void StartAutoupdateTimer() override {}
#endif
void SetApplicationLocale(const std::string& locale) override;
const std::string& GetApplicationLocale() override;
printing::PrintJobManager* print_job_manager() override;
StartupData* startup_data() override;
device::GeolocationManager* geolocation_manager() override;
void SetGeolocationManager(
std::unique_ptr<device::GeolocationManager> geolocation_manager) override;
private:
#if BUILDFLAG(ENABLE_PRINTING)
std::unique_ptr<printing::PrintJobManager> print_job_manager_;
#endif
std::unique_ptr<PrefService> local_state_;
std::unique_ptr<device::GeolocationManager> geolocation_manager_;
std::string locale_;
std::string system_locale_;
embedder_support::OriginTrialsSettingsStorage origin_trials_settings_storage_;
};
#endif // ELECTRON_SHELL_BROWSER_BROWSER_PROCESS_IMPL_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,484 |
[Bug]: navigator.connection.rtt is always 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.3.1
### What operating system are you using?
Ubuntu
### Operating System Version
20.04.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Executing `navigator.connection.rtt` should return a non-zero value when configured:
```
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
```
### Actual Behavior
when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values.
[Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38484
|
https://github.com/electron/electron/pull/38491
|
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
|
57147d1b8d1352e8f49d6086b9957869d0d1e75a
| 2023-05-30T04:30:26Z |
c++
| 2023-05-31T15:06:25Z |
shell/browser/electron_browser_main_parts.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_browser_main_parts.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/browser/ui/color/chrome_color_mixers.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/embedder_support/origin_trials/origin_trials_settings_storage.h"
#include "components/os_crypt/sync/key_storage_config_linux.h"
#include "components/os_crypt/sync/os_crypt.h"
#include "content/browser/browser_main_loop.h" // nogncheck
#include "content/public/browser/browser_child_process_host_delegate.h"
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/first_party_sets_handler.h"
#include "content/public/browser/web_ui_controller_factory.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/process_type.h"
#include "content/public/common/result_codes.h"
#include "electron/buildflags/buildflags.h"
#include "electron/fuses.h"
#include "media/base/localized_strings.h"
#include "services/network/public/cpp/features.h"
#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
#include "shell/app/electron_main_delegate.h"
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/browser.h"
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_web_ui_controller_factory.h"
#include "shell/browser/feature_list.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
#include "shell/browser/ui/devtools_manager_delegate.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_helper/trackable_object.h"
#include "shell/common/logging.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/idle/idle.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_switches.h"
#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "base/environment.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#include "electron/electron_gtk_stubs.h"
#include "ui/base/cursor/cursor_factory.h"
#include "ui/base/ime/linux/linux_input_method_context_factory.h"
#include "ui/gfx/color_utils.h"
#include "ui/gtk/gtk_compat.h" // nogncheck
#include "ui/gtk/gtk_util.h" // nogncheck
#include "ui/linux/linux_ui.h"
#include "ui/linux/linux_ui_factory.h"
#include "ui/linux/linux_ui_getter.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/display/win/dpi.h"
#include "ui/gfx/system_fonts_win.h"
#include "ui/strings/grit/app_locale_settings.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "components/os_crypt/sync/keychain_password_mac.h"
#include "shell/browser/ui/cocoa/views_delegate_mac.h"
#else
#include "shell/browser/ui/views/electron_views_delegate.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "components/keyed_service/content/browser_context_dependency_manager.h"
#include "extensions/browser/browser_context_keyed_service_factories.h"
#include "extensions/common/extension_api.h"
#include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h"
#include "shell/browser/extensions/electron_extensions_browser_client.h"
#include "shell/common/extensions/electron_extensions_client.h"
#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#include "shell/common/plugin_info.h"
#endif // BUILDFLAG(ENABLE_PLUGINS)
namespace electron {
namespace {
#if BUILDFLAG(IS_LINUX)
class LinuxUiGetterImpl : public ui::LinuxUiGetter {
public:
LinuxUiGetterImpl() = default;
~LinuxUiGetterImpl() override = default;
ui::LinuxUiTheme* GetForWindow(aura::Window* window) override {
return GetForProfile(nullptr);
}
ui::LinuxUiTheme* GetForProfile(Profile* profile) override {
return ui::GetLinuxUiTheme(ui::SystemTheme::kGtk);
}
};
#endif
template <typename T>
void Erase(T* container, typename T::iterator iter) {
container->erase(iter);
}
#if BUILDFLAG(IS_WIN)
// gfx::Font callbacks
void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) {
l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override,
&font_adjustment->font_scale);
font_adjustment->font_scale *= display::win::GetAccessibilityFontScale();
}
int GetMinimumFontSize() {
int min_font_size;
base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
&min_font_size);
return min_font_size;
}
#endif
std::u16string MediaStringProvider(media::MessageId id) {
switch (id) {
case media::DEFAULT_AUDIO_DEVICE_NAME:
return u"Default";
#if BUILDFLAG(IS_WIN)
case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
return u"Communications";
#endif
default:
return std::u16string();
}
}
#if BUILDFLAG(IS_LINUX)
// GTK does not provide a way to check if current theme is dark, so we compare
// the text and background luminosity to get a result.
// This trick comes from FireFox.
void UpdateDarkThemeSetting() {
float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel"));
float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel"));
bool is_dark = fg > bg;
// Pass it to NativeUi theme, which is used by the nativeTheme module and most
// places in Electron.
ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark);
// Pass it to Web Theme, to make "prefers-color-scheme" media query work.
ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark);
}
#endif
// A fake BrowserProcess object that used to feed the source code from chrome.
class FakeBrowserProcessImpl : public BrowserProcessImpl {
public:
embedder_support::OriginTrialsSettingsStorage*
GetOriginTrialsSettingsStorage() override {
return &origin_trials_settings_storage_;
}
private:
embedder_support::OriginTrialsSettingsStorage origin_trials_settings_storage_;
};
} // namespace
#if BUILDFLAG(IS_LINUX)
class DarkThemeObserver : public ui::NativeThemeObserver {
public:
DarkThemeObserver() = default;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override {
UpdateDarkThemeSetting();
}
};
#endif
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr;
ElectronBrowserMainParts::ElectronBrowserMainParts()
: fake_browser_process_(std::make_unique<BrowserProcessImpl>()),
browser_(std::make_unique<Browser>()),
node_bindings_(
NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)),
electron_bindings_(
std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {
DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts";
self_ = this;
}
ElectronBrowserMainParts::~ElectronBrowserMainParts() = default;
// static
ElectronBrowserMainParts* ElectronBrowserMainParts::Get() {
DCHECK(self_);
return self_;
}
bool ElectronBrowserMainParts::SetExitCode(int code) {
if (!exit_code_)
return false;
content::BrowserMainLoop::GetInstance()->SetResultCode(code);
*exit_code_ = code;
return true;
}
int ElectronBrowserMainParts::GetExitCode() const {
return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT);
}
int ElectronBrowserMainParts::PreEarlyInitialization() {
field_trial_list_ = std::make_unique<base::FieldTrialList>();
#if BUILDFLAG(IS_POSIX)
HandleSIGCHLD();
#endif
#if BUILDFLAG(IS_LINUX)
DetectOzonePlatform();
ui::OzonePlatform::PreEarlyInitialization();
#endif
#if BUILDFLAG(IS_MAC)
screen_ = std::make_unique<display::ScopedNativeScreen>();
#endif
ui::ColorProviderManager::Get().AppendColorProviderInitializer(
base::BindRepeating(AddChromeColorMixers));
return GetExitCode();
}
void ElectronBrowserMainParts::PostEarlyInitialization() {
// A workaround was previously needed because there was no ThreadTaskRunner
// set. If this check is failing we may need to re-add that workaround
DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault());
// The ProxyResolverV8 has setup a complete V8 environment, in order to
// avoid conflicts we only initialize our V8 environment after that.
js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop());
v8::HandleScope scope(js_env_->isolate());
node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext());
// Create the global environment.
node::Environment* env = node_bindings_->CreateEnvironment(
js_env_->isolate()->GetCurrentContext(), js_env_->platform());
node_env_ = std::make_unique<NodeEnvironment>(env);
env->set_trace_sync_io(env->options()->trace_sync_io);
// We do not want to crash the main process on unhandled rejections.
env->options()->unhandled_rejections = "warn-with-error-code";
// Add Electron extended APIs.
electron_bindings_->BindTo(js_env_->isolate(), env->process_object());
// Create explicit microtasks runner.
js_env_->CreateMicrotasksRunner();
// Wrap the uv loop with global env.
node_bindings_->set_uv_env(env);
// Load everything.
node_bindings_->LoadEnvironment(env);
// We already initialized the feature list in PreEarlyInitialization(), but
// the user JS script would not have had a chance to alter the command-line
// switches at that point. Lets reinitialize it here to pick up the
// command-line changes.
base::FeatureList::ClearInstanceForTesting();
InitializeFeatureList();
// Initialize field trials.
InitializeFieldTrials();
// Reinitialize logging now that the app has had a chance to set the app name
// and/or user data directory.
logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(),
/* is_preinit = */ false);
// Initialize after user script environment creation.
fake_browser_process_->PostEarlyInitialization();
}
int ElectronBrowserMainParts::PreCreateThreads() {
if (!views::LayoutProvider::Get()) {
layout_provider_ = std::make_unique<views::LayoutProvider>();
}
// Fetch the system locale for Electron.
#if BUILDFLAG(IS_MAC)
fake_browser_process_->SetSystemLocale(GetCurrentSystemLocale());
#else
fake_browser_process_->SetSystemLocale(base::i18n::GetConfiguredLocale());
#endif
auto* command_line = base::CommandLine::ForCurrentProcess();
std::string locale = command_line->GetSwitchValueASCII(::switches::kLang);
#if BUILDFLAG(IS_MAC)
// The browser process only wants to support the language Cocoa will use,
// so force the app locale to be overridden with that value. This must
// happen before the ResourceBundle is loaded
if (locale.empty())
l10n_util::OverrideLocaleWithCocoaLocale();
#elif BUILDFLAG(IS_LINUX)
// l10n_util::GetApplicationLocaleInternal uses g_get_language_names(),
// which keys off of getenv("LC_ALL").
// We must set this env first to make ui::ResourceBundle accept the custom
// locale.
auto env = base::Environment::Create();
absl::optional<std::string> lc_all;
if (!locale.empty()) {
std::string str;
if (env->GetVar("LC_ALL", &str))
lc_all.emplace(std::move(str));
env->SetVar("LC_ALL", locale.c_str());
}
#endif
// Load resources bundle according to locale.
std::string loaded_locale = LoadResourceBundle(locale);
#if defined(USE_AURA)
// NB: must be called _after_ locale resource bundle is loaded,
// because ui lib makes use of it in X11
if (!display::Screen::GetScreen()) {
screen_ = views::CreateDesktopScreen();
}
#endif
// Initialize the app locale for Electron and Chromium.
std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale);
ElectronBrowserClient::SetApplicationLocale(app_locale);
fake_browser_process_->SetApplicationLocale(app_locale);
#if BUILDFLAG(IS_LINUX)
// Reset to the original LC_ALL since we should not be changing it.
if (!locale.empty()) {
if (lc_all)
env->SetVar("LC_ALL", *lc_all);
else
env->UnSetVar("LC_ALL");
}
#endif
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
#if BUILDFLAG(IS_MAC)
ui::InitIdleMonitor();
Browser::Get()->ApplyForcedRTL();
#endif
fake_browser_process_->PreCreateThreads();
// Notify observers.
Browser::Get()->PreCreateThreads();
return 0;
}
void ElectronBrowserMainParts::PostCreateThreads() {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread));
#if BUILDFLAG(ENABLE_PLUGINS)
// PluginService can only be used on the UI thread
// and ContentClient::AddPlugins gets called for both browser and render
// process where the latter will not have UI thread which leads to DCHECK.
// Separate the WebPluginInfo registration for these processes.
std::vector<content::WebPluginInfo> plugins;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->RefreshPlugins();
GetInternalPlugins(&plugins);
for (const auto& plugin : plugins)
plugin_service->RegisterInternalPlugin(plugin, true);
#endif
}
void ElectronBrowserMainParts::PostDestroyThreads() {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_browser_client_.reset();
extensions::ExtensionsBrowserClient::Set(nullptr);
#endif
#if BUILDFLAG(IS_LINUX)
device::BluetoothAdapterFactory::Shutdown();
bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
fake_browser_process_->PostDestroyThreads();
}
void ElectronBrowserMainParts::ToolkitInitialized() {
#if BUILDFLAG(IS_LINUX)
auto* linux_ui = ui::GetDefaultLinuxUi();
CHECK(linux_ui);
linux_ui_getter_ = std::make_unique<LinuxUiGetterImpl>();
// Try loading gtk symbols used by Electron.
electron::InitializeElectron_gtk(gtk::GetLibGtk());
if (!electron::IsElectron_gtkInitialized()) {
electron::UninitializeElectron_gtk();
}
electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf());
CHECK(electron::IsElectron_gdk_pixbufInitialized())
<< "Failed to initialize libgdk_pixbuf-2.0.so.0";
// Chromium does not respect GTK dark theme setting, but they may change
// in future and this code might be no longer needed. Check the Chromium
// issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=998903
UpdateDarkThemeSetting();
// Update the native theme when GTK theme changes. The GetNativeTheme
// here returns a NativeThemeGtk, which monitors GTK settings.
dark_theme_observer_ = std::make_unique<DarkThemeObserver>();
auto* linux_ui_theme = ui::LinuxUiTheme::GetForProfile(nullptr);
CHECK(linux_ui_theme);
linux_ui_theme->GetNativeTheme()->AddObserver(dark_theme_observer_.get());
ui::LinuxUi::SetInstance(linux_ui);
// Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager
// implementation). Start observing them once it's initialized.
ui::CursorFactory::GetInstance()->ObserveThemeChanges();
#endif
#if defined(USE_AURA)
wm_state_ = std::make_unique<wm::WMState>();
#endif
#if BUILDFLAG(IS_WIN)
gfx::win::SetAdjustFontCallback(&AdjustUIFont);
gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize);
#endif
#if BUILDFLAG(IS_MAC)
views_delegate_ = std::make_unique<ViewsDelegateMac>();
#else
views_delegate_ = std::make_unique<ViewsDelegate>();
#endif
}
int ElectronBrowserMainParts::PreMainMessageLoopRun() {
// Run user's main script before most things get initialized, so we can have
// a chance to setup everything.
node_bindings_->PrepareEmbedThread();
node_bindings_->StartPolling();
// url::Add*Scheme are not threadsafe, this helps prevent data races.
url::LockSchemeRegistries();
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions_client_ = std::make_unique<ElectronExtensionsClient>();
extensions::ExtensionsClient::Set(extensions_client_.get());
// BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient.
extensions_browser_client_ =
std::make_unique<ElectronExtensionsBrowserClient>();
extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get());
extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt();
extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt();
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckServiceFactory::GetInstance();
#endif
content::WebUIControllerFactory::RegisterFactory(
ElectronWebUIControllerFactory::GetInstance());
auto* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) {
// --remote-debugging-pipe
auto on_disconnect = base::BindOnce([]() {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); }));
});
content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler(
std::move(on_disconnect));
} else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
// --remote-debugging-port
DevToolsManagerDelegate::StartHttpHandler();
}
#if !BUILDFLAG(IS_MAC)
// The corresponding call in macOS is in ElectronApplicationDelegate.
Browser::Get()->WillFinishLaunching();
Browser::Get()->DidFinishLaunching(base::Value::Dict());
#endif
// Notify observers that main thread message loop was initialized.
Browser::Get()->PreMainMessageLoopRun();
return GetExitCode();
}
void ElectronBrowserMainParts::WillRunMainMessageLoop(
std::unique_ptr<base::RunLoop>& run_loop) {
exit_code_ = content::RESULT_CODE_NORMAL_EXIT;
Browser::Get()->SetMainMessageLoopQuitClosure(
run_loop->QuitWhenIdleClosure());
}
void ElectronBrowserMainParts::PostCreateMainMessageLoop() {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
std::string app_name = electron::Browser::Get()->GetName();
#endif
#if BUILDFLAG(IS_LINUX)
auto shutdown_cb =
base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated());
ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop(
std::move(shutdown_cb),
content::GetUIThreadTaskRunner({content::BrowserTaskType::kUserInput}));
bluez::DBusBluezManagerWrapperLinux::Initialize();
// Set up crypt config. This needs to be done before anything starts the
// network service, as the raw encryption key needs to be shared with the
// network service for encrypted cookie storage.
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
std::unique_ptr<os_crypt::Config> config =
std::make_unique<os_crypt::Config>();
// Forward to os_crypt the flag to use a specific password store.
config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore);
config->product_name = app_name;
config->application_name = app_name;
config->main_thread_runner =
base::SingleThreadTaskRunner::GetCurrentDefault();
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/main:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1
config->should_use_preference =
command_line.HasSwitch(::switches::kEnableEncryptionSelection);
base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path);
OSCrypt::SetConfig(std::move(config));
#endif
#if BUILDFLAG(IS_MAC)
KeychainPassword::GetServiceName() = app_name + " Safe Storage";
KeychainPassword::GetAccountName() = app_name;
#endif
#if BUILDFLAG(IS_POSIX)
// Exit in response to SIGINT, SIGTERM, etc.
InstallShutdownSignalHandlers(
base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())),
content::GetUIThreadTaskRunner({}));
#endif
}
void ElectronBrowserMainParts::PostMainMessageLoopRun() {
#if BUILDFLAG(IS_MAC)
FreeAppDelegate();
#endif
// Shutdown the DownloadManager before destroying Node to prevent
// DownloadItem callbacks from crashing.
for (auto& iter : ElectronBrowserContext::browser_context_map()) {
auto* download_manager = iter.second.get()->GetDownloadManager();
if (download_manager) {
download_manager->Shutdown();
}
}
// Shutdown utility process created with Electron API before
// stopping Node.js so that exit events can be emitted. We don't let
// content layer perform this action since it destroys
// child process only after this step (PostMainMessageLoopRun) via
// BrowserProcessIOThread::ProcessHostCleanUp() which is too late for our
// use case.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1086-1108
//
// The following logic is based on
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_process_io_thread.cc;l=127-159
//
// Although content::BrowserChildProcessHostIterator is only to be called from
// IO thread, it is safe to call from PostMainMessageLoopRun because thread
// restrictions have been lifted.
// https://source.chromium.org/chromium/chromium/src/+/main:content/browser/browser_main_loop.cc;l=1062-1078
for (content::BrowserChildProcessHostIterator it(
content::PROCESS_TYPE_UTILITY);
!it.Done(); ++it) {
if (it.GetDelegate()->GetServiceName() == node::mojom::NodeService::Name_) {
auto& process = it.GetData().GetProcess();
if (!process.IsValid())
continue;
auto utility_process_wrapper =
api::UtilityProcessWrapper::FromProcessId(process.Pid());
if (utility_process_wrapper)
utility_process_wrapper->Shutdown(0 /* exit_code */);
}
}
// Destroy node platform after all destructors_ are executed, as they may
// invoke Node/V8 APIs inside them.
node_env_->env()->set_trace_sync_io(false);
js_env_->DestroyMicrotasksRunner();
node::Stop(node_env_->env(), node::StopFlags::kDoNotTerminateIsolate);
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();
}
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
| 38,484 |
[Bug]: navigator.connection.rtt is always 0
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.3.1
### What operating system are you using?
Ubuntu
### Operating System Version
20.04.1
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Executing `navigator.connection.rtt` should return a non-zero value when configured:
```
window.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
```
### Actual Behavior
when executing `navigator.connection.rtt` in the debugger console, this value is always `0`. However calling the same statement in Chromium based browsers returns a variety of values.
[Electron Docs](https://www.electronjs.org/docs/latest/api/session#sesenablenetworkemulationoptions)
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38484
|
https://github.com/electron/electron/pull/38491
|
67f273a6d69eb43fda8a520d5c9bba375a6bcdab
|
57147d1b8d1352e8f49d6086b9957869d0d1e75a
| 2023-05-30T04:30:26Z |
c++
| 2023-05-31T15:06:25Z |
spec/chromium-spec.ts
|
import { expect } from 'chai';
import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import * as https from 'https';
import * as http from 'http';
import * as path from 'path';
import * as fs from 'fs';
import * as url from 'url';
import * as ChildProcess from 'child_process';
import { EventEmitter, once } from 'events';
import { promisify } from 'util';
import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
import { PipeTransport } from './pipe-transport';
import * as ws from 'ws';
import { setTimeout } from 'timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
describe('reporting api', () => {
it('sends a report for an intervention', async () => {
const reporting = new EventEmitter();
// The Reporting API only works on https with valid certs. To dodge having
// to set up a trusted certificate, hack the validator.
session.defaultSession.setCertificateVerifyProc((req, cb) => {
cb(0);
});
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options, (req, res) => {
if (req.url?.endsWith('report')) {
let data = '';
req.on('data', (d) => { data += d.toString('utf-8'); });
req.on('end', () => {
reporting.emit('report', JSON.parse(data));
});
}
const { port } = server.address() as any;
res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`);
res.setHeader('Content-Type', 'text/html');
res.end('<script>window.navigator.vibrate(1)</script>');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`);
const [reports] = await reportGenerated;
expect(reports).to.be.an('array').with.lengthOf(1);
const { type, url, body } = reports[0];
expect(type).to.equal('intervention');
expect(url).to.equal(url);
expect(body.id).to.equal('NavigatorVibrate');
expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/);
} finally {
bw.destroy();
server.close();
}
});
});
describe('window.postMessage', () => {
afterEach(async () => {
await closeAllWindows();
});
it('sets the source and origin correctly', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
const [, message] = await once(ipcMain, 'complete');
expect(message.data).to.equal('testing');
expect(message.origin).to.equal('file://');
expect(message.sourceEqualsOpener).to.equal(true);
expect(message.eventOrigin).to.equal('file://');
});
});
describe('focus handling', () => {
let webviewContents: WebContents;
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
contextIsolation: false
}
});
const webviewReady = once(w.webContents, 'did-attach-webview');
await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
const [, wvContents] = await webviewReady;
webviewContents = wvContents;
await once(webviewContents, 'did-finish-load');
w.focus();
});
afterEach(() => {
webviewContents = null as unknown as WebContents;
w.destroy();
w = null as unknown as BrowserWindow;
});
const expectFocusChange = async () => {
const [, focusedElementId] = await once(ipcMain, 'focus-changed');
return focusedElementId;
};
describe('a TAB press', () => {
const tabPressEvent: any = {
type: 'keyDown',
keyCode: 'Tab'
};
it('moves focus to the next focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
});
});
describe('a SHIFT + TAB press', () => {
const shiftTabPressEvent: any = {
type: 'keyDown',
modifiers: ['Shift'],
keyCode: 'Tab'
};
it('moves focus to the previous focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
});
});
});
describe('web security', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('engages CORB when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,<script>
const s = document.createElement('script')
s.src = "${serverUrl}"
// The script will load successfully but its body will be emptied out
// by CORB, so we don't expect a syntax error.
s.onload = () => { require('electron').ipcRenderer.send('success') }
document.documentElement.appendChild(s)
</script>`);
await p;
});
it('bypasses CORB when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,
<script>
window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
</script>
<script src="${serverUrl}"></script>`);
await p;
});
it('engages CORS when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('failed');
});
it('bypasses CORS when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('passed');
});
describe('accessing file://', () => {
async function loadFile (w: BrowserWindow) {
const thisFile = url.format({
pathname: __filename.replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
await w.loadURL(`data:text/html,<script>
function loadFile() {
return new Promise((resolve) => {
fetch('${thisFile}').then(
() => resolve('loaded'),
() => resolve('failed')
)
});
}
</script>`);
return await w.webContents.executeJavaScript('loadFile()');
}
it('is forbidden when web security is enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
const result = await loadFile(w);
expect(result).to.equal('failed');
});
it('is allowed when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
const result = await loadFile(w);
expect(result).to.equal('loaded');
});
});
describe('wasm-eval csp', () => {
async function loadWasm (csp: string) {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
enableBlinkFeatures: 'WebAssemblyCSP'
}
});
await w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
</head>
<script>
function loadWasm() {
const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
return new Promise((resolve) => {
WebAssembly.instantiate(wasmBin).then(() => {
resolve('loaded')
}).catch((error) => {
resolve(error.message)
})
});
}
</script>`);
return await w.webContents.executeJavaScript('loadWasm()');
}
it('wasm codegen is disallowed by default', async () => {
const r = await loadWasm('');
expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"');
});
it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
const r = await loadWasm("'wasm-unsafe-eval'");
expect(r).to.equal('loaded');
});
});
describe('csp', () => {
for (const sandbox of [true, false]) {
describe(`when sandbox: ${sandbox}`, () => {
for (const contextIsolation of [true, false]) {
describe(`when contextIsolation: ${contextIsolation}`, () => {
it('prevents eval from running in an inline script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
</head>
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.match(/Refused to evaluate a string/);
});
it('does not prevent eval from running in an inline script when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.equal('true');
});
it('prevents eval from running in executeJavaScript', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>');
await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected();
});
it('does not prevent eval from running in executeJavaScript when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,');
expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true();
});
});
}
});
}
});
it('does not crash when multiple WebContent are created with web security disabled', () => {
const options = { show: false, webPreferences: { webSecurity: false } };
const w1 = new BrowserWindow(options);
w1.loadURL(serverUrl);
const w2 = new BrowserWindow(options);
w2.loadURL(serverUrl);
});
});
describe('command line switches', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
describe('--lang switch', () => {
const currentLocale = app.getLocale();
const currentSystemLocale = app.getSystemLocale();
const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages());
const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
const appPath = path.join(fixturesPath, 'api', 'locale-check');
const args = [appPath, `--set-lang=${locale}`];
if (printEnv) {
args.push('--print-env');
}
appProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
let stderr = '';
appProcess.stderr.on('data', (data) => { stderr += data; });
const [code, signal] = await once(appProcess, 'exit');
if (code !== 0) {
throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
}
output = output.replace(/(\r\n|\n|\r)/gm, '');
expect(output).to.equal(result);
};
it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`));
const lcAll = String(process.env.LC_ALL);
ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
// The LC_ALL env should not be set to DOM locale string.
expect(lcAll).to.not.equal(app.getLocale());
});
ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
});
describe('--remote-debugging-pipe switch', () => {
it('should expose CDP via pipe', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(message.result.product).to.contain('Chrome');
expect(message.result.userAgent).to.contain('Electron');
});
it('should override --remote-debugging-port switch', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
let stderr = '';
appProcess.stderr.on('data', (data: string) => { stderr += data; });
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(stderr).to.not.include('DevTools listening on');
});
it('should shut down Electron upon Browser.close CDP command', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
await once(appProcess, 'exit');
});
});
describe('--remote-debugging-port switch', () => {
it('should display the discovery page', (done) => {
const electronPath = process.execPath;
let output = '';
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
appProcess.stdout.on('data', (data) => {
console.log(data);
});
appProcess.stderr.on('data', (data) => {
console.log(data);
output += data;
const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
if (m) {
appProcess!.stderr.removeAllListeners('data');
const port = m[1];
http.get(`http://127.0.0.1:${port}`, (res) => {
try {
expect(res.statusCode).to.eql(200);
expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
done();
} catch (e) {
done(e);
} finally {
res.destroy();
}
});
}
});
});
});
});
describe('chromium features', () => {
afterEach(closeAllWindows);
describe('accessing key names also used as Node.js module names', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
});
});
describe('first party sets', () => {
const fps = [
'https://fps-member1.glitch.me',
'https://fps-member2.glitch.me',
'https://fps-member3.glitch.me'
];
it('loads first party sets', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base');
const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
it('loads sets from the command line', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line');
const args = [appPath, `--use-first-party-set=${fps}`];
const fpsProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
});
describe('loading jquery', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
});
});
describe('navigator.languages', () => {
it('should return the system locale only', async () => {
const appLocale = app.getLocale();
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const languages = await w.webContents.executeJavaScript('navigator.languages');
expect(languages.length).to.be.greaterThan(0);
expect(languages).to.contain(appLocale);
});
});
describe('navigator.serviceWorker', () => {
it('should register for file scheme', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for intercepted file scheme', (done) => {
const customSession = session.fromPartition('intercept-file');
customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
const content = fs.readFileSync(path.normalize(file));
const ext = path.extname(file);
let type = 'text/html';
if (ext === '.js') type = 'application/javascript';
callback({ data: content, mimeType: type } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol('file');
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for custom scheme', (done) => {
const customSession = session.fromPartition('custom-scheme');
customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
callback({ path: path.normalize(file) } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
});
it('should not allow nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
partition: 'sw-file-scheme-worker-spec',
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`);
const data = await w.webContents.executeJavaScript(`
navigator.serviceWorker.register('worker-no-node.js', {
scope: './'
}).then(() => navigator.serviceWorker.ready)
new Promise((resolve) => {
navigator.serviceWorker.onmessage = event => resolve(event.data);
});
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
describe('navigator.geolocation', () => {
ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'geolocation-spec',
contextIsolation: false
}
});
const message = once(w.webContents, 'ipc-message');
w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'geolocation') {
callback(false);
} else {
callback(true);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
const [, channel] = await message;
expect(channel).to.equal('success', 'unexpected response from geolocation api');
});
ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'geolocation-spec'
}
});
w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => {
callback(true);
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
x => resolve({coords: x.coords, timestamp: x.timestamp}),
err => reject(new Error(err.message))))`);
expect(position).to.have.property('coords');
expect(position).to.have.property('timestamp');
});
});
describe('web workers', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
appProcess = ChildProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
it('Worker can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
worker.postMessage(message);
eventPromise.then(t => t.data)
`);
expect(data).to.equal('ping');
});
it('Worker has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker_node.js');
new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('Worker has node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/worker.html`);
const [, data] = await once(ipcMain, 'worker-result');
expect(data).to.equal('object function object function');
});
describe('SharedWorker', () => {
it('can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
worker.port.postMessage(message);
eventPromise
`);
expect(data).to.equal('ping');
});
it('has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('does not have node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
});
describe('form submit', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
res.setHeader('Content-Type', 'application/json');
req.on('end', () => {
res.end(`body:${body}`);
});
});
serverUrl = (await listen(server)).url;
});
after(async () => {
server.close();
await closeAllWindows();
});
[true, false].forEach((isSandboxEnabled) =>
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const loadPromise = once(w.webContents, 'did-finish-load');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.submit();
`);
await loadPromise;
const res = await w.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
it('posts data to a new window with target=_blank', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const windowCreatedPromise = once(app, 'browser-window-created');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.target = '_blank';
form.submit();
`);
const [, newWin] = await windowCreatedPromise;
const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
})
);
});
describe('window.open', () => {
for (const show of [true, false]) {
it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
const w = new BrowserWindow({ show });
// toggle visibility
if (show) {
w.hide();
} else {
w.show();
}
defer(() => { w.close(); });
const promise = once(app, 'browser-window-created');
w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
const [, newWindow] = await promise;
expect(newWindow.isVisible()).to.equal(true);
});
}
// FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false')
const e = await message
b.close();
return {
eventData: e.data
}
})()`);
expect(eventData.isProcessGlobalUndefined).to.be.true();
});
it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
// NB. webSecurity is disabled because native window.open() is not
// allowed to load devtools:// URLs.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created');
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
it('can disable node integration when it is enabled on the parent window', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created');
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = require('url').format({
pathname: `${fixturesPath}/pages/window-no-javascript.html`,
protocol: 'file',
slashes: true
});
w.webContents.executeJavaScript(`
{ b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created');
await once(contents, 'did-finish-load');
// Click link on page
contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
const [, window] = await once(app, 'browser-window-created');
const preferences = window.webContents.getLastWebPreferences();
expect(preferences.javascript).to.be.false();
});
it('defines a window.location getter', async () => {
let targetURL: string;
if (process.platform === 'win32') {
targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
} else {
targetURL = `file://${fixturesPath}/pages/base-page.html`;
}
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
const [, window] = await once(app, 'browser-window-created');
await once(window.webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
});
it('defines a window.location setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('defines a window.location.href setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('open a blank page when no URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('open a blank page when an empty URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
const [, { webContents }] = await once(app, 'browser-window-created');
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('does not throw an exception when the frameName is a built-in object property', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
const frameName = await new Promise((resolve) => {
w.webContents.setWindowOpenHandler(details => {
setImmediate(() => resolve(details.frameName));
return { action: 'allow' };
});
});
expect(frameName).to.equal('__proto__');
});
// FIXME(nornagon): I'm not sure this ... ever was correct?
xit('inherit options of parent window', async () => {
const w = new BrowserWindow({ show: false, width: 123, height: 456 });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const url = `file://${fixturesPath}/pages/window-open-size.html`;
const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(url)}, '', 'show=false')
const e = await message
b.close();
const width = outerWidth;
const height = outerHeight;
return {
width,
height,
eventData: e.data
}
})()`);
expect(eventData).to.equal(`size: ${width} ${height}`);
expect(eventData).to.equal('size: 123 456');
});
it('does not override child options', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`;
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData).to.equal('size: 350 450');
});
it('disables the <webview> tag when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData.isWebViewGlobalUndefined).to.be.true();
});
it('throws an exception when the arguments cannot be converted to strings', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', { toString: null })')
).to.eventually.be.rejected();
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })')
).to.eventually.be.rejected();
});
it('does not throw an exception when the features include webPreferences', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null')
).to.eventually.be.fulfilled();
});
});
describe('window.opener', () => {
it('is null for main window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
const [, channel, opener] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('opener');
expect(opener).to.equal(null);
});
it('is not null for window opened by window.open', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener.html`;
const eventData = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data);
`);
expect(eventData).to.equal('object');
});
});
describe('window.opener.postMessage', () => {
it('sets source and origin correctly', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`;
const { sourceIsChild, origin } = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({
sourceIsChild: e.source === b,
origin: e.origin
}));
`);
expect(sourceIsChild).to.be.true();
expect(origin).to.equal('file://');
});
it('supports windows opened from a <webview>', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('about:blank');
const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html'));
childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`);
const message = await w.webContents.executeJavaScript(`
const webview = new WebView();
webview.allowpopups = true;
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = ${JSON.stringify(childWindowUrl)}
const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true}));
document.body.appendChild(webview);
consoleMessage.then(e => e.message)
`);
expect(message).to.equal('message');
});
describe('targetOrigin argument', () => {
let serverURL: string;
let server: any;
beforeEach(async () => {
server = http.createServer((req, res) => {
res.writeHead(200);
const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html');
res.end(fs.readFileSync(filePath, 'utf8'));
});
serverURL = (await listen(server)).url;
});
afterEach(() => {
server.close();
});
it('delivers messages that match the origin', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const data = await w.webContents.executeJavaScript(`
window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data)
`);
expect(data).to.equal('deliver');
});
});
});
describe('navigator.mediaDevices', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can return labels of enumerated devices', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.true();
});
it('does not return labels of enumerated devices when permission denied', async () => {
session.defaultSession.setPermissionCheckHandler(() => false);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.false();
});
it('returns the same device ids across reloads', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
});
it('can return new device id when cookie storage is cleared', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
await ses.clearStorageData({ storages: ['cookies'] });
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
});
it('provides a securityOrigin to the request handler', async () => {
session.defaultSession.setPermissionRequestHandler(
(wc, permission, callback, details) => {
if (details.securityOrigin !== undefined) {
callback(true);
} else {
callback(false);
}
}
);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
video: {
mandatory: {
chromeMediaSource: "desktop",
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream) => stream.getVideoTracks())`);
expect(labels.some((l: any) => l)).to.be.true();
});
it('fails with "not supported" for getDisplayMedia', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true);
expect(ok).to.be.false();
expect(err).to.equal('Not supported');
});
});
describe('window.opener access', () => {
const scheme = 'app';
const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
const httpUrl1 = `${scheme}://origin1`;
const httpUrl2 = `${scheme}://origin2`;
const fileBlank = `file://${fixturesPath}/pages/blank.html`;
const httpBlank = `${scheme}://origin1/blank`;
const table = [
{ parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
{ parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
// {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
// {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
// NB. this is different from Chrome's behavior, which isolates file: urls from each other
{ parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
{ parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
];
const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
if (request.url.includes('blank')) {
callback(`${fixturesPath}/pages/blank.html`);
} else {
callback(`${fixturesPath}/pages/window-opener-location.html`);
}
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
describe('when opened from main window', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
for (const sandboxPopup of [false, true]) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
sandbox: sandboxPopup
}
}
}));
await w.loadURL(parent);
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
window.addEventListener('message', function f(e) {
resolve(e.data)
})
window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
}
});
describe('when opened from <webview>', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
// This test involves three contexts:
// 1. The root BrowserWindow in which the test is run,
// 2. A <webview> belonging to the root window,
// 3. A window opened by calling window.open() from within the <webview>.
// We are testing whether context (3) can access context (2) under various conditions.
// This is context (1), the base window for the test.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
const parentCode = `new Promise((resolve) => {
// This is context (3), a child window of the WebView.
const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
window.addEventListener("message", e => {
resolve(e.data)
})
})`;
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
// This is context (2), a WebView which will call window.open()
const webview = new WebView()
webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
webview.setAttribute('webpreferences', 'contextIsolation=no')
webview.setAttribute('allowpopups', 'on')
webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
webview.addEventListener('dom-ready', async () => {
webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
})
document.body.appendChild(webview)
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
});
});
describe('storage', () => {
describe('custom non standard schemes', () => {
const protocolName = 'storage';
let contents: WebContents;
before(() => {
protocol.registerFileProtocol(protocolName, (request, callback) => {
const parsedUrl = url.parse(request.url);
let filename;
switch (parsedUrl.pathname) {
case '/localStorage' : filename = 'local_storage.html'; break;
case '/sessionStorage' : filename = 'session_storage.html'; break;
case '/WebSQL' : filename = 'web_sql.html'; break;
case '/indexedDB' : filename = 'indexed_db.html'; break;
case '/cookie' : filename = 'cookie.html'; break;
default : filename = '';
}
callback({ path: `${fixturesPath}/pages/storage/${filename}` });
});
});
after(() => {
protocol.unregisterProtocol(protocolName);
});
beforeEach(() => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
});
afterEach(() => {
contents.destroy();
contents = null as any;
});
it('cannot access localStorage', async () => {
const response = once(ipcMain, 'local-storage-response');
contents.loadURL(protocolName + '://host/localStorage');
const [, error] = await response;
expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access sessionStorage', async () => {
const response = once(ipcMain, 'session-storage-response');
contents.loadURL(`${protocolName}://host/sessionStorage`);
const [, error] = await response;
expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access WebSQL database', async () => {
const response = once(ipcMain, 'web-sql-response');
contents.loadURL(`${protocolName}://host/WebSQL`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
});
it('cannot access indexedDB', async () => {
const response = once(ipcMain, 'indexed-db-response');
contents.loadURL(`${protocolName}://host/indexedDB`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
});
it('cannot access cookie', async () => {
const response = once(ipcMain, 'cookie-response');
contents.loadURL(`${protocolName}://host/cookie`);
const [, error] = await response;
expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
});
});
describe('can be accessed', () => {
let server: http.Server;
let serverUrl: string;
let serverCrossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
server = null as any;
});
afterEach(closeAllWindows);
const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
it(testTitle, async () => {
const w = new BrowserWindow({
show: false,
...extraPreferences
});
let redirected = false;
w.webContents.on('render-process-gone', () => {
expect.fail('renderer crashed / was killed');
});
w.webContents.on('did-redirect-navigation', (event, url) => {
expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
redirected = true;
});
await w.loadURL(`${serverUrl}/redirect-cross-site`);
expect(redirected).to.be.true('didnt redirect');
});
};
testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
});
describe('enableWebSQL webpreference', () => {
const origin = `${standardScheme}://fake-host`;
const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
const sqlPartition = 'web-sql-preference-test';
const sqlSession = session.fromPartition(sqlPartition);
const securityError = 'An attempt was made to break through the security policy of the user agent.';
let contents: WebContents, w: BrowserWindow;
before(() => {
sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
callback({ path: filePath });
});
});
after(() => {
sqlSession.protocol.unregisterProtocol(standardScheme);
});
afterEach(async () => {
if (contents) {
contents.destroy();
contents = null as any;
}
await closeAllWindows();
(w as any) = null;
});
it('default value allows websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
});
it('when set to false can disallow websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
});
it('when set to false does not disable indexedDB', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
const dbName = 'random';
const result = await contents.executeJavaScript(`
new Promise((resolve, reject) => {
try {
let req = window.indexedDB.open('${dbName}');
req.onsuccess = (event) => {
let db = req.result;
resolve(db.name);
}
req.onerror = (event) => { resolve(event.target.code); }
} catch (e) {
resolve(e.message);
}
});
`);
expect(result).to.equal(dbName);
});
it('child webContents can override when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents cannot override when the embedder has disallowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableWebSQL: false,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL('data:text/html,<html></html>');
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents can use websql when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.be.null();
});
});
describe('DOM storage quota increase', () => {
['localStorage', 'sessionStorage'].forEach((storageName) => {
it(`allows saving at least 40MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// Although JavaScript strings use UTF-16, the underlying
// storage provider may encode strings differently, muddling the
// translation between character and byte counts. However,
// a string of 40 * 2^20 characters will require at least 40MiB
// and presumably no more than 80MiB, a size guaranteed to
// to exceed the original 10MiB quota yet stay within the
// new 100MiB quota.
// Note that both the key name and value affect the total size.
const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
const length = 40 * Math.pow(2, 20) - testKeyName.length;
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
// Wait at least one turn of the event loop to help avoid false positives
// Although not entirely necessary, the previous version of this test case
// failed to detect a real problem (perhaps related to DOM storage data caching)
// wherein calling `getItem` immediately after `setItem` would appear to work
// but then later (e.g. next tick) it would not.
await setTimeout(1);
try {
const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`);
expect(storedLength).to.equal(length);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
});
it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
await expect((async () => {
const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
const length = 128 * Math.pow(2, 20) - testKeyName.length;
try {
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
})()).to.eventually.be.rejected();
});
});
});
describe('persistent storage', () => {
it('can be requested', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => {
navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
})`);
expect(grantedBytes).to.equal(1048576);
});
});
});
ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
const pdfSource = url.format({
pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
it('successfully loads a PDF file', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
await once(w.webContents, 'did-finish-load');
});
it('opens when loading a pdf resource as top level navigation', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
const [, contents] = await once(app, 'web-contents-created');
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
it('opens when loading a pdf resource in a iframe', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
const [, contents] = await once(app, 'web-contents-created');
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
});
describe('window.history', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// History should have current page by now.
expect((w.webContents as any).length()).to.equal(1);
const waitCommit = once(w.webContents, 'navigation-entry-committed');
w.webContents.executeJavaScript('window.history.pushState({}, "")');
await waitCommit;
// Initial page + pushed state.
expect((w.webContents as any).length()).to.equal(2);
});
});
describe('window.history.back', () => {
it('should not allow sandboxed iframe to modify main frame state', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-frame-navigate'),
once(w.webContents, 'did-navigate')
]);
w.webContents.executeJavaScript('window.history.pushState(1, "")');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-navigate-in-page')
]);
(w.webContents as any).once('navigation-entry-committed', () => {
expect.fail('Unexpected navigation-entry-committed');
});
w.webContents.once('did-navigate-in-page', () => {
expect.fail('Unexpected did-navigate-in-page');
});
await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()');
expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1);
expect((w.webContents as any).getActiveIndex()).to.equal(1);
});
});
});
describe('chrome://media-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://media-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('chrome://webrtc-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://webrtc-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('document.hasFocus', () => {
it('has correct value when multiple windows are opened', async () => {
const w1 = new BrowserWindow({ show: true });
const w2 = new BrowserWindow({ show: true });
const w3 = new BrowserWindow({ show: false });
await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id);
let focus = false;
focus = await w1.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
focus = await w2.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.true();
focus = await w3.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
});
});
describe('navigator.userAgentData', () => {
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
describe('is not empty', () => {
it('by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a session-wide UA override', async () => {
const ses = session.fromPartition(`${Math.random()}`);
ses.setUserAgent('foobar');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setUserAgent('foo');
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override at load time', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl, {
userAgent: 'foo'
});
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
});
describe('brand list', () => {
it('contains chromium', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
expect(brands.map((b: any) => b.brand)).to.include('Chromium');
});
});
});
describe('Badging API', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
await w.webContents.executeJavaScript('navigator.setAppBadge()');
await w.webContents.executeJavaScript('navigator.clearAppBadge()');
});
});
describe('navigator.webkitGetUserMedia', () => {
it('calls its callbacks', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript(`new Promise((resolve) => {
navigator.webkitGetUserMedia({
audio: true,
video: false
}, () => resolve(),
() => resolve());
})`);
});
});
describe('navigator.language', () => {
it('should not be empty', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
});
});
describe('heap snapshot', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
});
});
// This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761
ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => {
it('can be gotten as context in canvas', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
document.createElement('canvas').getContext('webgl') != null;
`);
expect(canWebglContextBeCreated).to.be.true();
});
});
describe('iframe', () => {
it('does not have node integration', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const result = await w.webContents.executeJavaScript(`
const iframe = document.createElement('iframe')
iframe.src = './set-global.html';
document.body.appendChild(iframe);
new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
`);
expect(result).to.equal('undefined undefined undefined');
});
});
describe('websockets', () => {
it('has user agent', async () => {
const server = http.createServer();
const { port } = await listen(server);
const wss = new ws.Server({ server: server });
const finished = new Promise<string | undefined>((resolve, reject) => {
wss.on('error', reject);
wss.on('connection', (ws, upgradeReq) => {
resolve(upgradeReq.headers['user-agent']);
});
});
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
new WebSocket('ws://127.0.0.1:${port}');
`);
expect(await finished).to.include('Electron');
});
});
describe('fetch', () => {
it('does not crash', async () => {
const server = http.createServer((req, res) => {
res.end('test');
});
defer(() => server.close());
const { port } = await listen(server);
const w = new BrowserWindow({ show: false });
w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const x = await w.webContents.executeJavaScript(`
fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
.then((reader) => {
return reader.read().then((r) => {
reader.cancel();
return r.value;
});
})
`);
expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
});
});
describe('Promise', () => {
before(() => {
ipcMain.handle('ping', (e, arg) => arg);
});
after(() => {
ipcMain.removeHandler('ping');
});
itremote('resolves correctly in Node.js calls', async () => {
await new Promise<void>((resolve, reject) => {
class XElement extends HTMLElement {}
customElements.define('x-element', XElement);
setImmediate(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('x-element');
called = true;
});
});
});
itremote('resolves correctly in Electron calls', async () => {
await new Promise<void>((resolve, reject) => {
class YElement extends HTMLElement {}
customElements.define('y-element', YElement);
require('electron').ipcRenderer.invoke('ping').then(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('y-element');
called = true;
});
});
});
});
describe('synchronous prompts', () => {
describe('window.alert(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
window.alert({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
describe('window.confirm(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
(window.confirm as any)({ toString: null }, 'title');
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('window.history', () => {
describe('window.history.go(offset)', () => {
itremote('throws an exception when the argument cannot be converted to a string', () => {
expect(() => {
(window.history.go as any)({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('console functions', () => {
itremote('should exist', () => {
expect(console.log, 'log').to.be.a('function');
expect(console.error, 'error').to.be.a('function');
expect(console.warn, 'warn').to.be.a('function');
expect(console.info, 'info').to.be.a('function');
expect(console.debug, 'debug').to.be.a('function');
expect(console.trace, 'trace').to.be.a('function');
expect(console.time, 'time').to.be.a('function');
expect(console.timeEnd, 'timeEnd').to.be.a('function');
});
});
// FIXME(nornagon): this is broken on CI, it triggers:
// [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
// trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
// (null text in SpeechSynthesisUtterance struct).
describe('SpeechSynthesis', () => {
itremote('should emit lifecycle events', async () => {
const sentence = `long sentence which will take at least a few seconds to
utter so that it's possible to pause and resume before the end`;
const utter = new SpeechSynthesisUtterance(sentence);
// Create a dummy utterance so that speech synthesis state
// is initialized for later calls.
speechSynthesis.speak(new SpeechSynthesisUtterance());
speechSynthesis.cancel();
speechSynthesis.speak(utter);
// paused state after speak()
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onstart = resolve; });
// paused state after start event
expect(speechSynthesis.paused).to.be.false();
speechSynthesis.pause();
// paused state changes async, right before the pause event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onpause = resolve; });
expect(speechSynthesis.paused).to.be.true();
speechSynthesis.resume();
await new Promise((resolve) => { utter.onresume = resolve; });
// paused state after resume event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onend = resolve; });
});
});
});
describe('font fallback', () => {
async function getRenderedFonts (html: string) {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL(`data:text/html,${html}`);
w.webContents.debugger.attach();
const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
await sendCommand('CSS.enable');
const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
return fonts;
} finally {
w.close();
}
}
it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
const html = '<body style="font-family: sans-serif">test</body>';
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') {
expect(fonts[0].familyName).to.equal('Arial');
} else if (process.platform === 'darwin') {
expect(fonts[0].familyName).to.equal('Helvetica');
} else if (process.platform === 'linux') {
expect(fonts[0].familyName).to.equal('DejaVu Sans');
} // I think this depends on the distro? We don't specify a default.
});
ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
const html = `
<html lang="ja-JP">
<head>
<meta charset="utf-8" />
</head>
<body style="font-family: sans-serif">test 智史</body>
</html>
`;
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); }
});
});
describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
const fullscreenChildHtml = promisify(fs.readFile)(
path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
);
let w: BrowserWindow;
let server: http.Server;
let crossSiteUrl: string;
beforeEach(async () => {
server = http.createServer(async (_req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(await fullscreenChildHtml);
res.end();
});
const serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
w = new BrowserWindow({
show: true,
fullscreen: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeAllWindows();
(w as any) = null;
server.close();
});
ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await setTimeout(500);
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await once(w.webContents, 'leave-html-full-screen');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
w.setFullScreen(false);
await once(w, 'leave-full-screen');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
if (process.platform === 'darwin') await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.true();
await w.webContents.executeJavaScript('document.exitFullscreen()');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
});
describe('navigator.serial', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const getPorts: any = () => {
return w.webContents.executeJavaScript(`
navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.';
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.removeAllListeners('select-serial-port');
});
it('does not return a port if select-serial-port event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not return a port when permission denied', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback(portList[0].portId);
});
session.defaultSession.setPermissionCheckHandler(() => false);
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not crash when select-serial-port is called with an invalid port', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback('i-do-not-exist');
});
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('returns a port when select-serial-port event is defined', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
const port = await getPorts();
if (havePorts) {
expect(port).to.equal('[object SerialPort]');
} else {
expect(port).to.equal(notFoundError);
}
});
it('navigator.serial.getPorts() returns values', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts).to.not.be.empty();
}
});
it('supports port.forget()', async () => {
let forgottenPortFromEvent = {};
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
w.webContents.session.on('serial-port-revoked', (event, details) => {
forgottenPortFromEvent = details.port;
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
if (grantedPorts.length > 0) {
const forgottenPort = await w.webContents.executeJavaScript(`
navigator.serial.getPorts().then(async(ports) => {
const portInfo = await ports[0].getInfo();
await ports[0].forget();
if (portInfo.usbVendorId && portInfo.usbProductId) {
return {
vendorId: '' + portInfo.usbVendorId,
productId: '' + portInfo.usbProductId
}
} else {
return {};
}
})
`);
const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length);
if (forgottenPort.vendorId && forgottenPort.productId) {
expect(forgottenPortFromEvent).to.include(forgottenPort);
}
}
}
});
});
describe('window.getScreenDetails', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
const getScreenDetails: any = () => {
return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true);
};
it('returns screens when a PermissionRequestHandler is not defined', async () => {
const screens = await getScreenDetails();
expect(screens).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(false);
} else {
callback(true);
}
});
const screens = await getScreenDetails();
expect(screens).to.equal('Permission denied.');
});
it('returns screens when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(true);
} else {
callback(false);
}
});
const screens = await getScreenDetails();
expect(screens).to.not.equal('Permission denied.');
});
});
describe('navigator.clipboard.read', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const readClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.equal('Read permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
});
describe('navigator.clipboard.write', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const writeClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.writeText('Hello World!').catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.equal('Write permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
});
ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
let w: BrowserWindow;
const expectedBadgeCount = 42;
const fireAppBadgeAction: any = (action: string, value: any) => {
return w.webContents.executeJavaScript(`
navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
};
// For some reason on macOS changing the badge count doesn't happen right away, so wait
// until it changes.
async function waitForBadgeCount (value: number) {
let badgeCount = app.getBadgeCount();
while (badgeCount !== value) {
await setTimeout(10);
badgeCount = app.getBadgeCount();
}
return badgeCount;
}
describe('in the renderer', () => {
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can set a numerical value', async () => {
const result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
});
it('setAppBadge can set an empty(dot) value', async () => {
const result = await fireAppBadgeAction('set');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
it('clearAppBadge can clear a value', async () => {
let result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
result = await fireAppBadgeAction('clear');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
});
describe('in a service worker', () => {
beforeEach(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
});
afterEach(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
});
it('clearAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'setAppBadge') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS clearing app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
});
});
});
describe('navigator.bluetooth', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
enableBlinkFeatures: 'WebBluetooth'
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
it('can request bluetooth devices', async () => {
const bluetooth = await w.webContents.executeJavaScript(`
navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
});
});
describe('navigator.hid', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-hid-device');
});
it('does not return a device if select-hid-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal('');
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal('');
});
it('returns a device when select-hid-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
} else {
expect(device).to.equal('');
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal('');
}
});
it('excludes a device when a exclusionFilter is specified', async () => {
const exclusionFilters = <any>[];
let haveDevices = false;
let checkForExcludedDevice = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
if (checkForExcludedDevice) {
const compareDevice = {
vendorId: device.vendorId,
productId: device.productId
};
expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
} else {
haveDevices = true;
exclusionFilters.push({
vendorId: device.vendorId,
productId: device.productId
});
return true;
}
}
});
}
callback();
});
await requestDevices();
if (haveDevices) {
// We have devices to exclude, so check if exclusionFilters work
checkForExcludedDevice = true;
await w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
`, true);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('hid-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice = await w.webContents.executeJavaScript(`
navigator.hid.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
name: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
describe('navigator.usb', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-usb-device');
});
it('does not return a device if select-usb-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal(notFoundError);
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal(notFoundError);
});
it('returns a device when select-usb-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
} else {
expect(device).to.equal(notFoundError);
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal(notFoundError);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('usb-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(`
navigator.usb.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
productName: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,245 |
[Bug]: datalist positioning issues in browserview are not fully fixed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.2.0
### What operating system are you using?
Windows
### Operating System Version
win 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
The position of the datalist should display normally regardless of the x and y values of the browserview setBounds relative to the browserwindow
### Actual Behavior

If the x,y of the browserView setBounds is 0 with respect to the browserWindow, it displays normally

But if the x and y of the browserView setBounds are not 0 with respect to the browserWindow, the position of the datalist is biased
### Testcase Gist URL
https://gist.github.com/467faf384c3e25880d68ac1eba0adfe5
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38245
|
https://github.com/electron/electron/pull/38489
|
bb2ba35b51609e40c4cae2f3f904a04c795a7430
|
b2059f288acba385d91cec0cc86135605bf477cf
| 2023-05-10T12:12:20Z |
c++
| 2023-06-06T08:21:42Z |
shell/browser/electron_autofill_driver.cc
|
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_autofill_driver.h"
#include <memory>
#include <utility>
#include "content/public/browser/render_widget_host_view.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_window.h"
namespace electron {
AutofillDriver::AutofillDriver(content::RenderFrameHost* render_frame_host)
: render_frame_host_(render_frame_host) {
autofill_popup_ = std::make_unique<AutofillPopup>();
}
AutofillDriver::~AutofillDriver() = default;
void AutofillDriver::BindPendingReceiver(
mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver>
pending_receiver) {
receiver_.Bind(std::move(pending_receiver));
}
void AutofillDriver::ShowAutofillPopup(
const gfx::RectF& bounds,
const std::vector<std::u16string>& values,
const std::vector<std::u16string>& labels) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
auto* web_contents = api::WebContents::From(
content::WebContents::FromRenderFrameHost(render_frame_host_));
if (!web_contents || !web_contents->owner_window())
return;
auto* embedder = web_contents->embedder();
bool osr =
web_contents->IsOffScreen() || (embedder && embedder->IsOffScreen());
gfx::RectF popup_bounds(bounds);
content::RenderFrameHost* embedder_frame_host = nullptr;
if (embedder) {
auto* embedder_view =
embedder->web_contents()->GetPrimaryMainFrame()->GetView();
auto* view = web_contents->web_contents()->GetPrimaryMainFrame()->GetView();
auto offset = view->GetViewBounds().origin() -
embedder_view->GetViewBounds().origin();
popup_bounds.Offset(offset);
embedder_frame_host = embedder->web_contents()->GetPrimaryMainFrame();
}
autofill_popup_->CreateView(render_frame_host_, embedder_frame_host, osr,
web_contents->owner_window()->content_view(),
popup_bounds);
autofill_popup_->SetItems(values, labels);
}
void AutofillDriver::HideAutofillPopup() {
if (autofill_popup_)
autofill_popup_->Hide();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,245 |
[Bug]: datalist positioning issues in browserview are not fully fixed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
24.2.0
### What operating system are you using?
Windows
### Operating System Version
win 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
The position of the datalist should display normally regardless of the x and y values of the browserview setBounds relative to the browserwindow
### Actual Behavior

If the x,y of the browserView setBounds is 0 with respect to the browserWindow, it displays normally

But if the x and y of the browserView setBounds are not 0 with respect to the browserWindow, the position of the datalist is biased
### Testcase Gist URL
https://gist.github.com/467faf384c3e25880d68ac1eba0adfe5
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38245
|
https://github.com/electron/electron/pull/38489
|
bb2ba35b51609e40c4cae2f3f904a04c795a7430
|
b2059f288acba385d91cec0cc86135605bf477cf
| 2023-05-10T12:12:20Z |
c++
| 2023-06-06T08:21:42Z |
shell/browser/electron_autofill_driver.cc
|
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/electron_autofill_driver.h"
#include <memory>
#include <utility>
#include "content/public/browser/render_widget_host_view.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_window.h"
namespace electron {
AutofillDriver::AutofillDriver(content::RenderFrameHost* render_frame_host)
: render_frame_host_(render_frame_host) {
autofill_popup_ = std::make_unique<AutofillPopup>();
}
AutofillDriver::~AutofillDriver() = default;
void AutofillDriver::BindPendingReceiver(
mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver>
pending_receiver) {
receiver_.Bind(std::move(pending_receiver));
}
void AutofillDriver::ShowAutofillPopup(
const gfx::RectF& bounds,
const std::vector<std::u16string>& values,
const std::vector<std::u16string>& labels) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
auto* web_contents = api::WebContents::From(
content::WebContents::FromRenderFrameHost(render_frame_host_));
if (!web_contents || !web_contents->owner_window())
return;
auto* embedder = web_contents->embedder();
bool osr =
web_contents->IsOffScreen() || (embedder && embedder->IsOffScreen());
gfx::RectF popup_bounds(bounds);
content::RenderFrameHost* embedder_frame_host = nullptr;
if (embedder) {
auto* embedder_view =
embedder->web_contents()->GetPrimaryMainFrame()->GetView();
auto* view = web_contents->web_contents()->GetPrimaryMainFrame()->GetView();
auto offset = view->GetViewBounds().origin() -
embedder_view->GetViewBounds().origin();
popup_bounds.Offset(offset);
embedder_frame_host = embedder->web_contents()->GetPrimaryMainFrame();
}
autofill_popup_->CreateView(render_frame_host_, embedder_frame_host, osr,
web_contents->owner_window()->content_view(),
popup_bounds);
autofill_popup_->SetItems(values, labels);
}
void AutofillDriver::HideAutofillPopup() {
if (autofill_popup_)
autofill_popup_->Hide();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,553 |
[Bug]: TypeError: undefined is not iterable
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When using the `protocol.handle` api and returning an empty object as a result, a helpful error message is displayed to the user.
### Actual Behavior
When using the `protocol.handle` api and returning an empty object as a result, the output is as follows:
```
TypeError: undefined is not iterable
at Function.fromEntries (<anonymous>)
at AsyncFunction.<anonymous> (node:electron/js2c/browser_init:2:57533)
```
This error is kind of hard to debug since the error message doesn't point in the right direction and the stack trace doesn't include any user defined function.
### Testcase Gist URL
https://gist.github.com/SimonSiefke/cf52088c800054d6a63b16633db4d540
### Additional Information
I believe the error is happening here:
https://github.com/electron/electron/blob/d818f35ad4ec44c83f21dd3656ef1072e196c34f/lib/browser/api/protocol.ts#L76C5-L91
One idea could be to check if res is actually of type Response and throw a user-friendly error if not:
```js
if (!res || typeof res !== 'object' || !(res instanceof Response)) { // check if res is valid
throw new Error(`protocol response must be of type Response`) // throw user friendly error
}
```
|
https://github.com/electron/electron/issues/38553
|
https://github.com/electron/electron/pull/38587
|
5931f69f183bfcd57c9dc7dffe8560ac9163bb45
|
86824c070e31a674f6f523b52426549efc61aa6d
| 2023-06-01T15:22:07Z |
c++
| 2023-06-07T07:29:04Z |
lib/browser/api/protocol.ts
|
import { ProtocolRequest, session } from 'electron/main';
import { createReadStream } from 'fs';
import { Readable } from 'stream';
import { ReadableStream } from 'stream/web';
// Global protocol APIs.
const { registerSchemesAsPrivileged, getStandardSchemes, Protocol } = process._linkedBinding('electron_browser_protocol');
const ERR_FAILED = -2;
const ERR_UNEXPECTED = -9;
const isBuiltInScheme = (scheme: string) => scheme === 'http' || scheme === 'https';
function makeStreamFromPipe (pipe: any): ReadableStream {
const buf = new Uint8Array(1024 * 1024 /* 1 MB */);
return new ReadableStream({
async pull (controller) {
try {
const rv = await pipe.read(buf);
if (rv > 0) {
controller.enqueue(buf.subarray(0, rv));
} else {
controller.close();
}
} catch (e) {
controller.error(e);
}
}
});
}
function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] {
if (!uploadData) return null;
// Optimization: skip creating a stream if the request is just a single buffer.
if (uploadData.length === 1 && (uploadData[0] as any).type === 'rawData') return uploadData[0].bytes;
const chunks = [...uploadData] as any[]; // TODO: types are wrong
let current: ReadableStreamDefaultReader | null = null;
return new ReadableStream({
pull (controller) {
if (current) {
current.read().then(({ done, value }) => {
controller.enqueue(value);
if (done) current = null;
}, (err) => {
controller.error(err);
});
} else {
if (!chunks.length) { return controller.close(); }
const chunk = chunks.shift()!;
if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') {
current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader();
this.pull!(controller);
} else if (chunk.type === 'stream') {
current = makeStreamFromPipe(chunk.body).getReader();
this.pull!(controller);
}
}
}
}) as RequestInit['body'];
}
Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, handler: (req: Request) => Response | Promise<Response>) {
const register = isBuiltInScheme(scheme) ? this.interceptProtocol : this.registerProtocol;
const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => {
try {
const body = convertToRequestBody(preq.uploadData);
const req = new Request(preq.url, {
headers: preq.headers,
method: preq.method,
referrer: preq.referrer,
body,
duplex: body instanceof ReadableStream ? 'half' : undefined
} as any);
const res = await handler(req);
if (!res || typeof res !== 'object') {
return cb({ error: ERR_UNEXPECTED });
}
if (res.type === 'error') { cb({ error: ERR_FAILED }); } else {
cb({
data: res.body ? Readable.fromWeb(res.body as ReadableStream<ArrayBufferView>) : null,
headers: Object.fromEntries(res.headers),
statusCode: res.status,
statusText: res.statusText,
mimeType: (res as any).__original_resp?._responseHead?.mimeType
});
}
} catch (e) {
console.error(e);
cb({ error: ERR_UNEXPECTED });
}
});
if (!success) throw new Error(`Failed to register protocol: ${scheme}`);
};
Protocol.prototype.unhandle = function (this: Electron.Protocol, scheme: string) {
const unregister = isBuiltInScheme(scheme) ? this.uninterceptProtocol : this.unregisterProtocol;
if (!unregister.call(this, scheme)) { throw new Error(`Failed to unhandle protocol: ${scheme}`); }
};
Protocol.prototype.isProtocolHandled = function (this: Electron.Protocol, scheme: string) {
const isRegistered = isBuiltInScheme(scheme) ? this.isProtocolIntercepted : this.isProtocolRegistered;
return isRegistered.call(this, scheme);
};
const protocol = {
registerSchemesAsPrivileged,
getStandardSchemes,
registerStringProtocol: (...args) => session.defaultSession.protocol.registerStringProtocol(...args),
registerBufferProtocol: (...args) => session.defaultSession.protocol.registerBufferProtocol(...args),
registerStreamProtocol: (...args) => session.defaultSession.protocol.registerStreamProtocol(...args),
registerFileProtocol: (...args) => session.defaultSession.protocol.registerFileProtocol(...args),
registerHttpProtocol: (...args) => session.defaultSession.protocol.registerHttpProtocol(...args),
registerProtocol: (...args) => session.defaultSession.protocol.registerProtocol(...args),
unregisterProtocol: (...args) => session.defaultSession.protocol.unregisterProtocol(...args),
isProtocolRegistered: (...args) => session.defaultSession.protocol.isProtocolRegistered(...args),
interceptStringProtocol: (...args) => session.defaultSession.protocol.interceptStringProtocol(...args),
interceptBufferProtocol: (...args) => session.defaultSession.protocol.interceptBufferProtocol(...args),
interceptStreamProtocol: (...args) => session.defaultSession.protocol.interceptStreamProtocol(...args),
interceptFileProtocol: (...args) => session.defaultSession.protocol.interceptFileProtocol(...args),
interceptHttpProtocol: (...args) => session.defaultSession.protocol.interceptHttpProtocol(...args),
interceptProtocol: (...args) => session.defaultSession.protocol.interceptProtocol(...args),
uninterceptProtocol: (...args) => session.defaultSession.protocol.uninterceptProtocol(...args),
isProtocolIntercepted: (...args) => session.defaultSession.protocol.isProtocolIntercepted(...args),
handle: (...args) => session.defaultSession.protocol.handle(...args),
unhandle: (...args) => session.defaultSession.protocol.unhandle(...args),
isProtocolHandled: (...args) => session.defaultSession.protocol.isProtocolHandled(...args)
} as typeof Electron.protocol;
export default protocol;
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,553 |
[Bug]: TypeError: undefined is not iterable
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When using the `protocol.handle` api and returning an empty object as a result, a helpful error message is displayed to the user.
### Actual Behavior
When using the `protocol.handle` api and returning an empty object as a result, the output is as follows:
```
TypeError: undefined is not iterable
at Function.fromEntries (<anonymous>)
at AsyncFunction.<anonymous> (node:electron/js2c/browser_init:2:57533)
```
This error is kind of hard to debug since the error message doesn't point in the right direction and the stack trace doesn't include any user defined function.
### Testcase Gist URL
https://gist.github.com/SimonSiefke/cf52088c800054d6a63b16633db4d540
### Additional Information
I believe the error is happening here:
https://github.com/electron/electron/blob/d818f35ad4ec44c83f21dd3656ef1072e196c34f/lib/browser/api/protocol.ts#L76C5-L91
One idea could be to check if res is actually of type Response and throw a user-friendly error if not:
```js
if (!res || typeof res !== 'object' || !(res instanceof Response)) { // check if res is valid
throw new Error(`protocol response must be of type Response`) // throw user friendly error
}
```
|
https://github.com/electron/electron/issues/38553
|
https://github.com/electron/electron/pull/38587
|
5931f69f183bfcd57c9dc7dffe8560ac9163bb45
|
86824c070e31a674f6f523b52426549efc61aa6d
| 2023-06-01T15:22:07Z |
c++
| 2023-06-07T07:29:04Z |
spec/api-protocol-spec.ts
|
import { expect } from 'chai';
import { v4 } from 'uuid';
import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main';
import * as ChildProcess from 'child_process';
import * as path from 'path';
import * as url from 'url';
import * as http from 'http';
import * as fs from 'fs';
import * as qs from 'querystring';
import * as stream from 'stream';
import { EventEmitter, once } from 'events';
import { closeAllWindows, closeWindow } from './lib/window-helpers';
import { WebmGenerator } from './lib/video-helpers';
import { listen, defer, ifit } from './lib/spec-helpers';
import { setTimeout } from 'timers/promises';
const fixturesPath = path.resolve(__dirname, 'fixtures');
const registerStringProtocol = protocol.registerStringProtocol;
const registerBufferProtocol = protocol.registerBufferProtocol;
const registerFileProtocol = protocol.registerFileProtocol;
const registerStreamProtocol = protocol.registerStreamProtocol;
const interceptStringProtocol = protocol.interceptStringProtocol;
const interceptBufferProtocol = protocol.interceptBufferProtocol;
const interceptHttpProtocol = protocol.interceptHttpProtocol;
const interceptStreamProtocol = protocol.interceptStreamProtocol;
const unregisterProtocol = protocol.unregisterProtocol;
const uninterceptProtocol = protocol.uninterceptProtocol;
const text = 'valar morghulis';
const protocolName = 'no-cors';
const postData = {
name: 'post test',
type: 'string'
};
function getStream (chunkSize = text.length, data: Buffer | string = text) {
// allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks
// the stream isn't done when the readable half ends.
const body = new stream.PassThrough({ allowHalfOpen: false });
async function sendChunks () {
await setTimeout(0); // the stream protocol API breaks if you send data immediately.
let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer
for (;;) {
body.push(buf.slice(0, chunkSize));
buf = buf.slice(chunkSize);
if (!buf.length) {
break;
}
// emulate some network delay
await setTimeout(10);
}
body.push(null);
}
sendChunks();
return body;
}
function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> {
return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>;
}
// A promise that can be resolved externally.
function deferPromise (): Promise<any> & {resolve: Function, reject: Function} {
let promiseResolve: Function = null as unknown as Function;
let promiseReject: Function = null as unknown as Function;
const promise: any = new Promise((resolve, reject) => {
promiseResolve = resolve;
promiseReject = reject;
});
promise.resolve = promiseResolve;
promise.reject = promiseReject;
return promise;
}
describe('protocol module', () => {
let contents: WebContents;
// NB. sandbox: true is used because it makes navigations much (~8x) faster.
before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); });
after(() => contents.destroy());
async function ajax (url: string, options = {}) {
// Note that we need to do navigation every time after a protocol is
// registered or unregistered, otherwise the new protocol won't be
// recognized by current page when NetworkService is used.
await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`);
}
afterEach(() => {
protocol.unregisterProtocol(protocolName);
protocol.uninterceptProtocol('http');
});
describe('protocol.register(Any)Protocol', () => {
it('fails when scheme is already registered', () => {
expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true);
expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false);
});
it('does not crash when handler is called twice', async () => {
registerStringProtocol(protocolName, (request, callback) => {
try {
callback(text);
callback('');
} catch (error) {
// Ignore error
}
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sends error when callback is called with nothing', async () => {
registerBufferProtocol(protocolName, (req, cb: any) => cb());
await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected();
});
it('does not crash when callback is called in next tick', async () => {
registerStringProtocol(protocolName, (request, callback) => {
setImmediate(() => callback(text));
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('can redirect to the same scheme', async () => {
registerStringProtocol(protocolName, (request, callback) => {
if (request.url === `${protocolName}://fake-host/redirect`) {
callback({
statusCode: 302,
headers: {
Location: `${protocolName}://fake-host`
}
});
} else {
expect(request.url).to.equal(`${protocolName}://fake-host`);
callback('redirected');
}
});
const r = await ajax(`${protocolName}://fake-host/redirect`);
expect(r.data).to.equal('redirected');
});
});
describe('protocol.unregisterProtocol', () => {
it('returns false when scheme does not exist', () => {
expect(unregisterProtocol('not-exist')).to.equal(false);
});
});
for (const [registerStringProtocol, name] of [
[protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends string as response', async () => {
registerStringProtocol(protocolName, (request, callback) => callback(text));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sets Access-Control-Allow-Origin', async () => {
registerStringProtocol(protocolName, (request, callback) => callback(text));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sends object as response', async () => {
registerStringProtocol(protocolName, (request, callback) => {
callback({
data: text,
mimeType: 'text/html'
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('fails when sending object other than string', async () => {
const notAString = () => {};
registerStringProtocol(protocolName, (request, callback) => callback(notAString as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
});
}
for (const [registerBufferProtocol, name] of [
[protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
const buffer = Buffer.from(text);
it('sends Buffer as response', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sets Access-Control-Allow-Origin', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sends object as response', async () => {
registerBufferProtocol(protocolName, (request, callback) => {
callback({
data: buffer,
mimeType: 'text/html'
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
if (name !== 'protocol.registerProtocol') {
it('fails when sending string', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(text as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
}
});
}
for (const [registerFileProtocol, name] of [
[protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1');
const fileContent = fs.readFileSync(filePath);
const normalPath = path.join(fixturesPath, 'pages', 'a.html');
const normalContent = fs.readFileSync(normalPath);
afterEach(closeAllWindows);
if (name === 'protocol.registerFileProtocol') {
it('sends file path as response', async () => {
registerFileProtocol(protocolName, (request, callback) => callback(filePath));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
});
}
it('sets Access-Control-Allow-Origin', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sets custom headers', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({
path: filePath,
headers: { 'X-Great-Header': 'sogreat' }
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
expect(r.headers).to.have.property('x-great-header', 'sogreat');
});
it('can load iframes with custom protocols', (done) => {
registerFileProtocol('custom', (request, callback) => {
const filename = request.url.substring(9);
const p = path.join(__dirname, 'fixtures', 'pages', filename);
callback({ path: p });
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html'));
ipcMain.once('loaded-iframe-custom-protocol', () => done());
});
it('sends object as response', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
});
it('can send normal file', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(normalContent));
});
it('fails when sending unexist-file', async () => {
const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist');
registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath }));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('fails when sending unsupported content', async () => {
registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
});
}
for (const [registerHttpProtocol, name] of [
[protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends url as response', async () => {
const server = http.createServer((req, res) => {
expect(req.headers.accept).to.not.equal('');
res.end(text);
server.close();
});
const { url } = await listen(server);
registerHttpProtocol(protocolName, (request, callback) => callback({ url }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('fails when sending invalid url', async () => {
registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' }));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('fails when sending unsupported content', async () => {
registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('works when target URL redirects', async () => {
const server = http.createServer((req, res) => {
if (req.url === '/serverRedirect') {
res.statusCode = 301;
res.setHeader('Location', `http://${req.rawHeaders[1]}`);
res.end();
} else {
res.end(text);
}
});
after(() => server.close());
const { port } = await listen(server);
const url = `${protocolName}://fake-host`;
const redirectURL = `http://127.0.0.1:${port}/serverRedirect`;
registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL }));
const r = await ajax(url);
expect(r.data).to.equal(text);
});
it('can access request headers', (done) => {
protocol.registerHttpProtocol(protocolName, (request) => {
try {
expect(request).to.have.property('headers');
done();
} catch (e) {
done(e);
}
});
ajax(protocolName + '://fake-host').catch(() => {});
});
});
}
for (const [registerStreamProtocol, name] of [
[protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends Stream as response', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback(getStream()));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sends object as response', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.status).to.equal(200);
});
it('sends custom response headers', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({
data: getStream(3),
headers: {
'x-electron': ['a', 'b']
}
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.status).to.equal(200);
expect(r.headers).to.have.property('x-electron', 'a, b');
});
it('sends custom status code', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({
statusCode: 204,
data: null as any
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.be.empty('data');
expect(r.status).to.equal(204);
});
it('receives request headers', async () => {
registerStreamProtocol(protocolName, (request, callback) => {
callback({
headers: {
'content-type': 'application/json'
},
data: getStream(5, JSON.stringify(Object.assign({}, request.headers)))
});
});
const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } });
expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes');
});
it('returns response multiple response headers with the same name', async () => {
registerStreamProtocol(protocolName, (request, callback) => {
callback({
headers: {
header1: ['value1', 'value2'],
header2: 'value3'
},
data: getStream()
});
});
const r = await ajax(protocolName + '://fake-host');
// SUBTLE: when the response headers have multiple values it
// separates values by ", ". When the response headers are incorrectly
// converting an array to a string it separates values by ",".
expect(r.headers).to.have.property('header1', 'value1, value2');
expect(r.headers).to.have.property('header2', 'value3');
});
it('can handle large responses', async () => {
const data = Buffer.alloc(128 * 1024);
registerStreamProtocol(protocolName, (request, callback) => {
callback(getStream(data.length, data));
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.have.lengthOf(data.length);
});
it('can handle a stream completing while writing', async () => {
function dumbPassthrough () {
return new stream.Transform({
async transform (chunk, encoding, cb) {
cb(null, chunk);
}
});
}
registerStreamProtocol(protocolName, (request, callback) => {
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough())
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.have.lengthOf(1024 * 1024 * 2);
});
it('can handle next-tick scheduling during read calls', async () => {
const events = new EventEmitter();
function createStream () {
const buffers = [
Buffer.alloc(65536),
Buffer.alloc(65537),
Buffer.alloc(39156)
];
const e = new stream.Readable({ highWaterMark: 0 });
e.push(buffers.shift());
e._read = function () {
process.nextTick(() => this.push(buffers.shift() || null));
};
e.on('end', function () {
events.emit('end');
});
return e;
}
registerStreamProtocol(protocolName, (request, callback) => {
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: createStream()
});
});
const hasEndedPromise = once(events, 'end');
ajax(protocolName + '://fake-host').catch(() => {});
await hasEndedPromise;
});
it('destroys response streams when aborted before completion', async () => {
const events = new EventEmitter();
registerStreamProtocol(protocolName, (request, callback) => {
const responseStream = new stream.PassThrough();
responseStream.push('data\r\n');
responseStream.on('close', () => {
events.emit('close');
});
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: responseStream
});
events.emit('respond');
});
const hasRespondedPromise = once(events, 'respond');
const hasClosedPromise = once(events, 'close');
ajax(protocolName + '://fake-host').catch(() => {});
await hasRespondedPromise;
await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
await hasClosedPromise;
});
});
}
describe('protocol.isProtocolRegistered', () => {
it('returns false when scheme is not registered', () => {
const result = protocol.isProtocolRegistered('no-exist');
expect(result).to.be.false('no-exist: is handled');
});
it('returns true for custom protocol', () => {
registerStringProtocol(protocolName, (request, callback) => callback(''));
const result = protocol.isProtocolRegistered(protocolName);
expect(result).to.be.true('custom protocol is handled');
});
});
describe('protocol.isProtocolIntercepted', () => {
it('returns true for intercepted protocol', () => {
interceptStringProtocol('http', (request, callback) => callback(''));
const result = protocol.isProtocolIntercepted('http');
expect(result).to.be.true('intercepted protocol is handled');
});
});
describe('protocol.intercept(Any)Protocol', () => {
it('returns false when scheme is already intercepted', () => {
expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true);
expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false);
});
it('does not crash when handler is called twice', async () => {
interceptStringProtocol('http', (request, callback) => {
try {
callback(text);
callback('');
} catch (error) {
// Ignore error
}
});
const r = await ajax('http://fake-host');
expect(r.data).to.be.equal(text);
});
it('sends error when callback is called with nothing', async () => {
interceptStringProtocol('http', (request, callback: any) => callback());
await expect(ajax('http://fake-host')).to.be.eventually.rejected();
});
});
describe('protocol.interceptStringProtocol', () => {
it('can intercept http protocol', async () => {
interceptStringProtocol('http', (request, callback) => callback(text));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can set content-type', async () => {
interceptStringProtocol('http', (request, callback) => {
callback({
mimeType: 'application/json',
data: '{"value": 1}'
});
});
const r = await ajax('http://fake-host');
expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
});
it('can set content-type with charset', async () => {
interceptStringProtocol('http', (request, callback) => {
callback({
mimeType: 'application/json; charset=UTF-8',
data: '{"value": 1}'
});
});
const r = await ajax('http://fake-host');
expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
});
it('can receive post data', async () => {
interceptStringProtocol('http', (request, callback) => {
const uploadData = request.uploadData![0].bytes.toString();
callback({ data: uploadData });
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
});
describe('protocol.interceptBufferProtocol', () => {
it('can intercept http protocol', async () => {
interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text)));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can receive post data', async () => {
interceptBufferProtocol('http', (request, callback) => {
const uploadData = request.uploadData![0].bytes;
callback(uploadData);
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' });
});
});
describe('protocol.interceptHttpProtocol', () => {
// FIXME(zcbenz): This test was passing because the test itself was wrong,
// I don't know whether it ever passed before and we should take a look at
// it in future.
xit('can send POST request', async () => {
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
res.end(body);
});
server.close();
});
after(() => server.close());
const { url } = await listen(server);
interceptHttpProtocol('http', (request, callback) => {
const data: Electron.ProtocolResponse = {
url: url,
method: 'POST',
uploadData: {
contentType: 'application/x-www-form-urlencoded',
data: request.uploadData![0].bytes
},
session: undefined
};
callback(data);
});
const r = await ajax('http://fake-host', { type: 'POST', data: postData });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
it('can use custom session', async () => {
const customSession = session.fromPartition('custom-ses', { cache: false });
customSession.webRequest.onBeforeRequest((details, callback) => {
expect(details.url).to.equal('http://fake-host/');
callback({ cancel: true });
});
after(() => customSession.webRequest.onBeforeRequest(null));
interceptHttpProtocol('http', (request, callback) => {
callback({
url: request.url,
session: customSession
});
});
await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error);
});
it('can access request headers', (done) => {
protocol.interceptHttpProtocol('http', (request) => {
try {
expect(request).to.have.property('headers');
done();
} catch (e) {
done(e);
}
});
ajax('http://fake-host').catch(() => {});
});
});
describe('protocol.interceptStreamProtocol', () => {
it('can intercept http protocol', async () => {
interceptStreamProtocol('http', (request, callback) => callback(getStream()));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can receive post data', async () => {
interceptStreamProtocol('http', (request, callback) => {
callback(getStream(3, request.uploadData![0].bytes.toString()));
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
it('can execute redirects', async () => {
interceptStreamProtocol('http', (request, callback) => {
if (request.url.indexOf('http://fake-host') === 0) {
setTimeout(300).then(() => {
callback({
data: '',
statusCode: 302,
headers: {
Location: 'http://fake-redirect'
}
});
});
} else {
expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
callback(getStream(1, 'redirect'));
}
});
const r = await ajax('http://fake-host');
expect(r.data).to.equal('redirect');
});
it('should discard post data after redirection', async () => {
interceptStreamProtocol('http', (request, callback) => {
if (request.url.indexOf('http://fake-host') === 0) {
setTimeout(300).then(() => {
callback({
statusCode: 302,
headers: {
Location: 'http://fake-redirect'
}
});
});
} else {
expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
callback(getStream(3, request.method));
}
});
const r = await ajax('http://fake-host', { type: 'POST', data: postData });
expect(r.data).to.equal('GET');
});
});
describe('protocol.uninterceptProtocol', () => {
it('returns false when scheme does not exist', () => {
expect(uninterceptProtocol('not-exist')).to.equal(false);
});
it('returns false when scheme is not intercepted', () => {
expect(uninterceptProtocol('http')).to.equal(false);
});
});
describe('protocol.registerSchemeAsPrivileged', () => {
it('does not crash on exit', async () => {
const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js');
const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]);
let stdout = '';
let stderr = '';
appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; });
appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; });
const [code] = await once(appProcess, 'exit');
if (code !== 0) {
console.log('Exit code : ', code);
console.log('stdout : ', stdout);
console.log('stderr : ', stderr);
}
expect(code).to.equal(0);
expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
});
});
describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => {
protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => {
if (request.url.endsWith('.js')) {
cb({
mimeType: 'text/javascript',
charset: 'utf-8',
data: 'console.log("Loaded")'
});
} else {
cb({
mimeType: 'text/html',
charset: 'utf-8',
data: '<!DOCTYPE html>'
});
}
});
after(() => protocol.unregisterProtocol(serviceWorkerScheme));
it('should fail when registering invalid service worker', async () => {
await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected();
});
it('should be able to register service worker for custom scheme', async () => {
await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`);
});
});
describe('protocol.registerSchemesAsPrivileged standard', () => {
const origin = `${standardScheme}://fake-host`;
const imageURL = `${origin}/test.png`;
const filePath = path.join(fixturesPath, 'pages', 'b.html');
const fileContent = '<img src="/test.png" />';
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeWindow(w);
unregisterProtocol(standardScheme);
w = null as unknown as BrowserWindow;
});
it('resolves relative resources', async () => {
registerFileProtocol(standardScheme, (request, callback) => {
if (request.url === imageURL) {
callback('');
} else {
callback(filePath);
}
});
await w.loadURL(origin);
});
it('resolves absolute resources', async () => {
registerStringProtocol(standardScheme, (request, callback) => {
if (request.url === imageURL) {
callback('');
} else {
callback({
data: fileContent,
mimeType: 'text/html'
});
}
});
await w.loadURL(origin);
});
it('can have fetch working in it', async () => {
const requestReceived = deferPromise();
const server = http.createServer((req, res) => {
res.end();
server.close();
requestReceived.resolve();
});
const { url } = await listen(server);
const content = `<script>fetch(${JSON.stringify(url)})</script>`;
registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }));
await w.loadURL(origin);
await requestReceived;
});
it('can access files through the FileSystem API', (done) => {
const filePath = path.join(fixturesPath, 'pages', 'filesystem.html');
protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
w.loadURL(origin);
ipcMain.once('file-system-error', (event, err) => done(err));
ipcMain.once('file-system-write-end', () => done());
});
it('registers secure, when {secure: true}', (done) => {
const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html');
ipcMain.once('success', () => done());
ipcMain.once('failure', (event, err) => done(err));
protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
w.loadURL(origin);
});
});
describe('protocol.registerSchemesAsPrivileged cors-fetch', function () {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) {
protocol.unregisterProtocol(scheme);
}
});
it('supports fetch api by default', async () => {
const url = `file://${fixturesPath}/assets/logo.png`;
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`);
expect(ok).to.be.true('response ok');
});
it('allows CORS requests by default', async () => {
await allowsCORSRequests('cors', 200, new RegExp(''), () => {
const { ipcRenderer } = require('electron');
fetch('cors://myhost').then(function (response) {
ipcRenderer.send('response', response.status);
}).catch(function () {
ipcRenderer.send('response', 'failed');
});
});
});
// DISABLED-FIXME: Figure out why this test is failing
it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
const { ipcRenderer } = require('electron');
Promise.all([
new Promise(resolve => {
const req = new XMLHttpRequest();
req.onload = () => resolve('loaded xhr');
req.onerror = () => resolve('failed xhr');
req.open('GET', 'no-cors://myhost');
req.send();
}),
fetch('no-cors://myhost')
.then(() => 'loaded fetch')
.catch(() => 'failed fetch')
]).then(([xhr, fetch]) => {
ipcRenderer.send('response', [xhr, fetch]);
});
});
});
it('allows CORS, but disallows fetch requests, when specified', async () => {
await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
const { ipcRenderer } = require('electron');
Promise.all([
new Promise(resolve => {
const req = new XMLHttpRequest();
req.onload = () => resolve('loaded xhr');
req.onerror = () => resolve('failed xhr');
req.open('GET', 'no-fetch://myhost');
req.send();
}),
fetch('no-fetch://myhost')
.then(() => 'loaded fetch')
.catch(() => 'failed fetch')
]).then(([xhr, fetch]) => {
ipcRenderer.send('response', [xhr, fetch]);
});
});
});
async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
registerStringProtocol(standardScheme, (request, callback) => {
callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' });
});
registerStringProtocol(corsScheme, (request, callback) => {
callback('');
});
const newContents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
const consoleMessages: string[] = [];
newContents.on('console-message', (e, level, message) => consoleMessages.push(message));
try {
newContents.loadURL(standardScheme + '://fake-host');
const [, response] = await once(ipcMain, 'response');
expect(response).to.deep.equal(expected);
expect(consoleMessages.join('\n')).to.match(expectedConsole);
} finally {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout().then(() => {
newContents.destroy();
});
}
}
});
describe('protocol.registerSchemesAsPrivileged stream', async function () {
const pagePath = path.join(fixturesPath, 'pages', 'video.html');
const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp');
const videoPath = path.join(fixturesPath, 'video.webm');
let w: BrowserWindow;
before(async () => {
// generate test video
const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64');
const imageDataUrl = `data:image/webp;base64,${imageBase64}`;
const encoder = new WebmGenerator(15);
for (let i = 0; i < 30; i++) {
encoder.add(imageDataUrl);
}
await new Promise((resolve, reject) => {
encoder.compile((output:Uint8Array) => {
fs.promises.writeFile(videoPath, output).then(resolve, reject);
});
});
});
after(async () => {
await fs.promises.unlink(videoPath);
});
beforeEach(async function () {
w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
this.skip();
}
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
await protocol.unregisterProtocol(standardScheme);
await protocol.unregisterProtocol('stream');
});
it('successfully plays videos when content is buffered (stream: false)', async () => {
await streamsResponses(standardScheme, 'play');
});
it('successfully plays videos when streaming content (stream: true)', async () => {
await streamsResponses('stream', 'play');
});
async function streamsResponses (testingScheme: string, expected: any) {
const protocolHandler = (request: any, callback: Function) => {
if (request.url.includes('/video.webm')) {
const stat = fs.statSync(videoPath);
const fileSize = stat.size;
const range = request.headers.Range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = (end - start) + 1;
const headers = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': String(chunksize),
'Content-Type': 'video/webm'
};
callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) });
} else {
callback({
statusCode: 200,
headers: {
'Content-Length': String(fileSize),
'Content-Type': 'video/webm'
},
data: fs.createReadStream(videoPath)
});
}
} else {
callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 });
}
};
await registerStreamProtocol(standardScheme, protocolHandler);
await registerStreamProtocol('stream', protocolHandler);
const newContents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
try {
newContents.loadURL(testingScheme + '://fake-host');
const [, response] = await once(ipcMain, 'result');
expect(response).to.deep.equal(expected);
} finally {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout().then(() => {
newContents.destroy();
});
}
}
});
describe('handle', () => {
afterEach(closeAllWindows);
it('receives requests to a custom scheme', async () => {
protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.status).to.equal(200);
});
it('can be unhandled', async () => {
protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
defer(() => {
try {
// In case of failure, make sure we unhandle. But we should succeed
// :)
protocol.unhandle('test-scheme');
} catch (_ignored) { /* ignore */ }
});
const resp1 = await net.fetch('test-scheme://foo');
expect(resp1.status).to.equal(200);
protocol.unhandle('test-scheme');
await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/);
});
it('receives requests to an existing scheme', async () => {
protocol.handle('https', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('https'); });
const body = await net.fetch('https://foo').then(r => r.text());
expect(body).to.equal('hello https://foo/');
});
it('receives requests to an existing scheme when navigating', async () => {
protocol.handle('https', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('https'); });
const w = new BrowserWindow({ show: false });
await w.loadURL('https://localhost');
expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/');
});
it('can send buffer body', async () => {
protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url)));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal('hello test-scheme://foo');
});
it('can send stream body', async () => {
protocol.handle('test-scheme', () => new Response(getWebStream()));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal(text);
});
it('accepts urls with no hostname in non-standard schemes', async () => {
protocol.handle('test-scheme', (req) => new Response(req.url));
defer(() => { protocol.unhandle('test-scheme'); });
{
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal('test-scheme://foo');
}
{
const body = await net.fetch('test-scheme:///foo').then(r => r.text());
expect(body).to.equal('test-scheme:///foo');
}
{
const body = await net.fetch('test-scheme://').then(r => r.text());
expect(body).to.equal('test-scheme://');
}
});
it('accepts urls with a port-like component in non-standard schemes', async () => {
protocol.handle('test-scheme', (req) => new Response(req.url));
defer(() => { protocol.unhandle('test-scheme'); });
{
const body = await net.fetch('test-scheme://foo:30').then(r => r.text());
expect(body).to.equal('test-scheme://foo:30');
}
});
it('normalizes urls in standard schemes', async () => {
// NB. 'app' is registered as a standard scheme in test setup.
protocol.handle('app', (req) => new Response(req.url));
defer(() => { protocol.unhandle('app'); });
{
const body = await net.fetch('app://foo').then(r => r.text());
expect(body).to.equal('app://foo/');
}
{
const body = await net.fetch('app:///foo').then(r => r.text());
expect(body).to.equal('app://foo/');
}
// NB. 'app' is registered with the default scheme type of 'host'.
{
const body = await net.fetch('app://foo:1234').then(r => r.text());
expect(body).to.equal('app://foo/');
}
await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL');
});
it('fails on URLs with a username', async () => {
// NB. 'app' is registered as a standard scheme in test setup.
protocol.handle('http', (req) => new Response(req.url));
defer(() => { protocol.unhandle('http'); });
await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/);
});
it('normalizes http urls', async () => {
protocol.handle('http', (req) => new Response(req.url));
defer(() => { protocol.unhandle('http'); });
{
const body = await net.fetch('http://foo').then(r => r.text());
expect(body).to.equal('http://foo/');
}
});
it('can send errors', async () => {
protocol.handle('test-scheme', () => Response.error());
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED');
});
it('handles a synchronous error in the handler', async () => {
protocol.handle('test-scheme', () => { throw new Error('test'); });
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('handles an asynchronous error in the handler', async () => {
protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise')));
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('correctly sets statusCode', async () => {
protocol.handle('test-scheme', () => new Response(null, { status: 201 }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.status).to.equal(201);
});
it('correctly sets content-type and charset', async () => {
protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset');
});
it('can forward to http', async () => {
const server = http.createServer((req, res) => {
res.end(text);
});
defer(() => { server.close(); });
const { url } = await listen(server);
protocol.handle('test-scheme', () => net.fetch(url));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal(text);
});
it('can forward an http request with headers', async () => {
const server = http.createServer((req, res) => {
res.setHeader('foo', 'bar');
res.end(text);
});
defer(() => { server.close(); });
const { url } = await listen(server);
protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.headers.get('foo')).to.equal('bar');
});
it('can forward to file', async () => {
protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString()));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body.trimEnd()).to.equal('hello world');
});
it('can receive simple request body', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo', {
method: 'POST',
body: 'foobar'
}).then(r => r.text());
expect(body).to.equal('foobar');
});
it('can receive stream request body', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo', {
method: 'POST',
body: getWebStream(),
duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157
} as any).then(r => r.text());
expect(body).to.equal(text);
});
it('can receive multi-part postData from loadURL', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] });
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab');
});
it('can receive file postData from loadURL', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] });
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n');
});
it('can receive file postData from a form', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>');
const { debugger: dbg } = contents;
dbg.attach();
const { root } = await dbg.sendCommand('DOM.getDocument');
const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' });
await dbg.sendCommand('DOM.setFileInputFiles', {
nodeId: fileInputNodeId,
files: [
path.join(fixturesPath, 'hello.txt')
]
});
const navigated = once(contents, 'did-finish-load');
await contents.executeJavaScript('document.querySelector("form").submit()');
await navigated;
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/);
});
it('can receive streaming fetch upload', async () => {
protocol.handle('no-cors', (req) => new Response(req.body));
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('hello world');
controller.close();
},
}).pipeThrough(new TextEncoderStream());
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
`);
expect(fetchBodyResult).to.equal('hello world');
});
it('can receive streaming fetch upload when a webRequest handler is present', async () => {
session.defaultSession.webRequest.onBeforeRequest((details, cb) => {
console.log('webRequest', details.url, details.method);
cb({});
});
defer(() => {
session.defaultSession.webRequest.onBeforeRequest(null);
});
protocol.handle('no-cors', (req) => {
console.log('handle', req.url, req.method);
return new Response(req.body);
});
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('hello world');
controller.close();
},
}).pipeThrough(new TextEncoderStream());
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
`);
expect(fetchBodyResult).to.equal('hello world');
});
it('can receive an error from streaming fetch upload', async () => {
protocol.handle('no-cors', (req) => new Response(req.body));
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.error('test')
},
});
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
`);
expect(fetchBodyResult).to.be.an.instanceOf(Error);
});
it('gets an error from streaming fetch upload when the renderer dies', async () => {
let gotRequest: Function;
const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; });
protocol.handle('no-cors', (req) => {
if (/fetch/.test(req.url)) gotRequest(req);
return new Response();
});
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
window.controller = controller // no GC
},
});
fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
`);
const req = await receivedRequest;
contents.destroy();
// Undo .destroy() for the next test
contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED');
});
it('can bypass intercepeted protocol handlers', async () => {
protocol.handle('http', () => new Response('custom'));
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
res.end('default');
});
defer(() => server.close());
const { url } = await listen(server);
expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default');
});
it('bypassing custom protocol handlers also bypasses new protocols', async () => {
protocol.handle('app', () => new Response('custom'));
defer(() => { protocol.unhandle('app'); });
await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME');
});
it('can forward to the original handler', async () => {
protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true }));
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
res.end('hello');
server.close();
});
const { url } = await listen(server);
await contents.loadURL(url);
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello');
});
it('supports sniffing mime type', async () => {
protocol.handle('http', async (req) => {
return net.fetch(req, { bypassCustomProtocolHandlers: true });
});
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); }
});
const { url } = await listen(server);
defer(() => server.close());
{
await contents.loadURL(url);
const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
expect(doc).to.match(/white-space: pre-wrap/);
}
{
await contents.loadURL(url + '?html');
const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
expect(doc).to.equal('<html><head></head><body>hi</body></html>');
}
});
// TODO(nornagon): this test doesn't pass on Linux currently, investigate.
ifit(process.platform !== 'linux')('is fast', async () => {
// 128 MB of spaces.
const chunk = new Uint8Array(128 * 1024 * 1024);
chunk.fill(' '.charCodeAt(0));
const server = http.createServer((req, res) => {
// The sniffed mime type for the space-filled chunk will be
// text/plain, which chews up all its performance in the renderer
// trying to wrap lines. Setting content-type to text/html measures
// something closer to just the raw cost of getting the bytes over
// the wire.
res.setHeader('content-type', 'text/html');
res.end(chunk);
});
defer(() => server.close());
const { url } = await listen(server);
const rawTime = await (async () => {
await contents.loadURL(url); // warm
const begin = Date.now();
await contents.loadURL(url);
const end = Date.now();
return end - begin;
})();
// Fetching through an intercepted handler should not be too much slower
// than it would be if the protocol hadn't been intercepted.
protocol.handle('http', async (req) => {
return net.fetch(req, { bypassCustomProtocolHandlers: true });
});
defer(() => { protocol.unhandle('http'); });
const interceptedTime = await (async () => {
const begin = Date.now();
await contents.loadURL(url);
const end = Date.now();
return end - begin;
})();
expect(interceptedTime).to.be.lessThan(rawTime * 1.5);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,553 |
[Bug]: TypeError: undefined is not iterable
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When using the `protocol.handle` api and returning an empty object as a result, a helpful error message is displayed to the user.
### Actual Behavior
When using the `protocol.handle` api and returning an empty object as a result, the output is as follows:
```
TypeError: undefined is not iterable
at Function.fromEntries (<anonymous>)
at AsyncFunction.<anonymous> (node:electron/js2c/browser_init:2:57533)
```
This error is kind of hard to debug since the error message doesn't point in the right direction and the stack trace doesn't include any user defined function.
### Testcase Gist URL
https://gist.github.com/SimonSiefke/cf52088c800054d6a63b16633db4d540
### Additional Information
I believe the error is happening here:
https://github.com/electron/electron/blob/d818f35ad4ec44c83f21dd3656ef1072e196c34f/lib/browser/api/protocol.ts#L76C5-L91
One idea could be to check if res is actually of type Response and throw a user-friendly error if not:
```js
if (!res || typeof res !== 'object' || !(res instanceof Response)) { // check if res is valid
throw new Error(`protocol response must be of type Response`) // throw user friendly error
}
```
|
https://github.com/electron/electron/issues/38553
|
https://github.com/electron/electron/pull/38587
|
5931f69f183bfcd57c9dc7dffe8560ac9163bb45
|
86824c070e31a674f6f523b52426549efc61aa6d
| 2023-06-01T15:22:07Z |
c++
| 2023-06-07T07:29:04Z |
lib/browser/api/protocol.ts
|
import { ProtocolRequest, session } from 'electron/main';
import { createReadStream } from 'fs';
import { Readable } from 'stream';
import { ReadableStream } from 'stream/web';
// Global protocol APIs.
const { registerSchemesAsPrivileged, getStandardSchemes, Protocol } = process._linkedBinding('electron_browser_protocol');
const ERR_FAILED = -2;
const ERR_UNEXPECTED = -9;
const isBuiltInScheme = (scheme: string) => scheme === 'http' || scheme === 'https';
function makeStreamFromPipe (pipe: any): ReadableStream {
const buf = new Uint8Array(1024 * 1024 /* 1 MB */);
return new ReadableStream({
async pull (controller) {
try {
const rv = await pipe.read(buf);
if (rv > 0) {
controller.enqueue(buf.subarray(0, rv));
} else {
controller.close();
}
} catch (e) {
controller.error(e);
}
}
});
}
function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] {
if (!uploadData) return null;
// Optimization: skip creating a stream if the request is just a single buffer.
if (uploadData.length === 1 && (uploadData[0] as any).type === 'rawData') return uploadData[0].bytes;
const chunks = [...uploadData] as any[]; // TODO: types are wrong
let current: ReadableStreamDefaultReader | null = null;
return new ReadableStream({
pull (controller) {
if (current) {
current.read().then(({ done, value }) => {
controller.enqueue(value);
if (done) current = null;
}, (err) => {
controller.error(err);
});
} else {
if (!chunks.length) { return controller.close(); }
const chunk = chunks.shift()!;
if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') {
current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader();
this.pull!(controller);
} else if (chunk.type === 'stream') {
current = makeStreamFromPipe(chunk.body).getReader();
this.pull!(controller);
}
}
}
}) as RequestInit['body'];
}
Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, handler: (req: Request) => Response | Promise<Response>) {
const register = isBuiltInScheme(scheme) ? this.interceptProtocol : this.registerProtocol;
const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => {
try {
const body = convertToRequestBody(preq.uploadData);
const req = new Request(preq.url, {
headers: preq.headers,
method: preq.method,
referrer: preq.referrer,
body,
duplex: body instanceof ReadableStream ? 'half' : undefined
} as any);
const res = await handler(req);
if (!res || typeof res !== 'object') {
return cb({ error: ERR_UNEXPECTED });
}
if (res.type === 'error') { cb({ error: ERR_FAILED }); } else {
cb({
data: res.body ? Readable.fromWeb(res.body as ReadableStream<ArrayBufferView>) : null,
headers: Object.fromEntries(res.headers),
statusCode: res.status,
statusText: res.statusText,
mimeType: (res as any).__original_resp?._responseHead?.mimeType
});
}
} catch (e) {
console.error(e);
cb({ error: ERR_UNEXPECTED });
}
});
if (!success) throw new Error(`Failed to register protocol: ${scheme}`);
};
Protocol.prototype.unhandle = function (this: Electron.Protocol, scheme: string) {
const unregister = isBuiltInScheme(scheme) ? this.uninterceptProtocol : this.unregisterProtocol;
if (!unregister.call(this, scheme)) { throw new Error(`Failed to unhandle protocol: ${scheme}`); }
};
Protocol.prototype.isProtocolHandled = function (this: Electron.Protocol, scheme: string) {
const isRegistered = isBuiltInScheme(scheme) ? this.isProtocolIntercepted : this.isProtocolRegistered;
return isRegistered.call(this, scheme);
};
const protocol = {
registerSchemesAsPrivileged,
getStandardSchemes,
registerStringProtocol: (...args) => session.defaultSession.protocol.registerStringProtocol(...args),
registerBufferProtocol: (...args) => session.defaultSession.protocol.registerBufferProtocol(...args),
registerStreamProtocol: (...args) => session.defaultSession.protocol.registerStreamProtocol(...args),
registerFileProtocol: (...args) => session.defaultSession.protocol.registerFileProtocol(...args),
registerHttpProtocol: (...args) => session.defaultSession.protocol.registerHttpProtocol(...args),
registerProtocol: (...args) => session.defaultSession.protocol.registerProtocol(...args),
unregisterProtocol: (...args) => session.defaultSession.protocol.unregisterProtocol(...args),
isProtocolRegistered: (...args) => session.defaultSession.protocol.isProtocolRegistered(...args),
interceptStringProtocol: (...args) => session.defaultSession.protocol.interceptStringProtocol(...args),
interceptBufferProtocol: (...args) => session.defaultSession.protocol.interceptBufferProtocol(...args),
interceptStreamProtocol: (...args) => session.defaultSession.protocol.interceptStreamProtocol(...args),
interceptFileProtocol: (...args) => session.defaultSession.protocol.interceptFileProtocol(...args),
interceptHttpProtocol: (...args) => session.defaultSession.protocol.interceptHttpProtocol(...args),
interceptProtocol: (...args) => session.defaultSession.protocol.interceptProtocol(...args),
uninterceptProtocol: (...args) => session.defaultSession.protocol.uninterceptProtocol(...args),
isProtocolIntercepted: (...args) => session.defaultSession.protocol.isProtocolIntercepted(...args),
handle: (...args) => session.defaultSession.protocol.handle(...args),
unhandle: (...args) => session.defaultSession.protocol.unhandle(...args),
isProtocolHandled: (...args) => session.defaultSession.protocol.isProtocolHandled(...args)
} as typeof Electron.protocol;
export default protocol;
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,553 |
[Bug]: TypeError: undefined is not iterable
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
Ubuntu
### Operating System Version
Ubuntu 23.04
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
When using the `protocol.handle` api and returning an empty object as a result, a helpful error message is displayed to the user.
### Actual Behavior
When using the `protocol.handle` api and returning an empty object as a result, the output is as follows:
```
TypeError: undefined is not iterable
at Function.fromEntries (<anonymous>)
at AsyncFunction.<anonymous> (node:electron/js2c/browser_init:2:57533)
```
This error is kind of hard to debug since the error message doesn't point in the right direction and the stack trace doesn't include any user defined function.
### Testcase Gist URL
https://gist.github.com/SimonSiefke/cf52088c800054d6a63b16633db4d540
### Additional Information
I believe the error is happening here:
https://github.com/electron/electron/blob/d818f35ad4ec44c83f21dd3656ef1072e196c34f/lib/browser/api/protocol.ts#L76C5-L91
One idea could be to check if res is actually of type Response and throw a user-friendly error if not:
```js
if (!res || typeof res !== 'object' || !(res instanceof Response)) { // check if res is valid
throw new Error(`protocol response must be of type Response`) // throw user friendly error
}
```
|
https://github.com/electron/electron/issues/38553
|
https://github.com/electron/electron/pull/38587
|
5931f69f183bfcd57c9dc7dffe8560ac9163bb45
|
86824c070e31a674f6f523b52426549efc61aa6d
| 2023-06-01T15:22:07Z |
c++
| 2023-06-07T07:29:04Z |
spec/api-protocol-spec.ts
|
import { expect } from 'chai';
import { v4 } from 'uuid';
import { protocol, webContents, WebContents, session, BrowserWindow, ipcMain, net } from 'electron/main';
import * as ChildProcess from 'child_process';
import * as path from 'path';
import * as url from 'url';
import * as http from 'http';
import * as fs from 'fs';
import * as qs from 'querystring';
import * as stream from 'stream';
import { EventEmitter, once } from 'events';
import { closeAllWindows, closeWindow } from './lib/window-helpers';
import { WebmGenerator } from './lib/video-helpers';
import { listen, defer, ifit } from './lib/spec-helpers';
import { setTimeout } from 'timers/promises';
const fixturesPath = path.resolve(__dirname, 'fixtures');
const registerStringProtocol = protocol.registerStringProtocol;
const registerBufferProtocol = protocol.registerBufferProtocol;
const registerFileProtocol = protocol.registerFileProtocol;
const registerStreamProtocol = protocol.registerStreamProtocol;
const interceptStringProtocol = protocol.interceptStringProtocol;
const interceptBufferProtocol = protocol.interceptBufferProtocol;
const interceptHttpProtocol = protocol.interceptHttpProtocol;
const interceptStreamProtocol = protocol.interceptStreamProtocol;
const unregisterProtocol = protocol.unregisterProtocol;
const uninterceptProtocol = protocol.uninterceptProtocol;
const text = 'valar morghulis';
const protocolName = 'no-cors';
const postData = {
name: 'post test',
type: 'string'
};
function getStream (chunkSize = text.length, data: Buffer | string = text) {
// allowHalfOpen required, otherwise Readable.toWeb gets confused and thinks
// the stream isn't done when the readable half ends.
const body = new stream.PassThrough({ allowHalfOpen: false });
async function sendChunks () {
await setTimeout(0); // the stream protocol API breaks if you send data immediately.
let buf = Buffer.from(data as any); // nodejs typings are wrong, Buffer.from can take a Buffer
for (;;) {
body.push(buf.slice(0, chunkSize));
buf = buf.slice(chunkSize);
if (!buf.length) {
break;
}
// emulate some network delay
await setTimeout(10);
}
body.push(null);
}
sendChunks();
return body;
}
function getWebStream (chunkSize = text.length, data: Buffer | string = text): ReadableStream<ArrayBufferView> {
return stream.Readable.toWeb(getStream(chunkSize, data)) as ReadableStream<ArrayBufferView>;
}
// A promise that can be resolved externally.
function deferPromise (): Promise<any> & {resolve: Function, reject: Function} {
let promiseResolve: Function = null as unknown as Function;
let promiseReject: Function = null as unknown as Function;
const promise: any = new Promise((resolve, reject) => {
promiseResolve = resolve;
promiseReject = reject;
});
promise.resolve = promiseResolve;
promise.reject = promiseReject;
return promise;
}
describe('protocol module', () => {
let contents: WebContents;
// NB. sandbox: true is used because it makes navigations much (~8x) faster.
before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); });
after(() => contents.destroy());
async function ajax (url: string, options = {}) {
// Note that we need to do navigation every time after a protocol is
// registered or unregistered, otherwise the new protocol won't be
// recognized by current page when NetworkService is used.
await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`);
}
afterEach(() => {
protocol.unregisterProtocol(protocolName);
protocol.uninterceptProtocol('http');
});
describe('protocol.register(Any)Protocol', () => {
it('fails when scheme is already registered', () => {
expect(registerStringProtocol(protocolName, (req, cb) => cb(''))).to.equal(true);
expect(registerBufferProtocol(protocolName, (req, cb) => cb(Buffer.from('')))).to.equal(false);
});
it('does not crash when handler is called twice', async () => {
registerStringProtocol(protocolName, (request, callback) => {
try {
callback(text);
callback('');
} catch (error) {
// Ignore error
}
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sends error when callback is called with nothing', async () => {
registerBufferProtocol(protocolName, (req, cb: any) => cb());
await expect(ajax(protocolName + '://fake-host')).to.eventually.be.rejected();
});
it('does not crash when callback is called in next tick', async () => {
registerStringProtocol(protocolName, (request, callback) => {
setImmediate(() => callback(text));
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('can redirect to the same scheme', async () => {
registerStringProtocol(protocolName, (request, callback) => {
if (request.url === `${protocolName}://fake-host/redirect`) {
callback({
statusCode: 302,
headers: {
Location: `${protocolName}://fake-host`
}
});
} else {
expect(request.url).to.equal(`${protocolName}://fake-host`);
callback('redirected');
}
});
const r = await ajax(`${protocolName}://fake-host/redirect`);
expect(r.data).to.equal('redirected');
});
});
describe('protocol.unregisterProtocol', () => {
it('returns false when scheme does not exist', () => {
expect(unregisterProtocol('not-exist')).to.equal(false);
});
});
for (const [registerStringProtocol, name] of [
[protocol.registerStringProtocol, 'protocol.registerStringProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerStringProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends string as response', async () => {
registerStringProtocol(protocolName, (request, callback) => callback(text));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sets Access-Control-Allow-Origin', async () => {
registerStringProtocol(protocolName, (request, callback) => callback(text));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sends object as response', async () => {
registerStringProtocol(protocolName, (request, callback) => {
callback({
data: text,
mimeType: 'text/html'
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('fails when sending object other than string', async () => {
const notAString = () => {};
registerStringProtocol(protocolName, (request, callback) => callback(notAString as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
});
}
for (const [registerBufferProtocol, name] of [
[protocol.registerBufferProtocol, 'protocol.registerBufferProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerBufferProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
const buffer = Buffer.from(text);
it('sends Buffer as response', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sets Access-Control-Allow-Origin', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(buffer));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sends object as response', async () => {
registerBufferProtocol(protocolName, (request, callback) => {
callback({
data: buffer,
mimeType: 'text/html'
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
if (name !== 'protocol.registerProtocol') {
it('fails when sending string', async () => {
registerBufferProtocol(protocolName, (request, callback) => callback(text as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
}
});
}
for (const [registerFileProtocol, name] of [
[protocol.registerFileProtocol, 'protocol.registerFileProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerFileProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
const filePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'file1');
const fileContent = fs.readFileSync(filePath);
const normalPath = path.join(fixturesPath, 'pages', 'a.html');
const normalContent = fs.readFileSync(normalPath);
afterEach(closeAllWindows);
if (name === 'protocol.registerFileProtocol') {
it('sends file path as response', async () => {
registerFileProtocol(protocolName, (request, callback) => callback(filePath));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
});
}
it('sets Access-Control-Allow-Origin', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
expect(r.headers).to.have.property('access-control-allow-origin', '*');
});
it('sets custom headers', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({
path: filePath,
headers: { 'X-Great-Header': 'sogreat' }
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
expect(r.headers).to.have.property('x-great-header', 'sogreat');
});
it('can load iframes with custom protocols', (done) => {
registerFileProtocol('custom', (request, callback) => {
const filename = request.url.substring(9);
const p = path.join(__dirname, 'fixtures', 'pages', filename);
callback({ path: p });
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html'));
ipcMain.once('loaded-iframe-custom-protocol', () => done());
});
it('sends object as response', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: filePath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(fileContent));
});
it('can send normal file', async () => {
registerFileProtocol(protocolName, (request, callback) => callback({ path: normalPath }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(String(normalContent));
});
it('fails when sending unexist-file', async () => {
const fakeFilePath = path.join(fixturesPath, 'test.asar', 'a.asar', 'not-exist');
registerFileProtocol(protocolName, (request, callback) => callback({ path: fakeFilePath }));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('fails when sending unsupported content', async () => {
registerFileProtocol(protocolName, (request, callback) => callback(new Date() as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
});
}
for (const [registerHttpProtocol, name] of [
[protocol.registerHttpProtocol, 'protocol.registerHttpProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerHttpProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends url as response', async () => {
const server = http.createServer((req, res) => {
expect(req.headers.accept).to.not.equal('');
res.end(text);
server.close();
});
const { url } = await listen(server);
registerHttpProtocol(protocolName, (request, callback) => callback({ url }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('fails when sending invalid url', async () => {
registerHttpProtocol(protocolName, (request, callback) => callback({ url: 'url' }));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('fails when sending unsupported content', async () => {
registerHttpProtocol(protocolName, (request, callback) => callback(new Date() as any));
await expect(ajax(protocolName + '://fake-host')).to.be.eventually.rejected();
});
it('works when target URL redirects', async () => {
const server = http.createServer((req, res) => {
if (req.url === '/serverRedirect') {
res.statusCode = 301;
res.setHeader('Location', `http://${req.rawHeaders[1]}`);
res.end();
} else {
res.end(text);
}
});
after(() => server.close());
const { port } = await listen(server);
const url = `${protocolName}://fake-host`;
const redirectURL = `http://127.0.0.1:${port}/serverRedirect`;
registerHttpProtocol(protocolName, (request, callback) => callback({ url: redirectURL }));
const r = await ajax(url);
expect(r.data).to.equal(text);
});
it('can access request headers', (done) => {
protocol.registerHttpProtocol(protocolName, (request) => {
try {
expect(request).to.have.property('headers');
done();
} catch (e) {
done(e);
}
});
ajax(protocolName + '://fake-host').catch(() => {});
});
});
}
for (const [registerStreamProtocol, name] of [
[protocol.registerStreamProtocol, 'protocol.registerStreamProtocol'] as const,
[(protocol as any).registerProtocol as typeof protocol.registerStreamProtocol, 'protocol.registerProtocol'] as const
]) {
describe(name, () => {
it('sends Stream as response', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback(getStream()));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
});
it('sends object as response', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({ data: getStream() }));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.status).to.equal(200);
});
it('sends custom response headers', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({
data: getStream(3),
headers: {
'x-electron': ['a', 'b']
}
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.equal(text);
expect(r.status).to.equal(200);
expect(r.headers).to.have.property('x-electron', 'a, b');
});
it('sends custom status code', async () => {
registerStreamProtocol(protocolName, (request, callback) => callback({
statusCode: 204,
data: null as any
}));
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.be.empty('data');
expect(r.status).to.equal(204);
});
it('receives request headers', async () => {
registerStreamProtocol(protocolName, (request, callback) => {
callback({
headers: {
'content-type': 'application/json'
},
data: getStream(5, JSON.stringify(Object.assign({}, request.headers)))
});
});
const r = await ajax(protocolName + '://fake-host', { headers: { 'x-return-headers': 'yes' } });
expect(JSON.parse(r.data)['x-return-headers']).to.equal('yes');
});
it('returns response multiple response headers with the same name', async () => {
registerStreamProtocol(protocolName, (request, callback) => {
callback({
headers: {
header1: ['value1', 'value2'],
header2: 'value3'
},
data: getStream()
});
});
const r = await ajax(protocolName + '://fake-host');
// SUBTLE: when the response headers have multiple values it
// separates values by ", ". When the response headers are incorrectly
// converting an array to a string it separates values by ",".
expect(r.headers).to.have.property('header1', 'value1, value2');
expect(r.headers).to.have.property('header2', 'value3');
});
it('can handle large responses', async () => {
const data = Buffer.alloc(128 * 1024);
registerStreamProtocol(protocolName, (request, callback) => {
callback(getStream(data.length, data));
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.have.lengthOf(data.length);
});
it('can handle a stream completing while writing', async () => {
function dumbPassthrough () {
return new stream.Transform({
async transform (chunk, encoding, cb) {
cb(null, chunk);
}
});
}
registerStreamProtocol(protocolName, (request, callback) => {
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: getStream(1024 * 1024, Buffer.alloc(1024 * 1024 * 2)).pipe(dumbPassthrough())
});
});
const r = await ajax(protocolName + '://fake-host');
expect(r.data).to.have.lengthOf(1024 * 1024 * 2);
});
it('can handle next-tick scheduling during read calls', async () => {
const events = new EventEmitter();
function createStream () {
const buffers = [
Buffer.alloc(65536),
Buffer.alloc(65537),
Buffer.alloc(39156)
];
const e = new stream.Readable({ highWaterMark: 0 });
e.push(buffers.shift());
e._read = function () {
process.nextTick(() => this.push(buffers.shift() || null));
};
e.on('end', function () {
events.emit('end');
});
return e;
}
registerStreamProtocol(protocolName, (request, callback) => {
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: createStream()
});
});
const hasEndedPromise = once(events, 'end');
ajax(protocolName + '://fake-host').catch(() => {});
await hasEndedPromise;
});
it('destroys response streams when aborted before completion', async () => {
const events = new EventEmitter();
registerStreamProtocol(protocolName, (request, callback) => {
const responseStream = new stream.PassThrough();
responseStream.push('data\r\n');
responseStream.on('close', () => {
events.emit('close');
});
callback({
statusCode: 200,
headers: { 'Content-Type': 'text/plain' },
data: responseStream
});
events.emit('respond');
});
const hasRespondedPromise = once(events, 'respond');
const hasClosedPromise = once(events, 'close');
ajax(protocolName + '://fake-host').catch(() => {});
await hasRespondedPromise;
await contents.loadFile(path.join(__dirname, 'fixtures', 'pages', 'fetch.html'));
await hasClosedPromise;
});
});
}
describe('protocol.isProtocolRegistered', () => {
it('returns false when scheme is not registered', () => {
const result = protocol.isProtocolRegistered('no-exist');
expect(result).to.be.false('no-exist: is handled');
});
it('returns true for custom protocol', () => {
registerStringProtocol(protocolName, (request, callback) => callback(''));
const result = protocol.isProtocolRegistered(protocolName);
expect(result).to.be.true('custom protocol is handled');
});
});
describe('protocol.isProtocolIntercepted', () => {
it('returns true for intercepted protocol', () => {
interceptStringProtocol('http', (request, callback) => callback(''));
const result = protocol.isProtocolIntercepted('http');
expect(result).to.be.true('intercepted protocol is handled');
});
});
describe('protocol.intercept(Any)Protocol', () => {
it('returns false when scheme is already intercepted', () => {
expect(protocol.interceptStringProtocol('http', (request, callback) => callback(''))).to.equal(true);
expect(protocol.interceptBufferProtocol('http', (request, callback) => callback(Buffer.from('')))).to.equal(false);
});
it('does not crash when handler is called twice', async () => {
interceptStringProtocol('http', (request, callback) => {
try {
callback(text);
callback('');
} catch (error) {
// Ignore error
}
});
const r = await ajax('http://fake-host');
expect(r.data).to.be.equal(text);
});
it('sends error when callback is called with nothing', async () => {
interceptStringProtocol('http', (request, callback: any) => callback());
await expect(ajax('http://fake-host')).to.be.eventually.rejected();
});
});
describe('protocol.interceptStringProtocol', () => {
it('can intercept http protocol', async () => {
interceptStringProtocol('http', (request, callback) => callback(text));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can set content-type', async () => {
interceptStringProtocol('http', (request, callback) => {
callback({
mimeType: 'application/json',
data: '{"value": 1}'
});
});
const r = await ajax('http://fake-host');
expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
});
it('can set content-type with charset', async () => {
interceptStringProtocol('http', (request, callback) => {
callback({
mimeType: 'application/json; charset=UTF-8',
data: '{"value": 1}'
});
});
const r = await ajax('http://fake-host');
expect(JSON.parse(r.data)).to.have.property('value').that.is.equal(1);
});
it('can receive post data', async () => {
interceptStringProtocol('http', (request, callback) => {
const uploadData = request.uploadData![0].bytes.toString();
callback({ data: uploadData });
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
});
describe('protocol.interceptBufferProtocol', () => {
it('can intercept http protocol', async () => {
interceptBufferProtocol('http', (request, callback) => callback(Buffer.from(text)));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can receive post data', async () => {
interceptBufferProtocol('http', (request, callback) => {
const uploadData = request.uploadData![0].bytes;
callback(uploadData);
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect(qs.parse(r.data)).to.deep.equal({ name: 'post test', type: 'string' });
});
});
describe('protocol.interceptHttpProtocol', () => {
// FIXME(zcbenz): This test was passing because the test itself was wrong,
// I don't know whether it ever passed before and we should take a look at
// it in future.
xit('can send POST request', async () => {
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
res.end(body);
});
server.close();
});
after(() => server.close());
const { url } = await listen(server);
interceptHttpProtocol('http', (request, callback) => {
const data: Electron.ProtocolResponse = {
url: url,
method: 'POST',
uploadData: {
contentType: 'application/x-www-form-urlencoded',
data: request.uploadData![0].bytes
},
session: undefined
};
callback(data);
});
const r = await ajax('http://fake-host', { type: 'POST', data: postData });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
it('can use custom session', async () => {
const customSession = session.fromPartition('custom-ses', { cache: false });
customSession.webRequest.onBeforeRequest((details, callback) => {
expect(details.url).to.equal('http://fake-host/');
callback({ cancel: true });
});
after(() => customSession.webRequest.onBeforeRequest(null));
interceptHttpProtocol('http', (request, callback) => {
callback({
url: request.url,
session: customSession
});
});
await expect(ajax('http://fake-host')).to.be.eventually.rejectedWith(Error);
});
it('can access request headers', (done) => {
protocol.interceptHttpProtocol('http', (request) => {
try {
expect(request).to.have.property('headers');
done();
} catch (e) {
done(e);
}
});
ajax('http://fake-host').catch(() => {});
});
});
describe('protocol.interceptStreamProtocol', () => {
it('can intercept http protocol', async () => {
interceptStreamProtocol('http', (request, callback) => callback(getStream()));
const r = await ajax('http://fake-host');
expect(r.data).to.equal(text);
});
it('can receive post data', async () => {
interceptStreamProtocol('http', (request, callback) => {
callback(getStream(3, request.uploadData![0].bytes.toString()));
});
const r = await ajax('http://fake-host', { method: 'POST', body: qs.stringify(postData) });
expect({ ...qs.parse(r.data) }).to.deep.equal(postData);
});
it('can execute redirects', async () => {
interceptStreamProtocol('http', (request, callback) => {
if (request.url.indexOf('http://fake-host') === 0) {
setTimeout(300).then(() => {
callback({
data: '',
statusCode: 302,
headers: {
Location: 'http://fake-redirect'
}
});
});
} else {
expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
callback(getStream(1, 'redirect'));
}
});
const r = await ajax('http://fake-host');
expect(r.data).to.equal('redirect');
});
it('should discard post data after redirection', async () => {
interceptStreamProtocol('http', (request, callback) => {
if (request.url.indexOf('http://fake-host') === 0) {
setTimeout(300).then(() => {
callback({
statusCode: 302,
headers: {
Location: 'http://fake-redirect'
}
});
});
} else {
expect(request.url.indexOf('http://fake-redirect')).to.equal(0);
callback(getStream(3, request.method));
}
});
const r = await ajax('http://fake-host', { type: 'POST', data: postData });
expect(r.data).to.equal('GET');
});
});
describe('protocol.uninterceptProtocol', () => {
it('returns false when scheme does not exist', () => {
expect(uninterceptProtocol('not-exist')).to.equal(false);
});
it('returns false when scheme is not intercepted', () => {
expect(uninterceptProtocol('http')).to.equal(false);
});
});
describe('protocol.registerSchemeAsPrivileged', () => {
it('does not crash on exit', async () => {
const appPath = path.join(__dirname, 'fixtures', 'api', 'custom-protocol-shutdown.js');
const appProcess = ChildProcess.spawn(process.execPath, ['--enable-logging', appPath]);
let stdout = '';
let stderr = '';
appProcess.stdout.on('data', data => { process.stdout.write(data); stdout += data; });
appProcess.stderr.on('data', data => { process.stderr.write(data); stderr += data; });
const [code] = await once(appProcess, 'exit');
if (code !== 0) {
console.log('Exit code : ', code);
console.log('stdout : ', stdout);
console.log('stderr : ', stderr);
}
expect(code).to.equal(0);
expect(stdout).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
expect(stderr).to.not.contain('VALIDATION_ERROR_DESERIALIZATION_FAILED');
});
});
describe('protocol.registerSchemesAsPrivileged allowServiceWorkers', () => {
protocol.registerStringProtocol(serviceWorkerScheme, (request, cb) => {
if (request.url.endsWith('.js')) {
cb({
mimeType: 'text/javascript',
charset: 'utf-8',
data: 'console.log("Loaded")'
});
} else {
cb({
mimeType: 'text/html',
charset: 'utf-8',
data: '<!DOCTYPE html>'
});
}
});
after(() => protocol.unregisterProtocol(serviceWorkerScheme));
it('should fail when registering invalid service worker', async () => {
await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
await expect(contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.notjs', {scope: './'})`)).to.be.rejected();
});
it('should be able to register service worker for custom scheme', async () => {
await contents.loadURL(`${serviceWorkerScheme}://${v4()}.com`);
await contents.executeJavaScript(`navigator.serviceWorker.register('${v4()}.js', {scope: './'})`);
});
});
describe('protocol.registerSchemesAsPrivileged standard', () => {
const origin = `${standardScheme}://fake-host`;
const imageURL = `${origin}/test.png`;
const filePath = path.join(fixturesPath, 'pages', 'b.html');
const fileContent = '<img src="/test.png" />';
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeWindow(w);
unregisterProtocol(standardScheme);
w = null as unknown as BrowserWindow;
});
it('resolves relative resources', async () => {
registerFileProtocol(standardScheme, (request, callback) => {
if (request.url === imageURL) {
callback('');
} else {
callback(filePath);
}
});
await w.loadURL(origin);
});
it('resolves absolute resources', async () => {
registerStringProtocol(standardScheme, (request, callback) => {
if (request.url === imageURL) {
callback('');
} else {
callback({
data: fileContent,
mimeType: 'text/html'
});
}
});
await w.loadURL(origin);
});
it('can have fetch working in it', async () => {
const requestReceived = deferPromise();
const server = http.createServer((req, res) => {
res.end();
server.close();
requestReceived.resolve();
});
const { url } = await listen(server);
const content = `<script>fetch(${JSON.stringify(url)})</script>`;
registerStringProtocol(standardScheme, (request, callback) => callback({ data: content, mimeType: 'text/html' }));
await w.loadURL(origin);
await requestReceived;
});
it('can access files through the FileSystem API', (done) => {
const filePath = path.join(fixturesPath, 'pages', 'filesystem.html');
protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
w.loadURL(origin);
ipcMain.once('file-system-error', (event, err) => done(err));
ipcMain.once('file-system-write-end', () => done());
});
it('registers secure, when {secure: true}', (done) => {
const filePath = path.join(fixturesPath, 'pages', 'cache-storage.html');
ipcMain.once('success', () => done());
ipcMain.once('failure', (event, err) => done(err));
protocol.registerFileProtocol(standardScheme, (request, callback) => callback({ path: filePath }));
w.loadURL(origin);
});
});
describe('protocol.registerSchemesAsPrivileged cors-fetch', function () {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
for (const scheme of [standardScheme, 'cors', 'no-cors', 'no-fetch']) {
protocol.unregisterProtocol(scheme);
}
});
it('supports fetch api by default', async () => {
const url = `file://${fixturesPath}/assets/logo.png`;
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const ok = await w.webContents.executeJavaScript(`fetch(${JSON.stringify(url)}).then(r => r.ok)`);
expect(ok).to.be.true('response ok');
});
it('allows CORS requests by default', async () => {
await allowsCORSRequests('cors', 200, new RegExp(''), () => {
const { ipcRenderer } = require('electron');
fetch('cors://myhost').then(function (response) {
ipcRenderer.send('response', response.status);
}).catch(function () {
ipcRenderer.send('response', 'failed');
});
});
});
// DISABLED-FIXME: Figure out why this test is failing
it('disallows CORS and fetch requests when only supportFetchAPI is specified', async () => {
await allowsCORSRequests('no-cors', ['failed xhr', 'failed fetch'], /has been blocked by CORS policy/, () => {
const { ipcRenderer } = require('electron');
Promise.all([
new Promise(resolve => {
const req = new XMLHttpRequest();
req.onload = () => resolve('loaded xhr');
req.onerror = () => resolve('failed xhr');
req.open('GET', 'no-cors://myhost');
req.send();
}),
fetch('no-cors://myhost')
.then(() => 'loaded fetch')
.catch(() => 'failed fetch')
]).then(([xhr, fetch]) => {
ipcRenderer.send('response', [xhr, fetch]);
});
});
});
it('allows CORS, but disallows fetch requests, when specified', async () => {
await allowsCORSRequests('no-fetch', ['loaded xhr', 'failed fetch'], /Fetch API cannot load/, () => {
const { ipcRenderer } = require('electron');
Promise.all([
new Promise(resolve => {
const req = new XMLHttpRequest();
req.onload = () => resolve('loaded xhr');
req.onerror = () => resolve('failed xhr');
req.open('GET', 'no-fetch://myhost');
req.send();
}),
fetch('no-fetch://myhost')
.then(() => 'loaded fetch')
.catch(() => 'failed fetch')
]).then(([xhr, fetch]) => {
ipcRenderer.send('response', [xhr, fetch]);
});
});
});
async function allowsCORSRequests (corsScheme: string, expected: any, expectedConsole: RegExp, content: Function) {
registerStringProtocol(standardScheme, (request, callback) => {
callback({ data: `<script>(${content})()</script>`, mimeType: 'text/html' });
});
registerStringProtocol(corsScheme, (request, callback) => {
callback('');
});
const newContents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
const consoleMessages: string[] = [];
newContents.on('console-message', (e, level, message) => consoleMessages.push(message));
try {
newContents.loadURL(standardScheme + '://fake-host');
const [, response] = await once(ipcMain, 'response');
expect(response).to.deep.equal(expected);
expect(consoleMessages.join('\n')).to.match(expectedConsole);
} finally {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout().then(() => {
newContents.destroy();
});
}
}
});
describe('protocol.registerSchemesAsPrivileged stream', async function () {
const pagePath = path.join(fixturesPath, 'pages', 'video.html');
const videoSourceImagePath = path.join(fixturesPath, 'video-source-image.webp');
const videoPath = path.join(fixturesPath, 'video.webm');
let w: BrowserWindow;
before(async () => {
// generate test video
const imageBase64 = await fs.promises.readFile(videoSourceImagePath, 'base64');
const imageDataUrl = `data:image/webp;base64,${imageBase64}`;
const encoder = new WebmGenerator(15);
for (let i = 0; i < 30; i++) {
encoder.add(imageDataUrl);
}
await new Promise((resolve, reject) => {
encoder.compile((output:Uint8Array) => {
fs.promises.writeFile(videoPath, output).then(resolve, reject);
});
});
});
after(async () => {
await fs.promises.unlink(videoPath);
});
beforeEach(async function () {
w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) {
this.skip();
}
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
await protocol.unregisterProtocol(standardScheme);
await protocol.unregisterProtocol('stream');
});
it('successfully plays videos when content is buffered (stream: false)', async () => {
await streamsResponses(standardScheme, 'play');
});
it('successfully plays videos when streaming content (stream: true)', async () => {
await streamsResponses('stream', 'play');
});
async function streamsResponses (testingScheme: string, expected: any) {
const protocolHandler = (request: any, callback: Function) => {
if (request.url.includes('/video.webm')) {
const stat = fs.statSync(videoPath);
const fileSize = stat.size;
const range = request.headers.Range;
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = (end - start) + 1;
const headers = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': String(chunksize),
'Content-Type': 'video/webm'
};
callback({ statusCode: 206, headers, data: fs.createReadStream(videoPath, { start, end }) });
} else {
callback({
statusCode: 200,
headers: {
'Content-Length': String(fileSize),
'Content-Type': 'video/webm'
},
data: fs.createReadStream(videoPath)
});
}
} else {
callback({ data: fs.createReadStream(pagePath), headers: { 'Content-Type': 'text/html' }, statusCode: 200 });
}
};
await registerStreamProtocol(standardScheme, protocolHandler);
await registerStreamProtocol('stream', protocolHandler);
const newContents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
try {
newContents.loadURL(testingScheme + '://fake-host');
const [, response] = await once(ipcMain, 'result');
expect(response).to.deep.equal(expected);
} finally {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout().then(() => {
newContents.destroy();
});
}
}
});
describe('handle', () => {
afterEach(closeAllWindows);
it('receives requests to a custom scheme', async () => {
protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.status).to.equal(200);
});
it('can be unhandled', async () => {
protocol.handle('test-scheme', (req) => new Response('hello ' + req.url));
defer(() => {
try {
// In case of failure, make sure we unhandle. But we should succeed
// :)
protocol.unhandle('test-scheme');
} catch (_ignored) { /* ignore */ }
});
const resp1 = await net.fetch('test-scheme://foo');
expect(resp1.status).to.equal(200);
protocol.unhandle('test-scheme');
await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith(/ERR_UNKNOWN_URL_SCHEME/);
});
it('receives requests to an existing scheme', async () => {
protocol.handle('https', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('https'); });
const body = await net.fetch('https://foo').then(r => r.text());
expect(body).to.equal('hello https://foo/');
});
it('receives requests to an existing scheme when navigating', async () => {
protocol.handle('https', (req) => new Response('hello ' + req.url));
defer(() => { protocol.unhandle('https'); });
const w = new BrowserWindow({ show: false });
await w.loadURL('https://localhost');
expect(await w.webContents.executeJavaScript('document.body.textContent')).to.equal('hello https://localhost/');
});
it('can send buffer body', async () => {
protocol.handle('test-scheme', (req) => new Response(Buffer.from('hello ' + req.url)));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal('hello test-scheme://foo');
});
it('can send stream body', async () => {
protocol.handle('test-scheme', () => new Response(getWebStream()));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal(text);
});
it('accepts urls with no hostname in non-standard schemes', async () => {
protocol.handle('test-scheme', (req) => new Response(req.url));
defer(() => { protocol.unhandle('test-scheme'); });
{
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal('test-scheme://foo');
}
{
const body = await net.fetch('test-scheme:///foo').then(r => r.text());
expect(body).to.equal('test-scheme:///foo');
}
{
const body = await net.fetch('test-scheme://').then(r => r.text());
expect(body).to.equal('test-scheme://');
}
});
it('accepts urls with a port-like component in non-standard schemes', async () => {
protocol.handle('test-scheme', (req) => new Response(req.url));
defer(() => { protocol.unhandle('test-scheme'); });
{
const body = await net.fetch('test-scheme://foo:30').then(r => r.text());
expect(body).to.equal('test-scheme://foo:30');
}
});
it('normalizes urls in standard schemes', async () => {
// NB. 'app' is registered as a standard scheme in test setup.
protocol.handle('app', (req) => new Response(req.url));
defer(() => { protocol.unhandle('app'); });
{
const body = await net.fetch('app://foo').then(r => r.text());
expect(body).to.equal('app://foo/');
}
{
const body = await net.fetch('app:///foo').then(r => r.text());
expect(body).to.equal('app://foo/');
}
// NB. 'app' is registered with the default scheme type of 'host'.
{
const body = await net.fetch('app://foo:1234').then(r => r.text());
expect(body).to.equal('app://foo/');
}
await expect(net.fetch('app://')).to.be.rejectedWith('Invalid URL');
});
it('fails on URLs with a username', async () => {
// NB. 'app' is registered as a standard scheme in test setup.
protocol.handle('http', (req) => new Response(req.url));
defer(() => { protocol.unhandle('http'); });
await expect(contents.loadURL('http://x@foo:1234')).to.be.rejectedWith(/ERR_UNEXPECTED/);
});
it('normalizes http urls', async () => {
protocol.handle('http', (req) => new Response(req.url));
defer(() => { protocol.unhandle('http'); });
{
const body = await net.fetch('http://foo').then(r => r.text());
expect(body).to.equal('http://foo/');
}
});
it('can send errors', async () => {
protocol.handle('test-scheme', () => Response.error());
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.eventually.be.rejectedWith('net::ERR_FAILED');
});
it('handles a synchronous error in the handler', async () => {
protocol.handle('test-scheme', () => { throw new Error('test'); });
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('handles an asynchronous error in the handler', async () => {
protocol.handle('test-scheme', () => Promise.reject(new Error('rejected promise')));
defer(() => { protocol.unhandle('test-scheme'); });
await expect(net.fetch('test-scheme://foo')).to.be.rejectedWith('net::ERR_UNEXPECTED');
});
it('correctly sets statusCode', async () => {
protocol.handle('test-scheme', () => new Response(null, { status: 201 }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.status).to.equal(201);
});
it('correctly sets content-type and charset', async () => {
protocol.handle('test-scheme', () => new Response(null, { headers: { 'content-type': 'text/html; charset=testcharset' } }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.headers.get('content-type')).to.equal('text/html; charset=testcharset');
});
it('can forward to http', async () => {
const server = http.createServer((req, res) => {
res.end(text);
});
defer(() => { server.close(); });
const { url } = await listen(server);
protocol.handle('test-scheme', () => net.fetch(url));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body).to.equal(text);
});
it('can forward an http request with headers', async () => {
const server = http.createServer((req, res) => {
res.setHeader('foo', 'bar');
res.end(text);
});
defer(() => { server.close(); });
const { url } = await listen(server);
protocol.handle('test-scheme', (req) => net.fetch(url, { headers: req.headers }));
defer(() => { protocol.unhandle('test-scheme'); });
const resp = await net.fetch('test-scheme://foo');
expect(resp.headers.get('foo')).to.equal('bar');
});
it('can forward to file', async () => {
protocol.handle('test-scheme', () => net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString()));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo').then(r => r.text());
expect(body.trimEnd()).to.equal('hello world');
});
it('can receive simple request body', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo', {
method: 'POST',
body: 'foobar'
}).then(r => r.text());
expect(body).to.equal('foobar');
});
it('can receive stream request body', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
const body = await net.fetch('test-scheme://foo', {
method: 'POST',
body: getWebStream(),
duplex: 'half' // https://github.com/microsoft/TypeScript/issues/53157
} as any).then(r => r.text());
expect(body).to.equal(text);
});
it('can receive multi-part postData from loadURL', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('test-scheme://foo', { postData: [{ type: 'rawData', bytes: Buffer.from('a') }, { type: 'rawData', bytes: Buffer.from('b') }] });
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('ab');
});
it('can receive file postData from loadURL', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('test-scheme://foo', { postData: [{ type: 'file', filePath: path.join(fixturesPath, 'hello.txt'), length: 'hello world\n'.length, offset: 0, modificationTime: 0 }] });
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello world\n');
});
it('can receive file postData from a form', async () => {
protocol.handle('test-scheme', (req) => new Response(req.body));
defer(() => { protocol.unhandle('test-scheme'); });
await contents.loadURL('data:text/html,<form action="test-scheme://foo" method=POST enctype="multipart/form-data"><input name=foo type=file>');
const { debugger: dbg } = contents;
dbg.attach();
const { root } = await dbg.sendCommand('DOM.getDocument');
const { nodeId: fileInputNodeId } = await dbg.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: 'input' });
await dbg.sendCommand('DOM.setFileInputFiles', {
nodeId: fileInputNodeId,
files: [
path.join(fixturesPath, 'hello.txt')
]
});
const navigated = once(contents, 'did-finish-load');
await contents.executeJavaScript('document.querySelector("form").submit()');
await navigated;
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.match(/------WebKitFormBoundary.*\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\nContent-Type: text\/plain\n\nhello world\n\n------WebKitFormBoundary.*--\n/);
});
it('can receive streaming fetch upload', async () => {
protocol.handle('no-cors', (req) => new Response(req.body));
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('hello world');
controller.close();
},
}).pipeThrough(new TextEncoderStream());
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
`);
expect(fetchBodyResult).to.equal('hello world');
});
it('can receive streaming fetch upload when a webRequest handler is present', async () => {
session.defaultSession.webRequest.onBeforeRequest((details, cb) => {
console.log('webRequest', details.url, details.method);
cb({});
});
defer(() => {
session.defaultSession.webRequest.onBeforeRequest(null);
});
protocol.handle('no-cors', (req) => {
console.log('handle', req.url, req.method);
return new Response(req.body);
});
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.enqueue('hello world');
controller.close();
},
}).pipeThrough(new TextEncoderStream());
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text())
`);
expect(fetchBodyResult).to.equal('hello world');
});
it('can receive an error from streaming fetch upload', async () => {
protocol.handle('no-cors', (req) => new Response(req.body));
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
const fetchBodyResult = await contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
controller.error('test')
},
});
fetch(location.href, {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
`);
expect(fetchBodyResult).to.be.an.instanceOf(Error);
});
it('gets an error from streaming fetch upload when the renderer dies', async () => {
let gotRequest: Function;
const receivedRequest = new Promise<Request>(resolve => { gotRequest = resolve; });
protocol.handle('no-cors', (req) => {
if (/fetch/.test(req.url)) gotRequest(req);
return new Response();
});
defer(() => { protocol.unhandle('no-cors'); });
await contents.loadURL('no-cors://foo');
contents.executeJavaScript(`
const stream = new ReadableStream({
async start(controller) {
window.controller = controller // no GC
},
});
fetch(location.href + '/fetch', {method: 'POST', body: stream, duplex: 'half'}).then(x => x.text()).catch(err => err)
`);
const req = await receivedRequest;
contents.destroy();
// Undo .destroy() for the next test
contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
await expect(req.body!.getReader().read()).to.eventually.be.rejectedWith('net::ERR_FAILED');
});
it('can bypass intercepeted protocol handlers', async () => {
protocol.handle('http', () => new Response('custom'));
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
res.end('default');
});
defer(() => server.close());
const { url } = await listen(server);
expect(await net.fetch(url, { bypassCustomProtocolHandlers: true }).then(r => r.text())).to.equal('default');
});
it('bypassing custom protocol handlers also bypasses new protocols', async () => {
protocol.handle('app', () => new Response('custom'));
defer(() => { protocol.unhandle('app'); });
await expect(net.fetch('app://foo', { bypassCustomProtocolHandlers: true })).to.be.rejectedWith('net::ERR_UNKNOWN_URL_SCHEME');
});
it('can forward to the original handler', async () => {
protocol.handle('http', (req) => net.fetch(req, { bypassCustomProtocolHandlers: true }));
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
res.end('hello');
server.close();
});
const { url } = await listen(server);
await contents.loadURL(url);
expect(await contents.executeJavaScript('document.documentElement.textContent')).to.equal('hello');
});
it('supports sniffing mime type', async () => {
protocol.handle('http', async (req) => {
return net.fetch(req, { bypassCustomProtocolHandlers: true });
});
defer(() => { protocol.unhandle('http'); });
const server = http.createServer((req, res) => {
if (/html/.test(req.url ?? '')) { res.end('<!doctype html><body>hi'); } else { res.end('hi'); }
});
const { url } = await listen(server);
defer(() => server.close());
{
await contents.loadURL(url);
const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
expect(doc).to.match(/white-space: pre-wrap/);
}
{
await contents.loadURL(url + '?html');
const doc = await contents.executeJavaScript('document.documentElement.outerHTML');
expect(doc).to.equal('<html><head></head><body>hi</body></html>');
}
});
// TODO(nornagon): this test doesn't pass on Linux currently, investigate.
ifit(process.platform !== 'linux')('is fast', async () => {
// 128 MB of spaces.
const chunk = new Uint8Array(128 * 1024 * 1024);
chunk.fill(' '.charCodeAt(0));
const server = http.createServer((req, res) => {
// The sniffed mime type for the space-filled chunk will be
// text/plain, which chews up all its performance in the renderer
// trying to wrap lines. Setting content-type to text/html measures
// something closer to just the raw cost of getting the bytes over
// the wire.
res.setHeader('content-type', 'text/html');
res.end(chunk);
});
defer(() => server.close());
const { url } = await listen(server);
const rawTime = await (async () => {
await contents.loadURL(url); // warm
const begin = Date.now();
await contents.loadURL(url);
const end = Date.now();
return end - begin;
})();
// Fetching through an intercepted handler should not be too much slower
// than it would be if the protocol hadn't been intercepted.
protocol.handle('http', async (req) => {
return net.fetch(req, { bypassCustomProtocolHandlers: true });
});
defer(() => { protocol.unhandle('http'); });
const interceptedTime = await (async () => {
const begin = Date.now();
await contents.loadURL(url);
const end = Date.now();
return end - begin;
})();
expect(interceptedTime).to.be.lessThan(rawTime * 1.5);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,562 |
[Bug]: Crash when opening and closing a child window a few times on macOS
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
macOS
### Operating System Version
Ventura 13.4
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
A child window should be able to be opened and closed multiple times without crashing.
### Actual Behavior
The Electron app crashes after opening a child window and then closing it. This usually happens after opening the child window a few times in a row.
### Testcase Gist URL
https://gist.github.com/jorodi/cbf4378f978e44de5034ab2d91f30387
### Additional Information
Caught error output from VS code terminal:
```
2023-06-02 08:24:57.023 Electron[80994:4778831] -[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f
2023-06-02 08:24:57.025 Electron[80994:4778831] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff802c7918a __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80279f42b objc_exception_throw + 48
2 CoreFoundation 0x00007ff802d14fef -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007ff802be4797 ___forwarding___ + 1392
4 CoreFoundation 0x00007ff802be4198 _CF_forwarding_prep_0 + 120
5 Electron Framework 0x000000010b707e38 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 154760
6 Electron Framework 0x000000010b7073e0 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 152112
7 Electron Framework 0x000000010b646b23 _ZN2v89CodeEvent10GetCommentEv + 4099
8 Electron Framework 0x000000010b56dc93 ElectronInitializeICUandStartNode + 207619
9 Electron Framework 0x000000010b56f2c4 ElectronInitializeICUandStartNode + 213300
10 Electron Framework 0x000000010b56f9fe ElectronInitializeICUandStartNode + 215150
11 Electron Framework 0x000000010b5634e1 ElectronInitializeICUandStartNode + 164689
12 Electron Framework 0x000000010b5633d3 ElectronInitializeICUandStartNode + 164419
13 Electron Framework 0x000000010c83be34 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 15780
14 Electron Framework 0x000000010c83b9df _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 14671
15 Electron Framework 0x000000010c83ad24 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 11412
16 Electron Framework 0x000000010b25edf6 Electron Framework + 826870
17 Electron Framework 0x000000010b1c4ff2 Electron Framework + 196594
)
/Users/jordan/parent-child-error/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGILL
```
|
https://github.com/electron/electron/issues/38562
|
https://github.com/electron/electron/pull/38603
|
9a9d8ae5ea61e17fd01e8975e81ed2a137a5fef6
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
| 2023-06-02T13:02:06Z |
c++
| 2023-06-08T10:18:37Z |
shell/browser/native_window_mac.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#import <Cocoa/Cocoa.h>
#include <memory>
#include <string>
#include <vector>
#include "base/mac/scoped_nsobject.h"
#include "shell/browser/native_window.h"
#include "shell/common/api/api.mojom.h"
#include "ui/display/display_observer.h"
#include "ui/native_theme/native_theme_observer.h"
#include "ui/views/controls/native/native_view_host.h"
@class ElectronNSWindow;
@class ElectronNSWindowDelegate;
@class ElectronPreviewItem;
@class ElectronTouchBar;
@class WindowButtonsProxy;
namespace electron {
class RootViewMac;
class NativeWindowMac : public NativeWindow,
public ui::NativeThemeObserver,
public display::DisplayObserver {
public:
NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent);
~NativeWindowMac() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate = false) override;
gfx::Rect GetBounds() override;
bool IsNormal() override;
gfx::Rect GetNormalBounds() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relative_level) override;
std::string GetAlwaysOnTopLevel() override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
void SetBackgroundColor(SkColor color) override;
SkColor GetBackgroundColor() override;
void InvalidateShadow() override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetRepresentedFilename(const std::string& filename) override;
std::string GetRepresentedFilename() override;
void SetDocumentEdited(bool edited) override;
bool IsDocumentEdited() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
bool IsHiddenInMissionControl() override;
void SetHiddenInMissionControl(bool hidden) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetAutoHideCursor(bool auto_hide) override;
void SetVibrancy(const std::string& type) override;
void SetWindowButtonVisibility(bool visible) override;
bool GetWindowButtonVisibility() const override;
void SetWindowButtonPosition(absl::optional<gfx::Point> position) override;
absl::optional<gfx::Point> GetWindowButtonPosition() const override;
void RedrawTrafficLights() override;
void UpdateFrame() override;
void SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) override;
void RefreshTouchBarItem(const std::string& item_id) override;
void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override;
void SelectPreviousTab() override;
void SelectNextTab() override;
void MergeAllWindows() override;
void MoveTabToNewWindow() override;
void ToggleTabBar() override;
bool AddTabbedWindow(NativeWindow* window) override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void PreviewFile(const std::string& path,
const std::string& display_name) override;
void CloseFilePreview() override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
gfx::Rect GetWindowControlsOverlayRect() override;
void NotifyWindowEnterFullScreen() override;
void NotifyWindowLeaveFullScreen() override;
void SetActive(bool is_key) override;
bool IsActive() const override;
// Remove the specified child window without closing it.
void RemoveChildWindow(NativeWindow* child) override;
// Attach child windows, if the window is visible.
void AttachChildren() override;
// Detach window from parent without destroying it.
void DetachChildren() override;
void NotifyWindowWillEnterFullScreen();
void NotifyWindowWillLeaveFullScreen();
// Cleanup observers when window is getting closed. Note that the destructor
// can be called much later after window gets closed, so we should not do
// cleanup in destructor.
void Cleanup();
void UpdateVibrancyRadii(bool fullscreen);
void UpdateWindowOriginalFrame();
// Set the attribute of NSWindow while work around a bug of zoom button.
bool HasStyleMask(NSUInteger flag) const;
void SetStyleMask(bool on, NSUInteger flag);
void SetCollectionBehavior(bool on, NSUInteger flag);
void SetWindowLevel(int level);
bool HandleDeferredClose();
void SetHasDeferredWindowClose(bool defer_close) {
has_deferred_window_close_ = defer_close;
}
enum class VisualEffectState {
kFollowWindow,
kActive,
kInactive,
};
ElectronPreviewItem* preview_item() const { return preview_item_.get(); }
ElectronTouchBar* touch_bar() const { return touch_bar_.get(); }
bool zoom_to_page_width() const { return zoom_to_page_width_; }
bool always_simple_fullscreen() const { return always_simple_fullscreen_; }
// We need to save the result of windowWillUseStandardFrame:defaultFrame
// because macOS calls it with what it refers to as the "best fit" frame for a
// zoom. This means that even if an aspect ratio is set, macOS might adjust it
// to better fit the screen.
//
// Thus, we can't just calculate the maximized aspect ratio'd sizing from
// the current visible screen and compare that to the current window's frame
// to determine whether a window is maximized.
NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; }
void set_default_frame_for_zoom(NSRect frame) {
default_frame_for_zoom_ = frame;
}
protected:
// views::WidgetDelegate:
views::View* GetContentsView() override;
bool CanMaximize() const override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
// display::DisplayObserver:
void OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) override;
private:
// Add custom layers to the content view.
void AddContentViewLayers();
void InternalSetWindowButtonVisibility(bool visible);
void InternalSetParentWindow(NativeWindow* parent, bool attach);
void SetForwardMouseMessages(bool forward);
ElectronNSWindow* window_; // Weak ref, managed by widget_.
base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_;
base::scoped_nsobject<ElectronPreviewItem> preview_item_;
base::scoped_nsobject<ElectronTouchBar> touch_bar_;
// The views::View that fills the client area.
std::unique_ptr<RootViewMac> root_view_;
bool fullscreen_before_kiosk_ = false;
bool is_kiosk_ = false;
bool zoom_to_page_width_ = false;
absl::optional<gfx::Point> traffic_light_position_;
// Trying to close an NSWindow during a fullscreen transition will cause the
// window to lock up. Use this to track if CloseWindow was called during a
// fullscreen transition, to defer the -[NSWindow close] call until the
// transition is complete.
bool has_deferred_window_close_ = false;
NSInteger attention_request_id_ = 0; // identifier from requestUserAttention
// The presentation options before entering kiosk mode.
NSApplicationPresentationOptions kiosk_options_;
// The "visualEffectState" option.
VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow;
// The visibility mode of window button controls when explicitly set through
// setWindowButtonVisibility().
absl::optional<bool> window_button_visibility_;
// Controls the position and visibility of window buttons.
base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_;
std::unique_ptr<SkRegion> draggable_region_;
// Maximizable window state; necessary for persistence through redraws.
bool maximizable_ = true;
bool user_set_bounds_maximized_ = false;
// Simple (pre-Lion) Fullscreen Settings
bool always_simple_fullscreen_ = false;
bool is_simple_fullscreen_ = false;
bool was_maximizable_ = false;
bool was_movable_ = false;
bool is_active_ = false;
NSRect original_frame_;
NSInteger original_level_;
NSUInteger simple_fullscreen_mask_;
NSRect default_frame_for_zoom_;
std::string vibrancy_type_;
// The presentation options before entering simple fullscreen mode.
NSApplicationPresentationOptions simple_fullscreen_options_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,562 |
[Bug]: Crash when opening and closing a child window a few times on macOS
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
macOS
### Operating System Version
Ventura 13.4
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
A child window should be able to be opened and closed multiple times without crashing.
### Actual Behavior
The Electron app crashes after opening a child window and then closing it. This usually happens after opening the child window a few times in a row.
### Testcase Gist URL
https://gist.github.com/jorodi/cbf4378f978e44de5034ab2d91f30387
### Additional Information
Caught error output from VS code terminal:
```
2023-06-02 08:24:57.023 Electron[80994:4778831] -[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f
2023-06-02 08:24:57.025 Electron[80994:4778831] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff802c7918a __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80279f42b objc_exception_throw + 48
2 CoreFoundation 0x00007ff802d14fef -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007ff802be4797 ___forwarding___ + 1392
4 CoreFoundation 0x00007ff802be4198 _CF_forwarding_prep_0 + 120
5 Electron Framework 0x000000010b707e38 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 154760
6 Electron Framework 0x000000010b7073e0 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 152112
7 Electron Framework 0x000000010b646b23 _ZN2v89CodeEvent10GetCommentEv + 4099
8 Electron Framework 0x000000010b56dc93 ElectronInitializeICUandStartNode + 207619
9 Electron Framework 0x000000010b56f2c4 ElectronInitializeICUandStartNode + 213300
10 Electron Framework 0x000000010b56f9fe ElectronInitializeICUandStartNode + 215150
11 Electron Framework 0x000000010b5634e1 ElectronInitializeICUandStartNode + 164689
12 Electron Framework 0x000000010b5633d3 ElectronInitializeICUandStartNode + 164419
13 Electron Framework 0x000000010c83be34 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 15780
14 Electron Framework 0x000000010c83b9df _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 14671
15 Electron Framework 0x000000010c83ad24 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 11412
16 Electron Framework 0x000000010b25edf6 Electron Framework + 826870
17 Electron Framework 0x000000010b1c4ff2 Electron Framework + 196594
)
/Users/jordan/parent-child-error/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGILL
```
|
https://github.com/electron/electron/issues/38562
|
https://github.com/electron/electron/pull/38603
|
9a9d8ae5ea61e17fd01e8975e81ed2a137a5fef6
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
| 2023-06-02T13:02:06Z |
c++
| 2023-06-08T10:18:37Z |
shell/browser/native_window_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window_mac.h"
#include <AvailabilityMacros.h>
#include <objc/objc-runtime.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/sys_string_conversions.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "components/remote_cocoa/browser/scoped_cg_window_id.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "shell/browser/browser.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
#include "shell/browser/ui/cocoa/electron_ns_window.h"
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "shell/browser/ui/cocoa/root_view_mac.h"
#include "shell/browser/ui/cocoa/window_buttons_proxy.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/window_list.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "skia/ext/skia_utils_mac.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
#include "ui/base/hit_test.h"
#include "ui/display/screen.h"
#include "ui/gfx/skia_util.h"
#include "ui/gl/gpu_switching_manager.h"
#include "ui/views/background.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/native_frame_view_mac.h"
@interface ElectronProgressBar : NSProgressIndicator
@end
@implementation ElectronProgressBar
- (void)drawRect:(NSRect)dirtyRect {
if (self.style != NSProgressIndicatorBarStyle)
return;
// Draw edges of rounded rect.
NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
CGFloat radius = rect.size.height / 2;
NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:2.0];
[[NSColor grayColor] set];
[bezier_path stroke];
// Fill the rounded rect.
rect = NSInsetRect(rect, 2.0, 2.0);
radius = rect.size.height / 2;
bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:1.0];
[bezier_path addClip];
// Calculate the progress width.
rect.size.width =
floor(rect.size.width * ([self doubleValue] / [self maxValue]));
// Fill the progress bar with color blue.
[[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
NSRectFill(rect);
}
@end
namespace gin {
template <>
struct Converter<electron::NativeWindowMac::VisualEffectState> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindowMac::VisualEffectState* out) {
using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
std::string visual_effect_state;
if (!ConvertFromV8(isolate, val, &visual_effect_state))
return false;
if (visual_effect_state == "followWindow") {
*out = VisualEffectState::kFollowWindow;
} else if (visual_effect_state == "active") {
*out = VisualEffectState::kActive;
} else if (visual_effect_state == "inactive") {
*out = VisualEffectState::kInactive;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
bool IsFramelessWindow(NSView* view) {
NSWindow* nswindow = [view window];
if (![nswindow respondsToSelector:@selector(shell)])
return false;
NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell];
return window && !window->has_frame();
}
IMP original_set_frame_size = nullptr;
IMP original_view_did_move_to_superview = nullptr;
// This method is directly called by NSWindow during a window resize on OSX
// 10.10.0, beta 2. We must override it to prevent the content view from
// shrinking.
void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
if (!IsFramelessWindow(self)) {
auto original =
reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
return original(self, _cmd, size);
}
// For frameless window, resize the view to cover full window.
if ([self superview])
size = [[self superview] bounds].size;
auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
[[self superclass] instanceMethodForSelector:_cmd]);
super_impl(self, _cmd, size);
}
// The contentView gets moved around during certain full-screen operations.
// This is less than ideal, and should eventually be removed.
void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
if (!IsFramelessWindow(self)) {
// [BridgedContentView viewDidMoveToSuperview];
auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
original_view_did_move_to_superview);
if (original)
original(self, _cmd);
return;
}
[self setFrame:[[self superview] bounds]];
}
} // namespace
NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
display::Screen::GetScreen()->AddObserver(this);
int width = 800, height = 600;
options.Get(options::kWidth, &width);
options.Get(options::kHeight, &height);
NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
round((NSHeight(main_screen_rect) - height) / 2), width,
height);
bool resizable = true;
options.Get(options::kResizable, &resizable);
options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_);
options.Get(options::kVisualEffectState, &visual_effect_state_);
if (options.Has(options::kFullscreenWindowTitle)) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"\"fullscreenWindowTitle\" option has been deprecated and is "
"no-op now.",
"electron");
}
bool minimizable = true;
options.Get(options::kMinimizable, &minimizable);
bool maximizable = true;
options.Get(options::kMaximizable, &maximizable);
bool closable = true;
options.Get(options::kClosable, &closable);
std::string tabbingIdentifier;
options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
std::string windowType;
options.Get(options::kType, &windowType);
bool hiddenInMissionControl = false;
options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl);
bool useStandardWindow = true;
// eventually deprecate separate "standardWindow" option in favor of
// standard / textured window types
options.Get(options::kStandardWindow, &useStandardWindow);
if (windowType == "textured") {
useStandardWindow = false;
}
// The window without titlebar is treated the same with frameless window.
if (title_bar_style_ != TitleBarStyle::kNormal)
set_has_frame(false);
NSUInteger styleMask = NSWindowStyleMaskTitled;
// The NSWindowStyleMaskFullSizeContentView style removes rounded corners
// for frameless window.
bool rounded_corner = true;
options.Get(options::kRoundedCorners, &rounded_corner);
if (!rounded_corner && !has_frame())
styleMask = NSWindowStyleMaskBorderless;
if (minimizable)
styleMask |= NSWindowStyleMaskMiniaturizable;
if (closable)
styleMask |= NSWindowStyleMaskClosable;
if (resizable)
styleMask |= NSWindowStyleMaskResizable;
if (!useStandardWindow || transparent() || !has_frame())
styleMask |= NSWindowStyleMaskTexturedBackground;
// Create views::Widget and assign window_ with it.
// TODO(zcbenz): Get rid of the window_ in future.
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = bounds;
params.delegate = this;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
SetCanResize(resizable);
window_ = static_cast<ElectronNSWindow*>(
widget()->GetNativeWindow().GetNativeNSWindow());
RegisterDeleteDelegateCallback(base::BindOnce(
[](NativeWindowMac* window) {
if (window->window_)
window->window_ = nil;
if (window->buttons_proxy_)
window->buttons_proxy_.reset();
},
this));
[window_ setEnableLargerThanScreen:enable_larger_than_screen()];
window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]);
[window_ setDelegate:window_delegate_];
// Only use native parent window for non-modal windows.
if (parent && !is_modal()) {
SetParentWindow(parent);
}
if (transparent()) {
// Setting the background color to clear will also hide the shadow.
[window_ setBackgroundColor:[NSColor clearColor]];
}
if (windowType == "desktop") {
[window_ setLevel:kCGDesktopWindowLevel - 1];
[window_ setDisableKeyOrMainWindow:YES];
[window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorStationary |
NSWindowCollectionBehaviorIgnoresCycle)];
}
if (windowType == "panel") {
[window_ setLevel:NSFloatingWindowLevel];
}
bool focusable;
if (options.Get(options::kFocusable, &focusable) && !focusable)
[window_ setDisableKeyOrMainWindow:YES];
if (transparent() || !has_frame()) {
// Don't show title bar.
[window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden];
// Remove non-transparent corners, see
// https://github.com/electron/electron/issues/517.
[window_ setOpaque:NO];
// Show window buttons if titleBarStyle is not "normal".
if (title_bar_style_ == TitleBarStyle::kNormal) {
InternalSetWindowButtonVisibility(false);
} else {
buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]);
[buttons_proxy_ setHeight:titlebar_overlay_height()];
if (traffic_light_position_) {
[buttons_proxy_ setMargin:*traffic_light_position_];
} else if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
// For macOS >= 11, while this value does not match official macOS apps
// like Safari or Notes, it matches titleBarStyle's old implementation
// before Electron <= 12.
[buttons_proxy_ setMargin:gfx::Point(12, 11)];
}
if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
[buttons_proxy_ setShowOnHover:YES];
} else {
// customButtonsOnHover does not show buttons initially.
InternalSetWindowButtonVisibility(true);
}
}
}
// Create a tab only if tabbing identifier is specified and window has
// a native title bar.
if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
[window_ setTabbingMode:NSWindowTabbingModeDisallowed];
} else {
[window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
}
// Resize to content bounds.
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
if (!has_frame() || use_content_size)
SetContentSize(gfx::Size(width, height));
// Enable the NSView to accept first mouse event.
bool acceptsFirstMouse = false;
options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
[window_ setAcceptsFirstMouse:acceptsFirstMouse];
// Disable auto-hiding cursor.
bool disableAutoHideCursor = false;
options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
[window_ setDisableAutoHideCursor:disableAutoHideCursor];
SetHiddenInMissionControl(hiddenInMissionControl);
// Set maximizable state last to ensure zoom button does not get reset
// by calls to other APIs.
SetMaximizable(maximizable);
// Default content view.
SetContentView(new views::View());
AddContentViewLayers();
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
NativeWindowMac::~NativeWindowMac() = default;
void NativeWindowMac::SetContentView(views::View* view) {
views::View* root_view = GetContentsView();
if (content_view())
root_view->RemoveChildView(content_view());
set_content_view(view);
root_view->AddChildView(content_view());
root_view->Layout();
}
void NativeWindowMac::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
if (fullscreen_transition_state() != FullScreenTransitionState::kNone) {
SetHasDeferredWindowClose(true);
return;
}
// If a sheet is attached to the window when we call
// [window_ performClose:nil], the window won't close properly
// even after the user has ended the sheet.
// Ensure it's closed before calling [window_ performClose:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
if (is_modal() && parent() && IsVisible()) {
NotifyWindowCloseButtonClicked();
}
}
void NativeWindowMac::CloseImmediately() {
// Retain the child window before closing it. If the last reference to the
// NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
// See e.g. http://crbug.com/616701.
base::scoped_nsobject<NSWindow> child_window(window_,
base::scoped_policy::RETAIN);
[window_ close];
}
void NativeWindowMac::Focus(bool focus) {
if (!IsVisible())
return;
if (focus) {
[[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
[window_ makeKeyAndOrderFront:nil];
} else {
[window_ orderOut:nil];
[window_ orderBack:nil];
}
}
bool NativeWindowMac::IsFocused() {
return [window_ isKeyWindow];
}
void NativeWindowMac::Show() {
if (is_modal() && parent()) {
NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
if ([window_ sheetParent] == nil)
[window beginSheet:window_
completionHandler:^(NSModalResponse){
}];
return;
}
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
// This method is supposed to put focus on window, however if the app does not
// have focus then "makeKeyAndOrderFront" will only show the window.
[NSApp activateIgnoringOtherApps:YES];
[window_ makeKeyAndOrderFront:nil];
}
void NativeWindowMac::ShowInactive() {
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
[window_ orderFrontRegardless];
}
void NativeWindowMac::Hide() {
// If a sheet is attached to the window when we call [window_ orderOut:nil],
// the sheet won't be able to show again on the same window.
// Ensure it's closed before calling [window_ orderOut:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
if (is_modal() && parent()) {
[window_ orderOut:nil];
[parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
return;
}
DetachChildren();
// Detach the window from the parent before.
if (parent())
InternalSetParentWindow(parent(), false);
[window_ orderOut:nil];
}
bool NativeWindowMac::IsVisible() {
bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
return [window_ isVisible] && !occluded && !IsMinimized();
}
bool NativeWindowMac::IsEnabled() {
return [window_ attachedSheet] == nil;
}
void NativeWindowMac::SetEnabled(bool enable) {
if (!enable) {
NSRect frame = [window_ frame];
NSWindow* window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width,
frame.size.height)
styleMask:NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
[window setAlphaValue:0.5];
[window_ beginSheet:window
completionHandler:^(NSModalResponse returnCode) {
NSLog(@"main window disabled");
return;
}];
} else if ([window_ attachedSheet]) {
[window_ endSheet:[window_ attachedSheet]];
}
}
void NativeWindowMac::Maximize() {
const bool is_visible = [window_ isVisible];
if (IsMaximized()) {
if (!is_visible)
ShowInactive();
return;
}
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ zoom:nil];
if (!is_visible) {
ShowInactive();
NotifyWindowMaximize();
}
}
void NativeWindowMac::Unmaximize() {
// Bail if the last user set bounds were the same size as the window
// screen (e.g. the user set the window to maximized via setBounds)
//
// Per docs during zoom:
// > If there’s no saved user state because there has been no previous
// > zoom,the size and location of the window don’t change.
//
// However, in classic Apple fashion, this is not the case in practice,
// and the frame inexplicably becomes very tiny. We should prevent
// zoom from being called if the window is being unmaximized and its
// unmaximized window bounds are themselves functionally maximized.
if (!IsMaximized() || user_set_bounds_maximized_)
return;
[window_ zoom:nil];
}
bool NativeWindowMac::IsMaximized() {
// It's possible for [window_ isZoomed] to be true
// when the window is minimized or fullscreened.
if (IsMinimized() || IsFullscreen())
return false;
if (HasStyleMask(NSWindowStyleMaskResizable) != 0)
return [window_ isZoomed];
NSRect rectScreen = GetAspectRatio() > 0.0
? default_frame_for_zoom()
: [[NSScreen mainScreen] visibleFrame];
return NSEqualRects([window_ frame], rectScreen);
}
void NativeWindowMac::Minimize() {
if (IsMinimized())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ miniaturize:nil];
}
void NativeWindowMac::Restore() {
[window_ deminiaturize:nil];
}
bool NativeWindowMac::IsMinimized() {
return [window_ isMiniaturized];
}
bool NativeWindowMac::HandleDeferredClose() {
if (has_deferred_window_close_) {
SetHasDeferredWindowClose(false);
Close();
return true;
}
return false;
}
void NativeWindowMac::RemoveChildWindow(NativeWindow* child) {
child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); });
[window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()];
}
void NativeWindowMac::AttachChildren() {
for (auto* child : child_windows_) {
auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow();
if ([child_nswindow parentWindow] == window_)
continue;
// Attaching a window as a child window resets its window level, so
// save and restore it afterwards.
NSInteger level = window_.level;
[window_ addChildWindow:child_nswindow ordered:NSWindowAbove];
[window_ setLevel:level];
}
}
void NativeWindowMac::DetachChildren() {
DCHECK(child_windows_.size() == [[window_ childWindows] count]);
// Hide all children before hiding/minimizing the window.
// NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown()
// will DCHECK otherwise.
for (auto* child : child_windows_) {
[child->GetNativeWindow().GetNativeNSWindow() orderOut:nil];
}
}
void NativeWindowMac::SetFullScreen(bool fullscreen) {
if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled))
return;
// [NSWindow -toggleFullScreen] is an asynchronous operation, which means
// that it's possible to call it while a fullscreen transition is currently
// in process. This can create weird behavior (incl. phantom windows),
// so we want to schedule a transition for when the current one has completed.
if (fullscreen_transition_state() != FullScreenTransitionState::kNone) {
if (!pending_transitions_.empty()) {
bool last_pending = pending_transitions_.back();
// Only push new transitions if they're different than the last transition
// in the queue.
if (last_pending != fullscreen)
pending_transitions_.push(fullscreen);
} else {
pending_transitions_.push(fullscreen);
}
return;
}
if (fullscreen == IsFullscreen() || !IsFullScreenable())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
// This needs to be set here because it can be the case that
// SetFullScreen is called by a user before windowWillEnterFullScreen
// or windowWillExitFullScreen are invoked, and so a potential transition
// could be dropped.
fullscreen_transition_state_ = fullscreen
? FullScreenTransitionState::kEntering
: FullScreenTransitionState::kExiting;
[window_ toggleFullScreenMode:nil];
}
bool NativeWindowMac::IsFullscreen() const {
return HasStyleMask(NSWindowStyleMaskFullScreen);
}
void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
// Do nothing if in fullscreen mode.
if (IsFullscreen())
return;
// Check size constraints since setFrame does not check it.
gfx::Size size = bounds.size();
size.SetToMax(GetMinimumSize());
gfx::Size max_size = GetMaximumSize();
if (!max_size.IsEmpty())
size.SetToMin(max_size);
NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
// Flip coordinates based on the primary screen.
NSScreen* screen = [[NSScreen screens] firstObject];
cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
[window_ setFrame:cocoa_bounds display:YES animate:animate];
user_set_bounds_maximized_ = IsMaximized() ? true : false;
UpdateWindowOriginalFrame();
}
gfx::Rect NativeWindowMac::GetBounds() {
NSRect frame = [window_ frame];
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
}
bool NativeWindowMac::IsNormal() {
return NativeWindow::IsNormal() && !IsSimpleFullScreen();
}
gfx::Rect NativeWindowMac::GetNormalBounds() {
if (IsNormal()) {
return GetBounds();
}
NSRect frame = original_frame_;
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
// Works on OS_WIN !
// return widget()->GetRestoredBounds();
}
void NativeWindowMac::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
auto convertSize = [this](const gfx::Size& size) {
// Our frameless window still has titlebar attached, so setting contentSize
// will result in actual content size being larger.
if (!has_frame()) {
NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
NSRect content = [window_ originalContentRectForFrameRect:frame];
return content.size;
} else {
return NSMakeSize(size.width(), size.height());
}
};
NSView* content = [window_ contentView];
if (size_constraints.HasMinimumSize()) {
NSSize min_size = convertSize(size_constraints.GetMinimumSize());
[window_ setContentMinSize:[content convertSize:min_size toView:nil]];
}
if (size_constraints.HasMaximumSize()) {
NSSize max_size = convertSize(size_constraints.GetMaximumSize());
[window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
}
NativeWindow::SetContentSizeConstraints(size_constraints);
}
bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
if (id.type != content::DesktopMediaID::TYPE_WINDOW)
return false;
// Check if the window source is valid.
const CGWindowID window_id = id.id;
if (!webrtc::GetWindowOwnerPid(window_id))
return false;
[window_ orderWindow:NSWindowAbove relativeTo:id.id];
return true;
}
void NativeWindowMac::MoveTop() {
[window_ orderWindow:NSWindowAbove relativeTo:0];
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
SetCanResize(resizable);
}
bool NativeWindowMac::IsResizable() {
bool in_fs_transition =
fullscreen_transition_state() != FullScreenTransitionState::kNone;
bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable);
return has_rs_mask && !IsFullscreen() && !in_fs_transition;
}
void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable];
}
bool NativeWindowMac::IsMovable() {
return [window_ isMovable];
}
void NativeWindowMac::SetMinimizable(bool minimizable) {
SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable);
}
bool NativeWindowMac::IsMinimizable() {
return HasStyleMask(NSWindowStyleMaskMiniaturizable);
}
void NativeWindowMac::SetMaximizable(bool maximizable) {
maximizable_ = maximizable;
[[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
}
bool NativeWindowMac::IsMaximizable() {
return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
}
void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
SetCollectionBehavior(fullscreenable,
NSWindowCollectionBehaviorFullScreenPrimary);
// On EL Capitan this flag is required to hide fullscreen button.
SetCollectionBehavior(!fullscreenable,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsFullScreenable() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
}
void NativeWindowMac::SetClosable(bool closable) {
SetStyleMask(closable, NSWindowStyleMaskClosable);
}
bool NativeWindowMac::IsClosable() {
return HasStyleMask(NSWindowStyleMaskClosable);
}
void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level_name,
int relative_level) {
if (z_order == ui::ZOrderLevel::kNormal) {
SetWindowLevel(NSNormalWindowLevel);
return;
}
int level = NSNormalWindowLevel;
if (level_name == "floating") {
level = NSFloatingWindowLevel;
} else if (level_name == "torn-off-menu") {
level = NSTornOffMenuWindowLevel;
} else if (level_name == "modal-panel") {
level = NSModalPanelWindowLevel;
} else if (level_name == "main-menu") {
level = NSMainMenuWindowLevel;
} else if (level_name == "status") {
level = NSStatusWindowLevel;
} else if (level_name == "pop-up-menu") {
level = NSPopUpMenuWindowLevel;
} else if (level_name == "screen-saver") {
level = NSScreenSaverWindowLevel;
}
SetWindowLevel(level + relative_level);
}
std::string NativeWindowMac::GetAlwaysOnTopLevel() {
std::string level_name = "normal";
int level = [window_ level];
if (level == NSFloatingWindowLevel) {
level_name = "floating";
} else if (level == NSTornOffMenuWindowLevel) {
level_name = "torn-off-menu";
} else if (level == NSModalPanelWindowLevel) {
level_name = "modal-panel";
} else if (level == NSMainMenuWindowLevel) {
level_name = "main-menu";
} else if (level == NSStatusWindowLevel) {
level_name = "status";
} else if (level == NSPopUpMenuWindowLevel) {
level_name = "pop-up-menu";
} else if (level == NSScreenSaverWindowLevel) {
level_name = "screen-saver";
}
return level_name;
}
void NativeWindowMac::SetWindowLevel(int unbounded_level) {
int level = std::min(
std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
CGWindowLevelForKey(kCGMaximumWindowLevelKey));
ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
? ui::ZOrderLevel::kNormal
: ui::ZOrderLevel::kFloatingWindow;
bool did_z_order_level_change = z_order_level != GetZOrderLevel();
was_maximizable_ = IsMaximizable();
// We need to explicitly keep the NativeWidget up to date, since it stores the
// window level in a local variable, rather than reading it from the NSWindow.
// Unfortunately, it results in a second setLevel call. It's not ideal, but we
// don't expect this to cause any user-visible jank.
widget()->SetZOrderLevel(z_order_level);
[window_ setLevel:level];
// Set level will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(was_maximizable_);
// This must be notified at the very end or IsAlwaysOnTop
// will not yet have been updated to reflect the new status
if (did_z_order_level_change)
NativeWindow::NotifyWindowAlwaysOnTopChanged();
}
ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() {
return widget()->GetZOrderLevel();
}
void NativeWindowMac::Center() {
[window_ center];
}
void NativeWindowMac::Invalidate() {
[window_ flushWindow];
[[window_ contentView] setNeedsDisplay:YES];
}
void NativeWindowMac::SetTitle(const std::string& title) {
[window_ setTitle:base::SysUTF8ToNSString(title)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetTitle() {
return base::SysNSStringToUTF8([window_ title]);
}
void NativeWindowMac::FlashFrame(bool flash) {
if (flash) {
attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
} else {
[NSApp cancelUserAttentionRequest:attention_request_id_];
attention_request_id_ = 0;
}
}
void NativeWindowMac::SetSkipTaskbar(bool skip) {}
bool NativeWindowMac::IsExcludedFromShownWindowsMenu() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
return [window isExcludedFromWindowsMenu];
}
void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
[window setExcludedFromWindowsMenu:excluded];
}
void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
// We only want to force screen recalibration if we're in simpleFullscreen
// mode.
if (!is_simple_fullscreen_)
return;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
}
void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
if (simple_fullscreen && !is_simple_fullscreen_) {
is_simple_fullscreen_ = true;
// Take note of the current window size and level
if (IsNormal()) {
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
simple_fullscreen_mask_ = [window styleMask];
// We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
// bar
NSApplicationPresentationOptions options =
NSApplicationPresentationAutoHideDock |
NSApplicationPresentationAutoHideMenuBar;
[NSApp setPresentationOptions:options];
was_maximizable_ = IsMaximizable();
was_movable_ = IsMovable();
NSRect fullscreenFrame = [window.screen frame];
// If our app has dock hidden, set the window level higher so another app's
// menu bar doesn't appear on top of our fullscreen app.
if ([[NSRunningApplication currentApplication] activationPolicy] !=
NSApplicationActivationPolicyRegular) {
window.level = NSPopUpMenuWindowLevel;
}
// Always hide the titlebar in simple fullscreen mode.
//
// Note that we must remove the NSWindowStyleMaskTitled style instead of
// using the [window_ setTitleVisibility:], as the latter would leave the
// window with rounded corners.
SetStyleMask(false, NSWindowStyleMaskTitled);
if (!window_button_visibility_.has_value()) {
// Lets keep previous behaviour - hide window controls in titled
// fullscreen mode when not specified otherwise.
InternalSetWindowButtonVisibility(false);
}
[window setFrame:fullscreenFrame display:YES animate:YES];
// Fullscreen windows can't be resized, minimized, maximized, or moved
SetMinimizable(false);
SetResizable(false);
SetMaximizable(false);
SetMovable(false);
} else if (!simple_fullscreen && is_simple_fullscreen_) {
is_simple_fullscreen_ = false;
[window setFrame:original_frame_ display:YES animate:YES];
window.level = original_level_;
[NSApp setPresentationOptions:simple_fullscreen_options_];
// Restore original style mask
ScopedDisableResize disable_resize;
[window_ setStyleMask:simple_fullscreen_mask_];
// Restore window manipulation abilities
SetMaximizable(was_maximizable_);
SetMovable(was_movable_);
// Restore default window controls visibility state.
if (!window_button_visibility_.has_value()) {
bool visibility;
if (has_frame())
visibility = true;
else
visibility = title_bar_style_ != TitleBarStyle::kNormal;
InternalSetWindowButtonVisibility(visibility);
}
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
}
bool NativeWindowMac::IsSimpleFullScreen() {
return is_simple_fullscreen_;
}
void NativeWindowMac::SetKiosk(bool kiosk) {
if (kiosk && !is_kiosk_) {
kiosk_options_ = [NSApp currentSystemPresentationOptions];
NSApplicationPresentationOptions options =
NSApplicationPresentationHideDock |
NSApplicationPresentationHideMenuBar |
NSApplicationPresentationDisableAppleMenu |
NSApplicationPresentationDisableProcessSwitching |
NSApplicationPresentationDisableForceQuit |
NSApplicationPresentationDisableSessionTermination |
NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
is_kiosk_ = true;
fullscreen_before_kiosk_ = IsFullscreen();
if (!fullscreen_before_kiosk_)
SetFullScreen(true);
} else if (!kiosk && is_kiosk_) {
is_kiosk_ = false;
if (!fullscreen_before_kiosk_)
SetFullScreen(false);
// Set presentation options *after* asynchronously exiting
// fullscreen to ensure they take effect.
[NSApp setPresentationOptions:kiosk_options_];
}
}
bool NativeWindowMac::IsKiosk() {
return is_kiosk_;
}
void NativeWindowMac::SetBackgroundColor(SkColor color) {
base::ScopedCFTypeRef<CGColorRef> cgcolor(
skia::CGColorCreateFromSkColor(color));
[[[window_ contentView] layer] setBackgroundColor:cgcolor];
}
SkColor NativeWindowMac::GetBackgroundColor() {
CGColorRef color = [[[window_ contentView] layer] backgroundColor];
if (!color)
return SK_ColorTRANSPARENT;
return skia::CGColorRefToSkColor(color);
}
void NativeWindowMac::SetHasShadow(bool has_shadow) {
[window_ setHasShadow:has_shadow];
}
bool NativeWindowMac::HasShadow() {
return [window_ hasShadow];
}
void NativeWindowMac::InvalidateShadow() {
[window_ invalidateShadow];
}
void NativeWindowMac::SetOpacity(const double opacity) {
const double boundedOpacity = std::clamp(opacity, 0.0, 1.0);
[window_ setAlphaValue:boundedOpacity];
}
double NativeWindowMac::GetOpacity() {
return [window_ alphaValue];
}
void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
[window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetRepresentedFilename() {
return base::SysNSStringToUTF8([window_ representedFilename]);
}
void NativeWindowMac::SetDocumentEdited(bool edited) {
[window_ setDocumentEdited:edited];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
bool NativeWindowMac::IsDocumentEdited() {
return [window_ isDocumentEdited];
}
bool NativeWindowMac::IsHiddenInMissionControl() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorTransient;
}
void NativeWindowMac::SetHiddenInMissionControl(bool hidden) {
SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient);
}
void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
[window_ setIgnoresMouseEvents:ignore];
if (!ignore) {
SetForwardMouseMessages(NO);
} else {
SetForwardMouseMessages(forward);
}
}
void NativeWindowMac::SetContentProtection(bool enable) {
[window_
setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
}
void NativeWindowMac::SetFocusable(bool focusable) {
// No known way to unfocus the window if it had the focus. Here we do not
// want to call Focus(false) because it moves the window to the back, i.e.
// at the bottom in term of z-order.
[window_ setDisableKeyOrMainWindow:!focusable];
}
bool NativeWindowMac::IsFocusable() {
return ![window_ disableKeyOrMainWindow];
}
void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
if (view->GetInspectableWebContentsView())
[view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
removeFromSuperview];
remove_browser_view(view);
[CATransaction commit];
}
void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
remove_browser_view(view);
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
InternalSetParentWindow(parent, IsVisible());
}
gfx::NativeView NativeWindowMac::GetNativeView() const {
return [window_ contentView];
}
gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
return window_;
}
gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
return [window_ windowNumber];
}
content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
auto desktop_media_id = content::DesktopMediaID(
content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget());
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc
// Refs https://github.com/electron/electron/pull/30507
// TODO(deepak1556): Match upstream for `kWindowCaptureMacV2`
#if 0
if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) {
desktop_media_id.window_id = desktop_media_id.id;
}
#endif
return desktop_media_id;
}
NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
return [window_ contentView];
}
void NativeWindowMac::SetProgressBar(double progress,
const NativeWindow::ProgressState state) {
NSDockTile* dock_tile = [NSApp dockTile];
// Sometimes macOS would install a default contentView for dock, we must
// verify whether NSProgressIndicator has been installed.
bool first_time = !dock_tile.contentView ||
[[dock_tile.contentView subviews] count] == 0 ||
![[[dock_tile.contentView subviews] lastObject]
isKindOfClass:[NSProgressIndicator class]];
// For the first time API invoked, we need to create a ContentView in
// DockTile.
if (first_time) {
NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
[image_view setImage:[NSApp applicationIconImage]];
[dock_tile setContentView:image_view];
NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
NSProgressIndicator* progress_indicator =
[[[ElectronProgressBar alloc] initWithFrame:frame] autorelease];
[progress_indicator setStyle:NSProgressIndicatorBarStyle];
[progress_indicator setIndeterminate:NO];
[progress_indicator setBezeled:YES];
[progress_indicator setMinValue:0];
[progress_indicator setMaxValue:1];
[progress_indicator setHidden:NO];
[dock_tile.contentView addSubview:progress_indicator];
}
NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
[[[dock_tile contentView] subviews] lastObject]);
if (progress < 0) {
[progress_indicator setHidden:YES];
} else if (progress > 1) {
[progress_indicator setHidden:NO];
[progress_indicator setIndeterminate:YES];
[progress_indicator setDoubleValue:1];
} else {
[progress_indicator setHidden:NO];
[progress_indicator setDoubleValue:progress];
}
[dock_tile display];
}
void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {}
void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) {
// In order for NSWindows to be visible on fullscreen we need to invoke
// app.dock.hide() since Apple changed the underlying functionality of
// NSWindows starting with 10.14 to disallow NSWindows from floating on top of
// fullscreen apps.
if (!skipTransformProcessType) {
if (visibleOnFullScreen) {
Browser::Get()->DockHide();
} else {
Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate());
}
}
SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
SetCollectionBehavior(visibleOnFullScreen,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
}
void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
[window_ setDisableAutoHideCursor:!auto_hide];
}
void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (vibrantView != nil && !vibrancy_type_.empty()) {
const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled);
if (!has_frame() && !is_modal() && !no_rounded_corner) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (@available(macOS 11.0, *)) {
radius = 9.0f;
} else {
// Smaller corner radius on versions prior to Big Sur.
radius = 5.0f;
}
CGFloat dimension = 2 * radius + 1;
NSSize size = NSMakeSize(dimension, dimension);
NSImage* maskImage = [NSImage imageWithSize:size
flipped:NO
drawingHandler:^BOOL(NSRect rect) {
NSBezierPath* bezierPath = [NSBezierPath
bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[[NSColor blackColor] set];
[bezierPath fill];
return YES;
}];
[maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
[maskImage setResizingMode:NSImageResizingModeStretch];
[vibrantView setMaskImage:maskImage];
[window_ setCornerMask:maskImage];
}
}
}
void NativeWindowMac::UpdateWindowOriginalFrame() {
original_frame_ = [window_ frame];
}
void NativeWindowMac::SetVibrancy(const std::string& type) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (type.empty()) {
if (vibrantView == nil)
return;
[vibrantView removeFromSuperview];
[window_ setVibrantView:nil];
return;
}
std::string dep_warn = " has been deprecated and removed as of macOS 10.15.";
node::Environment* env =
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate());
NSVisualEffectMaterial vibrancyType{};
if (type == "appearance-based") {
EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialAppearanceBased;
} else if (type == "light") {
EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialLight;
} else if (type == "dark") {
EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialDark;
} else if (type == "titlebar") {
vibrancyType = NSVisualEffectMaterialTitlebar;
}
if (type == "selection") {
vibrancyType = NSVisualEffectMaterialSelection;
} else if (type == "menu") {
vibrancyType = NSVisualEffectMaterialMenu;
} else if (type == "popover") {
vibrancyType = NSVisualEffectMaterialPopover;
} else if (type == "sidebar") {
vibrancyType = NSVisualEffectMaterialSidebar;
} else if (type == "medium-light") {
EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialMediumLight;
} else if (type == "ultra-dark") {
EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialUltraDark;
}
if (@available(macOS 10.14, *)) {
if (type == "header") {
vibrancyType = NSVisualEffectMaterialHeaderView;
} else if (type == "sheet") {
vibrancyType = NSVisualEffectMaterialSheet;
} else if (type == "window") {
vibrancyType = NSVisualEffectMaterialWindowBackground;
} else if (type == "hud") {
vibrancyType = NSVisualEffectMaterialHUDWindow;
} else if (type == "fullscreen-ui") {
vibrancyType = NSVisualEffectMaterialFullScreenUI;
} else if (type == "tooltip") {
vibrancyType = NSVisualEffectMaterialToolTip;
} else if (type == "content") {
vibrancyType = NSVisualEffectMaterialContentBackground;
} else if (type == "under-window") {
vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
} else if (type == "under-page") {
vibrancyType = NSVisualEffectMaterialUnderPageBackground;
}
}
if (vibrancyType) {
vibrancy_type_ = type;
if (vibrantView == nil) {
vibrantView = [[[NSVisualEffectView alloc]
initWithFrame:[[window_ contentView] bounds]] autorelease];
[window_ setVibrantView:vibrantView];
[vibrantView
setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
if (visual_effect_state_ == VisualEffectState::kActive) {
[vibrantView setState:NSVisualEffectStateActive];
} else if (visual_effect_state_ == VisualEffectState::kInactive) {
[vibrantView setState:NSVisualEffectStateInactive];
} else {
[vibrantView setState:NSVisualEffectStateFollowsWindowActiveState];
}
[[window_ contentView] addSubview:vibrantView
positioned:NSWindowBelow
relativeTo:nil];
UpdateVibrancyRadii(IsFullscreen());
}
[vibrantView setMaterial:vibrancyType];
}
}
void NativeWindowMac::SetWindowButtonVisibility(bool visible) {
window_button_visibility_ = visible;
if (buttons_proxy_) {
if (visible)
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:visible];
}
if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover)
InternalSetWindowButtonVisibility(visible);
NotifyLayoutWindowControlsOverlay();
}
bool NativeWindowMac::GetWindowButtonVisibility() const {
return ![window_ standardWindowButton:NSWindowZoomButton].hidden ||
![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden ||
![window_ standardWindowButton:NSWindowCloseButton].hidden;
}
void NativeWindowMac::SetWindowButtonPosition(
absl::optional<gfx::Point> position) {
traffic_light_position_ = std::move(position);
if (buttons_proxy_) {
[buttons_proxy_ setMargin:traffic_light_position_];
NotifyLayoutWindowControlsOverlay();
}
}
absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const {
return traffic_light_position_;
}
void NativeWindowMac::RedrawTrafficLights() {
if (buttons_proxy_ && !IsFullscreen())
[buttons_proxy_ redraw];
}
// In simpleFullScreen mode, update the frame for new bounds.
void NativeWindowMac::UpdateFrame() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
NSRect fullscreenFrame = [window.screen frame];
[window setFrame:fullscreenFrame display:YES animate:YES];
}
void NativeWindowMac::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
touch_bar_.reset([[ElectronTouchBar alloc]
initWithDelegate:window_delegate_.get()
window:this
settings:std::move(items)]);
[window_ setTouchBar:nil];
}
void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
}
void NativeWindowMac::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ setEscapeTouchBarItem:std::move(item)
forTouchBar:[window_ touchBar]];
}
void NativeWindowMac::SelectPreviousTab() {
[window_ selectPreviousTab:nil];
}
void NativeWindowMac::SelectNextTab() {
[window_ selectNextTab:nil];
}
void NativeWindowMac::MergeAllWindows() {
[window_ mergeAllWindows:nil];
}
void NativeWindowMac::MoveTabToNewWindow() {
[window_ moveTabToNewWindow:nil];
}
void NativeWindowMac::ToggleTabBar() {
[window_ toggleTabBar:nil];
}
bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
return false;
} else {
[window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
ordered:NSWindowAbove];
}
return true;
}
void NativeWindowMac::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
// Reset the behaviour to default if aspect_ratio is set to 0 or less.
if (aspect_ratio > 0.0) {
NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0);
if (has_frame())
[window_ setContentAspectRatio:aspect_ratio_size];
else
[window_ setAspectRatio:aspect_ratio_size];
} else {
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
}
void NativeWindowMac::PreviewFile(const std::string& path,
const std::string& display_name) {
preview_item_.reset([[ElectronPreviewItem alloc]
initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
title:base::SysUTF8ToNSString(display_name)]);
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
}
void NativeWindowMac::CloseFilePreview() {
if ([QLPreviewPanel sharedPreviewPanelExists]) {
[[QLPreviewPanel sharedPreviewPanel] close];
}
}
gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect window_bounds(
[window_ frameRectForContentRect:bounds.ToCGRect()]);
int frame_height = window_bounds.height() - bounds.height();
window_bounds.set_y(window_bounds.y() - frame_height);
return window_bounds;
} else {
return bounds;
}
}
gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect content_bounds(
[window_ contentRectForFrameRect:bounds.ToCGRect()]);
int frame_height = bounds.height() - content_bounds.height();
content_bounds.set_y(content_bounds.y() + frame_height);
return content_bounds;
} else {
return bounds;
}
}
void NativeWindowMac::NotifyWindowEnterFullScreen() {
NativeWindow::NotifyWindowEnterFullScreen();
// Restore the window title under fullscreen mode.
if (buttons_proxy_)
[window_ setTitleVisibility:NSWindowTitleVisible];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
}
void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
UpdateVibrancyRadii(true);
}
void NativeWindowMac::NotifyWindowWillLeaveFullScreen() {
if (buttons_proxy_) {
// Hide window title when leaving fullscreen.
[window_ setTitleVisibility:NSWindowTitleHidden];
// Hide the container otherwise traffic light buttons jump.
[buttons_proxy_ setVisible:NO];
}
UpdateVibrancyRadii(false);
}
void NativeWindowMac::SetActive(bool is_key) {
is_active_ = is_key;
}
bool NativeWindowMac::IsActive() const {
return is_active_;
}
void NativeWindowMac::Cleanup() {
DCHECK(!IsClosed());
ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
}
class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {
public:
NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window)
: views::NativeFrameViewMac(frame), native_window_(window) {}
NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete;
NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) =
delete;
~NativeAppWindowFrameViewMac() override = default;
// NonClientFrameView:
int NonClientHitTest(const gfx::Point& point) override {
if (!bounds().Contains(point))
return HTNOWHERE;
if (GetWidget()->IsFullscreen())
return HTCLIENT;
// Check for possible draggable region in the client area for the frameless
// window.
int contents_hit_test = native_window_->NonClientHitTest(point);
if (contents_hit_test != HTNOWHERE)
return contents_hit_test;
return HTCLIENT;
}
private:
// Weak.
raw_ptr<NativeWindowMac> const native_window_;
};
std::unique_ptr<views::NonClientFrameView>
NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) {
return std::make_unique<NativeAppWindowFrameViewMac>(widget, this);
}
bool NativeWindowMac::HasStyleMask(NSUInteger flag) const {
return [window_ styleMask] & flag;
}
void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
// Changing the styleMask of a frameless windows causes it to change size so
// we explicitly disable resizing while setting it.
ScopedDisableResize disable_resize;
if (on)
[window_ setStyleMask:[window_ styleMask] | flag];
else
[window_ setStyleMask:[window_ styleMask] & (~flag)];
// Change style mask will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
if (on)
[window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
else
[window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
// Change collectionBehavior will make the zoom button revert to default,
// probably a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
views::View* NativeWindowMac::GetContentsView() {
return root_view_.get();
}
bool NativeWindowMac::CanMaximize() const {
return maximizable_;
}
void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
}
void NativeWindowMac::AddContentViewLayers() {
// Make sure the bottom corner is rounded for non-modal windows:
// http://crbug.com/396264.
if (!is_modal()) {
// For normal window, we need to explicitly set layer for contentView to
// make setBackgroundColor work correctly.
// There is no need to do so for frameless window, and doing so would make
// titleBarStyle stop working.
if (has_frame()) {
base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
[background_layer
setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
[[window_ contentView] setLayer:background_layer];
}
[[window_ contentView] setWantsLayer:YES];
}
}
void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) {
[[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
}
void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
bool attach) {
if (is_modal())
return;
NativeWindow::SetParentWindow(parent);
// Do not remove/add if we are already properly attached.
if (attach && parent &&
[window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
return;
// Remove current parent window.
if ([window_ parentWindow])
parent->RemoveChildWindow(this);
// Set new parent window.
if (parent && attach) {
parent->add_child_window(this);
parent->AttachChildren();
}
}
void NativeWindowMac::SetForwardMouseMessages(bool forward) {
[window_ setAcceptsMouseMovedEvents:forward];
}
gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() {
if (titlebar_overlay_ && buttons_proxy_ &&
window_button_visibility_.value_or(true)) {
NSRect buttons = [buttons_proxy_ getButtonsContainerBounds];
gfx::Rect overlay;
overlay.set_width(GetContentSize().width() - NSWidth(buttons));
if ([buttons_proxy_ useCustomHeight]) {
overlay.set_height(titlebar_overlay_height());
} else {
overlay.set_height(NSHeight(buttons));
}
if (!base::i18n::IsRTL())
overlay.set_x(NSMaxX(buttons));
return overlay;
}
return gfx::Rect();
}
// static
NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
NativeWindow* parent) {
return new NativeWindowMac(options, parent);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,562 |
[Bug]: Crash when opening and closing a child window a few times on macOS
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
macOS
### Operating System Version
Ventura 13.4
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
A child window should be able to be opened and closed multiple times without crashing.
### Actual Behavior
The Electron app crashes after opening a child window and then closing it. This usually happens after opening the child window a few times in a row.
### Testcase Gist URL
https://gist.github.com/jorodi/cbf4378f978e44de5034ab2d91f30387
### Additional Information
Caught error output from VS code terminal:
```
2023-06-02 08:24:57.023 Electron[80994:4778831] -[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f
2023-06-02 08:24:57.025 Electron[80994:4778831] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff802c7918a __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80279f42b objc_exception_throw + 48
2 CoreFoundation 0x00007ff802d14fef -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007ff802be4797 ___forwarding___ + 1392
4 CoreFoundation 0x00007ff802be4198 _CF_forwarding_prep_0 + 120
5 Electron Framework 0x000000010b707e38 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 154760
6 Electron Framework 0x000000010b7073e0 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 152112
7 Electron Framework 0x000000010b646b23 _ZN2v89CodeEvent10GetCommentEv + 4099
8 Electron Framework 0x000000010b56dc93 ElectronInitializeICUandStartNode + 207619
9 Electron Framework 0x000000010b56f2c4 ElectronInitializeICUandStartNode + 213300
10 Electron Framework 0x000000010b56f9fe ElectronInitializeICUandStartNode + 215150
11 Electron Framework 0x000000010b5634e1 ElectronInitializeICUandStartNode + 164689
12 Electron Framework 0x000000010b5633d3 ElectronInitializeICUandStartNode + 164419
13 Electron Framework 0x000000010c83be34 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 15780
14 Electron Framework 0x000000010c83b9df _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 14671
15 Electron Framework 0x000000010c83ad24 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 11412
16 Electron Framework 0x000000010b25edf6 Electron Framework + 826870
17 Electron Framework 0x000000010b1c4ff2 Electron Framework + 196594
)
/Users/jordan/parent-child-error/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGILL
```
|
https://github.com/electron/electron/issues/38562
|
https://github.com/electron/electron/pull/38603
|
9a9d8ae5ea61e17fd01e8975e81ed2a137a5fef6
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
| 2023-06-02T13:02:06Z |
c++
| 2023-06-08T10:18:37Z |
spec/api-browser-window-spec.ts
|
import { expect } from 'chai';
import * as childProcess from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import * as qs from 'querystring';
import * as http from 'http';
import * as os from 'os';
import { AddressInfo } from 'net';
import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main';
import { emittedUntil, emittedNTimes } from './lib/events-helpers';
import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers';
import { once } from 'events';
import { setTimeout } from 'timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixtures = path.resolve(__dirname, 'fixtures');
const mainFixtures = path.resolve(__dirname, 'fixtures');
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
const { scaleFactor } = screen.getPrimaryDisplay();
// Return true if scale factor is non-integer value
if (Math.round(scaleFactor) !== scaleFactor) return true;
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1;
};
const expectBoundsEqual = (actual: any, expected: any) => {
if (!isScaleFactorRounding()) {
expect(expected).to.deep.equal(actual);
} else if (Array.isArray(actual)) {
expect(actual[0]).to.be.closeTo(expected[0], 1);
expect(actual[1]).to.be.closeTo(expected[1], 1);
} else {
expect(actual.x).to.be.closeTo(expected.x, 1);
expect(actual.y).to.be.closeTo(expected.y, 1);
expect(actual.width).to.be.closeTo(expected.width, 1);
expect(actual.height).to.be.closeTo(expected.height, 1);
}
};
const isBeforeUnload = (event: Event, level: number, message: string) => {
return (message === 'beforeunload');
};
describe('BrowserWindow module', () => {
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
expect(() => {
const w = new BrowserWindow({
show: false,
// apparently void 0 had different behaviour from undefined in the
// issue that this test is supposed to catch.
webContents: void 0 // eslint-disable-line no-void
} as any);
w.destroy();
}).not.to.throw();
});
ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
const appProcess = childProcess.spawn(process.execPath, [appPath]);
await once(appProcess, 'exit');
});
it('does not crash or throw when passed an invalid icon', async () => {
expect(() => {
const w = new BrowserWindow({
icon: undefined
} as any);
w.destroy();
}).not.to.throw();
});
});
describe('garbage collection', () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
afterEach(closeAllWindows);
it('window does not get garbage collected when opened', async () => {
const w = new BrowserWindow({ show: false });
// Keep a weak reference to the window.
const wr = new WeakRef(w);
await setTimeout();
// Do garbage collection, since |w| is not referenced in this closure
// it would be gone after next call if there is no other reference.
v8Util.requestGarbageCollectionForTesting();
await setTimeout();
expect(wr.deref()).to.not.be.undefined();
});
});
describe('BrowserWindow.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should work if called when a messageBox is showing', async () => {
const closed = once(w, 'closed');
dialog.showMessageBox(w, { message: 'Hello Error' });
w.close();
await closed;
});
it('closes window without rounded corners', async () => {
await closeWindow(w);
w = new BrowserWindow({ show: false, frame: false, roundedCorners: false });
const closed = once(w, 'closed');
w.close();
await closed;
});
it('should not crash if called after webContents is destroyed', () => {
w.webContents.destroy();
w.webContents.on('destroyed', () => w.close());
});
it('should allow access to id after destruction', async () => {
const closed = once(w, 'closed');
w.destroy();
await closed;
expect(w.id).to.be.a('number');
});
it('should emit unload handler', async () => {
await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
const closed = once(w, 'closed');
w.close();
await closed;
const test = path.join(fixtures, 'api', 'unload');
const content = fs.readFileSync(test);
fs.unlinkSync(test);
expect(String(content)).to.equal('unload');
});
it('should emit beforeunload handler', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'before-unload-fired');
});
it('should not crash when keyboard event is sent before closing', async () => {
await w.loadURL('data:text/html,pls no crash');
const closed = once(w, 'closed');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
w.close();
await closed;
});
describe('when invoked synchronously inside navigation observer', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/301':
response.statusCode = 301;
response.setHeader('Location', '/200');
response.end();
break;
case '/200':
response.statusCode = 200;
response.end('hello');
break;
case '/title':
response.statusCode = 200;
response.end('<title>Hello</title>');
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', path: '/200' },
{ name: 'dom-ready', path: '/200' },
{ name: 'page-title-updated', path: '/title' },
{ name: 'did-stop-loading', path: '/200' },
{ name: 'did-finish-load', path: '/200' },
{ name: 'did-frame-finish-load', path: '/200' },
{ name: 'did-fail-load', path: '/net-error' }
];
for (const { name, path } of events) {
it(`should not crash when closed during ${name}`, async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once((name as any), () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.webContents.loadURL(url + path);
await destroyed;
});
}
});
});
describe('window.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload event', async () => {
w.loadFile(path.join(fixtures, 'api', 'close.html'));
await once(w, 'closed');
const test = path.join(fixtures, 'api', 'close');
const content = fs.readFileSync(test).toString();
fs.unlinkSync(test);
expect(content).to.equal('close');
});
it('should emit beforeunload event', async function () {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.webContents.executeJavaScript('window.close()', true);
await once(w.webContents, 'before-unload-fired');
});
});
describe('BrowserWindow.destroy()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('prevents users to access methods of webContents', async () => {
const contents = w.webContents;
w.destroy();
await new Promise(setImmediate);
expect(() => {
contents.getProcessId();
}).to.throw('Object has been destroyed');
});
it('should not crash when destroying windows with pending events', () => {
const focusListener = () => { };
app.on('browser-window-focus', focusListener);
const windowCount = 3;
const windowOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show());
windows.forEach(win => win.focus());
windows.forEach(win => win.destroy());
app.removeListener('browser-window-focus', focusListener);
});
});
describe('BrowserWindow.loadURL(url)', () => {
let w: BrowserWindow;
const scheme = 'other';
const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
callback(srcPath);
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
let server: http.Server;
let url: string;
let postData = null as any;
before(async () => {
const filePath = path.join(fixtures, 'pages', 'a.html');
const fileStats = fs.statSync(filePath);
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
];
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
let body = '';
req.on('data', (data) => {
if (data) body += data;
});
req.on('end', () => {
const parsedData = qs.parse(body);
fs.readFile(filePath, (err, data) => {
if (err) return;
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end();
}
});
});
} else if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
}
setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond);
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('should emit did-start-loading event', async () => {
const didStartLoading = once(w.webContents, 'did-start-loading');
w.loadURL('about:blank');
await didStartLoading;
});
it('should emit ready-to-show event', async () => {
const readyToShow = once(w, 'ready-to-show');
w.loadURL('about:blank');
await readyToShow;
});
// DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
// changed and adjust the test.
it('should emit did-fail-load event for files that do not exist', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('file://a.txt');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(code).to.equal(-6);
expect(desc).to.equal('ERR_FILE_NOT_FOUND');
expect(isMainFrame).to.equal(true);
});
it('should emit did-fail-load event for invalid URL', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('http://example:port');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should not emit did-fail-load for a successfully loaded media file', async () => {
w.webContents.on('did-fail-load', () => {
expect.fail('did-fail-load should not emit on media file loads');
});
const mediaStarted = once(w.webContents, 'media-started-playing');
w.loadFile(path.join(fixtures, 'cat-spin.mp4'));
await mediaStarted;
});
it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
const [,,,, isMainFrame] = await didFailLoad;
expect(isMainFrame).to.equal(false);
});
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
w.loadURL('http://127.0.0.1:11111');
done();
});
w.loadURL('http://127.0.0.1:11111');
});
it('should emit did-fail-load event for URL exceeding character limit', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL(`data:image/png;base64,${data}`);
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should return a promise', () => {
const p = w.loadURL('about:blank');
expect(p).to.have.property('then');
});
it('should return a promise that resolves', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('should return a promise that rejects on a load failure', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const p = w.loadURL(`data:image/png;base64,${data}`);
await expect(p).to.eventually.be.rejected;
});
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
await expect(p).to.eventually.be.fulfilled;
});
describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
it('supports specifying POST data', async () => {
await w.loadURL(url, { postData });
});
it('sets the content type header on URL encoded forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
});
it('sets the content type header on multi part forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
});
});
it('should support base url for data urls', async () => {
await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
});
});
for (const sandbox of [false, true]) {
describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('will-navigate event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-navigate');
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
await event;
w.close();
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame);
let initiator: WebFrameMain | undefined;
w.webContents.on('will-navigate', (e) => {
initiator = e.initiator;
});
const subframe = w.webContents.mainFrame.frames[0];
subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true);
await once(w.webContents, 'did-navigate');
expect(initiator).not.to.be.undefined();
expect(initiator).to.equal(subframe);
});
});
describe('will-frame-navigate event', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else if (req.url === '/navigate-iframe') {
res.end('<a href="/test">navigate iframe</a>');
} else if (req.url === '/navigate-iframe?navigated') {
res.end('Successfully navigated');
} else if (req.url === '/navigate-iframe-immediately') {
res.end(`
<script type="text/javascript" charset="utf-8">
location.href += '?navigated'
</script>
`);
} else if (req.url === '/navigate-iframe-immediately?navigated') {
res.end('Successfully navigated');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-frame-navigate', () => {
w.close();
done();
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented when navigating subframe', (done) => {
let willNavigate = false;
w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
if (isMainFrame) return;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(frame).to.not.be.undefined();
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
});
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`);
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await setTimeout(1000);
let willFrameNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willFrameNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willFrameNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.true();
});
it('is triggered when a cross-origin iframe navigates itself', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`);
await setTimeout(1000);
let willNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-frame-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.false();
});
it('can cancel when a cross-origin iframe navigates itself', async () => {
});
});
describe('will-redirect event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else if (req.url === '/navigate-302') {
res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
} else {
res.end();
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is emitted on redirects', async () => {
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
});
it('is emitted after will-navigate on redirects', async () => {
let navigateCalled = false;
w.webContents.on('will-navigate', () => {
navigateCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/navigate-302`);
await willRedirect;
expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
});
it('is emitted before did-stop-loading on redirects', async () => {
let stopCalled = false;
w.webContents.on('did-stop-loading', () => {
stopCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await event;
w.close();
});
it('can be prevented', (done) => {
w.webContents.once('will-redirect', (event) => {
event.preventDefault();
});
w.webContents.on('will-navigate', (e, u) => {
expect(u).to.equal(`${url}/302`);
});
w.webContents.on('did-stop-loading', () => {
try {
expect(w.webContents.getURL()).to.equal(
`${url}/navigate-302`,
'url should not have changed after navigation event'
);
done();
} catch (e) {
done(e);
}
});
w.webContents.on('will-redirect', (e, u) => {
try {
expect(u).to.equal(`${url}/200`);
} catch (e) {
done(e);
}
});
w.loadURL(`${url}/navigate-302`);
});
});
describe('ordering', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
const navigationEvents = [
'did-start-navigation',
'did-navigate-in-page',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate') {
res.end('<a href="/">navigate</a>');
} else if (req.url === '/redirect') {
res.end('<a href="/redirect2">redirect</a>');
} else if (req.url === '/redirect2') {
res.statusCode = 302;
res.setHeader('location', url);
res.end();
} else if (req.url === '/in-page') {
res.end('<a href="#in-page">redirect</a><div id="in-page"></div>');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
it('for initial navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-frame-navigate',
'did-navigate'
];
const allEvents = Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const timeout = setTimeout(1000);
w.loadURL(url);
await Promise.race([allEvents, timeout]);
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('for second navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}navigate`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating with redirection, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}redirect`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating in-page, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-navigate-in-page'
];
w.loadURL(`${url}in-page`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate-in-page');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
});
});
}
describe('focus and visibility', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.show()', () => {
it('should focus on window', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isFocused()).to.equal(true);
});
it('should make the window visible', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isVisible()).to.equal(true);
});
it('emits when window is shown', async () => {
const show = once(w, 'show');
w.show();
await show;
expect(w.isVisible()).to.equal(true);
});
});
describe('BrowserWindow.hide()', () => {
it('should defocus on window', () => {
w.hide();
expect(w.isFocused()).to.equal(false);
});
it('should make the window not visible', () => {
w.show();
w.hide();
expect(w.isVisible()).to.equal(false);
});
it('emits when window is hidden', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const hidden = once(w, 'hide');
w.hide();
await hidden;
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.minimize()', () => {
// TODO(codebytere): Enable for Linux once maximize/minimize events work in CI.
ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => {
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMinimized()).to.equal(true);
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
w.showInactive();
expect(w.isFocused()).to.equal(false);
});
// TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests
ifit(process.platform !== 'linux')('should not restore maximized windows', async () => {
const maximize = once(w, 'maximize');
const shown = once(w, 'show');
w.maximize();
// TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden
if (process.platform !== 'darwin') {
await maximize;
} else {
await setTimeout(1000);
}
w.showInactive();
await shown;
expect(w.isMaximized()).to.equal(true);
});
});
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
expect(w.isVisible()).to.equal(false);
w.focus();
expect(w.isVisible()).to.equal(false);
});
ifit(process.platform !== 'win32')('focuses a blurred window', async () => {
{
const isBlurred = once(w, 'blur');
const isShown = once(w, 'show');
w.show();
w.blur();
await isShown;
await isBlurred;
}
expect(w.isFocused()).to.equal(false);
w.focus();
expect(w.isFocused()).to.equal(true);
});
ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w1.focus();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w2.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w3.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
// TODO(RaisinTen): Make this work on Windows too.
// Refs: https://github.com/electron/electron/issues/20464.
ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => {
it('removes focus from window', async () => {
{
const isFocused = once(w, 'focus');
const isShown = once(w, 'show');
w.show();
await isShown;
await isFocused;
}
expect(w.isFocused()).to.equal(true);
w.blur();
expect(w.isFocused()).to.equal(false);
});
ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w3.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w2.blur();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w1.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', async () => {
const p = once(w, 'focus');
w.show();
await p;
w.webContents.openDevTools({ mode: 'undocked' });
await once(w.webContents, 'devtools-focused');
expect(BrowserWindow.getFocusedWindow()).to.equal(w);
});
});
describe('BrowserWindow.moveTop()', () => {
it('should not steal focus', async () => {
const posDelta = 50;
const wShownInactive = once(w, 'show');
w.showInactive();
await wShownInactive;
expect(w.isFocused()).to.equal(false);
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
const otherWindowShown = once(otherWindow, 'show');
const otherWindowFocused = once(otherWindow, 'focus');
otherWindow.show();
await otherWindowShown;
await otherWindowFocused;
expect(otherWindow.isFocused()).to.equal(true);
w.moveTop();
const wPos = w.getPosition();
const wMoving = once(w, 'move');
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
await wMoving;
expect(w.isFocused()).to.equal(false);
expect(otherWindow.isFocused()).to.equal(true);
const wFocused = once(w, 'focus');
const otherWindowBlurred = once(otherWindow, 'blur');
w.focus();
await wFocused;
await otherWindowBlurred;
expect(w.isFocused()).to.equal(true);
otherWindow.moveTop();
const otherWindowPos = otherWindow.getPosition();
const otherWindowMoving = once(otherWindow, 'move');
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
await otherWindowMoving;
expect(otherWindow.isFocused()).to.equal(false);
expect(w.isFocused()).to.equal(true);
await closeWindow(otherWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
});
});
describe('BrowserWindow.moveAbove(mediaSourceId)', () => {
it('should throw an exception if wrong formatting', async () => {
const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should throw an exception if wrong type', async () => {
const fakeSourceIds = [null as any, 123 as any];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */);
});
});
it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
'window:123456:9'];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should not throw an exception', async () => {
const w2 = new BrowserWindow({ show: false, title: 'window2' });
const w2Shown = once(w2, 'show');
w2.show();
await w2Shown;
expect(() => {
w.moveAbove(w2.getMediaSourceId());
}).to.not.throw();
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.setFocusable()', () => {
it('can set unfocusable window to focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
const w2Focused = once(w2, 'focus');
w2.setFocusable(true);
w2.focus();
await w2Focused;
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.isFocusable()', () => {
it('correctly returns whether a window is focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
expect(w2.isFocusable()).to.be.false();
w2.setFocusable(true);
expect(w2.isFocusable()).to.be.true();
await closeWindow(w2, { assertNotWindows: false });
});
});
});
describe('sizing', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, width: 400, height: 400 });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
it('sets the window bounds with full bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
expectBoundsEqual(w.getBounds(), fullBounds);
});
it('sets the window bounds with partial bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
const boundsUpdate = { width: 200 };
w.setBounds(boundsUpdate as any);
const expectedBounds = { ...fullBounds, ...boundsUpdate };
expectBoundsEqual(w.getBounds(), expectedBounds);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds, true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
const size = [300, 400];
const resized = once(w, 'resize');
w.setSize(size[0], size[1]);
await resized;
expectBoundsEqual(w.getSize(), size);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const size = [300, 400];
w.setSize(size[0], size[1], true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
expect(w.getMinimumSize()).to.deep.equal([0, 0]);
expect(w.getMaximumSize()).to.deep.equal([0, 0]);
w.setMinimumSize(100, 100);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [0, 0]);
w.setMaximumSize(900, 600);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [900, 600]);
});
});
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', async () => {
const size = [300, 400];
w.setAspectRatio(1 / 2);
w.setAspectRatio(0);
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getSize(), size);
});
it('doesn\'t change bounds when maximum size is set', () => {
w.setMenu(null);
w.setMaximumSize(400, 400);
// Without https://github.com/electron/electron/pull/29101
// following call would shrink the window to 384x361.
// There would be also DCHECK in resize_utils.cc on
// debug build.
w.setAspectRatio(1.0);
expectBoundsEqual(w.getSize(), [400, 400]);
});
});
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expect(w.getPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', async () => {
// NB. The CI server has a very small screen. Attempting to size the window
// larger than the screen will limit the window's size to the screen and
// cause the test to fail.
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
});
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
});
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', async () => {
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
});
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
});
describe('BrowserWindow.getBackgroundColor()', () => {
it('returns default value if no backgroundColor is set', () => {
w.destroy();
w = new BrowserWindow({});
expect(w.getBackgroundColor()).to.equal('#FFFFFF');
});
it('returns correct value if backgroundColor is set', () => {
const backgroundColor = '#BBAAFF';
w.destroy();
w = new BrowserWindow({
backgroundColor: backgroundColor
});
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct value from setBackgroundColor()', () => {
const backgroundColor = '#AABBFF';
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor(backgroundColor);
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct color with multiple passed formats', () => {
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor('#AABBFF');
expect(w.getBackgroundColor()).to.equal('#AABBFF');
w.setBackgroundColor('blueviolet');
expect(w.getBackgroundColor()).to.equal('#8A2BE2');
w.setBackgroundColor('rgb(255, 0, 185)');
expect(w.getBackgroundColor()).to.equal('#FF00B9');
w.setBackgroundColor('rgba(245, 40, 145, 0.8)');
expect(w.getBackgroundColor()).to.equal('#F52891');
w.setBackgroundColor('hsl(155, 100%, 50%)');
expect(w.getBackgroundColor()).to.equal('#00FF95');
});
});
describe('BrowserWindow.getNormalBounds()', () => {
describe('Normal state', () => {
it('checks normal bounds after resize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
it('checks normal bounds after move', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
});
ifdescribe(process.platform !== 'linux')('Maximized state', () => {
it('checks normal bounds when maximized', async () => {
const bounds = w.getBounds();
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and maximize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and maximize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unmaximized', async () => {
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly reports maximized state after maximizing then minimizing', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
expect(w.isMinimized()).to.equal(true);
});
it('correctly reports maximized state after maximizing then fullscreening', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
expect(w.isMaximized()).to.equal(false);
expect(w.isFullScreen()).to.equal(true);
});
it('checks normal bounds for maximized transparent window', async () => {
w.destroy();
w = new BrowserWindow({
transparent: true,
show: false
});
w.show();
const bounds = w.getNormalBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly checks transparent window maximization state', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
width: 300,
height: 300,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
const unmaximize = once(w, 'unmaximize');
w.unmaximize();
await unmaximize;
expect(w.isMaximized()).to.equal(false);
});
it('returns the correct value for windows with an aspect ratio', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
fullscreenable: false
});
w.setAspectRatio(16 / 11);
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
w.resizable = false;
expect(w.isMaximized()).to.equal(true);
});
});
ifdescribe(process.platform !== 'linux')('Minimized state', () => {
it('checks normal bounds when minimized', async () => {
const bounds = w.getBounds();
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after move and minimize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('updates normal bounds after resize and minimize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('checks normal bounds when restored', async () => {
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
it('with properties', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.fullScreen).to.be.true();
});
it('does not go fullscreen if roundedCorners are enabled', async () => {
w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true });
expect(w.fullScreen).to.be.false();
});
it('can be changed', () => {
w.fullScreen = false;
expect(w.fullScreen).to.be.false();
w.fullScreen = true;
expect(w.fullScreen).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
const enterFullScreen = once(w, 'enter-full-screen');
w.show();
w.fullScreen = true;
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.once('enter-full-screen', () => {
w.fullScreen = false;
});
const leaveFullScreen = once(w, 'leave-full-screen');
w.show();
w.fullScreen = true;
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
it('with functions', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.isFullScreen()).to.be.true();
});
it('can be changed', () => {
w.setFullScreen(false);
expect(w.isFullScreen()).to.be.false();
w.setFullScreen(true);
expect(w.isFullScreen()).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
});
});
});
ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.selectPreviousTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectPreviousTab();
}).to.not.throw();
});
});
describe('BrowserWindow.selectNextTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectNextTab();
}).to.not.throw();
});
});
describe('BrowserWindow.mergeAllWindows()', () => {
it('does not throw', () => {
expect(() => {
w.mergeAllWindows();
}).to.not.throw();
});
});
describe('BrowserWindow.moveTabToNewWindow()', () => {
it('does not throw', () => {
expect(() => {
w.moveTabToNewWindow();
}).to.not.throw();
});
});
describe('BrowserWindow.toggleTabBar()', () => {
it('does not throw', () => {
expect(() => {
w.toggleTabBar();
}).to.not.throw();
});
});
describe('BrowserWindow.addTabbedWindow()', () => {
it('does not throw', async () => {
const tabbedWindow = new BrowserWindow({});
expect(() => {
w.addTabbedWindow(tabbedWindow);
}).to.not.throw();
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
await closeWindow(tabbedWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
});
it('throws when called on itself', () => {
expect(() => {
w.addTabbedWindow(w);
}).to.throw('AddTabbedWindow cannot be called by a window on itself.');
});
});
});
describe('autoHideMenuBar state', () => {
afterEach(closeAllWindows);
it('for properties', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
w.autoHideMenuBar = true;
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
w.autoHideMenuBar = false;
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
});
});
it('for functions', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
w.setAutoHideMenuBar(true);
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
w.setAutoHideMenuBar(false);
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
});
});
});
describe('BrowserWindow.capturePage(rect)', () => {
afterEach(closeAllWindows);
it('returns a Promise with a Buffer', async () => {
const w = new BrowserWindow({ show: false });
const image = await w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => {
const w = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true });
const visible = await w.webContents.executeJavaScript('document.visibilityState');
expect(visible).to.equal('hidden');
});
it('resolves after the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
w.show();
const visibleImage = await w.capturePage();
expect(visibleImage.isEmpty()).to.equal(false);
w.hide();
const hiddenImage = await w.capturePage();
const isEmpty = process.platform !== 'darwin';
expect(hiddenImage.isEmpty()).to.equal(isEmpty);
});
it('resolves after the window is hidden and capturer count is non-zero', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
const image = await w.capturePage();
expect(image.isEmpty()).to.equal(false);
});
it('preserves transparency', async () => {
const w = new BrowserWindow({ show: false, transparent: true });
w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
await once(w, 'ready-to-show');
w.show();
const image = await w.capturePage();
const imgBuffer = image.toPNG();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6);
});
});
describe('BrowserWindow.setProgressBar(progress)', () => {
let w: BrowserWindow;
before(() => {
w = new BrowserWindow({ show: false });
});
after(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('sets the progress', () => {
expect(() => {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
}
w.setProgressBar(0.5);
if (process.platform === 'darwin') {
app.dock.setIcon(null as any);
}
w.setProgressBar(-1);
}).to.not.throw();
});
it('sets the progress using "paused" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'paused' });
}).to.not.throw();
});
it('sets the progress using "error" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'error' });
}).to.not.throw();
});
it('sets the progress using "normal" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'normal' });
}).to.not.throw();
});
});
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
let w: BrowserWindow;
afterEach(closeAllWindows);
beforeEach(() => {
w = new BrowserWindow({ show: true });
});
it('sets the window as always on top', () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
w.setAlwaysOnTop(false);
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
it('causes the right value to be emitted on `always-on-top-changed`', async () => {
const alwaysOnTopChanged = once(w, 'always-on-top-changed');
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
const [, alwaysOnTop] = await alwaysOnTopChanged;
expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ parent: w });
c.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.false();
expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver');
});
});
describe('preconnect feature', () => {
let w: BrowserWindow;
let server: http.Server;
let url: string;
let connections = 0;
beforeEach(async () => {
connections = 0;
server = http.createServer((req, res) => {
if (req.url === '/link') {
res.setHeader('Content-type', 'text/html');
res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
return;
}
res.end();
});
server.on('connection', () => { connections++; });
url = (await listen(server)).url;
});
afterEach(async () => {
server.close();
await closeWindow(w);
w = null as unknown as BrowserWindow;
server = null as unknown as http.Server;
});
it('calling preconnect() connects to the server', async () => {
w = new BrowserWindow({ show: false });
w.webContents.on('did-start-navigation', (event, url) => {
w.webContents.session.preconnect({ url, numSockets: 4 });
});
await w.loadURL(url);
expect(connections).to.equal(4);
});
it('does not preconnect unless requested', async () => {
w = new BrowserWindow({ show: false });
await w.loadURL(url);
expect(connections).to.equal(1);
});
it('parses <link rel=preconnect>', async () => {
w = new BrowserWindow({ show: true });
const p = once(w.webContents.session, 'preconnect');
w.loadURL(url + '/link');
const [, preconnectUrl, allowCredentials] = await p;
expect(preconnectUrl).to.equal('http://example.com/');
expect(allowCredentials).to.be.true('allowCredentials');
});
});
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('allows changing cursor auto-hiding', () => {
expect(() => {
w.setAutoHideCursor(false);
w.setAutoHideCursor(true);
}).to.not.throw();
});
});
ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
it('is not available', () => {
expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
});
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setWindowButtonVisibility(true);
w.setWindowButtonVisibility(false);
}).to.not.throw();
});
it('changes window button visibility for normal window', () => {
const w = new BrowserWindow({ show: false });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('changes window button visibility for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('changes window button visibility for hiddenInset window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
// Buttons of customButtonsOnHover are always hidden unless hovered.
it('does not change window button visibility for customButtonsOnHover window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
afterEach(closeAllWindows);
it('allows setting, changing, and removing the vibrancy', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('light');
w.setVibrancy('dark');
w.setVibrancy(null);
w.setVibrancy('ultra-dark');
w.setVibrancy('' as any);
}).to.not.throw();
});
it('does not crash if vibrancy is set to an invalid value', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
}).to.not.throw();
});
});
ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
const pos = { x: 10, y: 10 };
afterEach(closeAllWindows);
describe('BrowserWindow.getWindowButtonPosition(pos)', () => {
it('returns null when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition');
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setWindowButtonPosition(pos)', () => {
it('resets the position when null is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setWindowButtonPosition(null);
expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition');
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
});
// The set/getTrafficLightPosition APIs are deprecated.
describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
it('returns { x: 0, y: 0 } when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
it('resets the position when { x: 0, y: 0 } is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setTrafficLightPosition({ x: 0, y: 0 });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
afterEach(closeAllWindows);
it('supports setting the app details', () => {
const w = new BrowserWindow({ show: false });
const iconPath = path.join(fixtures, 'assets', 'icon.ico');
expect(() => {
w.setAppDetails({ appId: 'my.app.id' });
w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
w.setAppDetails({ appIconPath: iconPath });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
w.setAppDetails({ relaunchDisplayName: 'My app name' });
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
});
w.setAppDetails({});
}).to.not.throw();
expect(() => {
(w.setAppDetails as any)();
}).to.throw('Insufficient number of arguments.');
});
});
describe('BrowserWindow.fromId(id)', () => {
afterEach(closeAllWindows);
it('returns the window with id', () => {
const w = new BrowserWindow({ show: false });
expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
});
});
describe('Opening a BrowserWindow from a link', () => {
let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('can properly open and load a new window from a link', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
appProcess = childProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
});
describe('BrowserWindow.fromWebContents(webContents)', () => {
afterEach(closeAllWindows);
it('returns the window with the webContents', () => {
const w = new BrowserWindow({ show: false });
const found = BrowserWindow.fromWebContents(w.webContents);
expect(found!.id).to.equal(w.id);
});
it('returns null for webContents without a BrowserWindow', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
try {
expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
} finally {
contents.destroy();
}
});
it('returns the correct window for a BrowserView webcontents', async () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
await bv.webContents.loadURL('about:blank');
expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
});
it('returns the correct window for a WebView webcontents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
// NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
// https://github.com/electron/electron/issues/25413, and is not integral
// to the test.
const p = once(w.webContents, 'did-attach-webview');
const [, webviewContents] = await once(app, 'web-contents-created');
expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
await p;
});
it('is usable immediately on browser-window-created', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.open(""); null');
const [win, winFromWebContents] = await new Promise<any>((resolve) => {
app.once('browser-window-created', (e, win) => {
resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
});
});
expect(winFromWebContents).to.equal(win);
});
});
describe('BrowserWindow.openDevTools()', () => {
afterEach(closeAllWindows);
it('does not crash for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
w.webContents.openDevTools();
});
});
describe('BrowserWindow.fromBrowserView(browserView)', () => {
afterEach(closeAllWindows);
it('returns the window with the BrowserView', () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
});
it('returns the window when there are multiple BrowserViews', () => {
const w = new BrowserWindow({ show: false });
const bv1 = new BrowserView();
w.addBrowserView(bv1);
const bv2 = new BrowserView();
w.addBrowserView(bv2);
defer(() => {
w.removeBrowserView(bv1);
w.removeBrowserView(bv2);
bv1.webContents.destroy();
bv2.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
});
it('returns undefined if not attached', () => {
const bv = new BrowserView();
defer(() => {
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
});
});
describe('BrowserWindow.setOpacity(opacity)', () => {
afterEach(closeAllWindows);
ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
it('make window with initial opacity', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
expect(w.getOpacity()).to.equal(0.5);
});
it('allows setting the opacity', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setOpacity(0.0);
expect(w.getOpacity()).to.equal(0.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(0.5);
w.setOpacity(1.0);
expect(w.getOpacity()).to.equal(1.0);
}).to.not.throw();
});
it('clamps opacity to [0.0...1.0]', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
w.setOpacity(100);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(-100);
expect(w.getOpacity()).to.equal(0.0);
});
});
ifdescribe(process.platform === 'linux')(('Linux'), () => {
it('sets 1 regardless of parameter', () => {
const w = new BrowserWindow({ show: false });
w.setOpacity(0);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(1.0);
});
});
});
describe('BrowserWindow.setShape(rects)', () => {
afterEach(closeAllWindows);
it('allows setting shape', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setShape([]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
w.setShape([]);
}).to.not.throw();
});
});
describe('"useContentSize" option', () => {
afterEach(closeAllWindows);
it('make window created with content size when used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('make window created with window size when not used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400
});
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
it('works for a frameless window', () => {
const w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => {
const testWindowsOverlay = async (style: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: style,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: true
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRect.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRect.x).to.be.greaterThan(0);
} else {
expect(overlayRect.x).to.equal(0);
}
expect(overlayRect.width).to.be.greaterThan(0);
expect(overlayRect.height).to.be.greaterThan(0);
const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
expect(cssOverlayRect).to.deep.equal(overlayRect);
const geometryChange = once(ipcMain, 'geometrychange');
w.setBounds({ width: 800 });
const [, newOverlayRect] = await geometryChange;
expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('creates browser window with hidden title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('sets Window Control Overlay with hidden title bar', async () => {
await testWindowsOverlay('hidden');
});
ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
await testWindowsOverlay('hiddenInset');
});
ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
});
afterEach(async () => {
await closeAllWindows();
});
it('does not crash changing minimizability ', () => {
expect(() => {
w.setMinimizable(false);
}).to.not.throw();
});
it('does not crash changing maximizability', () => {
expect(() => {
w.setMaximizable(false);
}).to.not.throw();
});
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => {
const testWindowsOverlayHeight = async (size: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: size
}
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRectPreMax.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRectPreMax.x).to.be.greaterThan(0);
} else {
expect(overlayRectPreMax.x).to.equal(0);
}
expect(overlayRectPreMax.width).to.be.greaterThan(0);
expect(overlayRectPreMax.height).to.equal(size);
// Confirm that maximization only affected the height of the buttons and not the title bar
expect(overlayRectPostMax.height).to.equal(size);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('sets Window Control Overlay with title bar height of 40', async () => {
await testWindowsOverlayHeight(40);
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => {
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('does not crash when an invalid titleBarStyle was initially set', () => {
const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
expect(() => {
win.setTitleBarOverlay({
color: '#000000'
});
}).to.not.throw();
});
it('correctly updates the height of the overlay', async () => {
const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
if (firstRun) {
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(x).to.equal(0);
expect(y).to.equal(0);
expect(width).to.be.greaterThan(0);
expect(height).to.equal(size);
expect(preMaxHeight).to.equal(size);
};
const INITIAL_SIZE = 40;
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: INITIAL_SIZE
}
});
await testOverlay(w, INITIAL_SIZE, true);
w.setTitleBarOverlay({
height: INITIAL_SIZE + 10
});
await testOverlay(w, INITIAL_SIZE + 10, false);
});
});
ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
afterEach(closeAllWindows);
it('can move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, 50);
const after = w.getPosition();
expect(after).to.deep.equal([-10, 50]);
});
it('cannot move the window behind menu bar', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can move the window behind menu bar if it has no frame', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[0]).to.be.equal(-10);
expect(after[1]).to.be.equal(-10);
});
it('without it, cannot move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expectBoundsEqual(w.getSize(), [size.width, size.height]);
});
it('without it, cannot set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
});
});
ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
afterEach(closeAllWindows);
it('sets the window width to the page width when used', () => {
const w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
});
w.maximize();
expect(w.getSize()[0]).to.equal(500);
});
});
describe('"tabbingIdentifier" option', () => {
afterEach(closeAllWindows);
it('can be set on a window', () => {
expect(() => {
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group1'
});
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
});
}).not.to.throw();
});
});
describe('"webPreferences" option', () => {
afterEach(() => { ipcMain.removeAllListeners('answer'); });
afterEach(closeAllWindows);
describe('"preload" option', () => {
const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
it(name, async () => {
const w = new BrowserWindow({
webPreferences: {
...webPrefs,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
const [, result] = await once(ipcMain, 'leak-result');
expect(result).to.have.property('require', 'undefined');
expect(result).to.have.property('exports', 'undefined');
expect(result).to.have.property('windowExports', 'undefined');
expect(result).to.have.property('windowPreload', 'undefined');
expect(result).to.have.property('windowRequire', 'undefined');
});
};
doesNotLeakSpec('does not leak require', {
nodeIntegration: false,
sandbox: false,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when sandbox is enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when context isolation is enabled', {
nodeIntegration: false,
sandbox: false,
contextIsolation: true
});
doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: true
});
it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
let w = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, notIsolated] = await once(ipcMain, 'leak-result');
expect(notIsolated).to.have.property('globals');
w.destroy();
w = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, isolated] = await once(ipcMain, 'leak-result');
expect(isolated).to.have.property('globals');
const notIsolatedGlobals = new Set(notIsolated.globals);
for (const isolatedGlobal of isolated.globals) {
notIsolatedGlobals.delete(isolatedGlobal);
}
expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
});
it('loads the script before other scripts in window', async () => {
const preload = path.join(fixtures, 'module', 'set-global.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.eql('preload');
});
it('has synchronous access to all eventual window APIs', async () => {
const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.be.an('object');
expect(test.atPreload).to.be.an('array');
expect(test.atLoad).to.be.an('array');
expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
});
});
describe('session preload scripts', function () {
const preloads = [
path.join(fixtures, 'module', 'set-global-preload-1.js'),
path.join(fixtures, 'module', 'set-global-preload-2.js'),
path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
];
const defaultSession = session.defaultSession;
beforeEach(() => {
expect(defaultSession.getPreloads()).to.deep.equal([]);
defaultSession.setPreloads(preloads);
});
afterEach(() => {
defaultSession.setPreloads([]);
});
it('can set multiple session preload script', () => {
expect(defaultSession.getPreloads()).to.deep.equal(preloads);
});
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('loads the script before other scripts in window including normal preloads', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload: path.join(fixtures, 'module', 'get-global-preload.js'),
contextIsolation: false
}
});
w.loadURL('about:blank');
const [, preload1, preload2, preload3] = await once(ipcMain, 'vars');
expect(preload1).to.equal('preload-1');
expect(preload2).to.equal('preload-1-2');
expect(preload3).to.be.undefined('preload 3');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('"additionalArguments" option', () => {
it('adds extra args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg');
});
it('adds extra value args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg=foo']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg=foo');
});
});
describe('"node-integration" option', () => {
it('disables node integration by default', async () => {
const preload = path.join(fixtures, 'module', 'send-later.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer');
expect(typeofProcess).to.equal('undefined');
expect(typeofBuffer).to.equal('undefined');
});
});
describe('"sandbox" option', () => {
const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/cross-site':
response.end(`<html><body><h1>${request.url}</h1></body></html>`);
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('exposes ipcRenderer to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes ipcRenderer to preload script (path has special chars)', async () => {
const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preloadSpecialChars,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes "loaded" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
});
w.loadURL('about:blank');
await once(ipcMain, 'process-loaded');
});
it('exposes "exit" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
const pageUrl = 'file://' + htmlPath;
w.loadURL(pageUrl);
const [, url] = await once(ipcMain, 'answer');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
});
it('exposes full EventEmitter object to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
}
});
w.loadURL('about:blank');
const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer');
const { EventEmitter } = require('events');
const emitter = new EventEmitter();
const browserEventEmitterProperties = [];
let currentObj = emitter;
do {
browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
} while ((currentObj = Object.getPrototypeOf(currentObj)));
expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
});
it('should open windows in same domain with cross-scripting enabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
const pageUrl = 'file://' + htmlPath;
const answer = once(ipcMain, 'answer');
w.loadURL(pageUrl);
const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
expect(frameName).to.equal('popup!');
expect(options.width).to.equal(500);
expect(options.height).to.equal(600);
const [, html] = await answer;
expect(html).to.equal('<h1>scripting from opener</h1>');
});
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
w.loadFile(
path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
{ search: 'window-open-external' }
);
// Wait for a message from the main window saying that it's ready.
await once(ipcMain, 'opener-loaded');
// Ask the opener to open a popup with window.opener.
const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
w.webContents.send('open-the-popup', expectedPopupUrl);
// The page is going to open a popup that it won't be able to close.
// We have to close it from here later.
const [, popupWindow] = await once(app, 'browser-window-created');
// Ask the popup window for details.
const detailsAnswer = once(ipcMain, 'child-loaded');
popupWindow.webContents.send('provide-details');
const [, openerIsNull, , locationHref] = await detailsAnswer;
expect(openerIsNull).to.be.false('window.opener is null');
expect(locationHref).to.equal(expectedPopupUrl);
// Ask the page to access the popup.
const touchPopupResult = once(ipcMain, 'answer');
w.webContents.send('touch-the-popup');
const [, popupAccessMessage] = await touchPopupResult;
// Ask the popup to access the opener.
const touchOpenerResult = once(ipcMain, 'answer');
popupWindow.webContents.send('touch-the-opener');
const [, openerAccessMessage] = await touchOpenerResult;
// We don't need the popup anymore, and its parent page can't close it,
// so let's close it from here before we run any checks.
await closeWindow(popupWindow, { assertNotWindows: false });
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
});
it('should inherit the sandbox setting in opened windows', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [, { argv }] = await once(ipcMain, 'answer');
expect(argv).to.include('--enable-sandbox');
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
it('should set ipc event sender correctly', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
let childWc: WebContents | null = null;
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
w.webContents.on('did-create-window', (win) => {
childWc = win.webContents;
expect(w.webContents).to.not.equal(childWc);
});
ipcMain.once('parent-ready', function (event) {
expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
event.sender.send('verified');
});
ipcMain.once('child-ready', function (event) {
expect(childWc).to.not.be.null('child webcontents should be available');
expect(event.sender).to.equal(childWc, 'sender should be the child');
event.sender.send('verified');
});
const done = Promise.all([
'parent-answer',
'child-answer'
].map(name => once(ipcMain, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
await done;
});
describe('event handling', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
});
it('works for window events', async () => {
const pageTitleUpdated = once(w, 'page-title-updated');
w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
await pageTitleUpdated;
});
it('works for stop events', async () => {
const done = Promise.all([
'did-navigate',
'did-fail-load',
'did-stop-loading'
].map(name => once(w.webContents, name)));
w.loadURL('data:text/html,<script>stop()</script>');
await done;
});
it('works for web contents events', async () => {
const done = Promise.all([
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
].map(name => once(w.webContents, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
await done;
});
});
it('validates process APIs access in sandboxed renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.once('preload-error', (event, preloadPath, error) => {
throw error;
});
process.env.sandboxmain = 'foo';
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test.hasCrash).to.be.true('has crash');
expect(test.hasHang).to.be.true('has hang');
expect(test.heapStatistics).to.be.an('object');
expect(test.blinkMemoryInfo).to.be.an('object');
expect(test.processMemoryInfo).to.be.an('object');
expect(test.systemVersion).to.be.a('string');
expect(test.cpuUsage).to.be.an('object');
expect(test.ioCounters).to.be.an('object');
expect(test.uptime).to.be.a('number');
expect(test.arch).to.equal(process.arch);
expect(test.platform).to.equal(process.platform);
expect(test.env).to.deep.equal(process.env);
expect(test.execPath).to.equal(process.helperExecPath);
expect(test.sandboxed).to.be.true('sandboxed');
expect(test.contextIsolated).to.be.false('contextIsolated');
expect(test.type).to.equal('renderer');
expect(test.version).to.equal(process.version);
expect(test.versions).to.deep.equal(process.versions);
expect(test.contextId).to.be.a('string');
if (process.platform === 'linux' && test.osSandbox) {
expect(test.creationTime).to.be.null('creation time');
expect(test.systemMemoryInfo).to.be.null('system memory info');
} else {
expect(test.creationTime).to.be.a('number');
expect(test.systemMemoryInfo).to.be.an('object');
}
});
it('webview in sandbox renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
webviewTag: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview');
const webviewDomReady = once(ipcMain, 'webview-dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const [, id] = await webviewDomReady;
expect(webContents.id).to.equal(id);
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
// tests relies on preloads in opened windows
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
it('opens window of about:blank with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('blocks accessing cross-origin frames', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
const [, content] = await answer;
expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
});
it('opens window from <iframe> tags', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window with cross-scripting enabled from isolated context', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
w.reload();
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
});
it('<webview> works in a scriptable popup', async () => {
const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegrationInSubFrames: true,
webviewTag: true,
contextIsolation: false,
preload
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false,
webPreferences: {
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
preload
}
}
}));
const webviewLoaded = once(ipcMain, 'webview-loaded');
w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
await webviewLoaded;
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: preloadPath,
contextIsolation: false
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
describe('window.location', () => {
const protocols = [
['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
];
beforeEach(() => {
for (const [scheme, path] of protocols) {
protocol.registerBufferProtocol(scheme, (request, callback) => {
callback({
mimeType: 'text/html',
data: fs.readFileSync(path)
});
});
}
});
afterEach(() => {
for (const [scheme] of protocols) {
protocol.unregisterProtocol(scheme);
}
});
it('retains the original web preferences when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
contextIsolation: false,
nodeIntegrationInSubFrames: true
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer');
expect(nodeIntegration).to.be.false();
expect(typeofProcess).to.eql('undefined');
});
it('window.opener is not null when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer');
expect(windowOpenerIsNull).to.be.false('window.opener is null');
});
});
});
describe('"disableHtmlFullscreenWindowResize" option', () => {
it('prevents window from resizing when set', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
disableHtmlFullscreenWindowResize: true
}
});
await w.loadURL('about:blank');
const size = w.getSize();
const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen');
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await enterHtmlFullScreen;
expect(w.getSize()).to.deep.equal(size);
});
});
describe('"defaultFontFamily" option', () => {
it('can change the standard font family', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
defaultFontFamily: {
standard: 'Impact'
}
}
});
await w.loadFile(path.join(fixtures, 'pages', 'content.html'));
const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true);
expect(fontFamily).to.equal('Impact');
});
});
});
describe('beforeunload handler', function () {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(closeAllWindows);
it('returning undefined would not prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('returning false would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('returning empty string would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('emits for each close attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const destroyListener = () => { expect.fail('Close was not prevented'); };
w.webContents.once('destroyed', destroyListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.close();
await once(w.webContents, 'before-unload-fired');
w.close();
await once(w.webContents, 'before-unload-fired');
w.webContents.removeListener('destroyed', destroyListener);
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits for each reload attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.reload();
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.reload();
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
w.reload();
await once(w.webContents, 'did-finish-load');
});
it('emits for each navigation attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.loadURL('about:blank');
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.loadURL('about:blank');
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
await w.loadURL('about:blank');
});
});
describe('document.visibilityState/hidden', () => {
afterEach(closeAllWindows);
it('visibilityState is initially visible despite window being hidden', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let readyToShow = false;
w.once('ready-to-show', () => {
readyToShow = true;
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(readyToShow).to.be.false('ready to show');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.show();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.showInactive();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.minimize();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
// when we introduced the compositor recycling patch. Should figure out how to fix this
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
ipcMain.once('pong', (event, visibilityState, hidden) => {
throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
});
try {
const shown1 = once(w, 'show');
w.show();
await shown1;
const hidden = once(w, 'hide');
w.hide();
await hidden;
const shown2 = once(w, 'show');
w.show();
await shown2;
} finally {
ipcMain.removeAllListeners('pong');
}
});
});
ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
afterEach(closeAllWindows);
it('emits an event when window is maximized', async () => {
const w = new BrowserWindow({ show: false });
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits an event when a transparent window is maximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits only one event when frameless window is maximized', () => {
const w = new BrowserWindow({ show: false, frame: false });
let emitted = 0;
w.on('maximize', () => emitted++);
w.show();
w.maximize();
expect(emitted).to.equal(1);
});
it('emits an event when window is unmaximized', async () => {
const w = new BrowserWindow({ show: false });
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
w.unmaximize();
await unmaximize;
});
it('emits an event when a transparent window is unmaximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await maximize;
w.unmaximize();
await unmaximize;
});
it('emits an event when window is minimized', async () => {
const w = new BrowserWindow({ show: false });
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
});
});
describe('beginFrameSubscription method', () => {
it('does not crash when callback returns nothing', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function () {
// This callback might be called twice.
if (called) return;
called = true;
// Pending endFrameSubscription to next tick can reliably reproduce
// a crash which happens when nothing is returned in the callback.
setTimeout().then(() => {
w.webContents.endFrameSubscription();
done();
});
});
});
});
it('subscribes to frame updates', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return;
called = true;
try {
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
});
it('subscribes to frame updates (only dirty rectangle)', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
let gotInitialFullSizeFrame = false;
const [contentWidth, contentHeight] = w.getContentSize();
w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (image, rect) => {
if (image.isEmpty()) {
// Chromium sometimes sends a 0x0 frame at the beginning of the
// page load.
return;
}
if (rect.height === contentHeight && rect.width === contentWidth &&
!gotInitialFullSizeFrame) {
// The initial frame is full-size, but we're looking for a call
// with just the dirty-rect. The next frame should be a smaller
// rect.
gotInitialFullSizeFrame = true;
return;
}
// This callback might be called twice.
if (called) return;
// We asked for just the dirty rectangle, so we expect to receive a
// rect smaller than the full size.
// TODO(jeremy): this is failing on windows currently; investigate.
// assert(rect.width < contentWidth || rect.height < contentHeight)
called = true;
try {
const expectedSize = rect.width * rect.height * 4;
expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
});
it('throws error when subscriber is not well defined', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.beginFrameSubscription(true, true as any);
// TODO(zcbenz): gin is weak at guessing parameter types, we should
// upstream native_mate's implementation to gin.
}).to.throw('Error processing argument at index 1, conversion failure from ');
});
});
describe('savePage method', () => {
const savePageDir = path.join(fixtures, 'save_page');
const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
afterEach(() => {
closeAllWindows();
try {
fs.unlinkSync(savePageCssPath);
fs.unlinkSync(savePageJsPath);
fs.unlinkSync(savePageHtmlPath);
fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
fs.rmdirSync(savePageDir);
} catch {}
});
it('should throw when passing relative paths', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await expect(
w.webContents.savePage('save_page.html', 'HTMLComplete')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'HTMLOnly')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'MHTML')
).to.eventually.be.rejectedWith('Path must be absolute');
});
it('should save page to disk with HTMLOnly', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
});
it('should save page to disk with MHTML', async () => {
/* Use temp directory for saving MHTML file since the write handle
* gets passed to untrusted process and chromium will deny exec access to
* the path. To perform this task, chromium requires that the path is one
* of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416
*/
const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-'));
const savePageMHTMLPath = path.join(tmpDir, 'save_page.html');
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageMHTMLPath, 'MHTML');
expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
try {
await fs.promises.unlink(savePageMHTMLPath);
await fs.promises.rmdir(tmpDir);
} catch {}
});
it('should save page to disk with HTMLComplete', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
});
});
describe('BrowserWindow options argument is optional', () => {
afterEach(closeAllWindows);
it('should create a window with default size (800x600)', () => {
const w = new BrowserWindow();
expect(w.getSize()).to.deep.equal([800, 600]);
});
});
describe('BrowserWindow.restore()', () => {
afterEach(closeAllWindows);
it('should restore the previous window size', () => {
const w = new BrowserWindow({
minWidth: 800,
width: 800
});
const initialSize = w.getSize();
w.minimize();
w.restore();
expectBoundsEqual(w.getSize(), initialSize);
});
it('does not crash when restoring hidden minimized window', () => {
const w = new BrowserWindow({});
w.minimize();
w.hide();
w.show();
});
// TODO(zcbenz):
// This test does not run on Linux CI. See:
// https://github.com/electron/electron/issues/28699
ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => {
const w = new BrowserWindow({});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
const restore = once(w, 'restore');
w.restore();
await restore;
expect(w.isMaximized()).to.equal(true);
});
});
// TODO(dsanders11): Enable once maximize event works on Linux again on CI
ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
afterEach(closeAllWindows);
it('should show the window if it is not currently shown', async () => {
const w = new BrowserWindow({ show: false });
const hidden = once(w, 'hide');
let shown = once(w, 'show');
const maximize = once(w, 'maximize');
expect(w.isVisible()).to.be.false('visible');
w.maximize();
await maximize;
await shown;
expect(w.isMaximized()).to.be.true('maximized');
expect(w.isVisible()).to.be.true('visible');
// Even if the window is already maximized
w.hide();
await hidden;
expect(w.isVisible()).to.be.false('visible');
shown = once(w, 'show');
w.maximize();
await shown;
expect(w.isVisible()).to.be.true('visible');
});
});
describe('BrowserWindow.unmaximize()', () => {
afterEach(closeAllWindows);
it('should restore the previous window position', () => {
const w = new BrowserWindow();
const initialPosition = w.getPosition();
w.maximize();
w.unmaximize();
expectBoundsEqual(w.getPosition(), initialPosition);
});
// TODO(dsanders11): Enable once minimize event works on Linux again.
// See https://github.com/electron/electron/issues/28699
ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
const w = new BrowserWindow();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
w.unmaximize();
await setTimeout(1000);
expect(w.isMinimized()).to.be.true();
});
it('should not change the size or position of a normal window', async () => {
const w = new BrowserWindow();
const initialSize = w.getSize();
const initialPosition = w.getPosition();
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getSize(), initialSize);
expectBoundsEqual(w.getPosition(), initialPosition);
});
ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
const { workArea } = screen.getPrimaryDisplay();
const bounds = {
x: workArea.x,
y: workArea.y,
width: workArea.width,
height: workArea.height
};
const w = new BrowserWindow(bounds);
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getBounds(), bounds);
});
});
describe('setFullScreen(false)', () => {
afterEach(closeAllWindows);
// only applicable to windows: https://github.com/electron/electron/issues/6036
ifdescribe(process.platform === 'win32')('on windows', () => {
it('should restore a normal visible window from a fullscreen startup state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const shown = once(w, 'show');
// start fullscreen and hidden
w.setFullScreen(true);
w.show();
await shown;
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.true('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
it('should keep window hidden if already in hidden state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.false('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
it('exits HTML fullscreen when window leaves fullscreen', async () => {
const w = new BrowserWindow();
await w.loadURL('about:blank');
await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await once(w, 'enter-full-screen');
// Wait a tick for the full-screen state to 'stick'
await setTimeout();
w.setFullScreen(false);
await once(w, 'leave-html-full-screen');
});
});
});
describe('parent window', () => {
afterEach(closeAllWindows);
ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
const w = new BrowserWindow();
const sheetBegin = once(w, 'sheet-begin');
// eslint-disable-next-line no-new
new BrowserWindow({
modal: true,
parent: w
});
await sheetBegin;
});
ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
const w = new BrowserWindow();
const sheet = new BrowserWindow({
modal: true,
parent: w
});
const sheetEnd = once(w, 'sheet-end');
sheet.close();
await sheetEnd;
});
describe('parent option', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.getParentWindow()).to.equal(w);
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(w.getChildWindows()).to.deep.equal([c]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isVisible()).to.be.false('parent is visible');
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(c, 'minimize');
c.minimize();
await minimized;
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(c, 'restore');
c.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
it('closes a grandchild window when a middle child window is destroyed', (done) => {
const w = new BrowserWindow();
w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
w.webContents.executeJavaScript('window.open("")');
w.webContents.on('did-create-window', async (window) => {
const childWindow = new BrowserWindow({ parent: window });
await setTimeout();
window.close();
childWindow.on('closed', () => {
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
done();
});
});
});
it('should not affect the show option', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.isVisible()).to.be.false('child is visible');
expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
});
});
describe('win.setParentWindow(parent)', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getParentWindow()).to.be.null('w.parent');
expect(c.getParentWindow()).to.be.null('c.parent');
c.setParentWindow(w);
expect(c.getParentWindow()).to.equal(w);
c.setParentWindow(null);
expect(c.getParentWindow()).to.be.null('c.parent');
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getChildWindows()).to.deep.equal([]);
c.setParentWindow(w);
expect(w.getChildWindows()).to.deep.equal([c]);
c.setParentWindow(null);
expect(w.getChildWindows()).to.deep.equal([]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
const closed = once(c, 'closed');
c.setParentWindow(w);
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
});
describe('modal option', () => {
it('does not freeze or crash', async () => {
const parentWindow = new BrowserWindow();
const createTwo = async () => {
const two = new BrowserWindow({
width: 300,
height: 200,
parent: parentWindow,
modal: true,
show: false
});
const twoShown = once(two, 'show');
two.show();
await twoShown;
setTimeout(500).then(() => two.close());
await once(two, 'closed');
};
const one = new BrowserWindow({
width: 600,
height: 400,
parent: parentWindow,
modal: true,
show: false
});
const oneShown = once(one, 'show');
one.show();
await oneShown;
setTimeout(500).then(() => one.destroy());
await once(one, 'closed');
await createTwo();
});
ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
const w = new BrowserWindow({ show: false });
w.setEnabled(false);
expect(w.isEnabled()).to.be.false('w.isEnabled()');
w.setEnabled(true);
expect(w.isEnabled()).to.be.true('!w.isEnabled()');
});
ifit(process.platform !== 'darwin')('disables parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
expect(w.isEnabled()).to.be.true('w.isEnabled');
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
w.setEnabled(false);
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c.destroy();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.destroy();
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
});
});
describe('window states', () => {
afterEach(closeAllWindows);
it('does not resize frameless windows when states change', () => {
const w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
});
w.minimizable = false;
w.minimizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.resizable = false;
w.resizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.maximizable = false;
w.maximizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.fullScreenable = false;
w.fullScreenable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.closable = false;
w.closable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
});
describe('resizable state', () => {
it('with properties', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.resizable).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.maximizable).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
w.resizable = false;
expect(w.resizable).to.be.false('resizable');
w.resizable = true;
expect(w.resizable).to.be.true('resizable');
});
});
it('with functions', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.isResizable()).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.isMaximizable()).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isResizable()).to.be.true('resizable');
w.setResizable(false);
expect(w.isResizable()).to.be.false('resizable');
w.setResizable(true);
expect(w.isResizable()).to.be.true('resizable');
});
});
it('works for a frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w.resizable).to.be.true('resizable');
if (process.platform === 'win32') {
const w = new BrowserWindow({ show: false, thickFrame: false });
expect(w.resizable).to.be.false('resizable');
}
});
// On Linux there is no "resizable" property of a window.
ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
expect(w.maximizable).to.be.true('maximizable');
w.resizable = false;
expect(w.maximizable).to.be.false('not maximizable');
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
const w = new BrowserWindow({
show: false,
frame: false,
resizable: false,
transparent: true
});
w.setContentSize(60, 60);
expectBoundsEqual(w.getContentSize(), [60, 60]);
w.setContentSize(30, 30);
expectBoundsEqual(w.getContentSize(), [30, 30]);
w.setContentSize(10, 10);
expectBoundsEqual(w.getContentSize(), [10, 10]);
});
});
describe('loading main frame state', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is true when the main frame is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(serverUrl);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
it('is false when only a subframe is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/page2'
document.body.appendChild(iframe)
`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
});
it('is true when navigating to pages from the same origin', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(`${serverUrl}/page2`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
});
});
ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
// Not implemented on Linux.
afterEach(closeAllWindows);
describe('movable state', () => {
it('with properties', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.movable).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.movable).to.be.true('movable');
w.movable = false;
expect(w.movable).to.be.false('movable');
w.movable = true;
expect(w.movable).to.be.true('movable');
});
});
it('with functions', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.isMovable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMovable()).to.be.true('movable');
w.setMovable(false);
expect(w.isMovable()).to.be.false('movable');
w.setMovable(true);
expect(w.isMovable()).to.be.true('movable');
});
});
});
describe('visibleOnAllWorkspaces state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.visibleOnAllWorkspaces).to.be.false();
w.visibleOnAllWorkspaces = true;
expect(w.visibleOnAllWorkspaces).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isVisibleOnAllWorkspaces()).to.be.false();
w.setVisibleOnAllWorkspaces(true);
expect(w.isVisibleOnAllWorkspaces()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.documentEdited).to.be.false();
w.documentEdited = true;
expect(w.documentEdited).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isDocumentEdited()).to.be.false();
w.setDocumentEdited(true);
expect(w.isDocumentEdited()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('representedFilename', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.representedFilename).to.eql('');
w.representedFilename = 'a name';
expect(w.representedFilename).to.eql('a name');
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getRepresentedFilename()).to.eql('');
w.setRepresentedFilename('a name');
expect(w.getRepresentedFilename()).to.eql('a name');
});
});
});
describe('native window title', () => {
it('with properties', () => {
it('can be set with title constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.title).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.title).to.eql('Electron Test Main');
w.title = 'NEW TITLE';
expect(w.title).to.eql('NEW TITLE');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.getTitle()).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTitle()).to.eql('Electron Test Main');
w.setTitle('NEW TITLE');
expect(w.getTitle()).to.eql('NEW TITLE');
});
});
});
describe('minimizable state', () => {
it('with properties', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.minimizable).to.be.false('minimizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.minimizable).to.be.true('minimizable');
w.minimizable = false;
expect(w.minimizable).to.be.false('minimizable');
w.minimizable = true;
expect(w.minimizable).to.be.true('minimizable');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.isMinimizable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMinimizable()).to.be.true('isMinimizable');
w.setMinimizable(false);
expect(w.isMinimizable()).to.be.false('isMinimizable');
w.setMinimizable(true);
expect(w.isMinimizable()).to.be.true('isMinimizable');
});
});
});
describe('maximizable state (property)', () => {
it('with properties', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.maximizable).to.be.false('maximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.maximizable).to.be.true('maximizable');
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.minimizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.closable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
w.closable = true;
expect(w.maximizable).to.be.true('maximizable');
w.fullScreenable = false;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.isMaximizable()).to.be.false('isMaximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMinimizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setClosable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setClosable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setFullScreenable(false);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform === 'win32')('maximizable state', () => {
it('with properties', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
describe('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.menuBarVisible).to.be.true();
w.menuBarVisible = false;
expect(w.menuBarVisible).to.be.false();
w.menuBarVisible = true;
expect(w.menuBarVisible).to.be.true();
});
});
describe('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
w.setMenuBarVisibility(false);
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
w.setMenuBarVisibility(true);
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
it('with functions', () => {
it('can be set with fullscreenable constructor option', () => {
const w = new BrowserWindow({ show: false, fullscreenable: false });
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
w.setFullScreenable(false);
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
w.setFullScreenable(true);
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
});
});
});
ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => {
it('with functions', () => {
it('can be set with ignoreMissionControl constructor option', () => {
const w = new BrowserWindow({ show: false, hiddenInMissionControl: true });
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
w.setHiddenInMissionControl(true);
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
w.setHiddenInMissionControl(false);
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
});
});
});
// fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
ifdescribe(process.platform === 'darwin')('kiosk state', () => {
it('with properties', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.kiosk).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.kiosk = true;
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.kiosk = false;
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
it('with functions', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.isKiosk()).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
it('resizable flag should be set to false and restored', async () => {
const w = new BrowserWindow({ resizable: false });
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.false('resizable');
});
it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.true('resizable');
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
it('should not cause a crash if called when exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('should be able to load a URL while transitioning to fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true });
w.loadFile(path.join(fixtures, 'pages', 'c.html'));
const load = once(w.webContents, 'did-finish-load');
const enterFS = once(w, 'enter-full-screen');
await Promise.all([enterFS, load]);
expect(w.fullScreen).to.be.true();
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('can be changed with setFullScreen method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('handles several transitions starting with fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true, show: true });
expect(w.isFullScreen()).to.be.true('not fullscreen');
w.setFullScreen(false);
w.setFullScreen(true);
const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('not fullscreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several HTML fullscreen transitions', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFullScreen = once(w, 'enter-full-screen');
const leaveFullScreen = once(w, 'leave-full-screen');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
await setTimeout();
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several transitions in close proximity', async () => {
const w = new BrowserWindow();
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
w.setFullScreen(true);
w.setFullScreen(false);
w.setFullScreen(true);
w.setFullScreen(false);
await Promise.all([enterFS, leaveFS]);
expect(w.isFullScreen()).to.be.false('not fullscreen');
});
it('handles several chromium-initiated transitions in close proximity', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>(resolve => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', () => {
enterCount++;
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await done;
});
it('handles HTML fullscreen transitions when fullscreenable is false', async () => {
const w = new BrowserWindow({ fullscreenable: false });
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>((resolve, reject) => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', async () => {
enterCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement');
if (!isFS) reject(new Error('Document should have fullscreen element'));
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await expect(done).to.eventually.be.fulfilled();
});
it('does not crash when exiting simpleFullScreen (properties)', async () => {
const w = new BrowserWindow();
w.setSimpleFullScreen(true);
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('does not crash when exiting simpleFullScreen (functions)', async () => {
const w = new BrowserWindow();
w.simpleFullScreen = true;
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('should not be changed by setKiosk method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('should stay fullscreen if fullscreen before kiosk', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
w.setKiosk(true);
w.setKiosk(false);
// Wait enough time for a fullscreen change to take effect.
await setTimeout(2000);
expect(w.isFullScreen()).to.be.true('isFullScreen');
});
it('multiple windows inherit correct fullscreen state', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout(1000);
const w2 = new BrowserWindow({ show: false });
const enterFullScreen2 = once(w2, 'enter-full-screen');
w2.show();
await enterFullScreen2;
expect(w2.isFullScreen()).to.be.true('isFullScreen');
});
});
describe('closable state', () => {
it('with properties', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.closable).to.be.false('closable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.closable).to.be.true('closable');
w.closable = false;
expect(w.closable).to.be.false('closable');
w.closable = true;
expect(w.closable).to.be.true('closable');
});
});
it('with functions', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.isClosable()).to.be.false('isClosable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isClosable()).to.be.true('isClosable');
w.setClosable(false);
expect(w.isClosable()).to.be.false('isClosable');
w.setClosable(true);
expect(w.isClosable()).to.be.true('isClosable');
});
});
});
describe('hasShadow state', () => {
it('with properties', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
expect(w.shadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.shadow).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
w.shadow = true;
expect(w.shadow).to.be.true('hasShadow');
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
});
});
describe('with functions', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
const hasShadow = w.hasShadow();
expect(hasShadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.hasShadow()).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
w.setHasShadow(true);
expect(w.hasShadow()).to.be.true('hasShadow');
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
});
});
});
});
describe('window.getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns valid source id', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
// Check format 'window:1234:0'.
const sourceId = w.getMediaSourceId();
expect(sourceId).to.match(/^window:\d+:\d+$/);
});
});
ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
afterEach(closeAllWindows);
it('returns valid handle', () => {
const w = new BrowserWindow({ show: false });
// The module's source code is hosted at
// https://github.com/electron/node-is-valid-window
const isValidWindow = require('is-valid-window');
expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
});
});
ifdescribe(process.platform === 'darwin')('previewFile', () => {
afterEach(closeAllWindows);
it('opens the path in Quick Look on macOS', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.previewFile(__filename);
w.closeFilePreview();
}).to.not.throw();
});
it('should not call BrowserWindow show event', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
let showCalled = false;
w.on('show', () => {
showCalled = true;
});
w.previewFile(__filename);
await setTimeout(500);
expect(showCalled).to.equal(false, 'should not have called show twice');
});
});
// TODO (jkleinsc) renable these tests on mas arm64
ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
};
afterEach(closeAllWindows);
it('separates the page context from the Electron/preload context', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
iw.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('enables context isolation on child windows', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const browserWindowCreated = once(app, 'browser-window-created');
iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
const [, window] = await browserWindowCreated;
expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
});
it('separates the page context from the Electron/preload context with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
ws.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('supports fetch api', async () => {
const fetchWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
}
});
const p = once(ipcMain, 'isolated-fetch-error');
fetchWindow.loadURL('about:blank');
const [, error] = await p;
expect(error).to.equal('Failed to fetch');
});
it('doesn\'t break ipc serialization', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadURL('about:blank');
iw.webContents.executeJavaScript(`
const opened = window.open()
openedLocation = opened.location.href
opened.close()
window.postMessage({openedLocation}, '*')
`);
const [, data] = await p;
expect(data.pageContext.openedLocation).to.equal('about:blank');
});
it('reports process.contextIsolated', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-process.js')
}
});
const p = once(ipcMain, 'context-isolation');
iw.loadURL('about:blank');
const [, contextIsolation] = await p;
expect(contextIsolation).to.be.true('contextIsolation');
});
});
it('reloading does not cause Node.js module API hangs after reload', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let count = 0;
ipcMain.on('async-node-api-done', () => {
if (count === 3) {
ipcMain.removeAllListeners('async-node-api-done');
done();
} else {
count++;
w.reload();
}
});
w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
});
describe('window.webContents.focus()', () => {
afterEach(closeAllWindows);
it('focuses window', async () => {
const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
w1.loadURL('about:blank');
const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
w2.loadURL('about:blank');
const w1Focused = once(w1, 'focus');
w1.webContents.focus();
await w1Focused;
expect(w1.webContents.isFocused()).to.be.true('focuses window');
});
});
ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
let w: BrowserWindow;
beforeEach(function () {
w = new BrowserWindow({
width: 100,
height: 100,
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
});
});
afterEach(closeAllWindows);
it('creates offscreen window with correct size', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
const [,, data] = await paint;
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
const size = data.getSize();
const { scaleFactor } = screen.getPrimaryDisplay();
expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
});
it('does not crash after navigation', () => {
w.webContents.loadURL('about:blank');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
describe('window.webContents.isOffscreen()', () => {
it('is true for offscreen type', () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
});
it('is false for regular window', () => {
const c = new BrowserWindow({ show: false });
expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
c.destroy();
});
});
describe('window.webContents.isPainting()', () => {
it('returns whether is currently painting', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await paint;
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('window.webContents.stopPainting()', () => {
it('stops painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
expect(w.webContents.isPainting()).to.be.false('isPainting');
});
});
describe('window.webContents.startPainting()', () => {
it('starts painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
w.webContents.startPainting();
await once(w.webContents, 'paint');
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('frameRate APIs', () => {
it('has default frame rate (function)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(60);
});
it('has default frame rate (property)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(60);
});
it('sets custom frame rate (function)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.setFrameRate(30);
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(30);
});
it('sets custom frame rate (property)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.frameRate = 30;
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(30);
});
});
});
describe('"transparent" option', () => {
afterEach(closeAllWindows);
ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => {
const w = new BrowserWindow({
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.be.false();
expect(w.isMinimized()).to.be.true();
});
// Only applicable on Windows where transparent windows can't be maximized.
ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
show: true
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
expect(w.isMaximized()).to.be.true();
// Fails when the transparent HWND is in an invalid maximized state.
expect(w.getBounds()).to.deep.equal(display.workArea);
const newBounds = { width: 256, height: 256, x: 0, y: 0 };
w.setBounds(newBounds);
expect(w.getBounds()).to.deep.equal(newBounds);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.GREEN,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
show: true,
transparent: true,
frame: false,
hasShadow: false
});
const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html');
await foregroundWindow.loadFile(colorFile);
await setTimeout(1000);
const screenCapture = await captureScreen();
const leftHalfColor = getPixelColor(screenCapture, {
x: display.size.width / 4,
y: display.size.height / 2
});
const rightHalfColor = getPixelColor(screenCapture, {
x: display.size.width - (display.size.width / 4),
y: display.size.height / 2
});
expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true();
expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true();
});
ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.PURPLE,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
hasShadow: false,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
}
});
foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html'));
await once(ipcMain, 'set-transparent');
await setTimeout();
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => {
const display = screen.getPrimaryDisplay();
for (const transparent of [false, undefined]) {
const window = new BrowserWindow({
...display.bounds,
transparent
});
await once(window, 'show');
await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>');
await setTimeout(500);
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
window.close();
// color-scheme is set to dark so background should not be white
expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false();
}
});
});
describe('"backgroundColor" option', () => {
afterEach(closeAllWindows);
// Linux/WOA doesn't return any capture sources.
ifit(process.platform === 'darwin')('should display the set color', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
show: true,
backgroundColor: HexColors.BLUE
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true();
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,562 |
[Bug]: Crash when opening and closing a child window a few times on macOS
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
macOS
### Operating System Version
Ventura 13.4
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
A child window should be able to be opened and closed multiple times without crashing.
### Actual Behavior
The Electron app crashes after opening a child window and then closing it. This usually happens after opening the child window a few times in a row.
### Testcase Gist URL
https://gist.github.com/jorodi/cbf4378f978e44de5034ab2d91f30387
### Additional Information
Caught error output from VS code terminal:
```
2023-06-02 08:24:57.023 Electron[80994:4778831] -[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f
2023-06-02 08:24:57.025 Electron[80994:4778831] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff802c7918a __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80279f42b objc_exception_throw + 48
2 CoreFoundation 0x00007ff802d14fef -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007ff802be4797 ___forwarding___ + 1392
4 CoreFoundation 0x00007ff802be4198 _CF_forwarding_prep_0 + 120
5 Electron Framework 0x000000010b707e38 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 154760
6 Electron Framework 0x000000010b7073e0 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 152112
7 Electron Framework 0x000000010b646b23 _ZN2v89CodeEvent10GetCommentEv + 4099
8 Electron Framework 0x000000010b56dc93 ElectronInitializeICUandStartNode + 207619
9 Electron Framework 0x000000010b56f2c4 ElectronInitializeICUandStartNode + 213300
10 Electron Framework 0x000000010b56f9fe ElectronInitializeICUandStartNode + 215150
11 Electron Framework 0x000000010b5634e1 ElectronInitializeICUandStartNode + 164689
12 Electron Framework 0x000000010b5633d3 ElectronInitializeICUandStartNode + 164419
13 Electron Framework 0x000000010c83be34 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 15780
14 Electron Framework 0x000000010c83b9df _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 14671
15 Electron Framework 0x000000010c83ad24 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 11412
16 Electron Framework 0x000000010b25edf6 Electron Framework + 826870
17 Electron Framework 0x000000010b1c4ff2 Electron Framework + 196594
)
/Users/jordan/parent-child-error/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGILL
```
|
https://github.com/electron/electron/issues/38562
|
https://github.com/electron/electron/pull/38603
|
9a9d8ae5ea61e17fd01e8975e81ed2a137a5fef6
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
| 2023-06-02T13:02:06Z |
c++
| 2023-06-08T10:18:37Z |
shell/browser/native_window_mac.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
#import <Cocoa/Cocoa.h>
#include <memory>
#include <string>
#include <vector>
#include "base/mac/scoped_nsobject.h"
#include "shell/browser/native_window.h"
#include "shell/common/api/api.mojom.h"
#include "ui/display/display_observer.h"
#include "ui/native_theme/native_theme_observer.h"
#include "ui/views/controls/native/native_view_host.h"
@class ElectronNSWindow;
@class ElectronNSWindowDelegate;
@class ElectronPreviewItem;
@class ElectronTouchBar;
@class WindowButtonsProxy;
namespace electron {
class RootViewMac;
class NativeWindowMac : public NativeWindow,
public ui::NativeThemeObserver,
public display::DisplayObserver {
public:
NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent);
~NativeWindowMac() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate = false) override;
gfx::Rect GetBounds() override;
bool IsNormal() override;
gfx::Rect GetNormalBounds() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relative_level) override;
std::string GetAlwaysOnTopLevel() override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
void SetBackgroundColor(SkColor color) override;
SkColor GetBackgroundColor() override;
void InvalidateShadow() override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetRepresentedFilename(const std::string& filename) override;
std::string GetRepresentedFilename() override;
void SetDocumentEdited(bool edited) override;
bool IsDocumentEdited() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
bool IsHiddenInMissionControl() override;
void SetHiddenInMissionControl(bool hidden) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetAutoHideCursor(bool auto_hide) override;
void SetVibrancy(const std::string& type) override;
void SetWindowButtonVisibility(bool visible) override;
bool GetWindowButtonVisibility() const override;
void SetWindowButtonPosition(absl::optional<gfx::Point> position) override;
absl::optional<gfx::Point> GetWindowButtonPosition() const override;
void RedrawTrafficLights() override;
void UpdateFrame() override;
void SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) override;
void RefreshTouchBarItem(const std::string& item_id) override;
void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item) override;
void SelectPreviousTab() override;
void SelectNextTab() override;
void MergeAllWindows() override;
void MoveTabToNewWindow() override;
void ToggleTabBar() override;
bool AddTabbedWindow(NativeWindow* window) override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void PreviewFile(const std::string& path,
const std::string& display_name) override;
void CloseFilePreview() override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
gfx::Rect GetWindowControlsOverlayRect() override;
void NotifyWindowEnterFullScreen() override;
void NotifyWindowLeaveFullScreen() override;
void SetActive(bool is_key) override;
bool IsActive() const override;
// Remove the specified child window without closing it.
void RemoveChildWindow(NativeWindow* child) override;
// Attach child windows, if the window is visible.
void AttachChildren() override;
// Detach window from parent without destroying it.
void DetachChildren() override;
void NotifyWindowWillEnterFullScreen();
void NotifyWindowWillLeaveFullScreen();
// Cleanup observers when window is getting closed. Note that the destructor
// can be called much later after window gets closed, so we should not do
// cleanup in destructor.
void Cleanup();
void UpdateVibrancyRadii(bool fullscreen);
void UpdateWindowOriginalFrame();
// Set the attribute of NSWindow while work around a bug of zoom button.
bool HasStyleMask(NSUInteger flag) const;
void SetStyleMask(bool on, NSUInteger flag);
void SetCollectionBehavior(bool on, NSUInteger flag);
void SetWindowLevel(int level);
bool HandleDeferredClose();
void SetHasDeferredWindowClose(bool defer_close) {
has_deferred_window_close_ = defer_close;
}
enum class VisualEffectState {
kFollowWindow,
kActive,
kInactive,
};
ElectronPreviewItem* preview_item() const { return preview_item_.get(); }
ElectronTouchBar* touch_bar() const { return touch_bar_.get(); }
bool zoom_to_page_width() const { return zoom_to_page_width_; }
bool always_simple_fullscreen() const { return always_simple_fullscreen_; }
// We need to save the result of windowWillUseStandardFrame:defaultFrame
// because macOS calls it with what it refers to as the "best fit" frame for a
// zoom. This means that even if an aspect ratio is set, macOS might adjust it
// to better fit the screen.
//
// Thus, we can't just calculate the maximized aspect ratio'd sizing from
// the current visible screen and compare that to the current window's frame
// to determine whether a window is maximized.
NSRect default_frame_for_zoom() const { return default_frame_for_zoom_; }
void set_default_frame_for_zoom(NSRect frame) {
default_frame_for_zoom_ = frame;
}
protected:
// views::WidgetDelegate:
views::View* GetContentsView() override;
bool CanMaximize() const override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
// ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
// display::DisplayObserver:
void OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) override;
private:
// Add custom layers to the content view.
void AddContentViewLayers();
void InternalSetWindowButtonVisibility(bool visible);
void InternalSetParentWindow(NativeWindow* parent, bool attach);
void SetForwardMouseMessages(bool forward);
ElectronNSWindow* window_; // Weak ref, managed by widget_.
base::scoped_nsobject<ElectronNSWindowDelegate> window_delegate_;
base::scoped_nsobject<ElectronPreviewItem> preview_item_;
base::scoped_nsobject<ElectronTouchBar> touch_bar_;
// The views::View that fills the client area.
std::unique_ptr<RootViewMac> root_view_;
bool fullscreen_before_kiosk_ = false;
bool is_kiosk_ = false;
bool zoom_to_page_width_ = false;
absl::optional<gfx::Point> traffic_light_position_;
// Trying to close an NSWindow during a fullscreen transition will cause the
// window to lock up. Use this to track if CloseWindow was called during a
// fullscreen transition, to defer the -[NSWindow close] call until the
// transition is complete.
bool has_deferred_window_close_ = false;
NSInteger attention_request_id_ = 0; // identifier from requestUserAttention
// The presentation options before entering kiosk mode.
NSApplicationPresentationOptions kiosk_options_;
// The "visualEffectState" option.
VisualEffectState visual_effect_state_ = VisualEffectState::kFollowWindow;
// The visibility mode of window button controls when explicitly set through
// setWindowButtonVisibility().
absl::optional<bool> window_button_visibility_;
// Controls the position and visibility of window buttons.
base::scoped_nsobject<WindowButtonsProxy> buttons_proxy_;
std::unique_ptr<SkRegion> draggable_region_;
// Maximizable window state; necessary for persistence through redraws.
bool maximizable_ = true;
bool user_set_bounds_maximized_ = false;
// Simple (pre-Lion) Fullscreen Settings
bool always_simple_fullscreen_ = false;
bool is_simple_fullscreen_ = false;
bool was_maximizable_ = false;
bool was_movable_ = false;
bool is_active_ = false;
NSRect original_frame_;
NSInteger original_level_;
NSUInteger simple_fullscreen_mask_;
NSRect default_frame_for_zoom_;
std::string vibrancy_type_;
// The presentation options before entering simple fullscreen mode.
NSApplicationPresentationOptions simple_fullscreen_options_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_MAC_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,562 |
[Bug]: Crash when opening and closing a child window a few times on macOS
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
macOS
### Operating System Version
Ventura 13.4
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
A child window should be able to be opened and closed multiple times without crashing.
### Actual Behavior
The Electron app crashes after opening a child window and then closing it. This usually happens after opening the child window a few times in a row.
### Testcase Gist URL
https://gist.github.com/jorodi/cbf4378f978e44de5034ab2d91f30387
### Additional Information
Caught error output from VS code terminal:
```
2023-06-02 08:24:57.023 Electron[80994:4778831] -[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f
2023-06-02 08:24:57.025 Electron[80994:4778831] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff802c7918a __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80279f42b objc_exception_throw + 48
2 CoreFoundation 0x00007ff802d14fef -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007ff802be4797 ___forwarding___ + 1392
4 CoreFoundation 0x00007ff802be4198 _CF_forwarding_prep_0 + 120
5 Electron Framework 0x000000010b707e38 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 154760
6 Electron Framework 0x000000010b7073e0 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 152112
7 Electron Framework 0x000000010b646b23 _ZN2v89CodeEvent10GetCommentEv + 4099
8 Electron Framework 0x000000010b56dc93 ElectronInitializeICUandStartNode + 207619
9 Electron Framework 0x000000010b56f2c4 ElectronInitializeICUandStartNode + 213300
10 Electron Framework 0x000000010b56f9fe ElectronInitializeICUandStartNode + 215150
11 Electron Framework 0x000000010b5634e1 ElectronInitializeICUandStartNode + 164689
12 Electron Framework 0x000000010b5633d3 ElectronInitializeICUandStartNode + 164419
13 Electron Framework 0x000000010c83be34 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 15780
14 Electron Framework 0x000000010c83b9df _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 14671
15 Electron Framework 0x000000010c83ad24 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 11412
16 Electron Framework 0x000000010b25edf6 Electron Framework + 826870
17 Electron Framework 0x000000010b1c4ff2 Electron Framework + 196594
)
/Users/jordan/parent-child-error/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGILL
```
|
https://github.com/electron/electron/issues/38562
|
https://github.com/electron/electron/pull/38603
|
9a9d8ae5ea61e17fd01e8975e81ed2a137a5fef6
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
| 2023-06-02T13:02:06Z |
c++
| 2023-06-08T10:18:37Z |
shell/browser/native_window_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window_mac.h"
#include <AvailabilityMacros.h>
#include <objc/objc-runtime.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/mac/mac_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/sys_string_conversions.h"
#include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#include "components/remote_cocoa/browser/scoped_cg_window_id.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "shell/browser/browser.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/cocoa/electron_native_widget_mac.h"
#include "shell/browser/ui/cocoa/electron_ns_window.h"
#include "shell/browser/ui/cocoa/electron_ns_window_delegate.h"
#include "shell/browser/ui/cocoa/electron_preview_item.h"
#include "shell/browser/ui/cocoa/electron_touch_bar.h"
#include "shell/browser/ui/cocoa/root_view_mac.h"
#include "shell/browser/ui/cocoa/window_buttons_proxy.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/window_list.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "skia/ext/skia_utils_mac.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
#include "ui/base/hit_test.h"
#include "ui/display/screen.h"
#include "ui/gfx/skia_util.h"
#include "ui/gl/gpu_switching_manager.h"
#include "ui/views/background.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/native_frame_view_mac.h"
@interface ElectronProgressBar : NSProgressIndicator
@end
@implementation ElectronProgressBar
- (void)drawRect:(NSRect)dirtyRect {
if (self.style != NSProgressIndicatorBarStyle)
return;
// Draw edges of rounded rect.
NSRect rect = NSInsetRect([self bounds], 1.0, 1.0);
CGFloat radius = rect.size.height / 2;
NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:2.0];
[[NSColor grayColor] set];
[bezier_path stroke];
// Fill the rounded rect.
rect = NSInsetRect(rect, 2.0, 2.0);
radius = rect.size.height / 2;
bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[bezier_path setLineWidth:1.0];
[bezier_path addClip];
// Calculate the progress width.
rect.size.width =
floor(rect.size.width * ([self doubleValue] / [self maxValue]));
// Fill the progress bar with color blue.
[[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set];
NSRectFill(rect);
}
@end
namespace gin {
template <>
struct Converter<electron::NativeWindowMac::VisualEffectState> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindowMac::VisualEffectState* out) {
using VisualEffectState = electron::NativeWindowMac::VisualEffectState;
std::string visual_effect_state;
if (!ConvertFromV8(isolate, val, &visual_effect_state))
return false;
if (visual_effect_state == "followWindow") {
*out = VisualEffectState::kFollowWindow;
} else if (visual_effect_state == "active") {
*out = VisualEffectState::kActive;
} else if (visual_effect_state == "inactive") {
*out = VisualEffectState::kInactive;
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
bool IsFramelessWindow(NSView* view) {
NSWindow* nswindow = [view window];
if (![nswindow respondsToSelector:@selector(shell)])
return false;
NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell];
return window && !window->has_frame();
}
IMP original_set_frame_size = nullptr;
IMP original_view_did_move_to_superview = nullptr;
// This method is directly called by NSWindow during a window resize on OSX
// 10.10.0, beta 2. We must override it to prevent the content view from
// shrinking.
void SetFrameSize(NSView* self, SEL _cmd, NSSize size) {
if (!IsFramelessWindow(self)) {
auto original =
reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size);
return original(self, _cmd, size);
}
// For frameless window, resize the view to cover full window.
if ([self superview])
size = [[self superview] bounds].size;
auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>(
[[self superclass] instanceMethodForSelector:_cmd]);
super_impl(self, _cmd, size);
}
// The contentView gets moved around during certain full-screen operations.
// This is less than ideal, and should eventually be removed.
void ViewDidMoveToSuperview(NSView* self, SEL _cmd) {
if (!IsFramelessWindow(self)) {
// [BridgedContentView viewDidMoveToSuperview];
auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>(
original_view_did_move_to_superview);
if (original)
original(self, _cmd);
return;
}
[self setFrame:[[self superview] bounds]];
}
} // namespace
NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent), root_view_(new RootViewMac(this)) {
ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this);
display::Screen::GetScreen()->AddObserver(this);
int width = 800, height = 600;
options.Get(options::kWidth, &width);
options.Get(options::kHeight, &height);
NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame];
gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2),
round((NSHeight(main_screen_rect) - height) / 2), width,
height);
bool resizable = true;
options.Get(options::kResizable, &resizable);
options.Get(options::kZoomToPageWidth, &zoom_to_page_width_);
options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_);
options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_);
options.Get(options::kVisualEffectState, &visual_effect_state_);
if (options.Has(options::kFullscreenWindowTitle)) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"\"fullscreenWindowTitle\" option has been deprecated and is "
"no-op now.",
"electron");
}
bool minimizable = true;
options.Get(options::kMinimizable, &minimizable);
bool maximizable = true;
options.Get(options::kMaximizable, &maximizable);
bool closable = true;
options.Get(options::kClosable, &closable);
std::string tabbingIdentifier;
options.Get(options::kTabbingIdentifier, &tabbingIdentifier);
std::string windowType;
options.Get(options::kType, &windowType);
bool hiddenInMissionControl = false;
options.Get(options::kHiddenInMissionControl, &hiddenInMissionControl);
bool useStandardWindow = true;
// eventually deprecate separate "standardWindow" option in favor of
// standard / textured window types
options.Get(options::kStandardWindow, &useStandardWindow);
if (windowType == "textured") {
useStandardWindow = false;
}
// The window without titlebar is treated the same with frameless window.
if (title_bar_style_ != TitleBarStyle::kNormal)
set_has_frame(false);
NSUInteger styleMask = NSWindowStyleMaskTitled;
// The NSWindowStyleMaskFullSizeContentView style removes rounded corners
// for frameless window.
bool rounded_corner = true;
options.Get(options::kRoundedCorners, &rounded_corner);
if (!rounded_corner && !has_frame())
styleMask = NSWindowStyleMaskBorderless;
if (minimizable)
styleMask |= NSWindowStyleMaskMiniaturizable;
if (closable)
styleMask |= NSWindowStyleMaskClosable;
if (resizable)
styleMask |= NSWindowStyleMaskResizable;
if (!useStandardWindow || transparent() || !has_frame())
styleMask |= NSWindowStyleMaskTexturedBackground;
// Create views::Widget and assign window_ with it.
// TODO(zcbenz): Get rid of the window_ in future.
views::Widget::InitParams params;
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = bounds;
params.delegate = this;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
SetCanResize(resizable);
window_ = static_cast<ElectronNSWindow*>(
widget()->GetNativeWindow().GetNativeNSWindow());
RegisterDeleteDelegateCallback(base::BindOnce(
[](NativeWindowMac* window) {
if (window->window_)
window->window_ = nil;
if (window->buttons_proxy_)
window->buttons_proxy_.reset();
},
this));
[window_ setEnableLargerThanScreen:enable_larger_than_screen()];
window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]);
[window_ setDelegate:window_delegate_];
// Only use native parent window for non-modal windows.
if (parent && !is_modal()) {
SetParentWindow(parent);
}
if (transparent()) {
// Setting the background color to clear will also hide the shadow.
[window_ setBackgroundColor:[NSColor clearColor]];
}
if (windowType == "desktop") {
[window_ setLevel:kCGDesktopWindowLevel - 1];
[window_ setDisableKeyOrMainWindow:YES];
[window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorStationary |
NSWindowCollectionBehaviorIgnoresCycle)];
}
if (windowType == "panel") {
[window_ setLevel:NSFloatingWindowLevel];
}
bool focusable;
if (options.Get(options::kFocusable, &focusable) && !focusable)
[window_ setDisableKeyOrMainWindow:YES];
if (transparent() || !has_frame()) {
// Don't show title bar.
[window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden];
// Remove non-transparent corners, see
// https://github.com/electron/electron/issues/517.
[window_ setOpaque:NO];
// Show window buttons if titleBarStyle is not "normal".
if (title_bar_style_ == TitleBarStyle::kNormal) {
InternalSetWindowButtonVisibility(false);
} else {
buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]);
[buttons_proxy_ setHeight:titlebar_overlay_height()];
if (traffic_light_position_) {
[buttons_proxy_ setMargin:*traffic_light_position_];
} else if (title_bar_style_ == TitleBarStyle::kHiddenInset) {
// For macOS >= 11, while this value does not match official macOS apps
// like Safari or Notes, it matches titleBarStyle's old implementation
// before Electron <= 12.
[buttons_proxy_ setMargin:gfx::Point(12, 11)];
}
if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) {
[buttons_proxy_ setShowOnHover:YES];
} else {
// customButtonsOnHover does not show buttons initially.
InternalSetWindowButtonVisibility(true);
}
}
}
// Create a tab only if tabbing identifier is specified and window has
// a native title bar.
if (tabbingIdentifier.empty() || transparent() || !has_frame()) {
[window_ setTabbingMode:NSWindowTabbingModeDisallowed];
} else {
[window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)];
}
// Resize to content bounds.
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
if (!has_frame() || use_content_size)
SetContentSize(gfx::Size(width, height));
// Enable the NSView to accept first mouse event.
bool acceptsFirstMouse = false;
options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse);
[window_ setAcceptsFirstMouse:acceptsFirstMouse];
// Disable auto-hiding cursor.
bool disableAutoHideCursor = false;
options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor);
[window_ setDisableAutoHideCursor:disableAutoHideCursor];
SetHiddenInMissionControl(hiddenInMissionControl);
// Set maximizable state last to ensure zoom button does not get reset
// by calls to other APIs.
SetMaximizable(maximizable);
// Default content view.
SetContentView(new views::View());
AddContentViewLayers();
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
NativeWindowMac::~NativeWindowMac() = default;
void NativeWindowMac::SetContentView(views::View* view) {
views::View* root_view = GetContentsView();
if (content_view())
root_view->RemoveChildView(content_view());
set_content_view(view);
root_view->AddChildView(content_view());
root_view->Layout();
}
void NativeWindowMac::Close() {
if (!IsClosable()) {
WindowList::WindowCloseCancelled(this);
return;
}
if (fullscreen_transition_state() != FullScreenTransitionState::kNone) {
SetHasDeferredWindowClose(true);
return;
}
// If a sheet is attached to the window when we call
// [window_ performClose:nil], the window won't close properly
// even after the user has ended the sheet.
// Ensure it's closed before calling [window_ performClose:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
if (is_modal() && parent() && IsVisible()) {
NotifyWindowCloseButtonClicked();
}
}
void NativeWindowMac::CloseImmediately() {
// Retain the child window before closing it. If the last reference to the
// NSWindow goes away inside -[NSWindow close], then bad stuff can happen.
// See e.g. http://crbug.com/616701.
base::scoped_nsobject<NSWindow> child_window(window_,
base::scoped_policy::RETAIN);
[window_ close];
}
void NativeWindowMac::Focus(bool focus) {
if (!IsVisible())
return;
if (focus) {
[[NSApplication sharedApplication] activateIgnoringOtherApps:NO];
[window_ makeKeyAndOrderFront:nil];
} else {
[window_ orderOut:nil];
[window_ orderBack:nil];
}
}
bool NativeWindowMac::IsFocused() {
return [window_ isKeyWindow];
}
void NativeWindowMac::Show() {
if (is_modal() && parent()) {
NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow();
if ([window_ sheetParent] == nil)
[window beginSheet:window_
completionHandler:^(NSModalResponse){
}];
return;
}
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
// This method is supposed to put focus on window, however if the app does not
// have focus then "makeKeyAndOrderFront" will only show the window.
[NSApp activateIgnoringOtherApps:YES];
[window_ makeKeyAndOrderFront:nil];
}
void NativeWindowMac::ShowInactive() {
// Reattach the window to the parent to actually show it.
if (parent())
InternalSetParentWindow(parent(), true);
[window_ orderFrontRegardless];
}
void NativeWindowMac::Hide() {
// If a sheet is attached to the window when we call [window_ orderOut:nil],
// the sheet won't be able to show again on the same window.
// Ensure it's closed before calling [window_ orderOut:nil].
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
if (is_modal() && parent()) {
[window_ orderOut:nil];
[parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_];
return;
}
DetachChildren();
// Detach the window from the parent before.
if (parent())
InternalSetParentWindow(parent(), false);
[window_ orderOut:nil];
}
bool NativeWindowMac::IsVisible() {
bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible;
return [window_ isVisible] && !occluded && !IsMinimized();
}
bool NativeWindowMac::IsEnabled() {
return [window_ attachedSheet] == nil;
}
void NativeWindowMac::SetEnabled(bool enable) {
if (!enable) {
NSRect frame = [window_ frame];
NSWindow* window =
[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, frame.size.width,
frame.size.height)
styleMask:NSWindowStyleMaskTitled
backing:NSBackingStoreBuffered
defer:NO];
[window setAlphaValue:0.5];
[window_ beginSheet:window
completionHandler:^(NSModalResponse returnCode) {
NSLog(@"main window disabled");
return;
}];
} else if ([window_ attachedSheet]) {
[window_ endSheet:[window_ attachedSheet]];
}
}
void NativeWindowMac::Maximize() {
const bool is_visible = [window_ isVisible];
if (IsMaximized()) {
if (!is_visible)
ShowInactive();
return;
}
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ zoom:nil];
if (!is_visible) {
ShowInactive();
NotifyWindowMaximize();
}
}
void NativeWindowMac::Unmaximize() {
// Bail if the last user set bounds were the same size as the window
// screen (e.g. the user set the window to maximized via setBounds)
//
// Per docs during zoom:
// > If there’s no saved user state because there has been no previous
// > zoom,the size and location of the window don’t change.
//
// However, in classic Apple fashion, this is not the case in practice,
// and the frame inexplicably becomes very tiny. We should prevent
// zoom from being called if the window is being unmaximized and its
// unmaximized window bounds are themselves functionally maximized.
if (!IsMaximized() || user_set_bounds_maximized_)
return;
[window_ zoom:nil];
}
bool NativeWindowMac::IsMaximized() {
// It's possible for [window_ isZoomed] to be true
// when the window is minimized or fullscreened.
if (IsMinimized() || IsFullscreen())
return false;
if (HasStyleMask(NSWindowStyleMaskResizable) != 0)
return [window_ isZoomed];
NSRect rectScreen = GetAspectRatio() > 0.0
? default_frame_for_zoom()
: [[NSScreen mainScreen] visibleFrame];
return NSEqualRects([window_ frame], rectScreen);
}
void NativeWindowMac::Minimize() {
if (IsMinimized())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
[window_ miniaturize:nil];
}
void NativeWindowMac::Restore() {
[window_ deminiaturize:nil];
}
bool NativeWindowMac::IsMinimized() {
return [window_ isMiniaturized];
}
bool NativeWindowMac::HandleDeferredClose() {
if (has_deferred_window_close_) {
SetHasDeferredWindowClose(false);
Close();
return true;
}
return false;
}
void NativeWindowMac::RemoveChildWindow(NativeWindow* child) {
child_windows_.remove_if([&child](NativeWindow* w) { return (w == child); });
[window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()];
}
void NativeWindowMac::AttachChildren() {
for (auto* child : child_windows_) {
auto* child_nswindow = child->GetNativeWindow().GetNativeNSWindow();
if ([child_nswindow parentWindow] == window_)
continue;
// Attaching a window as a child window resets its window level, so
// save and restore it afterwards.
NSInteger level = window_.level;
[window_ addChildWindow:child_nswindow ordered:NSWindowAbove];
[window_ setLevel:level];
}
}
void NativeWindowMac::DetachChildren() {
DCHECK(child_windows_.size() == [[window_ childWindows] count]);
// Hide all children before hiding/minimizing the window.
// NativeWidgetNSWindowBridge::NotifyVisibilityChangeDown()
// will DCHECK otherwise.
for (auto* child : child_windows_) {
[child->GetNativeWindow().GetNativeNSWindow() orderOut:nil];
}
}
void NativeWindowMac::SetFullScreen(bool fullscreen) {
if (!has_frame() && !HasStyleMask(NSWindowStyleMaskTitled))
return;
// [NSWindow -toggleFullScreen] is an asynchronous operation, which means
// that it's possible to call it while a fullscreen transition is currently
// in process. This can create weird behavior (incl. phantom windows),
// so we want to schedule a transition for when the current one has completed.
if (fullscreen_transition_state() != FullScreenTransitionState::kNone) {
if (!pending_transitions_.empty()) {
bool last_pending = pending_transitions_.back();
// Only push new transitions if they're different than the last transition
// in the queue.
if (last_pending != fullscreen)
pending_transitions_.push(fullscreen);
} else {
pending_transitions_.push(fullscreen);
}
return;
}
if (fullscreen == IsFullscreen() || !IsFullScreenable())
return;
// Take note of the current window size
if (IsNormal())
UpdateWindowOriginalFrame();
// This needs to be set here because it can be the case that
// SetFullScreen is called by a user before windowWillEnterFullScreen
// or windowWillExitFullScreen are invoked, and so a potential transition
// could be dropped.
fullscreen_transition_state_ = fullscreen
? FullScreenTransitionState::kEntering
: FullScreenTransitionState::kExiting;
[window_ toggleFullScreenMode:nil];
}
bool NativeWindowMac::IsFullscreen() const {
return HasStyleMask(NSWindowStyleMaskFullScreen);
}
void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) {
// Do nothing if in fullscreen mode.
if (IsFullscreen())
return;
// Check size constraints since setFrame does not check it.
gfx::Size size = bounds.size();
size.SetToMax(GetMinimumSize());
gfx::Size max_size = GetMaximumSize();
if (!max_size.IsEmpty())
size.SetToMin(max_size);
NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height());
// Flip coordinates based on the primary screen.
NSScreen* screen = [[NSScreen screens] firstObject];
cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y();
[window_ setFrame:cocoa_bounds display:YES animate:animate];
user_set_bounds_maximized_ = IsMaximized() ? true : false;
UpdateWindowOriginalFrame();
}
gfx::Rect NativeWindowMac::GetBounds() {
NSRect frame = [window_ frame];
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
}
bool NativeWindowMac::IsNormal() {
return NativeWindow::IsNormal() && !IsSimpleFullScreen();
}
gfx::Rect NativeWindowMac::GetNormalBounds() {
if (IsNormal()) {
return GetBounds();
}
NSRect frame = original_frame_;
gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame));
NSScreen* screen = [[NSScreen screens] firstObject];
bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame));
return bounds;
// Works on OS_WIN !
// return widget()->GetRestoredBounds();
}
void NativeWindowMac::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
auto convertSize = [this](const gfx::Size& size) {
// Our frameless window still has titlebar attached, so setting contentSize
// will result in actual content size being larger.
if (!has_frame()) {
NSRect frame = NSMakeRect(0, 0, size.width(), size.height());
NSRect content = [window_ originalContentRectForFrameRect:frame];
return content.size;
} else {
return NSMakeSize(size.width(), size.height());
}
};
NSView* content = [window_ contentView];
if (size_constraints.HasMinimumSize()) {
NSSize min_size = convertSize(size_constraints.GetMinimumSize());
[window_ setContentMinSize:[content convertSize:min_size toView:nil]];
}
if (size_constraints.HasMaximumSize()) {
NSSize max_size = convertSize(size_constraints.GetMaximumSize());
[window_ setContentMaxSize:[content convertSize:max_size toView:nil]];
}
NativeWindow::SetContentSizeConstraints(size_constraints);
}
bool NativeWindowMac::MoveAbove(const std::string& sourceId) {
const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId);
if (id.type != content::DesktopMediaID::TYPE_WINDOW)
return false;
// Check if the window source is valid.
const CGWindowID window_id = id.id;
if (!webrtc::GetWindowOwnerPid(window_id))
return false;
[window_ orderWindow:NSWindowAbove relativeTo:id.id];
return true;
}
void NativeWindowMac::MoveTop() {
[window_ orderWindow:NSWindowAbove relativeTo:0];
}
void NativeWindowMac::SetResizable(bool resizable) {
ScopedDisableResize disable_resize;
SetStyleMask(resizable, NSWindowStyleMaskResizable);
SetCanResize(resizable);
}
bool NativeWindowMac::IsResizable() {
bool in_fs_transition =
fullscreen_transition_state() != FullScreenTransitionState::kNone;
bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable);
return has_rs_mask && !IsFullscreen() && !in_fs_transition;
}
void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable];
}
bool NativeWindowMac::IsMovable() {
return [window_ isMovable];
}
void NativeWindowMac::SetMinimizable(bool minimizable) {
SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable);
}
bool NativeWindowMac::IsMinimizable() {
return HasStyleMask(NSWindowStyleMaskMiniaturizable);
}
void NativeWindowMac::SetMaximizable(bool maximizable) {
maximizable_ = maximizable;
[[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable];
}
bool NativeWindowMac::IsMaximizable() {
return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled];
}
void NativeWindowMac::SetFullScreenable(bool fullscreenable) {
SetCollectionBehavior(fullscreenable,
NSWindowCollectionBehaviorFullScreenPrimary);
// On EL Capitan this flag is required to hide fullscreen button.
SetCollectionBehavior(!fullscreenable,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsFullScreenable() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
}
void NativeWindowMac::SetClosable(bool closable) {
SetStyleMask(closable, NSWindowStyleMaskClosable);
}
bool NativeWindowMac::IsClosable() {
return HasStyleMask(NSWindowStyleMaskClosable);
}
void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level_name,
int relative_level) {
if (z_order == ui::ZOrderLevel::kNormal) {
SetWindowLevel(NSNormalWindowLevel);
return;
}
int level = NSNormalWindowLevel;
if (level_name == "floating") {
level = NSFloatingWindowLevel;
} else if (level_name == "torn-off-menu") {
level = NSTornOffMenuWindowLevel;
} else if (level_name == "modal-panel") {
level = NSModalPanelWindowLevel;
} else if (level_name == "main-menu") {
level = NSMainMenuWindowLevel;
} else if (level_name == "status") {
level = NSStatusWindowLevel;
} else if (level_name == "pop-up-menu") {
level = NSPopUpMenuWindowLevel;
} else if (level_name == "screen-saver") {
level = NSScreenSaverWindowLevel;
}
SetWindowLevel(level + relative_level);
}
std::string NativeWindowMac::GetAlwaysOnTopLevel() {
std::string level_name = "normal";
int level = [window_ level];
if (level == NSFloatingWindowLevel) {
level_name = "floating";
} else if (level == NSTornOffMenuWindowLevel) {
level_name = "torn-off-menu";
} else if (level == NSModalPanelWindowLevel) {
level_name = "modal-panel";
} else if (level == NSMainMenuWindowLevel) {
level_name = "main-menu";
} else if (level == NSStatusWindowLevel) {
level_name = "status";
} else if (level == NSPopUpMenuWindowLevel) {
level_name = "pop-up-menu";
} else if (level == NSScreenSaverWindowLevel) {
level_name = "screen-saver";
}
return level_name;
}
void NativeWindowMac::SetWindowLevel(int unbounded_level) {
int level = std::min(
std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)),
CGWindowLevelForKey(kCGMaximumWindowLevelKey));
ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel
? ui::ZOrderLevel::kNormal
: ui::ZOrderLevel::kFloatingWindow;
bool did_z_order_level_change = z_order_level != GetZOrderLevel();
was_maximizable_ = IsMaximizable();
// We need to explicitly keep the NativeWidget up to date, since it stores the
// window level in a local variable, rather than reading it from the NSWindow.
// Unfortunately, it results in a second setLevel call. It's not ideal, but we
// don't expect this to cause any user-visible jank.
widget()->SetZOrderLevel(z_order_level);
[window_ setLevel:level];
// Set level will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(was_maximizable_);
// This must be notified at the very end or IsAlwaysOnTop
// will not yet have been updated to reflect the new status
if (did_z_order_level_change)
NativeWindow::NotifyWindowAlwaysOnTopChanged();
}
ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() {
return widget()->GetZOrderLevel();
}
void NativeWindowMac::Center() {
[window_ center];
}
void NativeWindowMac::Invalidate() {
[window_ flushWindow];
[[window_ contentView] setNeedsDisplay:YES];
}
void NativeWindowMac::SetTitle(const std::string& title) {
[window_ setTitle:base::SysUTF8ToNSString(title)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetTitle() {
return base::SysNSStringToUTF8([window_ title]);
}
void NativeWindowMac::FlashFrame(bool flash) {
if (flash) {
attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest];
} else {
[NSApp cancelUserAttentionRequest:attention_request_id_];
attention_request_id_ = 0;
}
}
void NativeWindowMac::SetSkipTaskbar(bool skip) {}
bool NativeWindowMac::IsExcludedFromShownWindowsMenu() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
return [window isExcludedFromWindowsMenu];
}
void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
[window setExcludedFromWindowsMenu:excluded];
}
void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
// We only want to force screen recalibration if we're in simpleFullscreen
// mode.
if (!is_simple_fullscreen_)
return;
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr()));
}
void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
if (simple_fullscreen && !is_simple_fullscreen_) {
is_simple_fullscreen_ = true;
// Take note of the current window size and level
if (IsNormal()) {
UpdateWindowOriginalFrame();
original_level_ = [window_ level];
}
simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions];
simple_fullscreen_mask_ = [window styleMask];
// We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu
// bar
NSApplicationPresentationOptions options =
NSApplicationPresentationAutoHideDock |
NSApplicationPresentationAutoHideMenuBar;
[NSApp setPresentationOptions:options];
was_maximizable_ = IsMaximizable();
was_movable_ = IsMovable();
NSRect fullscreenFrame = [window.screen frame];
// If our app has dock hidden, set the window level higher so another app's
// menu bar doesn't appear on top of our fullscreen app.
if ([[NSRunningApplication currentApplication] activationPolicy] !=
NSApplicationActivationPolicyRegular) {
window.level = NSPopUpMenuWindowLevel;
}
// Always hide the titlebar in simple fullscreen mode.
//
// Note that we must remove the NSWindowStyleMaskTitled style instead of
// using the [window_ setTitleVisibility:], as the latter would leave the
// window with rounded corners.
SetStyleMask(false, NSWindowStyleMaskTitled);
if (!window_button_visibility_.has_value()) {
// Lets keep previous behaviour - hide window controls in titled
// fullscreen mode when not specified otherwise.
InternalSetWindowButtonVisibility(false);
}
[window setFrame:fullscreenFrame display:YES animate:YES];
// Fullscreen windows can't be resized, minimized, maximized, or moved
SetMinimizable(false);
SetResizable(false);
SetMaximizable(false);
SetMovable(false);
} else if (!simple_fullscreen && is_simple_fullscreen_) {
is_simple_fullscreen_ = false;
[window setFrame:original_frame_ display:YES animate:YES];
window.level = original_level_;
[NSApp setPresentationOptions:simple_fullscreen_options_];
// Restore original style mask
ScopedDisableResize disable_resize;
[window_ setStyleMask:simple_fullscreen_mask_];
// Restore window manipulation abilities
SetMaximizable(was_maximizable_);
SetMovable(was_movable_);
// Restore default window controls visibility state.
if (!window_button_visibility_.has_value()) {
bool visibility;
if (has_frame())
visibility = true;
else
visibility = title_bar_style_ != TitleBarStyle::kNormal;
InternalSetWindowButtonVisibility(visibility);
}
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
}
bool NativeWindowMac::IsSimpleFullScreen() {
return is_simple_fullscreen_;
}
void NativeWindowMac::SetKiosk(bool kiosk) {
if (kiosk && !is_kiosk_) {
kiosk_options_ = [NSApp currentSystemPresentationOptions];
NSApplicationPresentationOptions options =
NSApplicationPresentationHideDock |
NSApplicationPresentationHideMenuBar |
NSApplicationPresentationDisableAppleMenu |
NSApplicationPresentationDisableProcessSwitching |
NSApplicationPresentationDisableForceQuit |
NSApplicationPresentationDisableSessionTermination |
NSApplicationPresentationDisableHideApplication;
[NSApp setPresentationOptions:options];
is_kiosk_ = true;
fullscreen_before_kiosk_ = IsFullscreen();
if (!fullscreen_before_kiosk_)
SetFullScreen(true);
} else if (!kiosk && is_kiosk_) {
is_kiosk_ = false;
if (!fullscreen_before_kiosk_)
SetFullScreen(false);
// Set presentation options *after* asynchronously exiting
// fullscreen to ensure they take effect.
[NSApp setPresentationOptions:kiosk_options_];
}
}
bool NativeWindowMac::IsKiosk() {
return is_kiosk_;
}
void NativeWindowMac::SetBackgroundColor(SkColor color) {
base::ScopedCFTypeRef<CGColorRef> cgcolor(
skia::CGColorCreateFromSkColor(color));
[[[window_ contentView] layer] setBackgroundColor:cgcolor];
}
SkColor NativeWindowMac::GetBackgroundColor() {
CGColorRef color = [[[window_ contentView] layer] backgroundColor];
if (!color)
return SK_ColorTRANSPARENT;
return skia::CGColorRefToSkColor(color);
}
void NativeWindowMac::SetHasShadow(bool has_shadow) {
[window_ setHasShadow:has_shadow];
}
bool NativeWindowMac::HasShadow() {
return [window_ hasShadow];
}
void NativeWindowMac::InvalidateShadow() {
[window_ invalidateShadow];
}
void NativeWindowMac::SetOpacity(const double opacity) {
const double boundedOpacity = std::clamp(opacity, 0.0, 1.0);
[window_ setAlphaValue:boundedOpacity];
}
double NativeWindowMac::GetOpacity() {
return [window_ alphaValue];
}
void NativeWindowMac::SetRepresentedFilename(const std::string& filename) {
[window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
std::string NativeWindowMac::GetRepresentedFilename() {
return base::SysNSStringToUTF8([window_ representedFilename]);
}
void NativeWindowMac::SetDocumentEdited(bool edited) {
[window_ setDocumentEdited:edited];
if (buttons_proxy_)
[buttons_proxy_ redraw];
}
bool NativeWindowMac::IsDocumentEdited() {
return [window_ isDocumentEdited];
}
bool NativeWindowMac::IsHiddenInMissionControl() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorTransient;
}
void NativeWindowMac::SetHiddenInMissionControl(bool hidden) {
SetCollectionBehavior(hidden, NSWindowCollectionBehaviorTransient);
}
void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) {
[window_ setIgnoresMouseEvents:ignore];
if (!ignore) {
SetForwardMouseMessages(NO);
} else {
SetForwardMouseMessages(forward);
}
}
void NativeWindowMac::SetContentProtection(bool enable) {
[window_
setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly];
}
void NativeWindowMac::SetFocusable(bool focusable) {
// No known way to unfocus the window if it had the focus. Here we do not
// want to call Focus(false) because it moves the window to the back, i.e.
// at the bottom in term of z-order.
[window_ setDisableKeyOrMainWindow:!focusable];
}
bool NativeWindowMac::IsFocusable() {
return ![window_ disableKeyOrMainWindow];
}
void NativeWindowMac::AddBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
if (view->GetInspectableWebContentsView())
[view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView()
removeFromSuperview];
remove_browser_view(view);
[CATransaction commit];
}
void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (!view) {
[CATransaction commit];
return;
}
remove_browser_view(view);
add_browser_view(view);
if (view->GetInspectableWebContentsView()) {
auto* native_view = view->GetInspectableWebContentsView()
->GetNativeView()
.GetNativeNSView();
[[window_ contentView] addSubview:native_view
positioned:NSWindowAbove
relativeTo:nil];
native_view.hidden = NO;
}
[CATransaction commit];
}
void NativeWindowMac::SetParentWindow(NativeWindow* parent) {
InternalSetParentWindow(parent, IsVisible());
}
gfx::NativeView NativeWindowMac::GetNativeView() const {
return [window_ contentView];
}
gfx::NativeWindow NativeWindowMac::GetNativeWindow() const {
return window_;
}
gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const {
return [window_ windowNumber];
}
content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const {
auto desktop_media_id = content::DesktopMediaID(
content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget());
// c.f.
// https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=775-780;drc=79502ab47f61bff351426f57f576daef02b1a8dc
// Refs https://github.com/electron/electron/pull/30507
// TODO(deepak1556): Match upstream for `kWindowCaptureMacV2`
#if 0
if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) {
desktop_media_id.window_id = desktop_media_id.id;
}
#endif
return desktop_media_id;
}
NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const {
return [window_ contentView];
}
void NativeWindowMac::SetProgressBar(double progress,
const NativeWindow::ProgressState state) {
NSDockTile* dock_tile = [NSApp dockTile];
// Sometimes macOS would install a default contentView for dock, we must
// verify whether NSProgressIndicator has been installed.
bool first_time = !dock_tile.contentView ||
[[dock_tile.contentView subviews] count] == 0 ||
![[[dock_tile.contentView subviews] lastObject]
isKindOfClass:[NSProgressIndicator class]];
// For the first time API invoked, we need to create a ContentView in
// DockTile.
if (first_time) {
NSImageView* image_view = [[[NSImageView alloc] init] autorelease];
[image_view setImage:[NSApp applicationIconImage]];
[dock_tile setContentView:image_view];
NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0);
NSProgressIndicator* progress_indicator =
[[[ElectronProgressBar alloc] initWithFrame:frame] autorelease];
[progress_indicator setStyle:NSProgressIndicatorBarStyle];
[progress_indicator setIndeterminate:NO];
[progress_indicator setBezeled:YES];
[progress_indicator setMinValue:0];
[progress_indicator setMaxValue:1];
[progress_indicator setHidden:NO];
[dock_tile.contentView addSubview:progress_indicator];
}
NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>(
[[[dock_tile contentView] subviews] lastObject]);
if (progress < 0) {
[progress_indicator setHidden:YES];
} else if (progress > 1) {
[progress_indicator setHidden:NO];
[progress_indicator setIndeterminate:YES];
[progress_indicator setDoubleValue:1];
} else {
[progress_indicator setHidden:NO];
[progress_indicator setDoubleValue:progress];
}
[dock_tile display];
}
void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) {}
void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) {
// In order for NSWindows to be visible on fullscreen we need to invoke
// app.dock.hide() since Apple changed the underlying functionality of
// NSWindows starting with 10.14 to disallow NSWindows from floating on top of
// fullscreen apps.
if (!skipTransformProcessType) {
if (visibleOnFullScreen) {
Browser::Get()->DockHide();
} else {
Browser::Get()->DockShow(JavascriptEnvironment::GetIsolate());
}
}
SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces);
SetCollectionBehavior(visibleOnFullScreen,
NSWindowCollectionBehaviorFullScreenAuxiliary);
}
bool NativeWindowMac::IsVisibleOnAllWorkspaces() {
NSUInteger collectionBehavior = [window_ collectionBehavior];
return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces;
}
void NativeWindowMac::SetAutoHideCursor(bool auto_hide) {
[window_ setDisableAutoHideCursor:!auto_hide];
}
void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (vibrantView != nil && !vibrancy_type_.empty()) {
const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled);
if (!has_frame() && !is_modal() && !no_rounded_corner) {
CGFloat radius;
if (fullscreen) {
radius = 0.0f;
} else if (@available(macOS 11.0, *)) {
radius = 9.0f;
} else {
// Smaller corner radius on versions prior to Big Sur.
radius = 5.0f;
}
CGFloat dimension = 2 * radius + 1;
NSSize size = NSMakeSize(dimension, dimension);
NSImage* maskImage = [NSImage imageWithSize:size
flipped:NO
drawingHandler:^BOOL(NSRect rect) {
NSBezierPath* bezierPath = [NSBezierPath
bezierPathWithRoundedRect:rect
xRadius:radius
yRadius:radius];
[[NSColor blackColor] set];
[bezierPath fill];
return YES;
}];
[maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
[maskImage setResizingMode:NSImageResizingModeStretch];
[vibrantView setMaskImage:maskImage];
[window_ setCornerMask:maskImage];
}
}
}
void NativeWindowMac::UpdateWindowOriginalFrame() {
original_frame_ = [window_ frame];
}
void NativeWindowMac::SetVibrancy(const std::string& type) {
NSVisualEffectView* vibrantView = [window_ vibrantView];
if (type.empty()) {
if (vibrantView == nil)
return;
[vibrantView removeFromSuperview];
[window_ setVibrantView:nil];
return;
}
std::string dep_warn = " has been deprecated and removed as of macOS 10.15.";
node::Environment* env =
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate());
NSVisualEffectMaterial vibrancyType{};
if (type == "appearance-based") {
EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialAppearanceBased;
} else if (type == "light") {
EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialLight;
} else if (type == "dark") {
EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialDark;
} else if (type == "titlebar") {
vibrancyType = NSVisualEffectMaterialTitlebar;
}
if (type == "selection") {
vibrancyType = NSVisualEffectMaterialSelection;
} else if (type == "menu") {
vibrancyType = NSVisualEffectMaterialMenu;
} else if (type == "popover") {
vibrancyType = NSVisualEffectMaterialPopover;
} else if (type == "sidebar") {
vibrancyType = NSVisualEffectMaterialSidebar;
} else if (type == "medium-light") {
EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn,
"electron");
vibrancyType = NSVisualEffectMaterialMediumLight;
} else if (type == "ultra-dark") {
EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron");
vibrancyType = NSVisualEffectMaterialUltraDark;
}
if (@available(macOS 10.14, *)) {
if (type == "header") {
vibrancyType = NSVisualEffectMaterialHeaderView;
} else if (type == "sheet") {
vibrancyType = NSVisualEffectMaterialSheet;
} else if (type == "window") {
vibrancyType = NSVisualEffectMaterialWindowBackground;
} else if (type == "hud") {
vibrancyType = NSVisualEffectMaterialHUDWindow;
} else if (type == "fullscreen-ui") {
vibrancyType = NSVisualEffectMaterialFullScreenUI;
} else if (type == "tooltip") {
vibrancyType = NSVisualEffectMaterialToolTip;
} else if (type == "content") {
vibrancyType = NSVisualEffectMaterialContentBackground;
} else if (type == "under-window") {
vibrancyType = NSVisualEffectMaterialUnderWindowBackground;
} else if (type == "under-page") {
vibrancyType = NSVisualEffectMaterialUnderPageBackground;
}
}
if (vibrancyType) {
vibrancy_type_ = type;
if (vibrantView == nil) {
vibrantView = [[[NSVisualEffectView alloc]
initWithFrame:[[window_ contentView] bounds]] autorelease];
[window_ setVibrantView:vibrantView];
[vibrantView
setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
if (visual_effect_state_ == VisualEffectState::kActive) {
[vibrantView setState:NSVisualEffectStateActive];
} else if (visual_effect_state_ == VisualEffectState::kInactive) {
[vibrantView setState:NSVisualEffectStateInactive];
} else {
[vibrantView setState:NSVisualEffectStateFollowsWindowActiveState];
}
[[window_ contentView] addSubview:vibrantView
positioned:NSWindowBelow
relativeTo:nil];
UpdateVibrancyRadii(IsFullscreen());
}
[vibrantView setMaterial:vibrancyType];
}
}
void NativeWindowMac::SetWindowButtonVisibility(bool visible) {
window_button_visibility_ = visible;
if (buttons_proxy_) {
if (visible)
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:visible];
}
if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover)
InternalSetWindowButtonVisibility(visible);
NotifyLayoutWindowControlsOverlay();
}
bool NativeWindowMac::GetWindowButtonVisibility() const {
return ![window_ standardWindowButton:NSWindowZoomButton].hidden ||
![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden ||
![window_ standardWindowButton:NSWindowCloseButton].hidden;
}
void NativeWindowMac::SetWindowButtonPosition(
absl::optional<gfx::Point> position) {
traffic_light_position_ = std::move(position);
if (buttons_proxy_) {
[buttons_proxy_ setMargin:traffic_light_position_];
NotifyLayoutWindowControlsOverlay();
}
}
absl::optional<gfx::Point> NativeWindowMac::GetWindowButtonPosition() const {
return traffic_light_position_;
}
void NativeWindowMac::RedrawTrafficLights() {
if (buttons_proxy_ && !IsFullscreen())
[buttons_proxy_ redraw];
}
// In simpleFullScreen mode, update the frame for new bounds.
void NativeWindowMac::UpdateFrame() {
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
NSRect fullscreenFrame = [window.screen frame];
[window setFrame:fullscreenFrame display:YES animate:YES];
}
void NativeWindowMac::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {
touch_bar_.reset([[ElectronTouchBar alloc]
initWithDelegate:window_delegate_.get()
window:this
settings:std::move(items)]);
[window_ setTouchBar:nil];
}
void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id];
}
void NativeWindowMac::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {
if (touch_bar_ && [window_ touchBar])
[touch_bar_ setEscapeTouchBarItem:std::move(item)
forTouchBar:[window_ touchBar]];
}
void NativeWindowMac::SelectPreviousTab() {
[window_ selectPreviousTab:nil];
}
void NativeWindowMac::SelectNextTab() {
[window_ selectNextTab:nil];
}
void NativeWindowMac::MergeAllWindows() {
[window_ mergeAllWindows:nil];
}
void NativeWindowMac::MoveTabToNewWindow() {
[window_ moveTabToNewWindow:nil];
}
void NativeWindowMac::ToggleTabBar() {
[window_ toggleTabBar:nil];
}
bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) {
if (window_ == window->GetNativeWindow().GetNativeNSWindow()) {
return false;
} else {
[window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow()
ordered:NSWindowAbove];
}
return true;
}
void NativeWindowMac::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
NativeWindow::SetAspectRatio(aspect_ratio, extra_size);
// Reset the behaviour to default if aspect_ratio is set to 0 or less.
if (aspect_ratio > 0.0) {
NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0);
if (has_frame())
[window_ setContentAspectRatio:aspect_ratio_size];
else
[window_ setAspectRatio:aspect_ratio_size];
} else {
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
}
void NativeWindowMac::PreviewFile(const std::string& path,
const std::string& display_name) {
preview_item_.reset([[ElectronPreviewItem alloc]
initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)]
title:base::SysUTF8ToNSString(display_name)]);
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
}
void NativeWindowMac::CloseFilePreview() {
if ([QLPreviewPanel sharedPreviewPanelExists]) {
[[QLPreviewPanel sharedPreviewPanel] close];
}
}
gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect window_bounds(
[window_ frameRectForContentRect:bounds.ToCGRect()]);
int frame_height = window_bounds.height() - bounds.height();
window_bounds.set_y(window_bounds.y() - frame_height);
return window_bounds;
} else {
return bounds;
}
}
gfx::Rect NativeWindowMac::WindowBoundsToContentBounds(
const gfx::Rect& bounds) const {
if (has_frame()) {
gfx::Rect content_bounds(
[window_ contentRectForFrameRect:bounds.ToCGRect()]);
int frame_height = bounds.height() - content_bounds.height();
content_bounds.set_y(content_bounds.y() + frame_height);
return content_bounds;
} else {
return bounds;
}
}
void NativeWindowMac::NotifyWindowEnterFullScreen() {
NativeWindow::NotifyWindowEnterFullScreen();
// Restore the window title under fullscreen mode.
if (buttons_proxy_)
[window_ setTitleVisibility:NSWindowTitleVisible];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
NativeWindow::NotifyWindowLeaveFullScreen();
// Restore window buttons.
if (buttons_proxy_ && window_button_visibility_.value_or(true)) {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
}
void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
UpdateVibrancyRadii(true);
}
void NativeWindowMac::NotifyWindowWillLeaveFullScreen() {
if (buttons_proxy_) {
// Hide window title when leaving fullscreen.
[window_ setTitleVisibility:NSWindowTitleHidden];
// Hide the container otherwise traffic light buttons jump.
[buttons_proxy_ setVisible:NO];
}
UpdateVibrancyRadii(false);
}
void NativeWindowMac::SetActive(bool is_key) {
is_active_ = is_key;
}
bool NativeWindowMac::IsActive() const {
return is_active_;
}
void NativeWindowMac::Cleanup() {
DCHECK(!IsClosed());
ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this);
display::Screen::GetScreen()->RemoveObserver(this);
}
class NativeAppWindowFrameViewMac : public views::NativeFrameViewMac {
public:
NativeAppWindowFrameViewMac(views::Widget* frame, NativeWindowMac* window)
: views::NativeFrameViewMac(frame), native_window_(window) {}
NativeAppWindowFrameViewMac(const NativeAppWindowFrameViewMac&) = delete;
NativeAppWindowFrameViewMac& operator=(const NativeAppWindowFrameViewMac&) =
delete;
~NativeAppWindowFrameViewMac() override = default;
// NonClientFrameView:
int NonClientHitTest(const gfx::Point& point) override {
if (!bounds().Contains(point))
return HTNOWHERE;
if (GetWidget()->IsFullscreen())
return HTCLIENT;
// Check for possible draggable region in the client area for the frameless
// window.
int contents_hit_test = native_window_->NonClientHitTest(point);
if (contents_hit_test != HTNOWHERE)
return contents_hit_test;
return HTCLIENT;
}
private:
// Weak.
raw_ptr<NativeWindowMac> const native_window_;
};
std::unique_ptr<views::NonClientFrameView>
NativeWindowMac::CreateNonClientFrameView(views::Widget* widget) {
return std::make_unique<NativeAppWindowFrameViewMac>(widget, this);
}
bool NativeWindowMac::HasStyleMask(NSUInteger flag) const {
return [window_ styleMask] & flag;
}
void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) {
// Changing the styleMask of a frameless windows causes it to change size so
// we explicitly disable resizing while setting it.
ScopedDisableResize disable_resize;
if (on)
[window_ setStyleMask:[window_ styleMask] | flag];
else
[window_ setStyleMask:[window_ styleMask] & (~flag)];
// Change style mask will make the zoom button revert to default, probably
// a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) {
if (on)
[window_ setCollectionBehavior:[window_ collectionBehavior] | flag];
else
[window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)];
// Change collectionBehavior will make the zoom button revert to default,
// probably a bug of Cocoa or macOS.
SetMaximizable(maximizable_);
}
views::View* NativeWindowMac::GetContentsView() {
return root_view_.get();
}
bool NativeWindowMac::CanMaximize() const {
return maximizable_;
}
void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr()));
}
void NativeWindowMac::AddContentViewLayers() {
// Make sure the bottom corner is rounded for non-modal windows:
// http://crbug.com/396264.
if (!is_modal()) {
// For normal window, we need to explicitly set layer for contentView to
// make setBackgroundColor work correctly.
// There is no need to do so for frameless window, and doing so would make
// titleBarStyle stop working.
if (has_frame()) {
base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]);
[background_layer
setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable];
[[window_ contentView] setLayer:background_layer];
}
[[window_ contentView] setWantsLayer:YES];
}
}
void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) {
[[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible];
[[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible];
}
void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent,
bool attach) {
if (is_modal())
return;
NativeWindow::SetParentWindow(parent);
// Do not remove/add if we are already properly attached.
if (attach && parent &&
[window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow())
return;
// Remove current parent window.
if ([window_ parentWindow])
parent->RemoveChildWindow(this);
// Set new parent window.
if (parent && attach) {
parent->add_child_window(this);
parent->AttachChildren();
}
}
void NativeWindowMac::SetForwardMouseMessages(bool forward) {
[window_ setAcceptsMouseMovedEvents:forward];
}
gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() {
if (titlebar_overlay_ && buttons_proxy_ &&
window_button_visibility_.value_or(true)) {
NSRect buttons = [buttons_proxy_ getButtonsContainerBounds];
gfx::Rect overlay;
overlay.set_width(GetContentSize().width() - NSWidth(buttons));
if ([buttons_proxy_ useCustomHeight]) {
overlay.set_height(titlebar_overlay_height());
} else {
overlay.set_height(NSHeight(buttons));
}
if (!base::i18n::IsRTL())
overlay.set_x(NSMaxX(buttons));
return overlay;
}
return gfx::Rect();
}
// static
NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options,
NativeWindow* parent) {
return new NativeWindowMac(options, parent);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,562 |
[Bug]: Crash when opening and closing a child window a few times on macOS
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.1
### What operating system are you using?
macOS
### Operating System Version
Ventura 13.4
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
A child window should be able to be opened and closed multiple times without crashing.
### Actual Behavior
The Electron app crashes after opening a child window and then closing it. This usually happens after opening the child window a few times in a row.
### Testcase Gist URL
https://gist.github.com/jorodi/cbf4378f978e44de5034ab2d91f30387
### Additional Information
Caught error output from VS code terminal:
```
2023-06-02 08:24:57.023 Electron[80994:4778831] -[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f
2023-06-02 08:24:57.025 Electron[80994:4778831] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber parentWindow]: unrecognized selector sent to instance 0x3f030a000201160f'
*** First throw call stack:
(
0 CoreFoundation 0x00007ff802c7918a __exceptionPreprocess + 242
1 libobjc.A.dylib 0x00007ff80279f42b objc_exception_throw + 48
2 CoreFoundation 0x00007ff802d14fef -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x00007ff802be4797 ___forwarding___ + 1392
4 CoreFoundation 0x00007ff802be4198 _CF_forwarding_prep_0 + 120
5 Electron Framework 0x000000010b707e38 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 154760
6 Electron Framework 0x000000010b7073e0 _ZNK2v88internal11interpreter20BytecodeArrayBuilder5LocalEi + 152112
7 Electron Framework 0x000000010b646b23 _ZN2v89CodeEvent10GetCommentEv + 4099
8 Electron Framework 0x000000010b56dc93 ElectronInitializeICUandStartNode + 207619
9 Electron Framework 0x000000010b56f2c4 ElectronInitializeICUandStartNode + 213300
10 Electron Framework 0x000000010b56f9fe ElectronInitializeICUandStartNode + 215150
11 Electron Framework 0x000000010b5634e1 ElectronInitializeICUandStartNode + 164689
12 Electron Framework 0x000000010b5633d3 ElectronInitializeICUandStartNode + 164419
13 Electron Framework 0x000000010c83be34 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 15780
14 Electron Framework 0x000000010c83b9df _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 14671
15 Electron Framework 0x000000010c83ad24 _ZN2v88internal9Accessors12MakeAccessorEPNS0_7IsolateENS0_6HandleINS0_4NameEEEPFvNS_5LocalINS_4NameEEERKNS_20PropertyCallbackInfoINS_5ValueEEEEPFvS9_NS7_ISB_EERKNSA_INS_7BooleanEEEE + 11412
16 Electron Framework 0x000000010b25edf6 Electron Framework + 826870
17 Electron Framework 0x000000010b1c4ff2 Electron Framework + 196594
)
/Users/jordan/parent-child-error/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron exited with signal SIGILL
```
|
https://github.com/electron/electron/issues/38562
|
https://github.com/electron/electron/pull/38603
|
9a9d8ae5ea61e17fd01e8975e81ed2a137a5fef6
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
| 2023-06-02T13:02:06Z |
c++
| 2023-06-08T10:18:37Z |
spec/api-browser-window-spec.ts
|
import { expect } from 'chai';
import * as childProcess from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import * as qs from 'querystring';
import * as http from 'http';
import * as os from 'os';
import { AddressInfo } from 'net';
import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main';
import { emittedUntil, emittedNTimes } from './lib/events-helpers';
import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers';
import { once } from 'events';
import { setTimeout } from 'timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixtures = path.resolve(__dirname, 'fixtures');
const mainFixtures = path.resolve(__dirname, 'fixtures');
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
const { scaleFactor } = screen.getPrimaryDisplay();
// Return true if scale factor is non-integer value
if (Math.round(scaleFactor) !== scaleFactor) return true;
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1;
};
const expectBoundsEqual = (actual: any, expected: any) => {
if (!isScaleFactorRounding()) {
expect(expected).to.deep.equal(actual);
} else if (Array.isArray(actual)) {
expect(actual[0]).to.be.closeTo(expected[0], 1);
expect(actual[1]).to.be.closeTo(expected[1], 1);
} else {
expect(actual.x).to.be.closeTo(expected.x, 1);
expect(actual.y).to.be.closeTo(expected.y, 1);
expect(actual.width).to.be.closeTo(expected.width, 1);
expect(actual.height).to.be.closeTo(expected.height, 1);
}
};
const isBeforeUnload = (event: Event, level: number, message: string) => {
return (message === 'beforeunload');
};
describe('BrowserWindow module', () => {
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
expect(() => {
const w = new BrowserWindow({
show: false,
// apparently void 0 had different behaviour from undefined in the
// issue that this test is supposed to catch.
webContents: void 0 // eslint-disable-line no-void
} as any);
w.destroy();
}).not.to.throw();
});
ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
const appProcess = childProcess.spawn(process.execPath, [appPath]);
await once(appProcess, 'exit');
});
it('does not crash or throw when passed an invalid icon', async () => {
expect(() => {
const w = new BrowserWindow({
icon: undefined
} as any);
w.destroy();
}).not.to.throw();
});
});
describe('garbage collection', () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
afterEach(closeAllWindows);
it('window does not get garbage collected when opened', async () => {
const w = new BrowserWindow({ show: false });
// Keep a weak reference to the window.
const wr = new WeakRef(w);
await setTimeout();
// Do garbage collection, since |w| is not referenced in this closure
// it would be gone after next call if there is no other reference.
v8Util.requestGarbageCollectionForTesting();
await setTimeout();
expect(wr.deref()).to.not.be.undefined();
});
});
describe('BrowserWindow.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should work if called when a messageBox is showing', async () => {
const closed = once(w, 'closed');
dialog.showMessageBox(w, { message: 'Hello Error' });
w.close();
await closed;
});
it('closes window without rounded corners', async () => {
await closeWindow(w);
w = new BrowserWindow({ show: false, frame: false, roundedCorners: false });
const closed = once(w, 'closed');
w.close();
await closed;
});
it('should not crash if called after webContents is destroyed', () => {
w.webContents.destroy();
w.webContents.on('destroyed', () => w.close());
});
it('should allow access to id after destruction', async () => {
const closed = once(w, 'closed');
w.destroy();
await closed;
expect(w.id).to.be.a('number');
});
it('should emit unload handler', async () => {
await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
const closed = once(w, 'closed');
w.close();
await closed;
const test = path.join(fixtures, 'api', 'unload');
const content = fs.readFileSync(test);
fs.unlinkSync(test);
expect(String(content)).to.equal('unload');
});
it('should emit beforeunload handler', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'before-unload-fired');
});
it('should not crash when keyboard event is sent before closing', async () => {
await w.loadURL('data:text/html,pls no crash');
const closed = once(w, 'closed');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
w.close();
await closed;
});
describe('when invoked synchronously inside navigation observer', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/301':
response.statusCode = 301;
response.setHeader('Location', '/200');
response.end();
break;
case '/200':
response.statusCode = 200;
response.end('hello');
break;
case '/title':
response.statusCode = 200;
response.end('<title>Hello</title>');
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', path: '/200' },
{ name: 'dom-ready', path: '/200' },
{ name: 'page-title-updated', path: '/title' },
{ name: 'did-stop-loading', path: '/200' },
{ name: 'did-finish-load', path: '/200' },
{ name: 'did-frame-finish-load', path: '/200' },
{ name: 'did-fail-load', path: '/net-error' }
];
for (const { name, path } of events) {
it(`should not crash when closed during ${name}`, async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once((name as any), () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.webContents.loadURL(url + path);
await destroyed;
});
}
});
});
describe('window.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload event', async () => {
w.loadFile(path.join(fixtures, 'api', 'close.html'));
await once(w, 'closed');
const test = path.join(fixtures, 'api', 'close');
const content = fs.readFileSync(test).toString();
fs.unlinkSync(test);
expect(content).to.equal('close');
});
it('should emit beforeunload event', async function () {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.webContents.executeJavaScript('window.close()', true);
await once(w.webContents, 'before-unload-fired');
});
});
describe('BrowserWindow.destroy()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('prevents users to access methods of webContents', async () => {
const contents = w.webContents;
w.destroy();
await new Promise(setImmediate);
expect(() => {
contents.getProcessId();
}).to.throw('Object has been destroyed');
});
it('should not crash when destroying windows with pending events', () => {
const focusListener = () => { };
app.on('browser-window-focus', focusListener);
const windowCount = 3;
const windowOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show());
windows.forEach(win => win.focus());
windows.forEach(win => win.destroy());
app.removeListener('browser-window-focus', focusListener);
});
});
describe('BrowserWindow.loadURL(url)', () => {
let w: BrowserWindow;
const scheme = 'other';
const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
callback(srcPath);
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
let server: http.Server;
let url: string;
let postData = null as any;
before(async () => {
const filePath = path.join(fixtures, 'pages', 'a.html');
const fileStats = fs.statSync(filePath);
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
];
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
let body = '';
req.on('data', (data) => {
if (data) body += data;
});
req.on('end', () => {
const parsedData = qs.parse(body);
fs.readFile(filePath, (err, data) => {
if (err) return;
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end();
}
});
});
} else if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
}
setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond);
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('should emit did-start-loading event', async () => {
const didStartLoading = once(w.webContents, 'did-start-loading');
w.loadURL('about:blank');
await didStartLoading;
});
it('should emit ready-to-show event', async () => {
const readyToShow = once(w, 'ready-to-show');
w.loadURL('about:blank');
await readyToShow;
});
// DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
// changed and adjust the test.
it('should emit did-fail-load event for files that do not exist', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('file://a.txt');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(code).to.equal(-6);
expect(desc).to.equal('ERR_FILE_NOT_FOUND');
expect(isMainFrame).to.equal(true);
});
it('should emit did-fail-load event for invalid URL', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('http://example:port');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should not emit did-fail-load for a successfully loaded media file', async () => {
w.webContents.on('did-fail-load', () => {
expect.fail('did-fail-load should not emit on media file loads');
});
const mediaStarted = once(w.webContents, 'media-started-playing');
w.loadFile(path.join(fixtures, 'cat-spin.mp4'));
await mediaStarted;
});
it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
const [,,,, isMainFrame] = await didFailLoad;
expect(isMainFrame).to.equal(false);
});
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
w.loadURL('http://127.0.0.1:11111');
done();
});
w.loadURL('http://127.0.0.1:11111');
});
it('should emit did-fail-load event for URL exceeding character limit', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL(`data:image/png;base64,${data}`);
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should return a promise', () => {
const p = w.loadURL('about:blank');
expect(p).to.have.property('then');
});
it('should return a promise that resolves', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('should return a promise that rejects on a load failure', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const p = w.loadURL(`data:image/png;base64,${data}`);
await expect(p).to.eventually.be.rejected;
});
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
await expect(p).to.eventually.be.fulfilled;
});
describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
it('supports specifying POST data', async () => {
await w.loadURL(url, { postData });
});
it('sets the content type header on URL encoded forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
});
it('sets the content type header on multi part forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
});
});
it('should support base url for data urls', async () => {
await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
});
});
for (const sandbox of [false, true]) {
describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('will-navigate event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-navigate');
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
await event;
w.close();
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame);
let initiator: WebFrameMain | undefined;
w.webContents.on('will-navigate', (e) => {
initiator = e.initiator;
});
const subframe = w.webContents.mainFrame.frames[0];
subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true);
await once(w.webContents, 'did-navigate');
expect(initiator).not.to.be.undefined();
expect(initiator).to.equal(subframe);
});
});
describe('will-frame-navigate event', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else if (req.url === '/navigate-iframe') {
res.end('<a href="/test">navigate iframe</a>');
} else if (req.url === '/navigate-iframe?navigated') {
res.end('Successfully navigated');
} else if (req.url === '/navigate-iframe-immediately') {
res.end(`
<script type="text/javascript" charset="utf-8">
location.href += '?navigated'
</script>
`);
} else if (req.url === '/navigate-iframe-immediately?navigated') {
res.end('Successfully navigated');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-frame-navigate', () => {
w.close();
done();
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented when navigating subframe', (done) => {
let willNavigate = false;
w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
if (isMainFrame) return;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(frame).to.not.be.undefined();
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
});
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`);
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await setTimeout(1000);
let willFrameNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willFrameNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willFrameNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.true();
});
it('is triggered when a cross-origin iframe navigates itself', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`);
await setTimeout(1000);
let willNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-frame-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.false();
});
it('can cancel when a cross-origin iframe navigates itself', async () => {
});
});
describe('will-redirect event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else if (req.url === '/navigate-302') {
res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
} else {
res.end();
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is emitted on redirects', async () => {
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
});
it('is emitted after will-navigate on redirects', async () => {
let navigateCalled = false;
w.webContents.on('will-navigate', () => {
navigateCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/navigate-302`);
await willRedirect;
expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
});
it('is emitted before did-stop-loading on redirects', async () => {
let stopCalled = false;
w.webContents.on('did-stop-loading', () => {
stopCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await event;
w.close();
});
it('can be prevented', (done) => {
w.webContents.once('will-redirect', (event) => {
event.preventDefault();
});
w.webContents.on('will-navigate', (e, u) => {
expect(u).to.equal(`${url}/302`);
});
w.webContents.on('did-stop-loading', () => {
try {
expect(w.webContents.getURL()).to.equal(
`${url}/navigate-302`,
'url should not have changed after navigation event'
);
done();
} catch (e) {
done(e);
}
});
w.webContents.on('will-redirect', (e, u) => {
try {
expect(u).to.equal(`${url}/200`);
} catch (e) {
done(e);
}
});
w.loadURL(`${url}/navigate-302`);
});
});
describe('ordering', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
const navigationEvents = [
'did-start-navigation',
'did-navigate-in-page',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate') {
res.end('<a href="/">navigate</a>');
} else if (req.url === '/redirect') {
res.end('<a href="/redirect2">redirect</a>');
} else if (req.url === '/redirect2') {
res.statusCode = 302;
res.setHeader('location', url);
res.end();
} else if (req.url === '/in-page') {
res.end('<a href="#in-page">redirect</a><div id="in-page"></div>');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
it('for initial navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-frame-navigate',
'did-navigate'
];
const allEvents = Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const timeout = setTimeout(1000);
w.loadURL(url);
await Promise.race([allEvents, timeout]);
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('for second navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}navigate`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating with redirection, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}redirect`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating in-page, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-navigate-in-page'
];
w.loadURL(`${url}in-page`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate-in-page');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
});
});
}
describe('focus and visibility', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.show()', () => {
it('should focus on window', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isFocused()).to.equal(true);
});
it('should make the window visible', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isVisible()).to.equal(true);
});
it('emits when window is shown', async () => {
const show = once(w, 'show');
w.show();
await show;
expect(w.isVisible()).to.equal(true);
});
});
describe('BrowserWindow.hide()', () => {
it('should defocus on window', () => {
w.hide();
expect(w.isFocused()).to.equal(false);
});
it('should make the window not visible', () => {
w.show();
w.hide();
expect(w.isVisible()).to.equal(false);
});
it('emits when window is hidden', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const hidden = once(w, 'hide');
w.hide();
await hidden;
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.minimize()', () => {
// TODO(codebytere): Enable for Linux once maximize/minimize events work in CI.
ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => {
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMinimized()).to.equal(true);
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
w.showInactive();
expect(w.isFocused()).to.equal(false);
});
// TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests
ifit(process.platform !== 'linux')('should not restore maximized windows', async () => {
const maximize = once(w, 'maximize');
const shown = once(w, 'show');
w.maximize();
// TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden
if (process.platform !== 'darwin') {
await maximize;
} else {
await setTimeout(1000);
}
w.showInactive();
await shown;
expect(w.isMaximized()).to.equal(true);
});
});
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
expect(w.isVisible()).to.equal(false);
w.focus();
expect(w.isVisible()).to.equal(false);
});
ifit(process.platform !== 'win32')('focuses a blurred window', async () => {
{
const isBlurred = once(w, 'blur');
const isShown = once(w, 'show');
w.show();
w.blur();
await isShown;
await isBlurred;
}
expect(w.isFocused()).to.equal(false);
w.focus();
expect(w.isFocused()).to.equal(true);
});
ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w1.focus();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w2.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w3.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
// TODO(RaisinTen): Make this work on Windows too.
// Refs: https://github.com/electron/electron/issues/20464.
ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => {
it('removes focus from window', async () => {
{
const isFocused = once(w, 'focus');
const isShown = once(w, 'show');
w.show();
await isShown;
await isFocused;
}
expect(w.isFocused()).to.equal(true);
w.blur();
expect(w.isFocused()).to.equal(false);
});
ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w3.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w2.blur();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w1.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', async () => {
const p = once(w, 'focus');
w.show();
await p;
w.webContents.openDevTools({ mode: 'undocked' });
await once(w.webContents, 'devtools-focused');
expect(BrowserWindow.getFocusedWindow()).to.equal(w);
});
});
describe('BrowserWindow.moveTop()', () => {
it('should not steal focus', async () => {
const posDelta = 50;
const wShownInactive = once(w, 'show');
w.showInactive();
await wShownInactive;
expect(w.isFocused()).to.equal(false);
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
const otherWindowShown = once(otherWindow, 'show');
const otherWindowFocused = once(otherWindow, 'focus');
otherWindow.show();
await otherWindowShown;
await otherWindowFocused;
expect(otherWindow.isFocused()).to.equal(true);
w.moveTop();
const wPos = w.getPosition();
const wMoving = once(w, 'move');
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
await wMoving;
expect(w.isFocused()).to.equal(false);
expect(otherWindow.isFocused()).to.equal(true);
const wFocused = once(w, 'focus');
const otherWindowBlurred = once(otherWindow, 'blur');
w.focus();
await wFocused;
await otherWindowBlurred;
expect(w.isFocused()).to.equal(true);
otherWindow.moveTop();
const otherWindowPos = otherWindow.getPosition();
const otherWindowMoving = once(otherWindow, 'move');
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
await otherWindowMoving;
expect(otherWindow.isFocused()).to.equal(false);
expect(w.isFocused()).to.equal(true);
await closeWindow(otherWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
});
});
describe('BrowserWindow.moveAbove(mediaSourceId)', () => {
it('should throw an exception if wrong formatting', async () => {
const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should throw an exception if wrong type', async () => {
const fakeSourceIds = [null as any, 123 as any];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */);
});
});
it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
'window:123456:9'];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should not throw an exception', async () => {
const w2 = new BrowserWindow({ show: false, title: 'window2' });
const w2Shown = once(w2, 'show');
w2.show();
await w2Shown;
expect(() => {
w.moveAbove(w2.getMediaSourceId());
}).to.not.throw();
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.setFocusable()', () => {
it('can set unfocusable window to focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
const w2Focused = once(w2, 'focus');
w2.setFocusable(true);
w2.focus();
await w2Focused;
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.isFocusable()', () => {
it('correctly returns whether a window is focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
expect(w2.isFocusable()).to.be.false();
w2.setFocusable(true);
expect(w2.isFocusable()).to.be.true();
await closeWindow(w2, { assertNotWindows: false });
});
});
});
describe('sizing', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, width: 400, height: 400 });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
it('sets the window bounds with full bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
expectBoundsEqual(w.getBounds(), fullBounds);
});
it('sets the window bounds with partial bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
const boundsUpdate = { width: 200 };
w.setBounds(boundsUpdate as any);
const expectedBounds = { ...fullBounds, ...boundsUpdate };
expectBoundsEqual(w.getBounds(), expectedBounds);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds, true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
const size = [300, 400];
const resized = once(w, 'resize');
w.setSize(size[0], size[1]);
await resized;
expectBoundsEqual(w.getSize(), size);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const size = [300, 400];
w.setSize(size[0], size[1], true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
expect(w.getMinimumSize()).to.deep.equal([0, 0]);
expect(w.getMaximumSize()).to.deep.equal([0, 0]);
w.setMinimumSize(100, 100);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [0, 0]);
w.setMaximumSize(900, 600);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [900, 600]);
});
});
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', async () => {
const size = [300, 400];
w.setAspectRatio(1 / 2);
w.setAspectRatio(0);
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getSize(), size);
});
it('doesn\'t change bounds when maximum size is set', () => {
w.setMenu(null);
w.setMaximumSize(400, 400);
// Without https://github.com/electron/electron/pull/29101
// following call would shrink the window to 384x361.
// There would be also DCHECK in resize_utils.cc on
// debug build.
w.setAspectRatio(1.0);
expectBoundsEqual(w.getSize(), [400, 400]);
});
});
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expect(w.getPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', async () => {
// NB. The CI server has a very small screen. Attempting to size the window
// larger than the screen will limit the window's size to the screen and
// cause the test to fail.
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
});
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
});
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', async () => {
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
});
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
});
describe('BrowserWindow.getBackgroundColor()', () => {
it('returns default value if no backgroundColor is set', () => {
w.destroy();
w = new BrowserWindow({});
expect(w.getBackgroundColor()).to.equal('#FFFFFF');
});
it('returns correct value if backgroundColor is set', () => {
const backgroundColor = '#BBAAFF';
w.destroy();
w = new BrowserWindow({
backgroundColor: backgroundColor
});
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct value from setBackgroundColor()', () => {
const backgroundColor = '#AABBFF';
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor(backgroundColor);
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct color with multiple passed formats', () => {
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor('#AABBFF');
expect(w.getBackgroundColor()).to.equal('#AABBFF');
w.setBackgroundColor('blueviolet');
expect(w.getBackgroundColor()).to.equal('#8A2BE2');
w.setBackgroundColor('rgb(255, 0, 185)');
expect(w.getBackgroundColor()).to.equal('#FF00B9');
w.setBackgroundColor('rgba(245, 40, 145, 0.8)');
expect(w.getBackgroundColor()).to.equal('#F52891');
w.setBackgroundColor('hsl(155, 100%, 50%)');
expect(w.getBackgroundColor()).to.equal('#00FF95');
});
});
describe('BrowserWindow.getNormalBounds()', () => {
describe('Normal state', () => {
it('checks normal bounds after resize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
it('checks normal bounds after move', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
});
ifdescribe(process.platform !== 'linux')('Maximized state', () => {
it('checks normal bounds when maximized', async () => {
const bounds = w.getBounds();
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and maximize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and maximize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unmaximized', async () => {
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly reports maximized state after maximizing then minimizing', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
expect(w.isMinimized()).to.equal(true);
});
it('correctly reports maximized state after maximizing then fullscreening', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
expect(w.isMaximized()).to.equal(false);
expect(w.isFullScreen()).to.equal(true);
});
it('checks normal bounds for maximized transparent window', async () => {
w.destroy();
w = new BrowserWindow({
transparent: true,
show: false
});
w.show();
const bounds = w.getNormalBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly checks transparent window maximization state', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
width: 300,
height: 300,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
const unmaximize = once(w, 'unmaximize');
w.unmaximize();
await unmaximize;
expect(w.isMaximized()).to.equal(false);
});
it('returns the correct value for windows with an aspect ratio', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
fullscreenable: false
});
w.setAspectRatio(16 / 11);
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
w.resizable = false;
expect(w.isMaximized()).to.equal(true);
});
});
ifdescribe(process.platform !== 'linux')('Minimized state', () => {
it('checks normal bounds when minimized', async () => {
const bounds = w.getBounds();
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after move and minimize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('updates normal bounds after resize and minimize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('checks normal bounds when restored', async () => {
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
it('with properties', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.fullScreen).to.be.true();
});
it('does not go fullscreen if roundedCorners are enabled', async () => {
w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true });
expect(w.fullScreen).to.be.false();
});
it('can be changed', () => {
w.fullScreen = false;
expect(w.fullScreen).to.be.false();
w.fullScreen = true;
expect(w.fullScreen).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
const enterFullScreen = once(w, 'enter-full-screen');
w.show();
w.fullScreen = true;
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.once('enter-full-screen', () => {
w.fullScreen = false;
});
const leaveFullScreen = once(w, 'leave-full-screen');
w.show();
w.fullScreen = true;
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
it('with functions', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.isFullScreen()).to.be.true();
});
it('can be changed', () => {
w.setFullScreen(false);
expect(w.isFullScreen()).to.be.false();
w.setFullScreen(true);
expect(w.isFullScreen()).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
});
});
});
ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.selectPreviousTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectPreviousTab();
}).to.not.throw();
});
});
describe('BrowserWindow.selectNextTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectNextTab();
}).to.not.throw();
});
});
describe('BrowserWindow.mergeAllWindows()', () => {
it('does not throw', () => {
expect(() => {
w.mergeAllWindows();
}).to.not.throw();
});
});
describe('BrowserWindow.moveTabToNewWindow()', () => {
it('does not throw', () => {
expect(() => {
w.moveTabToNewWindow();
}).to.not.throw();
});
});
describe('BrowserWindow.toggleTabBar()', () => {
it('does not throw', () => {
expect(() => {
w.toggleTabBar();
}).to.not.throw();
});
});
describe('BrowserWindow.addTabbedWindow()', () => {
it('does not throw', async () => {
const tabbedWindow = new BrowserWindow({});
expect(() => {
w.addTabbedWindow(tabbedWindow);
}).to.not.throw();
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
await closeWindow(tabbedWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
});
it('throws when called on itself', () => {
expect(() => {
w.addTabbedWindow(w);
}).to.throw('AddTabbedWindow cannot be called by a window on itself.');
});
});
});
describe('autoHideMenuBar state', () => {
afterEach(closeAllWindows);
it('for properties', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
w.autoHideMenuBar = true;
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
w.autoHideMenuBar = false;
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
});
});
it('for functions', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
w.setAutoHideMenuBar(true);
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
w.setAutoHideMenuBar(false);
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
});
});
});
describe('BrowserWindow.capturePage(rect)', () => {
afterEach(closeAllWindows);
it('returns a Promise with a Buffer', async () => {
const w = new BrowserWindow({ show: false });
const image = await w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => {
const w = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true });
const visible = await w.webContents.executeJavaScript('document.visibilityState');
expect(visible).to.equal('hidden');
});
it('resolves after the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
w.show();
const visibleImage = await w.capturePage();
expect(visibleImage.isEmpty()).to.equal(false);
w.hide();
const hiddenImage = await w.capturePage();
const isEmpty = process.platform !== 'darwin';
expect(hiddenImage.isEmpty()).to.equal(isEmpty);
});
it('resolves after the window is hidden and capturer count is non-zero', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
const image = await w.capturePage();
expect(image.isEmpty()).to.equal(false);
});
it('preserves transparency', async () => {
const w = new BrowserWindow({ show: false, transparent: true });
w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
await once(w, 'ready-to-show');
w.show();
const image = await w.capturePage();
const imgBuffer = image.toPNG();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6);
});
});
describe('BrowserWindow.setProgressBar(progress)', () => {
let w: BrowserWindow;
before(() => {
w = new BrowserWindow({ show: false });
});
after(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('sets the progress', () => {
expect(() => {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
}
w.setProgressBar(0.5);
if (process.platform === 'darwin') {
app.dock.setIcon(null as any);
}
w.setProgressBar(-1);
}).to.not.throw();
});
it('sets the progress using "paused" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'paused' });
}).to.not.throw();
});
it('sets the progress using "error" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'error' });
}).to.not.throw();
});
it('sets the progress using "normal" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'normal' });
}).to.not.throw();
});
});
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
let w: BrowserWindow;
afterEach(closeAllWindows);
beforeEach(() => {
w = new BrowserWindow({ show: true });
});
it('sets the window as always on top', () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
w.setAlwaysOnTop(false);
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
it('causes the right value to be emitted on `always-on-top-changed`', async () => {
const alwaysOnTopChanged = once(w, 'always-on-top-changed');
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
const [, alwaysOnTop] = await alwaysOnTopChanged;
expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ parent: w });
c.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.false();
expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver');
});
});
describe('preconnect feature', () => {
let w: BrowserWindow;
let server: http.Server;
let url: string;
let connections = 0;
beforeEach(async () => {
connections = 0;
server = http.createServer((req, res) => {
if (req.url === '/link') {
res.setHeader('Content-type', 'text/html');
res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
return;
}
res.end();
});
server.on('connection', () => { connections++; });
url = (await listen(server)).url;
});
afterEach(async () => {
server.close();
await closeWindow(w);
w = null as unknown as BrowserWindow;
server = null as unknown as http.Server;
});
it('calling preconnect() connects to the server', async () => {
w = new BrowserWindow({ show: false });
w.webContents.on('did-start-navigation', (event, url) => {
w.webContents.session.preconnect({ url, numSockets: 4 });
});
await w.loadURL(url);
expect(connections).to.equal(4);
});
it('does not preconnect unless requested', async () => {
w = new BrowserWindow({ show: false });
await w.loadURL(url);
expect(connections).to.equal(1);
});
it('parses <link rel=preconnect>', async () => {
w = new BrowserWindow({ show: true });
const p = once(w.webContents.session, 'preconnect');
w.loadURL(url + '/link');
const [, preconnectUrl, allowCredentials] = await p;
expect(preconnectUrl).to.equal('http://example.com/');
expect(allowCredentials).to.be.true('allowCredentials');
});
});
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('allows changing cursor auto-hiding', () => {
expect(() => {
w.setAutoHideCursor(false);
w.setAutoHideCursor(true);
}).to.not.throw();
});
});
ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
it('is not available', () => {
expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
});
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setWindowButtonVisibility(true);
w.setWindowButtonVisibility(false);
}).to.not.throw();
});
it('changes window button visibility for normal window', () => {
const w = new BrowserWindow({ show: false });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('changes window button visibility for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('changes window button visibility for hiddenInset window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
// Buttons of customButtonsOnHover are always hidden unless hovered.
it('does not change window button visibility for customButtonsOnHover window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
afterEach(closeAllWindows);
it('allows setting, changing, and removing the vibrancy', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('light');
w.setVibrancy('dark');
w.setVibrancy(null);
w.setVibrancy('ultra-dark');
w.setVibrancy('' as any);
}).to.not.throw();
});
it('does not crash if vibrancy is set to an invalid value', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
}).to.not.throw();
});
});
ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
const pos = { x: 10, y: 10 };
afterEach(closeAllWindows);
describe('BrowserWindow.getWindowButtonPosition(pos)', () => {
it('returns null when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition');
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setWindowButtonPosition(pos)', () => {
it('resets the position when null is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setWindowButtonPosition(null);
expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition');
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
});
// The set/getTrafficLightPosition APIs are deprecated.
describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
it('returns { x: 0, y: 0 } when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
it('resets the position when { x: 0, y: 0 } is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setTrafficLightPosition({ x: 0, y: 0 });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
afterEach(closeAllWindows);
it('supports setting the app details', () => {
const w = new BrowserWindow({ show: false });
const iconPath = path.join(fixtures, 'assets', 'icon.ico');
expect(() => {
w.setAppDetails({ appId: 'my.app.id' });
w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
w.setAppDetails({ appIconPath: iconPath });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
w.setAppDetails({ relaunchDisplayName: 'My app name' });
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
});
w.setAppDetails({});
}).to.not.throw();
expect(() => {
(w.setAppDetails as any)();
}).to.throw('Insufficient number of arguments.');
});
});
describe('BrowserWindow.fromId(id)', () => {
afterEach(closeAllWindows);
it('returns the window with id', () => {
const w = new BrowserWindow({ show: false });
expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
});
});
describe('Opening a BrowserWindow from a link', () => {
let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('can properly open and load a new window from a link', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
appProcess = childProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
});
describe('BrowserWindow.fromWebContents(webContents)', () => {
afterEach(closeAllWindows);
it('returns the window with the webContents', () => {
const w = new BrowserWindow({ show: false });
const found = BrowserWindow.fromWebContents(w.webContents);
expect(found!.id).to.equal(w.id);
});
it('returns null for webContents without a BrowserWindow', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
try {
expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
} finally {
contents.destroy();
}
});
it('returns the correct window for a BrowserView webcontents', async () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
await bv.webContents.loadURL('about:blank');
expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
});
it('returns the correct window for a WebView webcontents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
// NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
// https://github.com/electron/electron/issues/25413, and is not integral
// to the test.
const p = once(w.webContents, 'did-attach-webview');
const [, webviewContents] = await once(app, 'web-contents-created');
expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
await p;
});
it('is usable immediately on browser-window-created', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.open(""); null');
const [win, winFromWebContents] = await new Promise<any>((resolve) => {
app.once('browser-window-created', (e, win) => {
resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
});
});
expect(winFromWebContents).to.equal(win);
});
});
describe('BrowserWindow.openDevTools()', () => {
afterEach(closeAllWindows);
it('does not crash for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
w.webContents.openDevTools();
});
});
describe('BrowserWindow.fromBrowserView(browserView)', () => {
afterEach(closeAllWindows);
it('returns the window with the BrowserView', () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
});
it('returns the window when there are multiple BrowserViews', () => {
const w = new BrowserWindow({ show: false });
const bv1 = new BrowserView();
w.addBrowserView(bv1);
const bv2 = new BrowserView();
w.addBrowserView(bv2);
defer(() => {
w.removeBrowserView(bv1);
w.removeBrowserView(bv2);
bv1.webContents.destroy();
bv2.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
});
it('returns undefined if not attached', () => {
const bv = new BrowserView();
defer(() => {
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
});
});
describe('BrowserWindow.setOpacity(opacity)', () => {
afterEach(closeAllWindows);
ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
it('make window with initial opacity', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
expect(w.getOpacity()).to.equal(0.5);
});
it('allows setting the opacity', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setOpacity(0.0);
expect(w.getOpacity()).to.equal(0.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(0.5);
w.setOpacity(1.0);
expect(w.getOpacity()).to.equal(1.0);
}).to.not.throw();
});
it('clamps opacity to [0.0...1.0]', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
w.setOpacity(100);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(-100);
expect(w.getOpacity()).to.equal(0.0);
});
});
ifdescribe(process.platform === 'linux')(('Linux'), () => {
it('sets 1 regardless of parameter', () => {
const w = new BrowserWindow({ show: false });
w.setOpacity(0);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(1.0);
});
});
});
describe('BrowserWindow.setShape(rects)', () => {
afterEach(closeAllWindows);
it('allows setting shape', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setShape([]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
w.setShape([]);
}).to.not.throw();
});
});
describe('"useContentSize" option', () => {
afterEach(closeAllWindows);
it('make window created with content size when used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('make window created with window size when not used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400
});
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
it('works for a frameless window', () => {
const w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => {
const testWindowsOverlay = async (style: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: style,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: true
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRect.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRect.x).to.be.greaterThan(0);
} else {
expect(overlayRect.x).to.equal(0);
}
expect(overlayRect.width).to.be.greaterThan(0);
expect(overlayRect.height).to.be.greaterThan(0);
const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
expect(cssOverlayRect).to.deep.equal(overlayRect);
const geometryChange = once(ipcMain, 'geometrychange');
w.setBounds({ width: 800 });
const [, newOverlayRect] = await geometryChange;
expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('creates browser window with hidden title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('sets Window Control Overlay with hidden title bar', async () => {
await testWindowsOverlay('hidden');
});
ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
await testWindowsOverlay('hiddenInset');
});
ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
});
afterEach(async () => {
await closeAllWindows();
});
it('does not crash changing minimizability ', () => {
expect(() => {
w.setMinimizable(false);
}).to.not.throw();
});
it('does not crash changing maximizability', () => {
expect(() => {
w.setMaximizable(false);
}).to.not.throw();
});
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => {
const testWindowsOverlayHeight = async (size: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: size
}
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRectPreMax.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRectPreMax.x).to.be.greaterThan(0);
} else {
expect(overlayRectPreMax.x).to.equal(0);
}
expect(overlayRectPreMax.width).to.be.greaterThan(0);
expect(overlayRectPreMax.height).to.equal(size);
// Confirm that maximization only affected the height of the buttons and not the title bar
expect(overlayRectPostMax.height).to.equal(size);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('sets Window Control Overlay with title bar height of 40', async () => {
await testWindowsOverlayHeight(40);
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => {
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('does not crash when an invalid titleBarStyle was initially set', () => {
const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
expect(() => {
win.setTitleBarOverlay({
color: '#000000'
});
}).to.not.throw();
});
it('correctly updates the height of the overlay', async () => {
const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
if (firstRun) {
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(x).to.equal(0);
expect(y).to.equal(0);
expect(width).to.be.greaterThan(0);
expect(height).to.equal(size);
expect(preMaxHeight).to.equal(size);
};
const INITIAL_SIZE = 40;
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: INITIAL_SIZE
}
});
await testOverlay(w, INITIAL_SIZE, true);
w.setTitleBarOverlay({
height: INITIAL_SIZE + 10
});
await testOverlay(w, INITIAL_SIZE + 10, false);
});
});
ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
afterEach(closeAllWindows);
it('can move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, 50);
const after = w.getPosition();
expect(after).to.deep.equal([-10, 50]);
});
it('cannot move the window behind menu bar', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can move the window behind menu bar if it has no frame', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[0]).to.be.equal(-10);
expect(after[1]).to.be.equal(-10);
});
it('without it, cannot move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expectBoundsEqual(w.getSize(), [size.width, size.height]);
});
it('without it, cannot set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
});
});
ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
afterEach(closeAllWindows);
it('sets the window width to the page width when used', () => {
const w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
});
w.maximize();
expect(w.getSize()[0]).to.equal(500);
});
});
describe('"tabbingIdentifier" option', () => {
afterEach(closeAllWindows);
it('can be set on a window', () => {
expect(() => {
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group1'
});
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
});
}).not.to.throw();
});
});
describe('"webPreferences" option', () => {
afterEach(() => { ipcMain.removeAllListeners('answer'); });
afterEach(closeAllWindows);
describe('"preload" option', () => {
const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
it(name, async () => {
const w = new BrowserWindow({
webPreferences: {
...webPrefs,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
const [, result] = await once(ipcMain, 'leak-result');
expect(result).to.have.property('require', 'undefined');
expect(result).to.have.property('exports', 'undefined');
expect(result).to.have.property('windowExports', 'undefined');
expect(result).to.have.property('windowPreload', 'undefined');
expect(result).to.have.property('windowRequire', 'undefined');
});
};
doesNotLeakSpec('does not leak require', {
nodeIntegration: false,
sandbox: false,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when sandbox is enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when context isolation is enabled', {
nodeIntegration: false,
sandbox: false,
contextIsolation: true
});
doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: true
});
it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
let w = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, notIsolated] = await once(ipcMain, 'leak-result');
expect(notIsolated).to.have.property('globals');
w.destroy();
w = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, isolated] = await once(ipcMain, 'leak-result');
expect(isolated).to.have.property('globals');
const notIsolatedGlobals = new Set(notIsolated.globals);
for (const isolatedGlobal of isolated.globals) {
notIsolatedGlobals.delete(isolatedGlobal);
}
expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
});
it('loads the script before other scripts in window', async () => {
const preload = path.join(fixtures, 'module', 'set-global.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.eql('preload');
});
it('has synchronous access to all eventual window APIs', async () => {
const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.be.an('object');
expect(test.atPreload).to.be.an('array');
expect(test.atLoad).to.be.an('array');
expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
});
});
describe('session preload scripts', function () {
const preloads = [
path.join(fixtures, 'module', 'set-global-preload-1.js'),
path.join(fixtures, 'module', 'set-global-preload-2.js'),
path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
];
const defaultSession = session.defaultSession;
beforeEach(() => {
expect(defaultSession.getPreloads()).to.deep.equal([]);
defaultSession.setPreloads(preloads);
});
afterEach(() => {
defaultSession.setPreloads([]);
});
it('can set multiple session preload script', () => {
expect(defaultSession.getPreloads()).to.deep.equal(preloads);
});
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('loads the script before other scripts in window including normal preloads', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload: path.join(fixtures, 'module', 'get-global-preload.js'),
contextIsolation: false
}
});
w.loadURL('about:blank');
const [, preload1, preload2, preload3] = await once(ipcMain, 'vars');
expect(preload1).to.equal('preload-1');
expect(preload2).to.equal('preload-1-2');
expect(preload3).to.be.undefined('preload 3');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('"additionalArguments" option', () => {
it('adds extra args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg');
});
it('adds extra value args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg=foo']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg=foo');
});
});
describe('"node-integration" option', () => {
it('disables node integration by default', async () => {
const preload = path.join(fixtures, 'module', 'send-later.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer');
expect(typeofProcess).to.equal('undefined');
expect(typeofBuffer).to.equal('undefined');
});
});
describe('"sandbox" option', () => {
const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/cross-site':
response.end(`<html><body><h1>${request.url}</h1></body></html>`);
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('exposes ipcRenderer to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes ipcRenderer to preload script (path has special chars)', async () => {
const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preloadSpecialChars,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes "loaded" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
});
w.loadURL('about:blank');
await once(ipcMain, 'process-loaded');
});
it('exposes "exit" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
const pageUrl = 'file://' + htmlPath;
w.loadURL(pageUrl);
const [, url] = await once(ipcMain, 'answer');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
});
it('exposes full EventEmitter object to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
}
});
w.loadURL('about:blank');
const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer');
const { EventEmitter } = require('events');
const emitter = new EventEmitter();
const browserEventEmitterProperties = [];
let currentObj = emitter;
do {
browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
} while ((currentObj = Object.getPrototypeOf(currentObj)));
expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
});
it('should open windows in same domain with cross-scripting enabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
const pageUrl = 'file://' + htmlPath;
const answer = once(ipcMain, 'answer');
w.loadURL(pageUrl);
const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
expect(frameName).to.equal('popup!');
expect(options.width).to.equal(500);
expect(options.height).to.equal(600);
const [, html] = await answer;
expect(html).to.equal('<h1>scripting from opener</h1>');
});
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
w.loadFile(
path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
{ search: 'window-open-external' }
);
// Wait for a message from the main window saying that it's ready.
await once(ipcMain, 'opener-loaded');
// Ask the opener to open a popup with window.opener.
const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
w.webContents.send('open-the-popup', expectedPopupUrl);
// The page is going to open a popup that it won't be able to close.
// We have to close it from here later.
const [, popupWindow] = await once(app, 'browser-window-created');
// Ask the popup window for details.
const detailsAnswer = once(ipcMain, 'child-loaded');
popupWindow.webContents.send('provide-details');
const [, openerIsNull, , locationHref] = await detailsAnswer;
expect(openerIsNull).to.be.false('window.opener is null');
expect(locationHref).to.equal(expectedPopupUrl);
// Ask the page to access the popup.
const touchPopupResult = once(ipcMain, 'answer');
w.webContents.send('touch-the-popup');
const [, popupAccessMessage] = await touchPopupResult;
// Ask the popup to access the opener.
const touchOpenerResult = once(ipcMain, 'answer');
popupWindow.webContents.send('touch-the-opener');
const [, openerAccessMessage] = await touchOpenerResult;
// We don't need the popup anymore, and its parent page can't close it,
// so let's close it from here before we run any checks.
await closeWindow(popupWindow, { assertNotWindows: false });
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
});
it('should inherit the sandbox setting in opened windows', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [, { argv }] = await once(ipcMain, 'answer');
expect(argv).to.include('--enable-sandbox');
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
it('should set ipc event sender correctly', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
let childWc: WebContents | null = null;
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
w.webContents.on('did-create-window', (win) => {
childWc = win.webContents;
expect(w.webContents).to.not.equal(childWc);
});
ipcMain.once('parent-ready', function (event) {
expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
event.sender.send('verified');
});
ipcMain.once('child-ready', function (event) {
expect(childWc).to.not.be.null('child webcontents should be available');
expect(event.sender).to.equal(childWc, 'sender should be the child');
event.sender.send('verified');
});
const done = Promise.all([
'parent-answer',
'child-answer'
].map(name => once(ipcMain, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
await done;
});
describe('event handling', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
});
it('works for window events', async () => {
const pageTitleUpdated = once(w, 'page-title-updated');
w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
await pageTitleUpdated;
});
it('works for stop events', async () => {
const done = Promise.all([
'did-navigate',
'did-fail-load',
'did-stop-loading'
].map(name => once(w.webContents, name)));
w.loadURL('data:text/html,<script>stop()</script>');
await done;
});
it('works for web contents events', async () => {
const done = Promise.all([
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
].map(name => once(w.webContents, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
await done;
});
});
it('validates process APIs access in sandboxed renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.once('preload-error', (event, preloadPath, error) => {
throw error;
});
process.env.sandboxmain = 'foo';
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test.hasCrash).to.be.true('has crash');
expect(test.hasHang).to.be.true('has hang');
expect(test.heapStatistics).to.be.an('object');
expect(test.blinkMemoryInfo).to.be.an('object');
expect(test.processMemoryInfo).to.be.an('object');
expect(test.systemVersion).to.be.a('string');
expect(test.cpuUsage).to.be.an('object');
expect(test.ioCounters).to.be.an('object');
expect(test.uptime).to.be.a('number');
expect(test.arch).to.equal(process.arch);
expect(test.platform).to.equal(process.platform);
expect(test.env).to.deep.equal(process.env);
expect(test.execPath).to.equal(process.helperExecPath);
expect(test.sandboxed).to.be.true('sandboxed');
expect(test.contextIsolated).to.be.false('contextIsolated');
expect(test.type).to.equal('renderer');
expect(test.version).to.equal(process.version);
expect(test.versions).to.deep.equal(process.versions);
expect(test.contextId).to.be.a('string');
if (process.platform === 'linux' && test.osSandbox) {
expect(test.creationTime).to.be.null('creation time');
expect(test.systemMemoryInfo).to.be.null('system memory info');
} else {
expect(test.creationTime).to.be.a('number');
expect(test.systemMemoryInfo).to.be.an('object');
}
});
it('webview in sandbox renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
webviewTag: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview');
const webviewDomReady = once(ipcMain, 'webview-dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const [, id] = await webviewDomReady;
expect(webContents.id).to.equal(id);
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
// tests relies on preloads in opened windows
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
it('opens window of about:blank with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('blocks accessing cross-origin frames', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
const [, content] = await answer;
expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
});
it('opens window from <iframe> tags', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window with cross-scripting enabled from isolated context', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
w.reload();
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
});
it('<webview> works in a scriptable popup', async () => {
const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegrationInSubFrames: true,
webviewTag: true,
contextIsolation: false,
preload
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false,
webPreferences: {
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
preload
}
}
}));
const webviewLoaded = once(ipcMain, 'webview-loaded');
w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
await webviewLoaded;
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: preloadPath,
contextIsolation: false
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
describe('window.location', () => {
const protocols = [
['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
];
beforeEach(() => {
for (const [scheme, path] of protocols) {
protocol.registerBufferProtocol(scheme, (request, callback) => {
callback({
mimeType: 'text/html',
data: fs.readFileSync(path)
});
});
}
});
afterEach(() => {
for (const [scheme] of protocols) {
protocol.unregisterProtocol(scheme);
}
});
it('retains the original web preferences when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
contextIsolation: false,
nodeIntegrationInSubFrames: true
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer');
expect(nodeIntegration).to.be.false();
expect(typeofProcess).to.eql('undefined');
});
it('window.opener is not null when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer');
expect(windowOpenerIsNull).to.be.false('window.opener is null');
});
});
});
describe('"disableHtmlFullscreenWindowResize" option', () => {
it('prevents window from resizing when set', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
disableHtmlFullscreenWindowResize: true
}
});
await w.loadURL('about:blank');
const size = w.getSize();
const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen');
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await enterHtmlFullScreen;
expect(w.getSize()).to.deep.equal(size);
});
});
describe('"defaultFontFamily" option', () => {
it('can change the standard font family', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
defaultFontFamily: {
standard: 'Impact'
}
}
});
await w.loadFile(path.join(fixtures, 'pages', 'content.html'));
const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true);
expect(fontFamily).to.equal('Impact');
});
});
});
describe('beforeunload handler', function () {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(closeAllWindows);
it('returning undefined would not prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('returning false would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('returning empty string would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('emits for each close attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const destroyListener = () => { expect.fail('Close was not prevented'); };
w.webContents.once('destroyed', destroyListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.close();
await once(w.webContents, 'before-unload-fired');
w.close();
await once(w.webContents, 'before-unload-fired');
w.webContents.removeListener('destroyed', destroyListener);
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits for each reload attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.reload();
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.reload();
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
w.reload();
await once(w.webContents, 'did-finish-load');
});
it('emits for each navigation attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.loadURL('about:blank');
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.loadURL('about:blank');
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
await w.loadURL('about:blank');
});
});
describe('document.visibilityState/hidden', () => {
afterEach(closeAllWindows);
it('visibilityState is initially visible despite window being hidden', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let readyToShow = false;
w.once('ready-to-show', () => {
readyToShow = true;
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(readyToShow).to.be.false('ready to show');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.show();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.showInactive();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.minimize();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
// when we introduced the compositor recycling patch. Should figure out how to fix this
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
ipcMain.once('pong', (event, visibilityState, hidden) => {
throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
});
try {
const shown1 = once(w, 'show');
w.show();
await shown1;
const hidden = once(w, 'hide');
w.hide();
await hidden;
const shown2 = once(w, 'show');
w.show();
await shown2;
} finally {
ipcMain.removeAllListeners('pong');
}
});
});
ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
afterEach(closeAllWindows);
it('emits an event when window is maximized', async () => {
const w = new BrowserWindow({ show: false });
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits an event when a transparent window is maximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits only one event when frameless window is maximized', () => {
const w = new BrowserWindow({ show: false, frame: false });
let emitted = 0;
w.on('maximize', () => emitted++);
w.show();
w.maximize();
expect(emitted).to.equal(1);
});
it('emits an event when window is unmaximized', async () => {
const w = new BrowserWindow({ show: false });
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
w.unmaximize();
await unmaximize;
});
it('emits an event when a transparent window is unmaximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await maximize;
w.unmaximize();
await unmaximize;
});
it('emits an event when window is minimized', async () => {
const w = new BrowserWindow({ show: false });
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
});
});
describe('beginFrameSubscription method', () => {
it('does not crash when callback returns nothing', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function () {
// This callback might be called twice.
if (called) return;
called = true;
// Pending endFrameSubscription to next tick can reliably reproduce
// a crash which happens when nothing is returned in the callback.
setTimeout().then(() => {
w.webContents.endFrameSubscription();
done();
});
});
});
});
it('subscribes to frame updates', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return;
called = true;
try {
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
});
it('subscribes to frame updates (only dirty rectangle)', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
let gotInitialFullSizeFrame = false;
const [contentWidth, contentHeight] = w.getContentSize();
w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (image, rect) => {
if (image.isEmpty()) {
// Chromium sometimes sends a 0x0 frame at the beginning of the
// page load.
return;
}
if (rect.height === contentHeight && rect.width === contentWidth &&
!gotInitialFullSizeFrame) {
// The initial frame is full-size, but we're looking for a call
// with just the dirty-rect. The next frame should be a smaller
// rect.
gotInitialFullSizeFrame = true;
return;
}
// This callback might be called twice.
if (called) return;
// We asked for just the dirty rectangle, so we expect to receive a
// rect smaller than the full size.
// TODO(jeremy): this is failing on windows currently; investigate.
// assert(rect.width < contentWidth || rect.height < contentHeight)
called = true;
try {
const expectedSize = rect.width * rect.height * 4;
expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
});
it('throws error when subscriber is not well defined', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.beginFrameSubscription(true, true as any);
// TODO(zcbenz): gin is weak at guessing parameter types, we should
// upstream native_mate's implementation to gin.
}).to.throw('Error processing argument at index 1, conversion failure from ');
});
});
describe('savePage method', () => {
const savePageDir = path.join(fixtures, 'save_page');
const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
afterEach(() => {
closeAllWindows();
try {
fs.unlinkSync(savePageCssPath);
fs.unlinkSync(savePageJsPath);
fs.unlinkSync(savePageHtmlPath);
fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
fs.rmdirSync(savePageDir);
} catch {}
});
it('should throw when passing relative paths', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await expect(
w.webContents.savePage('save_page.html', 'HTMLComplete')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'HTMLOnly')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'MHTML')
).to.eventually.be.rejectedWith('Path must be absolute');
});
it('should save page to disk with HTMLOnly', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
});
it('should save page to disk with MHTML', async () => {
/* Use temp directory for saving MHTML file since the write handle
* gets passed to untrusted process and chromium will deny exec access to
* the path. To perform this task, chromium requires that the path is one
* of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416
*/
const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-'));
const savePageMHTMLPath = path.join(tmpDir, 'save_page.html');
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageMHTMLPath, 'MHTML');
expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
try {
await fs.promises.unlink(savePageMHTMLPath);
await fs.promises.rmdir(tmpDir);
} catch {}
});
it('should save page to disk with HTMLComplete', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
});
});
describe('BrowserWindow options argument is optional', () => {
afterEach(closeAllWindows);
it('should create a window with default size (800x600)', () => {
const w = new BrowserWindow();
expect(w.getSize()).to.deep.equal([800, 600]);
});
});
describe('BrowserWindow.restore()', () => {
afterEach(closeAllWindows);
it('should restore the previous window size', () => {
const w = new BrowserWindow({
minWidth: 800,
width: 800
});
const initialSize = w.getSize();
w.minimize();
w.restore();
expectBoundsEqual(w.getSize(), initialSize);
});
it('does not crash when restoring hidden minimized window', () => {
const w = new BrowserWindow({});
w.minimize();
w.hide();
w.show();
});
// TODO(zcbenz):
// This test does not run on Linux CI. See:
// https://github.com/electron/electron/issues/28699
ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => {
const w = new BrowserWindow({});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
const restore = once(w, 'restore');
w.restore();
await restore;
expect(w.isMaximized()).to.equal(true);
});
});
// TODO(dsanders11): Enable once maximize event works on Linux again on CI
ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
afterEach(closeAllWindows);
it('should show the window if it is not currently shown', async () => {
const w = new BrowserWindow({ show: false });
const hidden = once(w, 'hide');
let shown = once(w, 'show');
const maximize = once(w, 'maximize');
expect(w.isVisible()).to.be.false('visible');
w.maximize();
await maximize;
await shown;
expect(w.isMaximized()).to.be.true('maximized');
expect(w.isVisible()).to.be.true('visible');
// Even if the window is already maximized
w.hide();
await hidden;
expect(w.isVisible()).to.be.false('visible');
shown = once(w, 'show');
w.maximize();
await shown;
expect(w.isVisible()).to.be.true('visible');
});
});
describe('BrowserWindow.unmaximize()', () => {
afterEach(closeAllWindows);
it('should restore the previous window position', () => {
const w = new BrowserWindow();
const initialPosition = w.getPosition();
w.maximize();
w.unmaximize();
expectBoundsEqual(w.getPosition(), initialPosition);
});
// TODO(dsanders11): Enable once minimize event works on Linux again.
// See https://github.com/electron/electron/issues/28699
ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
const w = new BrowserWindow();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
w.unmaximize();
await setTimeout(1000);
expect(w.isMinimized()).to.be.true();
});
it('should not change the size or position of a normal window', async () => {
const w = new BrowserWindow();
const initialSize = w.getSize();
const initialPosition = w.getPosition();
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getSize(), initialSize);
expectBoundsEqual(w.getPosition(), initialPosition);
});
ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
const { workArea } = screen.getPrimaryDisplay();
const bounds = {
x: workArea.x,
y: workArea.y,
width: workArea.width,
height: workArea.height
};
const w = new BrowserWindow(bounds);
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getBounds(), bounds);
});
});
describe('setFullScreen(false)', () => {
afterEach(closeAllWindows);
// only applicable to windows: https://github.com/electron/electron/issues/6036
ifdescribe(process.platform === 'win32')('on windows', () => {
it('should restore a normal visible window from a fullscreen startup state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const shown = once(w, 'show');
// start fullscreen and hidden
w.setFullScreen(true);
w.show();
await shown;
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.true('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
it('should keep window hidden if already in hidden state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.false('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
it('exits HTML fullscreen when window leaves fullscreen', async () => {
const w = new BrowserWindow();
await w.loadURL('about:blank');
await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await once(w, 'enter-full-screen');
// Wait a tick for the full-screen state to 'stick'
await setTimeout();
w.setFullScreen(false);
await once(w, 'leave-html-full-screen');
});
});
});
describe('parent window', () => {
afterEach(closeAllWindows);
ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
const w = new BrowserWindow();
const sheetBegin = once(w, 'sheet-begin');
// eslint-disable-next-line no-new
new BrowserWindow({
modal: true,
parent: w
});
await sheetBegin;
});
ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
const w = new BrowserWindow();
const sheet = new BrowserWindow({
modal: true,
parent: w
});
const sheetEnd = once(w, 'sheet-end');
sheet.close();
await sheetEnd;
});
describe('parent option', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.getParentWindow()).to.equal(w);
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(w.getChildWindows()).to.deep.equal([c]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isVisible()).to.be.false('parent is visible');
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(c, 'minimize');
c.minimize();
await minimized;
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(c, 'restore');
c.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
it('closes a grandchild window when a middle child window is destroyed', (done) => {
const w = new BrowserWindow();
w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
w.webContents.executeJavaScript('window.open("")');
w.webContents.on('did-create-window', async (window) => {
const childWindow = new BrowserWindow({ parent: window });
await setTimeout();
window.close();
childWindow.on('closed', () => {
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
done();
});
});
});
it('should not affect the show option', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.isVisible()).to.be.false('child is visible');
expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
});
});
describe('win.setParentWindow(parent)', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getParentWindow()).to.be.null('w.parent');
expect(c.getParentWindow()).to.be.null('c.parent');
c.setParentWindow(w);
expect(c.getParentWindow()).to.equal(w);
c.setParentWindow(null);
expect(c.getParentWindow()).to.be.null('c.parent');
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getChildWindows()).to.deep.equal([]);
c.setParentWindow(w);
expect(w.getChildWindows()).to.deep.equal([c]);
c.setParentWindow(null);
expect(w.getChildWindows()).to.deep.equal([]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
const closed = once(c, 'closed');
c.setParentWindow(w);
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
});
describe('modal option', () => {
it('does not freeze or crash', async () => {
const parentWindow = new BrowserWindow();
const createTwo = async () => {
const two = new BrowserWindow({
width: 300,
height: 200,
parent: parentWindow,
modal: true,
show: false
});
const twoShown = once(two, 'show');
two.show();
await twoShown;
setTimeout(500).then(() => two.close());
await once(two, 'closed');
};
const one = new BrowserWindow({
width: 600,
height: 400,
parent: parentWindow,
modal: true,
show: false
});
const oneShown = once(one, 'show');
one.show();
await oneShown;
setTimeout(500).then(() => one.destroy());
await once(one, 'closed');
await createTwo();
});
ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
const w = new BrowserWindow({ show: false });
w.setEnabled(false);
expect(w.isEnabled()).to.be.false('w.isEnabled()');
w.setEnabled(true);
expect(w.isEnabled()).to.be.true('!w.isEnabled()');
});
ifit(process.platform !== 'darwin')('disables parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
expect(w.isEnabled()).to.be.true('w.isEnabled');
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
w.setEnabled(false);
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c.destroy();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.destroy();
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
});
});
describe('window states', () => {
afterEach(closeAllWindows);
it('does not resize frameless windows when states change', () => {
const w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
});
w.minimizable = false;
w.minimizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.resizable = false;
w.resizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.maximizable = false;
w.maximizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.fullScreenable = false;
w.fullScreenable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.closable = false;
w.closable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
});
describe('resizable state', () => {
it('with properties', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.resizable).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.maximizable).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
w.resizable = false;
expect(w.resizable).to.be.false('resizable');
w.resizable = true;
expect(w.resizable).to.be.true('resizable');
});
});
it('with functions', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.isResizable()).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.isMaximizable()).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isResizable()).to.be.true('resizable');
w.setResizable(false);
expect(w.isResizable()).to.be.false('resizable');
w.setResizable(true);
expect(w.isResizable()).to.be.true('resizable');
});
});
it('works for a frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w.resizable).to.be.true('resizable');
if (process.platform === 'win32') {
const w = new BrowserWindow({ show: false, thickFrame: false });
expect(w.resizable).to.be.false('resizable');
}
});
// On Linux there is no "resizable" property of a window.
ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
expect(w.maximizable).to.be.true('maximizable');
w.resizable = false;
expect(w.maximizable).to.be.false('not maximizable');
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
const w = new BrowserWindow({
show: false,
frame: false,
resizable: false,
transparent: true
});
w.setContentSize(60, 60);
expectBoundsEqual(w.getContentSize(), [60, 60]);
w.setContentSize(30, 30);
expectBoundsEqual(w.getContentSize(), [30, 30]);
w.setContentSize(10, 10);
expectBoundsEqual(w.getContentSize(), [10, 10]);
});
});
describe('loading main frame state', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is true when the main frame is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(serverUrl);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
it('is false when only a subframe is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/page2'
document.body.appendChild(iframe)
`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
});
it('is true when navigating to pages from the same origin', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(`${serverUrl}/page2`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
});
});
ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
// Not implemented on Linux.
afterEach(closeAllWindows);
describe('movable state', () => {
it('with properties', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.movable).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.movable).to.be.true('movable');
w.movable = false;
expect(w.movable).to.be.false('movable');
w.movable = true;
expect(w.movable).to.be.true('movable');
});
});
it('with functions', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.isMovable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMovable()).to.be.true('movable');
w.setMovable(false);
expect(w.isMovable()).to.be.false('movable');
w.setMovable(true);
expect(w.isMovable()).to.be.true('movable');
});
});
});
describe('visibleOnAllWorkspaces state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.visibleOnAllWorkspaces).to.be.false();
w.visibleOnAllWorkspaces = true;
expect(w.visibleOnAllWorkspaces).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isVisibleOnAllWorkspaces()).to.be.false();
w.setVisibleOnAllWorkspaces(true);
expect(w.isVisibleOnAllWorkspaces()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.documentEdited).to.be.false();
w.documentEdited = true;
expect(w.documentEdited).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isDocumentEdited()).to.be.false();
w.setDocumentEdited(true);
expect(w.isDocumentEdited()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('representedFilename', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.representedFilename).to.eql('');
w.representedFilename = 'a name';
expect(w.representedFilename).to.eql('a name');
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getRepresentedFilename()).to.eql('');
w.setRepresentedFilename('a name');
expect(w.getRepresentedFilename()).to.eql('a name');
});
});
});
describe('native window title', () => {
it('with properties', () => {
it('can be set with title constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.title).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.title).to.eql('Electron Test Main');
w.title = 'NEW TITLE';
expect(w.title).to.eql('NEW TITLE');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.getTitle()).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTitle()).to.eql('Electron Test Main');
w.setTitle('NEW TITLE');
expect(w.getTitle()).to.eql('NEW TITLE');
});
});
});
describe('minimizable state', () => {
it('with properties', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.minimizable).to.be.false('minimizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.minimizable).to.be.true('minimizable');
w.minimizable = false;
expect(w.minimizable).to.be.false('minimizable');
w.minimizable = true;
expect(w.minimizable).to.be.true('minimizable');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.isMinimizable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMinimizable()).to.be.true('isMinimizable');
w.setMinimizable(false);
expect(w.isMinimizable()).to.be.false('isMinimizable');
w.setMinimizable(true);
expect(w.isMinimizable()).to.be.true('isMinimizable');
});
});
});
describe('maximizable state (property)', () => {
it('with properties', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.maximizable).to.be.false('maximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.maximizable).to.be.true('maximizable');
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.minimizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.closable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
w.closable = true;
expect(w.maximizable).to.be.true('maximizable');
w.fullScreenable = false;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.isMaximizable()).to.be.false('isMaximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMinimizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setClosable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setClosable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setFullScreenable(false);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform === 'win32')('maximizable state', () => {
it('with properties', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
describe('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.menuBarVisible).to.be.true();
w.menuBarVisible = false;
expect(w.menuBarVisible).to.be.false();
w.menuBarVisible = true;
expect(w.menuBarVisible).to.be.true();
});
});
describe('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
w.setMenuBarVisibility(false);
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
w.setMenuBarVisibility(true);
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
it('with functions', () => {
it('can be set with fullscreenable constructor option', () => {
const w = new BrowserWindow({ show: false, fullscreenable: false });
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
w.setFullScreenable(false);
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
w.setFullScreenable(true);
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
});
});
});
ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => {
it('with functions', () => {
it('can be set with ignoreMissionControl constructor option', () => {
const w = new BrowserWindow({ show: false, hiddenInMissionControl: true });
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
w.setHiddenInMissionControl(true);
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
w.setHiddenInMissionControl(false);
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
});
});
});
// fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
ifdescribe(process.platform === 'darwin')('kiosk state', () => {
it('with properties', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.kiosk).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.kiosk = true;
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.kiosk = false;
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
it('with functions', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.isKiosk()).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
it('resizable flag should be set to false and restored', async () => {
const w = new BrowserWindow({ resizable: false });
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.false('resizable');
});
it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.true('resizable');
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
it('should not cause a crash if called when exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('should be able to load a URL while transitioning to fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true });
w.loadFile(path.join(fixtures, 'pages', 'c.html'));
const load = once(w.webContents, 'did-finish-load');
const enterFS = once(w, 'enter-full-screen');
await Promise.all([enterFS, load]);
expect(w.fullScreen).to.be.true();
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('can be changed with setFullScreen method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('handles several transitions starting with fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true, show: true });
expect(w.isFullScreen()).to.be.true('not fullscreen');
w.setFullScreen(false);
w.setFullScreen(true);
const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('not fullscreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several HTML fullscreen transitions', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFullScreen = once(w, 'enter-full-screen');
const leaveFullScreen = once(w, 'leave-full-screen');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
await setTimeout();
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several transitions in close proximity', async () => {
const w = new BrowserWindow();
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
w.setFullScreen(true);
w.setFullScreen(false);
w.setFullScreen(true);
w.setFullScreen(false);
await Promise.all([enterFS, leaveFS]);
expect(w.isFullScreen()).to.be.false('not fullscreen');
});
it('handles several chromium-initiated transitions in close proximity', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>(resolve => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', () => {
enterCount++;
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await done;
});
it('handles HTML fullscreen transitions when fullscreenable is false', async () => {
const w = new BrowserWindow({ fullscreenable: false });
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>((resolve, reject) => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', async () => {
enterCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement');
if (!isFS) reject(new Error('Document should have fullscreen element'));
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await expect(done).to.eventually.be.fulfilled();
});
it('does not crash when exiting simpleFullScreen (properties)', async () => {
const w = new BrowserWindow();
w.setSimpleFullScreen(true);
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('does not crash when exiting simpleFullScreen (functions)', async () => {
const w = new BrowserWindow();
w.simpleFullScreen = true;
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('should not be changed by setKiosk method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('should stay fullscreen if fullscreen before kiosk', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
w.setKiosk(true);
w.setKiosk(false);
// Wait enough time for a fullscreen change to take effect.
await setTimeout(2000);
expect(w.isFullScreen()).to.be.true('isFullScreen');
});
it('multiple windows inherit correct fullscreen state', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout(1000);
const w2 = new BrowserWindow({ show: false });
const enterFullScreen2 = once(w2, 'enter-full-screen');
w2.show();
await enterFullScreen2;
expect(w2.isFullScreen()).to.be.true('isFullScreen');
});
});
describe('closable state', () => {
it('with properties', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.closable).to.be.false('closable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.closable).to.be.true('closable');
w.closable = false;
expect(w.closable).to.be.false('closable');
w.closable = true;
expect(w.closable).to.be.true('closable');
});
});
it('with functions', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.isClosable()).to.be.false('isClosable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isClosable()).to.be.true('isClosable');
w.setClosable(false);
expect(w.isClosable()).to.be.false('isClosable');
w.setClosable(true);
expect(w.isClosable()).to.be.true('isClosable');
});
});
});
describe('hasShadow state', () => {
it('with properties', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
expect(w.shadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.shadow).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
w.shadow = true;
expect(w.shadow).to.be.true('hasShadow');
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
});
});
describe('with functions', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
const hasShadow = w.hasShadow();
expect(hasShadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.hasShadow()).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
w.setHasShadow(true);
expect(w.hasShadow()).to.be.true('hasShadow');
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
});
});
});
});
describe('window.getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns valid source id', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
// Check format 'window:1234:0'.
const sourceId = w.getMediaSourceId();
expect(sourceId).to.match(/^window:\d+:\d+$/);
});
});
ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
afterEach(closeAllWindows);
it('returns valid handle', () => {
const w = new BrowserWindow({ show: false });
// The module's source code is hosted at
// https://github.com/electron/node-is-valid-window
const isValidWindow = require('is-valid-window');
expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
});
});
ifdescribe(process.platform === 'darwin')('previewFile', () => {
afterEach(closeAllWindows);
it('opens the path in Quick Look on macOS', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.previewFile(__filename);
w.closeFilePreview();
}).to.not.throw();
});
it('should not call BrowserWindow show event', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
let showCalled = false;
w.on('show', () => {
showCalled = true;
});
w.previewFile(__filename);
await setTimeout(500);
expect(showCalled).to.equal(false, 'should not have called show twice');
});
});
// TODO (jkleinsc) renable these tests on mas arm64
ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
};
afterEach(closeAllWindows);
it('separates the page context from the Electron/preload context', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
iw.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('enables context isolation on child windows', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const browserWindowCreated = once(app, 'browser-window-created');
iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
const [, window] = await browserWindowCreated;
expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
});
it('separates the page context from the Electron/preload context with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
ws.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('supports fetch api', async () => {
const fetchWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
}
});
const p = once(ipcMain, 'isolated-fetch-error');
fetchWindow.loadURL('about:blank');
const [, error] = await p;
expect(error).to.equal('Failed to fetch');
});
it('doesn\'t break ipc serialization', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadURL('about:blank');
iw.webContents.executeJavaScript(`
const opened = window.open()
openedLocation = opened.location.href
opened.close()
window.postMessage({openedLocation}, '*')
`);
const [, data] = await p;
expect(data.pageContext.openedLocation).to.equal('about:blank');
});
it('reports process.contextIsolated', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-process.js')
}
});
const p = once(ipcMain, 'context-isolation');
iw.loadURL('about:blank');
const [, contextIsolation] = await p;
expect(contextIsolation).to.be.true('contextIsolation');
});
});
it('reloading does not cause Node.js module API hangs after reload', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let count = 0;
ipcMain.on('async-node-api-done', () => {
if (count === 3) {
ipcMain.removeAllListeners('async-node-api-done');
done();
} else {
count++;
w.reload();
}
});
w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
});
describe('window.webContents.focus()', () => {
afterEach(closeAllWindows);
it('focuses window', async () => {
const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
w1.loadURL('about:blank');
const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
w2.loadURL('about:blank');
const w1Focused = once(w1, 'focus');
w1.webContents.focus();
await w1Focused;
expect(w1.webContents.isFocused()).to.be.true('focuses window');
});
});
ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
let w: BrowserWindow;
beforeEach(function () {
w = new BrowserWindow({
width: 100,
height: 100,
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
});
});
afterEach(closeAllWindows);
it('creates offscreen window with correct size', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
const [,, data] = await paint;
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
const size = data.getSize();
const { scaleFactor } = screen.getPrimaryDisplay();
expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
});
it('does not crash after navigation', () => {
w.webContents.loadURL('about:blank');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
describe('window.webContents.isOffscreen()', () => {
it('is true for offscreen type', () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
});
it('is false for regular window', () => {
const c = new BrowserWindow({ show: false });
expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
c.destroy();
});
});
describe('window.webContents.isPainting()', () => {
it('returns whether is currently painting', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await paint;
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('window.webContents.stopPainting()', () => {
it('stops painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
expect(w.webContents.isPainting()).to.be.false('isPainting');
});
});
describe('window.webContents.startPainting()', () => {
it('starts painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
w.webContents.startPainting();
await once(w.webContents, 'paint');
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('frameRate APIs', () => {
it('has default frame rate (function)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(60);
});
it('has default frame rate (property)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(60);
});
it('sets custom frame rate (function)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.setFrameRate(30);
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(30);
});
it('sets custom frame rate (property)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.frameRate = 30;
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(30);
});
});
});
describe('"transparent" option', () => {
afterEach(closeAllWindows);
ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => {
const w = new BrowserWindow({
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.be.false();
expect(w.isMinimized()).to.be.true();
});
// Only applicable on Windows where transparent windows can't be maximized.
ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
show: true
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
expect(w.isMaximized()).to.be.true();
// Fails when the transparent HWND is in an invalid maximized state.
expect(w.getBounds()).to.deep.equal(display.workArea);
const newBounds = { width: 256, height: 256, x: 0, y: 0 };
w.setBounds(newBounds);
expect(w.getBounds()).to.deep.equal(newBounds);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.GREEN,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
show: true,
transparent: true,
frame: false,
hasShadow: false
});
const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html');
await foregroundWindow.loadFile(colorFile);
await setTimeout(1000);
const screenCapture = await captureScreen();
const leftHalfColor = getPixelColor(screenCapture, {
x: display.size.width / 4,
y: display.size.height / 2
});
const rightHalfColor = getPixelColor(screenCapture, {
x: display.size.width - (display.size.width / 4),
y: display.size.height / 2
});
expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true();
expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true();
});
ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.PURPLE,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
hasShadow: false,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
}
});
foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html'));
await once(ipcMain, 'set-transparent');
await setTimeout();
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => {
const display = screen.getPrimaryDisplay();
for (const transparent of [false, undefined]) {
const window = new BrowserWindow({
...display.bounds,
transparent
});
await once(window, 'show');
await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>');
await setTimeout(500);
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
window.close();
// color-scheme is set to dark so background should not be white
expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false();
}
});
});
describe('"backgroundColor" option', () => {
afterEach(closeAllWindows);
// Linux/WOA doesn't return any capture sources.
ifit(process.platform === 'darwin')('should display the set color', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
show: true,
backgroundColor: HexColors.BLUE
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true();
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,807 |
[Bug]: Menu Bar Visibility
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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
### What operating system are you using?
Other Linux
### Operating System Version
Fedora 36
### What arch are you using?
x64
### Last Known Working Electron version
19.0.0
### Expected Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
then menu bar will be hidden which is great. But if you spam F11 key, menu bar will become visible again.
### Actual Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
Menu bar shouldn't be visible even while spamming F11.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35807
|
https://github.com/electron/electron/pull/38599
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
|
c8bdd014c87b5c33b77c845f853b7e52bb31de8f
| 2022-09-25T15:23:42Z |
c++
| 2023-06-08T10:19:34Z |
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 <dwmapi.h>
#include <wrl/client.h>
#endif
#include <memory>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/memory/raw_ptr.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/inspectable_web_contents.h"
#include "shell/browser/ui/views/inspectable_web_contents_view_views.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/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 "base/win/windows_version.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)
DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) {
if (material == "none") {
return DWMSBT_NONE;
} else if (material == "acrylic") {
return DWMSBT_TRANSIENTWINDOW;
} else if (material == "mica") {
return DWMSBT_MAINWINDOW;
} else if (material == "tabbed") {
return DWMSBT_TABBEDWINDOW;
}
return DWMSBT_AUTO;
}
// 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_{raw_ref<NativeWindowViews>::from_ptr(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:
const raw_ref<NativeWindowViews> window_;
};
} // namespace
NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent) {
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() {
#if BUILDFLAG(IS_WIN)
// widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a
// window or any of its parent windows are visible. We want to only check the
// current window.
bool visible =
::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE;
// WS_VISIBLE is true even if a window is miminized - explicitly check that.
return visible && !IsMinimized();
#else
return widget()->IsVisible();
#endif
}
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() && !IsMinimized()) {
// 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() {
#if BUILDFLAG(IS_WIN)
if (IsMaximized() && transparent())
return restore_bounds_;
#endif
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 = std::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::SetBackgroundMaterial(const std::string& material) {
#if BUILDFLAG(IS_WIN)
// DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up.
if (base::win::GetVersion() < base::win::Version::WIN11_22H2)
return;
DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material);
HRESULT result =
DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE,
&backdrop_type, sizeof(backdrop_type));
if (FAILED(result))
LOG(WARNING) << "Failed to set background material to " << material;
#endif
}
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 base::Contains(wm_states, sticky_atom);
}
#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;
}
#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_;
}
bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) {
return NonClientHitTest(location) == HTNOWHERE;
}
views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
return new NativeWindowClientView{widget, GetContentsView(), 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
| 35,807 |
[Bug]: Menu Bar Visibility
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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
### What operating system are you using?
Other Linux
### Operating System Version
Fedora 36
### What arch are you using?
x64
### Last Known Working Electron version
19.0.0
### Expected Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
then menu bar will be hidden which is great. But if you spam F11 key, menu bar will become visible again.
### Actual Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
Menu bar shouldn't be visible even while spamming F11.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35807
|
https://github.com/electron/electron/pull/38599
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
|
c8bdd014c87b5c33b77c845f853b7e52bb31de8f
| 2022-09-25T15:23:42Z |
c++
| 2023-06-08T10:19:34Z |
shell/browser/native_window_views.h
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#include "shell/browser/native_window.h"
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "shell/browser/ui/views/root_view.h"
#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include "ui/views/widget/widget_observer.h"
#if defined(USE_OZONE)
#include "ui/ozone/buildflags.h"
#if BUILDFLAG(OZONE_PLATFORM_X11)
#define USE_OZONE_PLATFORM_X11
#endif
#endif
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
namespace electron {
class GlobalMenuBarX11;
class WindowStateWatcher;
#if defined(USE_OZONE_PLATFORM_X11)
class EventDisabler;
#endif
#if BUILDFLAG(IS_WIN)
gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds);
#endif
class NativeWindowViews : public NativeWindow,
public views::WidgetObserver,
public ui::EventHandler {
public:
NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent);
~NativeWindowViews() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate) override;
gfx::Rect GetBounds() override;
gfx::Rect GetContentBounds() override;
gfx::Size GetContentSize() override;
gfx::Rect GetNormalBounds() override;
SkColor GetBackgroundColor() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relativeLevel) override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
bool IsTabletMode() const override;
void SetBackgroundColor(SkColor color) override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void SetMenu(ElectronMenuModel* menu_model) override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetAutoHideMenuBar(bool auto_hide) override;
bool IsMenuBarAutoHide() override;
void SetMenuBarVisibility(bool visible) override;
bool IsMenuBarVisible() override;
void SetBackgroundMaterial(const std::string& type) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetGTKDarkThemeEnabled(bool use_dark_theme) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
void IncrementChildModals();
void DecrementChildModals();
#if BUILDFLAG(IS_WIN)
// Catch-all message handling and filtering. Called before
// HWNDMessageHandler's built-in handling, which may pre-empt some
// expectations in Views/Aura if messages are consumed. Returns true if the
// message was consumed by the delegate and should not be processed further
// by the HWNDMessageHandler. In this case, |result| is returned. |result| is
// not modified otherwise.
bool PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result);
void SetIcon(HICON small_icon, HICON app_icon);
#elif BUILDFLAG(IS_LINUX)
void SetIcon(const gfx::ImageSkia& icon);
#endif
#if BUILDFLAG(IS_WIN)
TaskbarHost& taskbar_host() { return taskbar_host_; }
#endif
#if BUILDFLAG(IS_WIN)
bool IsWindowControlsOverlayEnabled() const {
return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) &&
titlebar_overlay_;
}
SkColor overlay_button_color() const { return overlay_button_color_; }
void set_overlay_button_color(SkColor color) {
overlay_button_color_ = color;
}
SkColor overlay_symbol_color() const { return overlay_symbol_color_; }
void set_overlay_symbol_color(SkColor color) {
overlay_symbol_color_ = color;
}
#endif
private:
// views::WidgetObserver:
void OnWidgetActivationChanged(views::Widget* widget, bool active) override;
void OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& bounds) override;
void OnWidgetDestroying(views::Widget* widget) override;
void OnWidgetDestroyed(views::Widget* widget) override;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override;
bool CanMaximize() const override;
bool CanMinimize() const override;
std::u16string GetWindowTitle() const override;
views::View* GetContentsView() override;
bool ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) override;
views::ClientView* CreateClientView(views::Widget* widget) override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
void OnWidgetMove() override;
#if BUILDFLAG(IS_WIN)
bool ExecuteWindowsCommand(int command_id) override;
#endif
#if BUILDFLAG(IS_WIN)
void HandleSizeEvent(WPARAM w_param, LPARAM l_param);
void ResetWindowControls();
void SetForwardMouseMessages(bool forward);
static LRESULT CALLBACK SubclassProc(HWND hwnd,
UINT msg,
WPARAM w_param,
LPARAM l_param,
UINT_PTR subclass_id,
DWORD_PTR ref_data);
static LRESULT CALLBACK MouseHookProc(int n_code,
WPARAM w_param,
LPARAM l_param);
#endif
// Enable/disable:
bool ShouldBeEnabled();
void SetEnabledInternal(bool enabled);
// NativeWindow:
void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) override;
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override;
// Returns the restore state for the window.
ui::WindowShowState GetRestoredState();
// Maintain window placement.
void MoveBehindTaskBarIfNeeded();
RootView root_view_{this};
// The view should be focused by default.
raw_ptr<views::View> focused_view_ = nullptr;
// The "resizable" flag on Linux is implemented by setting size constraints,
// we need to make sure size constraints are restored when window becomes
// resizable again. This is also used on Windows, to keep taskbar resize
// events from resizing the window.
extensions::SizeConstraints old_size_constraints_;
#if defined(USE_OZONE)
std::unique_ptr<GlobalMenuBarX11> global_menu_bar_;
#endif
#if defined(USE_OZONE_PLATFORM_X11)
// To disable the mouse events.
std::unique_ptr<EventDisabler> event_disabler_;
#endif
#if BUILDFLAG(IS_WIN)
ui::WindowShowState last_window_state_;
gfx::Rect last_normal_placement_bounds_;
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
// Memoized version of a11y check
bool checked_for_a11y_support_ = false;
// Whether to show the WS_THICKFRAME style.
bool thick_frame_ = true;
// The bounds of window before maximize/fullscreen.
gfx::Rect restore_bounds_;
// The icons of window and taskbar.
base::win::ScopedHICON window_icon_;
base::win::ScopedHICON app_icon_;
// The set of windows currently forwarding mouse messages.
static std::set<NativeWindowViews*> forwarding_windows_;
static HHOOK mouse_hook_;
bool forwarding_mouse_messages_ = false;
HWND legacy_window_ = NULL;
bool layered_ = false;
// Set to true if the window is always on top and behind the task bar.
bool behind_task_bar_ = false;
// Whether we want to set window placement without side effect.
bool is_setting_window_placement_ = false;
// Whether the window is currently being resized.
bool is_resizing_ = false;
// Whether the window is currently being moved.
bool is_moving_ = false;
absl::optional<gfx::Rect> pending_bounds_change_;
// The color to use as the theme and symbol colors respectively for Window
// Controls Overlay if enabled on Windows.
SkColor overlay_button_color_;
SkColor overlay_symbol_color_;
#endif
// Handles unhandled keyboard messages coming back from the renderer process.
views::UnhandledKeyboardEventHandler keyboard_event_handler_;
// Whether the window should be enabled based on user calls to SetEnabled()
bool is_enabled_ = true;
// How many modal children this window has;
// used to determine enabled state
unsigned int num_modal_children_ = 0;
bool use_content_size_ = false;
bool movable_ = true;
bool resizable_ = true;
bool maximizable_ = true;
bool minimizable_ = true;
bool fullscreenable_ = true;
std::string title_;
gfx::Size widget_size_;
double opacity_ = 1.0;
bool widget_destroyed_ = false;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,807 |
[Bug]: Menu Bar Visibility
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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
### What operating system are you using?
Other Linux
### Operating System Version
Fedora 36
### What arch are you using?
x64
### Last Known Working Electron version
19.0.0
### Expected Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
then menu bar will be hidden which is great. But if you spam F11 key, menu bar will become visible again.
### Actual Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
Menu bar shouldn't be visible even while spamming F11.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35807
|
https://github.com/electron/electron/pull/38599
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
|
c8bdd014c87b5c33b77c845f853b7e52bb31de8f
| 2022-09-25T15:23:42Z |
c++
| 2023-06-08T10:19:34Z |
spec/api-browser-window-spec.ts
|
import { expect } from 'chai';
import * as childProcess from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import * as qs from 'querystring';
import * as http from 'http';
import * as os from 'os';
import { AddressInfo } from 'net';
import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main';
import { emittedUntil, emittedNTimes } from './lib/events-helpers';
import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers';
import { once } from 'events';
import { setTimeout } from 'timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixtures = path.resolve(__dirname, 'fixtures');
const mainFixtures = path.resolve(__dirname, 'fixtures');
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
const { scaleFactor } = screen.getPrimaryDisplay();
// Return true if scale factor is non-integer value
if (Math.round(scaleFactor) !== scaleFactor) return true;
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1;
};
const expectBoundsEqual = (actual: any, expected: any) => {
if (!isScaleFactorRounding()) {
expect(expected).to.deep.equal(actual);
} else if (Array.isArray(actual)) {
expect(actual[0]).to.be.closeTo(expected[0], 1);
expect(actual[1]).to.be.closeTo(expected[1], 1);
} else {
expect(actual.x).to.be.closeTo(expected.x, 1);
expect(actual.y).to.be.closeTo(expected.y, 1);
expect(actual.width).to.be.closeTo(expected.width, 1);
expect(actual.height).to.be.closeTo(expected.height, 1);
}
};
const isBeforeUnload = (event: Event, level: number, message: string) => {
return (message === 'beforeunload');
};
describe('BrowserWindow module', () => {
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
expect(() => {
const w = new BrowserWindow({
show: false,
// apparently void 0 had different behaviour from undefined in the
// issue that this test is supposed to catch.
webContents: void 0 // eslint-disable-line no-void
} as any);
w.destroy();
}).not.to.throw();
});
ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
const appProcess = childProcess.spawn(process.execPath, [appPath]);
await once(appProcess, 'exit');
});
it('does not crash or throw when passed an invalid icon', async () => {
expect(() => {
const w = new BrowserWindow({
icon: undefined
} as any);
w.destroy();
}).not.to.throw();
});
});
describe('garbage collection', () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
afterEach(closeAllWindows);
it('window does not get garbage collected when opened', async () => {
const w = new BrowserWindow({ show: false });
// Keep a weak reference to the window.
const wr = new WeakRef(w);
await setTimeout();
// Do garbage collection, since |w| is not referenced in this closure
// it would be gone after next call if there is no other reference.
v8Util.requestGarbageCollectionForTesting();
await setTimeout();
expect(wr.deref()).to.not.be.undefined();
});
});
describe('BrowserWindow.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should work if called when a messageBox is showing', async () => {
const closed = once(w, 'closed');
dialog.showMessageBox(w, { message: 'Hello Error' });
w.close();
await closed;
});
it('closes window without rounded corners', async () => {
await closeWindow(w);
w = new BrowserWindow({ show: false, frame: false, roundedCorners: false });
const closed = once(w, 'closed');
w.close();
await closed;
});
it('should not crash if called after webContents is destroyed', () => {
w.webContents.destroy();
w.webContents.on('destroyed', () => w.close());
});
it('should allow access to id after destruction', async () => {
const closed = once(w, 'closed');
w.destroy();
await closed;
expect(w.id).to.be.a('number');
});
it('should emit unload handler', async () => {
await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
const closed = once(w, 'closed');
w.close();
await closed;
const test = path.join(fixtures, 'api', 'unload');
const content = fs.readFileSync(test);
fs.unlinkSync(test);
expect(String(content)).to.equal('unload');
});
it('should emit beforeunload handler', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'before-unload-fired');
});
it('should not crash when keyboard event is sent before closing', async () => {
await w.loadURL('data:text/html,pls no crash');
const closed = once(w, 'closed');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
w.close();
await closed;
});
describe('when invoked synchronously inside navigation observer', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/301':
response.statusCode = 301;
response.setHeader('Location', '/200');
response.end();
break;
case '/200':
response.statusCode = 200;
response.end('hello');
break;
case '/title':
response.statusCode = 200;
response.end('<title>Hello</title>');
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', path: '/200' },
{ name: 'dom-ready', path: '/200' },
{ name: 'page-title-updated', path: '/title' },
{ name: 'did-stop-loading', path: '/200' },
{ name: 'did-finish-load', path: '/200' },
{ name: 'did-frame-finish-load', path: '/200' },
{ name: 'did-fail-load', path: '/net-error' }
];
for (const { name, path } of events) {
it(`should not crash when closed during ${name}`, async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once((name as any), () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.webContents.loadURL(url + path);
await destroyed;
});
}
});
});
describe('window.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload event', async () => {
w.loadFile(path.join(fixtures, 'api', 'close.html'));
await once(w, 'closed');
const test = path.join(fixtures, 'api', 'close');
const content = fs.readFileSync(test).toString();
fs.unlinkSync(test);
expect(content).to.equal('close');
});
it('should emit beforeunload event', async function () {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.webContents.executeJavaScript('window.close()', true);
await once(w.webContents, 'before-unload-fired');
});
});
describe('BrowserWindow.destroy()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('prevents users to access methods of webContents', async () => {
const contents = w.webContents;
w.destroy();
await new Promise(setImmediate);
expect(() => {
contents.getProcessId();
}).to.throw('Object has been destroyed');
});
it('should not crash when destroying windows with pending events', () => {
const focusListener = () => { };
app.on('browser-window-focus', focusListener);
const windowCount = 3;
const windowOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show());
windows.forEach(win => win.focus());
windows.forEach(win => win.destroy());
app.removeListener('browser-window-focus', focusListener);
});
});
describe('BrowserWindow.loadURL(url)', () => {
let w: BrowserWindow;
const scheme = 'other';
const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
callback(srcPath);
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
let server: http.Server;
let url: string;
let postData = null as any;
before(async () => {
const filePath = path.join(fixtures, 'pages', 'a.html');
const fileStats = fs.statSync(filePath);
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
];
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
let body = '';
req.on('data', (data) => {
if (data) body += data;
});
req.on('end', () => {
const parsedData = qs.parse(body);
fs.readFile(filePath, (err, data) => {
if (err) return;
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end();
}
});
});
} else if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
}
setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond);
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('should emit did-start-loading event', async () => {
const didStartLoading = once(w.webContents, 'did-start-loading');
w.loadURL('about:blank');
await didStartLoading;
});
it('should emit ready-to-show event', async () => {
const readyToShow = once(w, 'ready-to-show');
w.loadURL('about:blank');
await readyToShow;
});
// DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
// changed and adjust the test.
it('should emit did-fail-load event for files that do not exist', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('file://a.txt');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(code).to.equal(-6);
expect(desc).to.equal('ERR_FILE_NOT_FOUND');
expect(isMainFrame).to.equal(true);
});
it('should emit did-fail-load event for invalid URL', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('http://example:port');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should not emit did-fail-load for a successfully loaded media file', async () => {
w.webContents.on('did-fail-load', () => {
expect.fail('did-fail-load should not emit on media file loads');
});
const mediaStarted = once(w.webContents, 'media-started-playing');
w.loadFile(path.join(fixtures, 'cat-spin.mp4'));
await mediaStarted;
});
it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
const [,,,, isMainFrame] = await didFailLoad;
expect(isMainFrame).to.equal(false);
});
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
w.loadURL('http://127.0.0.1:11111');
done();
});
w.loadURL('http://127.0.0.1:11111');
});
it('should emit did-fail-load event for URL exceeding character limit', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL(`data:image/png;base64,${data}`);
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should return a promise', () => {
const p = w.loadURL('about:blank');
expect(p).to.have.property('then');
});
it('should return a promise that resolves', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('should return a promise that rejects on a load failure', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const p = w.loadURL(`data:image/png;base64,${data}`);
await expect(p).to.eventually.be.rejected;
});
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
await expect(p).to.eventually.be.fulfilled;
});
describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
it('supports specifying POST data', async () => {
await w.loadURL(url, { postData });
});
it('sets the content type header on URL encoded forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
});
it('sets the content type header on multi part forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
});
});
it('should support base url for data urls', async () => {
await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
});
});
for (const sandbox of [false, true]) {
describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('will-navigate event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-navigate');
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
await event;
w.close();
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame);
let initiator: WebFrameMain | undefined;
w.webContents.on('will-navigate', (e) => {
initiator = e.initiator;
});
const subframe = w.webContents.mainFrame.frames[0];
subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true);
await once(w.webContents, 'did-navigate');
expect(initiator).not.to.be.undefined();
expect(initiator).to.equal(subframe);
});
});
describe('will-frame-navigate event', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else if (req.url === '/navigate-iframe') {
res.end('<a href="/test">navigate iframe</a>');
} else if (req.url === '/navigate-iframe?navigated') {
res.end('Successfully navigated');
} else if (req.url === '/navigate-iframe-immediately') {
res.end(`
<script type="text/javascript" charset="utf-8">
location.href += '?navigated'
</script>
`);
} else if (req.url === '/navigate-iframe-immediately?navigated') {
res.end('Successfully navigated');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-frame-navigate', () => {
w.close();
done();
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented when navigating subframe', (done) => {
let willNavigate = false;
w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
if (isMainFrame) return;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(frame).to.not.be.undefined();
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
});
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`);
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await setTimeout(1000);
let willFrameNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willFrameNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willFrameNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.true();
});
it('is triggered when a cross-origin iframe navigates itself', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`);
await setTimeout(1000);
let willNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-frame-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.false();
});
it('can cancel when a cross-origin iframe navigates itself', async () => {
});
});
describe('will-redirect event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else if (req.url === '/navigate-302') {
res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
} else {
res.end();
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is emitted on redirects', async () => {
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
});
it('is emitted after will-navigate on redirects', async () => {
let navigateCalled = false;
w.webContents.on('will-navigate', () => {
navigateCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/navigate-302`);
await willRedirect;
expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
});
it('is emitted before did-stop-loading on redirects', async () => {
let stopCalled = false;
w.webContents.on('did-stop-loading', () => {
stopCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await event;
w.close();
});
it('can be prevented', (done) => {
w.webContents.once('will-redirect', (event) => {
event.preventDefault();
});
w.webContents.on('will-navigate', (e, u) => {
expect(u).to.equal(`${url}/302`);
});
w.webContents.on('did-stop-loading', () => {
try {
expect(w.webContents.getURL()).to.equal(
`${url}/navigate-302`,
'url should not have changed after navigation event'
);
done();
} catch (e) {
done(e);
}
});
w.webContents.on('will-redirect', (e, u) => {
try {
expect(u).to.equal(`${url}/200`);
} catch (e) {
done(e);
}
});
w.loadURL(`${url}/navigate-302`);
});
});
describe('ordering', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
const navigationEvents = [
'did-start-navigation',
'did-navigate-in-page',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate') {
res.end('<a href="/">navigate</a>');
} else if (req.url === '/redirect') {
res.end('<a href="/redirect2">redirect</a>');
} else if (req.url === '/redirect2') {
res.statusCode = 302;
res.setHeader('location', url);
res.end();
} else if (req.url === '/in-page') {
res.end('<a href="#in-page">redirect</a><div id="in-page"></div>');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
it('for initial navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-frame-navigate',
'did-navigate'
];
const allEvents = Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const timeout = setTimeout(1000);
w.loadURL(url);
await Promise.race([allEvents, timeout]);
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('for second navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}navigate`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating with redirection, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}redirect`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating in-page, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-navigate-in-page'
];
w.loadURL(`${url}in-page`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate-in-page');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
});
});
}
describe('focus and visibility', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.show()', () => {
it('should focus on window', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isFocused()).to.equal(true);
});
it('should make the window visible', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isVisible()).to.equal(true);
});
it('emits when window is shown', async () => {
const show = once(w, 'show');
w.show();
await show;
expect(w.isVisible()).to.equal(true);
});
});
describe('BrowserWindow.hide()', () => {
it('should defocus on window', () => {
w.hide();
expect(w.isFocused()).to.equal(false);
});
it('should make the window not visible', () => {
w.show();
w.hide();
expect(w.isVisible()).to.equal(false);
});
it('emits when window is hidden', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const hidden = once(w, 'hide');
w.hide();
await hidden;
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.minimize()', () => {
// TODO(codebytere): Enable for Linux once maximize/minimize events work in CI.
ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => {
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMinimized()).to.equal(true);
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
w.showInactive();
expect(w.isFocused()).to.equal(false);
});
// TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests
ifit(process.platform !== 'linux')('should not restore maximized windows', async () => {
const maximize = once(w, 'maximize');
const shown = once(w, 'show');
w.maximize();
// TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden
if (process.platform !== 'darwin') {
await maximize;
} else {
await setTimeout(1000);
}
w.showInactive();
await shown;
expect(w.isMaximized()).to.equal(true);
});
});
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
expect(w.isVisible()).to.equal(false);
w.focus();
expect(w.isVisible()).to.equal(false);
});
ifit(process.platform !== 'win32')('focuses a blurred window', async () => {
{
const isBlurred = once(w, 'blur');
const isShown = once(w, 'show');
w.show();
w.blur();
await isShown;
await isBlurred;
}
expect(w.isFocused()).to.equal(false);
w.focus();
expect(w.isFocused()).to.equal(true);
});
ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w1.focus();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w2.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w3.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
// TODO(RaisinTen): Make this work on Windows too.
// Refs: https://github.com/electron/electron/issues/20464.
ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => {
it('removes focus from window', async () => {
{
const isFocused = once(w, 'focus');
const isShown = once(w, 'show');
w.show();
await isShown;
await isFocused;
}
expect(w.isFocused()).to.equal(true);
w.blur();
expect(w.isFocused()).to.equal(false);
});
ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w3.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w2.blur();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w1.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', async () => {
const p = once(w, 'focus');
w.show();
await p;
w.webContents.openDevTools({ mode: 'undocked' });
await once(w.webContents, 'devtools-focused');
expect(BrowserWindow.getFocusedWindow()).to.equal(w);
});
});
describe('BrowserWindow.moveTop()', () => {
it('should not steal focus', async () => {
const posDelta = 50;
const wShownInactive = once(w, 'show');
w.showInactive();
await wShownInactive;
expect(w.isFocused()).to.equal(false);
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
const otherWindowShown = once(otherWindow, 'show');
const otherWindowFocused = once(otherWindow, 'focus');
otherWindow.show();
await otherWindowShown;
await otherWindowFocused;
expect(otherWindow.isFocused()).to.equal(true);
w.moveTop();
const wPos = w.getPosition();
const wMoving = once(w, 'move');
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
await wMoving;
expect(w.isFocused()).to.equal(false);
expect(otherWindow.isFocused()).to.equal(true);
const wFocused = once(w, 'focus');
const otherWindowBlurred = once(otherWindow, 'blur');
w.focus();
await wFocused;
await otherWindowBlurred;
expect(w.isFocused()).to.equal(true);
otherWindow.moveTop();
const otherWindowPos = otherWindow.getPosition();
const otherWindowMoving = once(otherWindow, 'move');
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
await otherWindowMoving;
expect(otherWindow.isFocused()).to.equal(false);
expect(w.isFocused()).to.equal(true);
await closeWindow(otherWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
});
});
describe('BrowserWindow.moveAbove(mediaSourceId)', () => {
it('should throw an exception if wrong formatting', async () => {
const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should throw an exception if wrong type', async () => {
const fakeSourceIds = [null as any, 123 as any];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */);
});
});
it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
'window:123456:9'];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should not throw an exception', async () => {
const w2 = new BrowserWindow({ show: false, title: 'window2' });
const w2Shown = once(w2, 'show');
w2.show();
await w2Shown;
expect(() => {
w.moveAbove(w2.getMediaSourceId());
}).to.not.throw();
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.setFocusable()', () => {
it('can set unfocusable window to focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
const w2Focused = once(w2, 'focus');
w2.setFocusable(true);
w2.focus();
await w2Focused;
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.isFocusable()', () => {
it('correctly returns whether a window is focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
expect(w2.isFocusable()).to.be.false();
w2.setFocusable(true);
expect(w2.isFocusable()).to.be.true();
await closeWindow(w2, { assertNotWindows: false });
});
});
});
describe('sizing', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, width: 400, height: 400 });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
it('sets the window bounds with full bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
expectBoundsEqual(w.getBounds(), fullBounds);
});
it('sets the window bounds with partial bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
const boundsUpdate = { width: 200 };
w.setBounds(boundsUpdate as any);
const expectedBounds = { ...fullBounds, ...boundsUpdate };
expectBoundsEqual(w.getBounds(), expectedBounds);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds, true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
const size = [300, 400];
const resized = once(w, 'resize');
w.setSize(size[0], size[1]);
await resized;
expectBoundsEqual(w.getSize(), size);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const size = [300, 400];
w.setSize(size[0], size[1], true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
expect(w.getMinimumSize()).to.deep.equal([0, 0]);
expect(w.getMaximumSize()).to.deep.equal([0, 0]);
w.setMinimumSize(100, 100);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [0, 0]);
w.setMaximumSize(900, 600);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [900, 600]);
});
});
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', async () => {
const size = [300, 400];
w.setAspectRatio(1 / 2);
w.setAspectRatio(0);
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getSize(), size);
});
it('doesn\'t change bounds when maximum size is set', () => {
w.setMenu(null);
w.setMaximumSize(400, 400);
// Without https://github.com/electron/electron/pull/29101
// following call would shrink the window to 384x361.
// There would be also DCHECK in resize_utils.cc on
// debug build.
w.setAspectRatio(1.0);
expectBoundsEqual(w.getSize(), [400, 400]);
});
});
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expect(w.getPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', async () => {
// NB. The CI server has a very small screen. Attempting to size the window
// larger than the screen will limit the window's size to the screen and
// cause the test to fail.
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
});
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
});
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', async () => {
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
});
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
});
describe('BrowserWindow.getBackgroundColor()', () => {
it('returns default value if no backgroundColor is set', () => {
w.destroy();
w = new BrowserWindow({});
expect(w.getBackgroundColor()).to.equal('#FFFFFF');
});
it('returns correct value if backgroundColor is set', () => {
const backgroundColor = '#BBAAFF';
w.destroy();
w = new BrowserWindow({
backgroundColor: backgroundColor
});
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct value from setBackgroundColor()', () => {
const backgroundColor = '#AABBFF';
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor(backgroundColor);
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct color with multiple passed formats', () => {
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor('#AABBFF');
expect(w.getBackgroundColor()).to.equal('#AABBFF');
w.setBackgroundColor('blueviolet');
expect(w.getBackgroundColor()).to.equal('#8A2BE2');
w.setBackgroundColor('rgb(255, 0, 185)');
expect(w.getBackgroundColor()).to.equal('#FF00B9');
w.setBackgroundColor('rgba(245, 40, 145, 0.8)');
expect(w.getBackgroundColor()).to.equal('#F52891');
w.setBackgroundColor('hsl(155, 100%, 50%)');
expect(w.getBackgroundColor()).to.equal('#00FF95');
});
});
describe('BrowserWindow.getNormalBounds()', () => {
describe('Normal state', () => {
it('checks normal bounds after resize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
it('checks normal bounds after move', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
});
ifdescribe(process.platform !== 'linux')('Maximized state', () => {
it('checks normal bounds when maximized', async () => {
const bounds = w.getBounds();
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and maximize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and maximize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unmaximized', async () => {
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly reports maximized state after maximizing then minimizing', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
expect(w.isMinimized()).to.equal(true);
});
it('correctly reports maximized state after maximizing then fullscreening', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
expect(w.isMaximized()).to.equal(false);
expect(w.isFullScreen()).to.equal(true);
});
it('checks normal bounds for maximized transparent window', async () => {
w.destroy();
w = new BrowserWindow({
transparent: true,
show: false
});
w.show();
const bounds = w.getNormalBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly checks transparent window maximization state', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
width: 300,
height: 300,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
const unmaximize = once(w, 'unmaximize');
w.unmaximize();
await unmaximize;
expect(w.isMaximized()).to.equal(false);
});
it('returns the correct value for windows with an aspect ratio', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
fullscreenable: false
});
w.setAspectRatio(16 / 11);
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
w.resizable = false;
expect(w.isMaximized()).to.equal(true);
});
});
ifdescribe(process.platform !== 'linux')('Minimized state', () => {
it('checks normal bounds when minimized', async () => {
const bounds = w.getBounds();
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after move and minimize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('updates normal bounds after resize and minimize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('checks normal bounds when restored', async () => {
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
it('with properties', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.fullScreen).to.be.true();
});
it('does not go fullscreen if roundedCorners are enabled', async () => {
w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true });
expect(w.fullScreen).to.be.false();
});
it('can be changed', () => {
w.fullScreen = false;
expect(w.fullScreen).to.be.false();
w.fullScreen = true;
expect(w.fullScreen).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
const enterFullScreen = once(w, 'enter-full-screen');
w.show();
w.fullScreen = true;
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.once('enter-full-screen', () => {
w.fullScreen = false;
});
const leaveFullScreen = once(w, 'leave-full-screen');
w.show();
w.fullScreen = true;
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
it('with functions', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.isFullScreen()).to.be.true();
});
it('can be changed', () => {
w.setFullScreen(false);
expect(w.isFullScreen()).to.be.false();
w.setFullScreen(true);
expect(w.isFullScreen()).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
});
});
});
ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.selectPreviousTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectPreviousTab();
}).to.not.throw();
});
});
describe('BrowserWindow.selectNextTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectNextTab();
}).to.not.throw();
});
});
describe('BrowserWindow.mergeAllWindows()', () => {
it('does not throw', () => {
expect(() => {
w.mergeAllWindows();
}).to.not.throw();
});
});
describe('BrowserWindow.moveTabToNewWindow()', () => {
it('does not throw', () => {
expect(() => {
w.moveTabToNewWindow();
}).to.not.throw();
});
});
describe('BrowserWindow.toggleTabBar()', () => {
it('does not throw', () => {
expect(() => {
w.toggleTabBar();
}).to.not.throw();
});
});
describe('BrowserWindow.addTabbedWindow()', () => {
it('does not throw', async () => {
const tabbedWindow = new BrowserWindow({});
expect(() => {
w.addTabbedWindow(tabbedWindow);
}).to.not.throw();
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
await closeWindow(tabbedWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
});
it('throws when called on itself', () => {
expect(() => {
w.addTabbedWindow(w);
}).to.throw('AddTabbedWindow cannot be called by a window on itself.');
});
});
});
describe('autoHideMenuBar state', () => {
afterEach(closeAllWindows);
it('for properties', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
w.autoHideMenuBar = true;
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
w.autoHideMenuBar = false;
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
});
});
it('for functions', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
w.setAutoHideMenuBar(true);
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
w.setAutoHideMenuBar(false);
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
});
});
});
describe('BrowserWindow.capturePage(rect)', () => {
afterEach(closeAllWindows);
it('returns a Promise with a Buffer', async () => {
const w = new BrowserWindow({ show: false });
const image = await w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => {
const w = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true });
const visible = await w.webContents.executeJavaScript('document.visibilityState');
expect(visible).to.equal('hidden');
});
it('resolves after the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
w.show();
const visibleImage = await w.capturePage();
expect(visibleImage.isEmpty()).to.equal(false);
w.hide();
const hiddenImage = await w.capturePage();
const isEmpty = process.platform !== 'darwin';
expect(hiddenImage.isEmpty()).to.equal(isEmpty);
});
it('resolves after the window is hidden and capturer count is non-zero', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
const image = await w.capturePage();
expect(image.isEmpty()).to.equal(false);
});
it('preserves transparency', async () => {
const w = new BrowserWindow({ show: false, transparent: true });
w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
await once(w, 'ready-to-show');
w.show();
const image = await w.capturePage();
const imgBuffer = image.toPNG();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6);
});
});
describe('BrowserWindow.setProgressBar(progress)', () => {
let w: BrowserWindow;
before(() => {
w = new BrowserWindow({ show: false });
});
after(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('sets the progress', () => {
expect(() => {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
}
w.setProgressBar(0.5);
if (process.platform === 'darwin') {
app.dock.setIcon(null as any);
}
w.setProgressBar(-1);
}).to.not.throw();
});
it('sets the progress using "paused" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'paused' });
}).to.not.throw();
});
it('sets the progress using "error" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'error' });
}).to.not.throw();
});
it('sets the progress using "normal" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'normal' });
}).to.not.throw();
});
});
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
let w: BrowserWindow;
afterEach(closeAllWindows);
beforeEach(() => {
w = new BrowserWindow({ show: true });
});
it('sets the window as always on top', () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
w.setAlwaysOnTop(false);
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
it('causes the right value to be emitted on `always-on-top-changed`', async () => {
const alwaysOnTopChanged = once(w, 'always-on-top-changed');
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
const [, alwaysOnTop] = await alwaysOnTopChanged;
expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ parent: w });
c.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.false();
expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver');
});
});
describe('preconnect feature', () => {
let w: BrowserWindow;
let server: http.Server;
let url: string;
let connections = 0;
beforeEach(async () => {
connections = 0;
server = http.createServer((req, res) => {
if (req.url === '/link') {
res.setHeader('Content-type', 'text/html');
res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
return;
}
res.end();
});
server.on('connection', () => { connections++; });
url = (await listen(server)).url;
});
afterEach(async () => {
server.close();
await closeWindow(w);
w = null as unknown as BrowserWindow;
server = null as unknown as http.Server;
});
it('calling preconnect() connects to the server', async () => {
w = new BrowserWindow({ show: false });
w.webContents.on('did-start-navigation', (event, url) => {
w.webContents.session.preconnect({ url, numSockets: 4 });
});
await w.loadURL(url);
expect(connections).to.equal(4);
});
it('does not preconnect unless requested', async () => {
w = new BrowserWindow({ show: false });
await w.loadURL(url);
expect(connections).to.equal(1);
});
it('parses <link rel=preconnect>', async () => {
w = new BrowserWindow({ show: true });
const p = once(w.webContents.session, 'preconnect');
w.loadURL(url + '/link');
const [, preconnectUrl, allowCredentials] = await p;
expect(preconnectUrl).to.equal('http://example.com/');
expect(allowCredentials).to.be.true('allowCredentials');
});
});
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('allows changing cursor auto-hiding', () => {
expect(() => {
w.setAutoHideCursor(false);
w.setAutoHideCursor(true);
}).to.not.throw();
});
});
ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
it('is not available', () => {
expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
});
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setWindowButtonVisibility(true);
w.setWindowButtonVisibility(false);
}).to.not.throw();
});
it('changes window button visibility for normal window', () => {
const w = new BrowserWindow({ show: false });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('changes window button visibility for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('changes window button visibility for hiddenInset window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
// Buttons of customButtonsOnHover are always hidden unless hovered.
it('does not change window button visibility for customButtonsOnHover window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
afterEach(closeAllWindows);
it('allows setting, changing, and removing the vibrancy', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('light');
w.setVibrancy('dark');
w.setVibrancy(null);
w.setVibrancy('ultra-dark');
w.setVibrancy('' as any);
}).to.not.throw();
});
it('does not crash if vibrancy is set to an invalid value', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
}).to.not.throw();
});
});
ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
const pos = { x: 10, y: 10 };
afterEach(closeAllWindows);
describe('BrowserWindow.getWindowButtonPosition(pos)', () => {
it('returns null when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition');
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setWindowButtonPosition(pos)', () => {
it('resets the position when null is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setWindowButtonPosition(null);
expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition');
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
});
// The set/getTrafficLightPosition APIs are deprecated.
describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
it('returns { x: 0, y: 0 } when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
it('resets the position when { x: 0, y: 0 } is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setTrafficLightPosition({ x: 0, y: 0 });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
afterEach(closeAllWindows);
it('supports setting the app details', () => {
const w = new BrowserWindow({ show: false });
const iconPath = path.join(fixtures, 'assets', 'icon.ico');
expect(() => {
w.setAppDetails({ appId: 'my.app.id' });
w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
w.setAppDetails({ appIconPath: iconPath });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
w.setAppDetails({ relaunchDisplayName: 'My app name' });
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
});
w.setAppDetails({});
}).to.not.throw();
expect(() => {
(w.setAppDetails as any)();
}).to.throw('Insufficient number of arguments.');
});
});
describe('BrowserWindow.fromId(id)', () => {
afterEach(closeAllWindows);
it('returns the window with id', () => {
const w = new BrowserWindow({ show: false });
expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
});
});
describe('Opening a BrowserWindow from a link', () => {
let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('can properly open and load a new window from a link', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
appProcess = childProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
});
describe('BrowserWindow.fromWebContents(webContents)', () => {
afterEach(closeAllWindows);
it('returns the window with the webContents', () => {
const w = new BrowserWindow({ show: false });
const found = BrowserWindow.fromWebContents(w.webContents);
expect(found!.id).to.equal(w.id);
});
it('returns null for webContents without a BrowserWindow', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
try {
expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
} finally {
contents.destroy();
}
});
it('returns the correct window for a BrowserView webcontents', async () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
await bv.webContents.loadURL('about:blank');
expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
});
it('returns the correct window for a WebView webcontents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
// NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
// https://github.com/electron/electron/issues/25413, and is not integral
// to the test.
const p = once(w.webContents, 'did-attach-webview');
const [, webviewContents] = await once(app, 'web-contents-created');
expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
await p;
});
it('is usable immediately on browser-window-created', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.open(""); null');
const [win, winFromWebContents] = await new Promise<any>((resolve) => {
app.once('browser-window-created', (e, win) => {
resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
});
});
expect(winFromWebContents).to.equal(win);
});
});
describe('BrowserWindow.openDevTools()', () => {
afterEach(closeAllWindows);
it('does not crash for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
w.webContents.openDevTools();
});
});
describe('BrowserWindow.fromBrowserView(browserView)', () => {
afterEach(closeAllWindows);
it('returns the window with the BrowserView', () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
});
it('returns the window when there are multiple BrowserViews', () => {
const w = new BrowserWindow({ show: false });
const bv1 = new BrowserView();
w.addBrowserView(bv1);
const bv2 = new BrowserView();
w.addBrowserView(bv2);
defer(() => {
w.removeBrowserView(bv1);
w.removeBrowserView(bv2);
bv1.webContents.destroy();
bv2.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
});
it('returns undefined if not attached', () => {
const bv = new BrowserView();
defer(() => {
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
});
});
describe('BrowserWindow.setOpacity(opacity)', () => {
afterEach(closeAllWindows);
ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
it('make window with initial opacity', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
expect(w.getOpacity()).to.equal(0.5);
});
it('allows setting the opacity', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setOpacity(0.0);
expect(w.getOpacity()).to.equal(0.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(0.5);
w.setOpacity(1.0);
expect(w.getOpacity()).to.equal(1.0);
}).to.not.throw();
});
it('clamps opacity to [0.0...1.0]', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
w.setOpacity(100);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(-100);
expect(w.getOpacity()).to.equal(0.0);
});
});
ifdescribe(process.platform === 'linux')(('Linux'), () => {
it('sets 1 regardless of parameter', () => {
const w = new BrowserWindow({ show: false });
w.setOpacity(0);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(1.0);
});
});
});
describe('BrowserWindow.setShape(rects)', () => {
afterEach(closeAllWindows);
it('allows setting shape', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setShape([]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
w.setShape([]);
}).to.not.throw();
});
});
describe('"useContentSize" option', () => {
afterEach(closeAllWindows);
it('make window created with content size when used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('make window created with window size when not used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400
});
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
it('works for a frameless window', () => {
const w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => {
const testWindowsOverlay = async (style: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: style,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: true
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRect.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRect.x).to.be.greaterThan(0);
} else {
expect(overlayRect.x).to.equal(0);
}
expect(overlayRect.width).to.be.greaterThan(0);
expect(overlayRect.height).to.be.greaterThan(0);
const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
expect(cssOverlayRect).to.deep.equal(overlayRect);
const geometryChange = once(ipcMain, 'geometrychange');
w.setBounds({ width: 800 });
const [, newOverlayRect] = await geometryChange;
expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('creates browser window with hidden title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('sets Window Control Overlay with hidden title bar', async () => {
await testWindowsOverlay('hidden');
});
ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
await testWindowsOverlay('hiddenInset');
});
ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
});
afterEach(async () => {
await closeAllWindows();
});
it('does not crash changing minimizability ', () => {
expect(() => {
w.setMinimizable(false);
}).to.not.throw();
});
it('does not crash changing maximizability', () => {
expect(() => {
w.setMaximizable(false);
}).to.not.throw();
});
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => {
const testWindowsOverlayHeight = async (size: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: size
}
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRectPreMax.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRectPreMax.x).to.be.greaterThan(0);
} else {
expect(overlayRectPreMax.x).to.equal(0);
}
expect(overlayRectPreMax.width).to.be.greaterThan(0);
expect(overlayRectPreMax.height).to.equal(size);
// Confirm that maximization only affected the height of the buttons and not the title bar
expect(overlayRectPostMax.height).to.equal(size);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('sets Window Control Overlay with title bar height of 40', async () => {
await testWindowsOverlayHeight(40);
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => {
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('does not crash when an invalid titleBarStyle was initially set', () => {
const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
expect(() => {
win.setTitleBarOverlay({
color: '#000000'
});
}).to.not.throw();
});
it('correctly updates the height of the overlay', async () => {
const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
if (firstRun) {
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(x).to.equal(0);
expect(y).to.equal(0);
expect(width).to.be.greaterThan(0);
expect(height).to.equal(size);
expect(preMaxHeight).to.equal(size);
};
const INITIAL_SIZE = 40;
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: INITIAL_SIZE
}
});
await testOverlay(w, INITIAL_SIZE, true);
w.setTitleBarOverlay({
height: INITIAL_SIZE + 10
});
await testOverlay(w, INITIAL_SIZE + 10, false);
});
});
ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
afterEach(closeAllWindows);
it('can move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, 50);
const after = w.getPosition();
expect(after).to.deep.equal([-10, 50]);
});
it('cannot move the window behind menu bar', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can move the window behind menu bar if it has no frame', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[0]).to.be.equal(-10);
expect(after[1]).to.be.equal(-10);
});
it('without it, cannot move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expectBoundsEqual(w.getSize(), [size.width, size.height]);
});
it('without it, cannot set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
});
});
ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
afterEach(closeAllWindows);
it('sets the window width to the page width when used', () => {
const w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
});
w.maximize();
expect(w.getSize()[0]).to.equal(500);
});
});
describe('"tabbingIdentifier" option', () => {
afterEach(closeAllWindows);
it('can be set on a window', () => {
expect(() => {
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group1'
});
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
});
}).not.to.throw();
});
});
describe('"webPreferences" option', () => {
afterEach(() => { ipcMain.removeAllListeners('answer'); });
afterEach(closeAllWindows);
describe('"preload" option', () => {
const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
it(name, async () => {
const w = new BrowserWindow({
webPreferences: {
...webPrefs,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
const [, result] = await once(ipcMain, 'leak-result');
expect(result).to.have.property('require', 'undefined');
expect(result).to.have.property('exports', 'undefined');
expect(result).to.have.property('windowExports', 'undefined');
expect(result).to.have.property('windowPreload', 'undefined');
expect(result).to.have.property('windowRequire', 'undefined');
});
};
doesNotLeakSpec('does not leak require', {
nodeIntegration: false,
sandbox: false,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when sandbox is enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when context isolation is enabled', {
nodeIntegration: false,
sandbox: false,
contextIsolation: true
});
doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: true
});
it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
let w = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, notIsolated] = await once(ipcMain, 'leak-result');
expect(notIsolated).to.have.property('globals');
w.destroy();
w = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, isolated] = await once(ipcMain, 'leak-result');
expect(isolated).to.have.property('globals');
const notIsolatedGlobals = new Set(notIsolated.globals);
for (const isolatedGlobal of isolated.globals) {
notIsolatedGlobals.delete(isolatedGlobal);
}
expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
});
it('loads the script before other scripts in window', async () => {
const preload = path.join(fixtures, 'module', 'set-global.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.eql('preload');
});
it('has synchronous access to all eventual window APIs', async () => {
const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.be.an('object');
expect(test.atPreload).to.be.an('array');
expect(test.atLoad).to.be.an('array');
expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
});
});
describe('session preload scripts', function () {
const preloads = [
path.join(fixtures, 'module', 'set-global-preload-1.js'),
path.join(fixtures, 'module', 'set-global-preload-2.js'),
path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
];
const defaultSession = session.defaultSession;
beforeEach(() => {
expect(defaultSession.getPreloads()).to.deep.equal([]);
defaultSession.setPreloads(preloads);
});
afterEach(() => {
defaultSession.setPreloads([]);
});
it('can set multiple session preload script', () => {
expect(defaultSession.getPreloads()).to.deep.equal(preloads);
});
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('loads the script before other scripts in window including normal preloads', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload: path.join(fixtures, 'module', 'get-global-preload.js'),
contextIsolation: false
}
});
w.loadURL('about:blank');
const [, preload1, preload2, preload3] = await once(ipcMain, 'vars');
expect(preload1).to.equal('preload-1');
expect(preload2).to.equal('preload-1-2');
expect(preload3).to.be.undefined('preload 3');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('"additionalArguments" option', () => {
it('adds extra args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg');
});
it('adds extra value args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg=foo']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg=foo');
});
});
describe('"node-integration" option', () => {
it('disables node integration by default', async () => {
const preload = path.join(fixtures, 'module', 'send-later.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer');
expect(typeofProcess).to.equal('undefined');
expect(typeofBuffer).to.equal('undefined');
});
});
describe('"sandbox" option', () => {
const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/cross-site':
response.end(`<html><body><h1>${request.url}</h1></body></html>`);
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('exposes ipcRenderer to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes ipcRenderer to preload script (path has special chars)', async () => {
const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preloadSpecialChars,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes "loaded" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
});
w.loadURL('about:blank');
await once(ipcMain, 'process-loaded');
});
it('exposes "exit" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
const pageUrl = 'file://' + htmlPath;
w.loadURL(pageUrl);
const [, url] = await once(ipcMain, 'answer');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
});
it('exposes full EventEmitter object to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
}
});
w.loadURL('about:blank');
const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer');
const { EventEmitter } = require('events');
const emitter = new EventEmitter();
const browserEventEmitterProperties = [];
let currentObj = emitter;
do {
browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
} while ((currentObj = Object.getPrototypeOf(currentObj)));
expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
});
it('should open windows in same domain with cross-scripting enabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
const pageUrl = 'file://' + htmlPath;
const answer = once(ipcMain, 'answer');
w.loadURL(pageUrl);
const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
expect(frameName).to.equal('popup!');
expect(options.width).to.equal(500);
expect(options.height).to.equal(600);
const [, html] = await answer;
expect(html).to.equal('<h1>scripting from opener</h1>');
});
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
w.loadFile(
path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
{ search: 'window-open-external' }
);
// Wait for a message from the main window saying that it's ready.
await once(ipcMain, 'opener-loaded');
// Ask the opener to open a popup with window.opener.
const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
w.webContents.send('open-the-popup', expectedPopupUrl);
// The page is going to open a popup that it won't be able to close.
// We have to close it from here later.
const [, popupWindow] = await once(app, 'browser-window-created');
// Ask the popup window for details.
const detailsAnswer = once(ipcMain, 'child-loaded');
popupWindow.webContents.send('provide-details');
const [, openerIsNull, , locationHref] = await detailsAnswer;
expect(openerIsNull).to.be.false('window.opener is null');
expect(locationHref).to.equal(expectedPopupUrl);
// Ask the page to access the popup.
const touchPopupResult = once(ipcMain, 'answer');
w.webContents.send('touch-the-popup');
const [, popupAccessMessage] = await touchPopupResult;
// Ask the popup to access the opener.
const touchOpenerResult = once(ipcMain, 'answer');
popupWindow.webContents.send('touch-the-opener');
const [, openerAccessMessage] = await touchOpenerResult;
// We don't need the popup anymore, and its parent page can't close it,
// so let's close it from here before we run any checks.
await closeWindow(popupWindow, { assertNotWindows: false });
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
});
it('should inherit the sandbox setting in opened windows', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [, { argv }] = await once(ipcMain, 'answer');
expect(argv).to.include('--enable-sandbox');
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
it('should set ipc event sender correctly', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
let childWc: WebContents | null = null;
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
w.webContents.on('did-create-window', (win) => {
childWc = win.webContents;
expect(w.webContents).to.not.equal(childWc);
});
ipcMain.once('parent-ready', function (event) {
expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
event.sender.send('verified');
});
ipcMain.once('child-ready', function (event) {
expect(childWc).to.not.be.null('child webcontents should be available');
expect(event.sender).to.equal(childWc, 'sender should be the child');
event.sender.send('verified');
});
const done = Promise.all([
'parent-answer',
'child-answer'
].map(name => once(ipcMain, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
await done;
});
describe('event handling', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
});
it('works for window events', async () => {
const pageTitleUpdated = once(w, 'page-title-updated');
w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
await pageTitleUpdated;
});
it('works for stop events', async () => {
const done = Promise.all([
'did-navigate',
'did-fail-load',
'did-stop-loading'
].map(name => once(w.webContents, name)));
w.loadURL('data:text/html,<script>stop()</script>');
await done;
});
it('works for web contents events', async () => {
const done = Promise.all([
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
].map(name => once(w.webContents, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
await done;
});
});
it('validates process APIs access in sandboxed renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.once('preload-error', (event, preloadPath, error) => {
throw error;
});
process.env.sandboxmain = 'foo';
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test.hasCrash).to.be.true('has crash');
expect(test.hasHang).to.be.true('has hang');
expect(test.heapStatistics).to.be.an('object');
expect(test.blinkMemoryInfo).to.be.an('object');
expect(test.processMemoryInfo).to.be.an('object');
expect(test.systemVersion).to.be.a('string');
expect(test.cpuUsage).to.be.an('object');
expect(test.ioCounters).to.be.an('object');
expect(test.uptime).to.be.a('number');
expect(test.arch).to.equal(process.arch);
expect(test.platform).to.equal(process.platform);
expect(test.env).to.deep.equal(process.env);
expect(test.execPath).to.equal(process.helperExecPath);
expect(test.sandboxed).to.be.true('sandboxed');
expect(test.contextIsolated).to.be.false('contextIsolated');
expect(test.type).to.equal('renderer');
expect(test.version).to.equal(process.version);
expect(test.versions).to.deep.equal(process.versions);
expect(test.contextId).to.be.a('string');
if (process.platform === 'linux' && test.osSandbox) {
expect(test.creationTime).to.be.null('creation time');
expect(test.systemMemoryInfo).to.be.null('system memory info');
} else {
expect(test.creationTime).to.be.a('number');
expect(test.systemMemoryInfo).to.be.an('object');
}
});
it('webview in sandbox renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
webviewTag: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview');
const webviewDomReady = once(ipcMain, 'webview-dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const [, id] = await webviewDomReady;
expect(webContents.id).to.equal(id);
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
// tests relies on preloads in opened windows
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
it('opens window of about:blank with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('blocks accessing cross-origin frames', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
const [, content] = await answer;
expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
});
it('opens window from <iframe> tags', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window with cross-scripting enabled from isolated context', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
w.reload();
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
});
it('<webview> works in a scriptable popup', async () => {
const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegrationInSubFrames: true,
webviewTag: true,
contextIsolation: false,
preload
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false,
webPreferences: {
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
preload
}
}
}));
const webviewLoaded = once(ipcMain, 'webview-loaded');
w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
await webviewLoaded;
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: preloadPath,
contextIsolation: false
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
describe('window.location', () => {
const protocols = [
['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
];
beforeEach(() => {
for (const [scheme, path] of protocols) {
protocol.registerBufferProtocol(scheme, (request, callback) => {
callback({
mimeType: 'text/html',
data: fs.readFileSync(path)
});
});
}
});
afterEach(() => {
for (const [scheme] of protocols) {
protocol.unregisterProtocol(scheme);
}
});
it('retains the original web preferences when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
contextIsolation: false,
nodeIntegrationInSubFrames: true
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer');
expect(nodeIntegration).to.be.false();
expect(typeofProcess).to.eql('undefined');
});
it('window.opener is not null when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer');
expect(windowOpenerIsNull).to.be.false('window.opener is null');
});
});
});
describe('"disableHtmlFullscreenWindowResize" option', () => {
it('prevents window from resizing when set', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
disableHtmlFullscreenWindowResize: true
}
});
await w.loadURL('about:blank');
const size = w.getSize();
const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen');
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await enterHtmlFullScreen;
expect(w.getSize()).to.deep.equal(size);
});
});
describe('"defaultFontFamily" option', () => {
it('can change the standard font family', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
defaultFontFamily: {
standard: 'Impact'
}
}
});
await w.loadFile(path.join(fixtures, 'pages', 'content.html'));
const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true);
expect(fontFamily).to.equal('Impact');
});
});
});
describe('beforeunload handler', function () {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(closeAllWindows);
it('returning undefined would not prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('returning false would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('returning empty string would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('emits for each close attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const destroyListener = () => { expect.fail('Close was not prevented'); };
w.webContents.once('destroyed', destroyListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.close();
await once(w.webContents, 'before-unload-fired');
w.close();
await once(w.webContents, 'before-unload-fired');
w.webContents.removeListener('destroyed', destroyListener);
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits for each reload attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.reload();
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.reload();
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
w.reload();
await once(w.webContents, 'did-finish-load');
});
it('emits for each navigation attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.loadURL('about:blank');
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.loadURL('about:blank');
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
await w.loadURL('about:blank');
});
});
describe('document.visibilityState/hidden', () => {
afterEach(closeAllWindows);
it('visibilityState is initially visible despite window being hidden', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let readyToShow = false;
w.once('ready-to-show', () => {
readyToShow = true;
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(readyToShow).to.be.false('ready to show');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.show();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.showInactive();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.minimize();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
// when we introduced the compositor recycling patch. Should figure out how to fix this
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
ipcMain.once('pong', (event, visibilityState, hidden) => {
throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
});
try {
const shown1 = once(w, 'show');
w.show();
await shown1;
const hidden = once(w, 'hide');
w.hide();
await hidden;
const shown2 = once(w, 'show');
w.show();
await shown2;
} finally {
ipcMain.removeAllListeners('pong');
}
});
});
ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
afterEach(closeAllWindows);
it('emits an event when window is maximized', async () => {
const w = new BrowserWindow({ show: false });
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits an event when a transparent window is maximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits only one event when frameless window is maximized', () => {
const w = new BrowserWindow({ show: false, frame: false });
let emitted = 0;
w.on('maximize', () => emitted++);
w.show();
w.maximize();
expect(emitted).to.equal(1);
});
it('emits an event when window is unmaximized', async () => {
const w = new BrowserWindow({ show: false });
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
w.unmaximize();
await unmaximize;
});
it('emits an event when a transparent window is unmaximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await maximize;
w.unmaximize();
await unmaximize;
});
it('emits an event when window is minimized', async () => {
const w = new BrowserWindow({ show: false });
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
});
});
describe('beginFrameSubscription method', () => {
it('does not crash when callback returns nothing', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function () {
// This callback might be called twice.
if (called) return;
called = true;
// Pending endFrameSubscription to next tick can reliably reproduce
// a crash which happens when nothing is returned in the callback.
setTimeout().then(() => {
w.webContents.endFrameSubscription();
done();
});
});
});
});
it('subscribes to frame updates', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return;
called = true;
try {
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
});
it('subscribes to frame updates (only dirty rectangle)', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
let gotInitialFullSizeFrame = false;
const [contentWidth, contentHeight] = w.getContentSize();
w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (image, rect) => {
if (image.isEmpty()) {
// Chromium sometimes sends a 0x0 frame at the beginning of the
// page load.
return;
}
if (rect.height === contentHeight && rect.width === contentWidth &&
!gotInitialFullSizeFrame) {
// The initial frame is full-size, but we're looking for a call
// with just the dirty-rect. The next frame should be a smaller
// rect.
gotInitialFullSizeFrame = true;
return;
}
// This callback might be called twice.
if (called) return;
// We asked for just the dirty rectangle, so we expect to receive a
// rect smaller than the full size.
// TODO(jeremy): this is failing on windows currently; investigate.
// assert(rect.width < contentWidth || rect.height < contentHeight)
called = true;
try {
const expectedSize = rect.width * rect.height * 4;
expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
});
it('throws error when subscriber is not well defined', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.beginFrameSubscription(true, true as any);
// TODO(zcbenz): gin is weak at guessing parameter types, we should
// upstream native_mate's implementation to gin.
}).to.throw('Error processing argument at index 1, conversion failure from ');
});
});
describe('savePage method', () => {
const savePageDir = path.join(fixtures, 'save_page');
const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
afterEach(() => {
closeAllWindows();
try {
fs.unlinkSync(savePageCssPath);
fs.unlinkSync(savePageJsPath);
fs.unlinkSync(savePageHtmlPath);
fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
fs.rmdirSync(savePageDir);
} catch {}
});
it('should throw when passing relative paths', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await expect(
w.webContents.savePage('save_page.html', 'HTMLComplete')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'HTMLOnly')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'MHTML')
).to.eventually.be.rejectedWith('Path must be absolute');
});
it('should save page to disk with HTMLOnly', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
});
it('should save page to disk with MHTML', async () => {
/* Use temp directory for saving MHTML file since the write handle
* gets passed to untrusted process and chromium will deny exec access to
* the path. To perform this task, chromium requires that the path is one
* of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416
*/
const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-'));
const savePageMHTMLPath = path.join(tmpDir, 'save_page.html');
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageMHTMLPath, 'MHTML');
expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
try {
await fs.promises.unlink(savePageMHTMLPath);
await fs.promises.rmdir(tmpDir);
} catch {}
});
it('should save page to disk with HTMLComplete', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
});
});
describe('BrowserWindow options argument is optional', () => {
afterEach(closeAllWindows);
it('should create a window with default size (800x600)', () => {
const w = new BrowserWindow();
expect(w.getSize()).to.deep.equal([800, 600]);
});
});
describe('BrowserWindow.restore()', () => {
afterEach(closeAllWindows);
it('should restore the previous window size', () => {
const w = new BrowserWindow({
minWidth: 800,
width: 800
});
const initialSize = w.getSize();
w.minimize();
w.restore();
expectBoundsEqual(w.getSize(), initialSize);
});
it('does not crash when restoring hidden minimized window', () => {
const w = new BrowserWindow({});
w.minimize();
w.hide();
w.show();
});
// TODO(zcbenz):
// This test does not run on Linux CI. See:
// https://github.com/electron/electron/issues/28699
ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => {
const w = new BrowserWindow({});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
const restore = once(w, 'restore');
w.restore();
await restore;
expect(w.isMaximized()).to.equal(true);
});
});
// TODO(dsanders11): Enable once maximize event works on Linux again on CI
ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
afterEach(closeAllWindows);
it('should show the window if it is not currently shown', async () => {
const w = new BrowserWindow({ show: false });
const hidden = once(w, 'hide');
let shown = once(w, 'show');
const maximize = once(w, 'maximize');
expect(w.isVisible()).to.be.false('visible');
w.maximize();
await maximize;
await shown;
expect(w.isMaximized()).to.be.true('maximized');
expect(w.isVisible()).to.be.true('visible');
// Even if the window is already maximized
w.hide();
await hidden;
expect(w.isVisible()).to.be.false('visible');
shown = once(w, 'show');
w.maximize();
await shown;
expect(w.isVisible()).to.be.true('visible');
});
});
describe('BrowserWindow.unmaximize()', () => {
afterEach(closeAllWindows);
it('should restore the previous window position', () => {
const w = new BrowserWindow();
const initialPosition = w.getPosition();
w.maximize();
w.unmaximize();
expectBoundsEqual(w.getPosition(), initialPosition);
});
// TODO(dsanders11): Enable once minimize event works on Linux again.
// See https://github.com/electron/electron/issues/28699
ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
const w = new BrowserWindow();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
w.unmaximize();
await setTimeout(1000);
expect(w.isMinimized()).to.be.true();
});
it('should not change the size or position of a normal window', async () => {
const w = new BrowserWindow();
const initialSize = w.getSize();
const initialPosition = w.getPosition();
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getSize(), initialSize);
expectBoundsEqual(w.getPosition(), initialPosition);
});
ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
const { workArea } = screen.getPrimaryDisplay();
const bounds = {
x: workArea.x,
y: workArea.y,
width: workArea.width,
height: workArea.height
};
const w = new BrowserWindow(bounds);
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getBounds(), bounds);
});
});
describe('setFullScreen(false)', () => {
afterEach(closeAllWindows);
// only applicable to windows: https://github.com/electron/electron/issues/6036
ifdescribe(process.platform === 'win32')('on windows', () => {
it('should restore a normal visible window from a fullscreen startup state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const shown = once(w, 'show');
// start fullscreen and hidden
w.setFullScreen(true);
w.show();
await shown;
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.true('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
it('should keep window hidden if already in hidden state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.false('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
it('exits HTML fullscreen when window leaves fullscreen', async () => {
const w = new BrowserWindow();
await w.loadURL('about:blank');
await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await once(w, 'enter-full-screen');
// Wait a tick for the full-screen state to 'stick'
await setTimeout();
w.setFullScreen(false);
await once(w, 'leave-html-full-screen');
});
});
});
describe('parent window', () => {
afterEach(closeAllWindows);
ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
const w = new BrowserWindow();
const sheetBegin = once(w, 'sheet-begin');
// eslint-disable-next-line no-new
new BrowserWindow({
modal: true,
parent: w
});
await sheetBegin;
});
ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
const w = new BrowserWindow();
const sheet = new BrowserWindow({
modal: true,
parent: w
});
const sheetEnd = once(w, 'sheet-end');
sheet.close();
await sheetEnd;
});
describe('parent option', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.getParentWindow()).to.equal(w);
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(w.getChildWindows()).to.deep.equal([c]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
it('can handle child window close and reparent multiple times', async () => {
const w = new BrowserWindow({ show: false });
let c: BrowserWindow | null;
for (let i = 0; i < 5; i++) {
c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
}
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isVisible()).to.be.false('parent is visible');
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(c, 'minimize');
c.minimize();
await minimized;
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(c, 'restore');
c.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
it('closes a grandchild window when a middle child window is destroyed', (done) => {
const w = new BrowserWindow();
w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
w.webContents.executeJavaScript('window.open("")');
w.webContents.on('did-create-window', async (window) => {
const childWindow = new BrowserWindow({ parent: window });
await setTimeout();
window.close();
childWindow.on('closed', () => {
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
done();
});
});
});
it('should not affect the show option', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.isVisible()).to.be.false('child is visible');
expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
});
});
describe('win.setParentWindow(parent)', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getParentWindow()).to.be.null('w.parent');
expect(c.getParentWindow()).to.be.null('c.parent');
c.setParentWindow(w);
expect(c.getParentWindow()).to.equal(w);
c.setParentWindow(null);
expect(c.getParentWindow()).to.be.null('c.parent');
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getChildWindows()).to.deep.equal([]);
c.setParentWindow(w);
expect(w.getChildWindows()).to.deep.equal([c]);
c.setParentWindow(null);
expect(w.getChildWindows()).to.deep.equal([]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
const closed = once(c, 'closed');
c.setParentWindow(w);
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
});
describe('modal option', () => {
it('does not freeze or crash', async () => {
const parentWindow = new BrowserWindow();
const createTwo = async () => {
const two = new BrowserWindow({
width: 300,
height: 200,
parent: parentWindow,
modal: true,
show: false
});
const twoShown = once(two, 'show');
two.show();
await twoShown;
setTimeout(500).then(() => two.close());
await once(two, 'closed');
};
const one = new BrowserWindow({
width: 600,
height: 400,
parent: parentWindow,
modal: true,
show: false
});
const oneShown = once(one, 'show');
one.show();
await oneShown;
setTimeout(500).then(() => one.destroy());
await once(one, 'closed');
await createTwo();
});
ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
const w = new BrowserWindow({ show: false });
w.setEnabled(false);
expect(w.isEnabled()).to.be.false('w.isEnabled()');
w.setEnabled(true);
expect(w.isEnabled()).to.be.true('!w.isEnabled()');
});
ifit(process.platform !== 'darwin')('disables parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
expect(w.isEnabled()).to.be.true('w.isEnabled');
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
w.setEnabled(false);
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c.destroy();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.destroy();
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
});
});
describe('window states', () => {
afterEach(closeAllWindows);
it('does not resize frameless windows when states change', () => {
const w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
});
w.minimizable = false;
w.minimizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.resizable = false;
w.resizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.maximizable = false;
w.maximizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.fullScreenable = false;
w.fullScreenable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.closable = false;
w.closable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
});
describe('resizable state', () => {
it('with properties', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.resizable).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.maximizable).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
w.resizable = false;
expect(w.resizable).to.be.false('resizable');
w.resizable = true;
expect(w.resizable).to.be.true('resizable');
});
});
it('with functions', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.isResizable()).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.isMaximizable()).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isResizable()).to.be.true('resizable');
w.setResizable(false);
expect(w.isResizable()).to.be.false('resizable');
w.setResizable(true);
expect(w.isResizable()).to.be.true('resizable');
});
});
it('works for a frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w.resizable).to.be.true('resizable');
if (process.platform === 'win32') {
const w = new BrowserWindow({ show: false, thickFrame: false });
expect(w.resizable).to.be.false('resizable');
}
});
// On Linux there is no "resizable" property of a window.
ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
expect(w.maximizable).to.be.true('maximizable');
w.resizable = false;
expect(w.maximizable).to.be.false('not maximizable');
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
const w = new BrowserWindow({
show: false,
frame: false,
resizable: false,
transparent: true
});
w.setContentSize(60, 60);
expectBoundsEqual(w.getContentSize(), [60, 60]);
w.setContentSize(30, 30);
expectBoundsEqual(w.getContentSize(), [30, 30]);
w.setContentSize(10, 10);
expectBoundsEqual(w.getContentSize(), [10, 10]);
});
});
describe('loading main frame state', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is true when the main frame is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(serverUrl);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
it('is false when only a subframe is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/page2'
document.body.appendChild(iframe)
`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
});
it('is true when navigating to pages from the same origin', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(`${serverUrl}/page2`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
});
});
ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
// Not implemented on Linux.
afterEach(closeAllWindows);
describe('movable state', () => {
it('with properties', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.movable).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.movable).to.be.true('movable');
w.movable = false;
expect(w.movable).to.be.false('movable');
w.movable = true;
expect(w.movable).to.be.true('movable');
});
});
it('with functions', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.isMovable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMovable()).to.be.true('movable');
w.setMovable(false);
expect(w.isMovable()).to.be.false('movable');
w.setMovable(true);
expect(w.isMovable()).to.be.true('movable');
});
});
});
describe('visibleOnAllWorkspaces state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.visibleOnAllWorkspaces).to.be.false();
w.visibleOnAllWorkspaces = true;
expect(w.visibleOnAllWorkspaces).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isVisibleOnAllWorkspaces()).to.be.false();
w.setVisibleOnAllWorkspaces(true);
expect(w.isVisibleOnAllWorkspaces()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.documentEdited).to.be.false();
w.documentEdited = true;
expect(w.documentEdited).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isDocumentEdited()).to.be.false();
w.setDocumentEdited(true);
expect(w.isDocumentEdited()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('representedFilename', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.representedFilename).to.eql('');
w.representedFilename = 'a name';
expect(w.representedFilename).to.eql('a name');
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getRepresentedFilename()).to.eql('');
w.setRepresentedFilename('a name');
expect(w.getRepresentedFilename()).to.eql('a name');
});
});
});
describe('native window title', () => {
it('with properties', () => {
it('can be set with title constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.title).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.title).to.eql('Electron Test Main');
w.title = 'NEW TITLE';
expect(w.title).to.eql('NEW TITLE');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.getTitle()).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTitle()).to.eql('Electron Test Main');
w.setTitle('NEW TITLE');
expect(w.getTitle()).to.eql('NEW TITLE');
});
});
});
describe('minimizable state', () => {
it('with properties', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.minimizable).to.be.false('minimizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.minimizable).to.be.true('minimizable');
w.minimizable = false;
expect(w.minimizable).to.be.false('minimizable');
w.minimizable = true;
expect(w.minimizable).to.be.true('minimizable');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.isMinimizable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMinimizable()).to.be.true('isMinimizable');
w.setMinimizable(false);
expect(w.isMinimizable()).to.be.false('isMinimizable');
w.setMinimizable(true);
expect(w.isMinimizable()).to.be.true('isMinimizable');
});
});
});
describe('maximizable state (property)', () => {
it('with properties', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.maximizable).to.be.false('maximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.maximizable).to.be.true('maximizable');
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.minimizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.closable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
w.closable = true;
expect(w.maximizable).to.be.true('maximizable');
w.fullScreenable = false;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.isMaximizable()).to.be.false('isMaximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMinimizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setClosable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setClosable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setFullScreenable(false);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform === 'win32')('maximizable state', () => {
it('with properties', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
describe('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.menuBarVisible).to.be.true();
w.menuBarVisible = false;
expect(w.menuBarVisible).to.be.false();
w.menuBarVisible = true;
expect(w.menuBarVisible).to.be.true();
});
});
describe('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
w.setMenuBarVisibility(false);
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
w.setMenuBarVisibility(true);
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
it('with functions', () => {
it('can be set with fullscreenable constructor option', () => {
const w = new BrowserWindow({ show: false, fullscreenable: false });
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
w.setFullScreenable(false);
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
w.setFullScreenable(true);
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
});
});
});
ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => {
it('with functions', () => {
it('can be set with ignoreMissionControl constructor option', () => {
const w = new BrowserWindow({ show: false, hiddenInMissionControl: true });
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
w.setHiddenInMissionControl(true);
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
w.setHiddenInMissionControl(false);
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
});
});
});
// fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
ifdescribe(process.platform === 'darwin')('kiosk state', () => {
it('with properties', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.kiosk).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.kiosk = true;
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.kiosk = false;
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
it('with functions', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.isKiosk()).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
it('resizable flag should be set to false and restored', async () => {
const w = new BrowserWindow({ resizable: false });
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.false('resizable');
});
it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.true('resizable');
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
it('should not cause a crash if called when exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('should be able to load a URL while transitioning to fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true });
w.loadFile(path.join(fixtures, 'pages', 'c.html'));
const load = once(w.webContents, 'did-finish-load');
const enterFS = once(w, 'enter-full-screen');
await Promise.all([enterFS, load]);
expect(w.fullScreen).to.be.true();
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('can be changed with setFullScreen method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('handles several transitions starting with fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true, show: true });
expect(w.isFullScreen()).to.be.true('not fullscreen');
w.setFullScreen(false);
w.setFullScreen(true);
const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('not fullscreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several HTML fullscreen transitions', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFullScreen = once(w, 'enter-full-screen');
const leaveFullScreen = once(w, 'leave-full-screen');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
await setTimeout();
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several transitions in close proximity', async () => {
const w = new BrowserWindow();
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
w.setFullScreen(true);
w.setFullScreen(false);
w.setFullScreen(true);
w.setFullScreen(false);
await Promise.all([enterFS, leaveFS]);
expect(w.isFullScreen()).to.be.false('not fullscreen');
});
it('handles several chromium-initiated transitions in close proximity', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>(resolve => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', () => {
enterCount++;
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await done;
});
it('handles HTML fullscreen transitions when fullscreenable is false', async () => {
const w = new BrowserWindow({ fullscreenable: false });
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>((resolve, reject) => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', async () => {
enterCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement');
if (!isFS) reject(new Error('Document should have fullscreen element'));
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await expect(done).to.eventually.be.fulfilled();
});
it('does not crash when exiting simpleFullScreen (properties)', async () => {
const w = new BrowserWindow();
w.setSimpleFullScreen(true);
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('does not crash when exiting simpleFullScreen (functions)', async () => {
const w = new BrowserWindow();
w.simpleFullScreen = true;
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('should not be changed by setKiosk method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('should stay fullscreen if fullscreen before kiosk', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
w.setKiosk(true);
w.setKiosk(false);
// Wait enough time for a fullscreen change to take effect.
await setTimeout(2000);
expect(w.isFullScreen()).to.be.true('isFullScreen');
});
it('multiple windows inherit correct fullscreen state', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout(1000);
const w2 = new BrowserWindow({ show: false });
const enterFullScreen2 = once(w2, 'enter-full-screen');
w2.show();
await enterFullScreen2;
expect(w2.isFullScreen()).to.be.true('isFullScreen');
});
});
describe('closable state', () => {
it('with properties', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.closable).to.be.false('closable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.closable).to.be.true('closable');
w.closable = false;
expect(w.closable).to.be.false('closable');
w.closable = true;
expect(w.closable).to.be.true('closable');
});
});
it('with functions', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.isClosable()).to.be.false('isClosable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isClosable()).to.be.true('isClosable');
w.setClosable(false);
expect(w.isClosable()).to.be.false('isClosable');
w.setClosable(true);
expect(w.isClosable()).to.be.true('isClosable');
});
});
});
describe('hasShadow state', () => {
it('with properties', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
expect(w.shadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.shadow).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
w.shadow = true;
expect(w.shadow).to.be.true('hasShadow');
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
});
});
describe('with functions', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
const hasShadow = w.hasShadow();
expect(hasShadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.hasShadow()).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
w.setHasShadow(true);
expect(w.hasShadow()).to.be.true('hasShadow');
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
});
});
});
});
describe('window.getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns valid source id', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
// Check format 'window:1234:0'.
const sourceId = w.getMediaSourceId();
expect(sourceId).to.match(/^window:\d+:\d+$/);
});
});
ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
afterEach(closeAllWindows);
it('returns valid handle', () => {
const w = new BrowserWindow({ show: false });
// The module's source code is hosted at
// https://github.com/electron/node-is-valid-window
const isValidWindow = require('is-valid-window');
expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
});
});
ifdescribe(process.platform === 'darwin')('previewFile', () => {
afterEach(closeAllWindows);
it('opens the path in Quick Look on macOS', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.previewFile(__filename);
w.closeFilePreview();
}).to.not.throw();
});
it('should not call BrowserWindow show event', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
let showCalled = false;
w.on('show', () => {
showCalled = true;
});
w.previewFile(__filename);
await setTimeout(500);
expect(showCalled).to.equal(false, 'should not have called show twice');
});
});
// TODO (jkleinsc) renable these tests on mas arm64
ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
};
afterEach(closeAllWindows);
it('separates the page context from the Electron/preload context', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
iw.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('enables context isolation on child windows', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const browserWindowCreated = once(app, 'browser-window-created');
iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
const [, window] = await browserWindowCreated;
expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
});
it('separates the page context from the Electron/preload context with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
ws.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('supports fetch api', async () => {
const fetchWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
}
});
const p = once(ipcMain, 'isolated-fetch-error');
fetchWindow.loadURL('about:blank');
const [, error] = await p;
expect(error).to.equal('Failed to fetch');
});
it('doesn\'t break ipc serialization', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadURL('about:blank');
iw.webContents.executeJavaScript(`
const opened = window.open()
openedLocation = opened.location.href
opened.close()
window.postMessage({openedLocation}, '*')
`);
const [, data] = await p;
expect(data.pageContext.openedLocation).to.equal('about:blank');
});
it('reports process.contextIsolated', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-process.js')
}
});
const p = once(ipcMain, 'context-isolation');
iw.loadURL('about:blank');
const [, contextIsolation] = await p;
expect(contextIsolation).to.be.true('contextIsolation');
});
});
it('reloading does not cause Node.js module API hangs after reload', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let count = 0;
ipcMain.on('async-node-api-done', () => {
if (count === 3) {
ipcMain.removeAllListeners('async-node-api-done');
done();
} else {
count++;
w.reload();
}
});
w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
});
describe('window.webContents.focus()', () => {
afterEach(closeAllWindows);
it('focuses window', async () => {
const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
w1.loadURL('about:blank');
const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
w2.loadURL('about:blank');
const w1Focused = once(w1, 'focus');
w1.webContents.focus();
await w1Focused;
expect(w1.webContents.isFocused()).to.be.true('focuses window');
});
});
ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
let w: BrowserWindow;
beforeEach(function () {
w = new BrowserWindow({
width: 100,
height: 100,
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
});
});
afterEach(closeAllWindows);
it('creates offscreen window with correct size', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
const [,, data] = await paint;
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
const size = data.getSize();
const { scaleFactor } = screen.getPrimaryDisplay();
expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
});
it('does not crash after navigation', () => {
w.webContents.loadURL('about:blank');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
describe('window.webContents.isOffscreen()', () => {
it('is true for offscreen type', () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
});
it('is false for regular window', () => {
const c = new BrowserWindow({ show: false });
expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
c.destroy();
});
});
describe('window.webContents.isPainting()', () => {
it('returns whether is currently painting', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await paint;
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('window.webContents.stopPainting()', () => {
it('stops painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
expect(w.webContents.isPainting()).to.be.false('isPainting');
});
});
describe('window.webContents.startPainting()', () => {
it('starts painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
w.webContents.startPainting();
await once(w.webContents, 'paint');
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('frameRate APIs', () => {
it('has default frame rate (function)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(60);
});
it('has default frame rate (property)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(60);
});
it('sets custom frame rate (function)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.setFrameRate(30);
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(30);
});
it('sets custom frame rate (property)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.frameRate = 30;
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(30);
});
});
});
describe('"transparent" option', () => {
afterEach(closeAllWindows);
ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => {
const w = new BrowserWindow({
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.be.false();
expect(w.isMinimized()).to.be.true();
});
// Only applicable on Windows where transparent windows can't be maximized.
ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
show: true
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
expect(w.isMaximized()).to.be.true();
// Fails when the transparent HWND is in an invalid maximized state.
expect(w.getBounds()).to.deep.equal(display.workArea);
const newBounds = { width: 256, height: 256, x: 0, y: 0 };
w.setBounds(newBounds);
expect(w.getBounds()).to.deep.equal(newBounds);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.GREEN,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
show: true,
transparent: true,
frame: false,
hasShadow: false
});
const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html');
await foregroundWindow.loadFile(colorFile);
await setTimeout(1000);
const screenCapture = await captureScreen();
const leftHalfColor = getPixelColor(screenCapture, {
x: display.size.width / 4,
y: display.size.height / 2
});
const rightHalfColor = getPixelColor(screenCapture, {
x: display.size.width - (display.size.width / 4),
y: display.size.height / 2
});
expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true();
expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true();
});
ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.PURPLE,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
hasShadow: false,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
}
});
foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html'));
await once(ipcMain, 'set-transparent');
await setTimeout();
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => {
const display = screen.getPrimaryDisplay();
for (const transparent of [false, undefined]) {
const window = new BrowserWindow({
...display.bounds,
transparent
});
await once(window, 'show');
await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>');
await setTimeout(500);
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
window.close();
// color-scheme is set to dark so background should not be white
expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false();
}
});
});
describe('"backgroundColor" option', () => {
afterEach(closeAllWindows);
// Linux/WOA doesn't return any capture sources.
ifit(process.platform === 'darwin')('should display the set color', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
show: true,
backgroundColor: HexColors.BLUE
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true();
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,807 |
[Bug]: Menu Bar Visibility
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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
### What operating system are you using?
Other Linux
### Operating System Version
Fedora 36
### What arch are you using?
x64
### Last Known Working Electron version
19.0.0
### Expected Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
then menu bar will be hidden which is great. But if you spam F11 key, menu bar will become visible again.
### Actual Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
Menu bar shouldn't be visible even while spamming F11.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35807
|
https://github.com/electron/electron/pull/38599
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
|
c8bdd014c87b5c33b77c845f853b7e52bb31de8f
| 2022-09-25T15:23:42Z |
c++
| 2023-06-08T10:19:34Z |
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 <dwmapi.h>
#include <wrl/client.h>
#endif
#include <memory>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/memory/raw_ptr.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/inspectable_web_contents.h"
#include "shell/browser/ui/views/inspectable_web_contents_view_views.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/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 "base/win/windows_version.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)
DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) {
if (material == "none") {
return DWMSBT_NONE;
} else if (material == "acrylic") {
return DWMSBT_TRANSIENTWINDOW;
} else if (material == "mica") {
return DWMSBT_MAINWINDOW;
} else if (material == "tabbed") {
return DWMSBT_TABBEDWINDOW;
}
return DWMSBT_AUTO;
}
// 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_{raw_ref<NativeWindowViews>::from_ptr(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:
const raw_ref<NativeWindowViews> window_;
};
} // namespace
NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent) {
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() {
#if BUILDFLAG(IS_WIN)
// widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a
// window or any of its parent windows are visible. We want to only check the
// current window.
bool visible =
::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE;
// WS_VISIBLE is true even if a window is miminized - explicitly check that.
return visible && !IsMinimized();
#else
return widget()->IsVisible();
#endif
}
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() && !IsMinimized()) {
// 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() {
#if BUILDFLAG(IS_WIN)
if (IsMaximized() && transparent())
return restore_bounds_;
#endif
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 = std::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::SetBackgroundMaterial(const std::string& material) {
#if BUILDFLAG(IS_WIN)
// DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up.
if (base::win::GetVersion() < base::win::Version::WIN11_22H2)
return;
DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material);
HRESULT result =
DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE,
&backdrop_type, sizeof(backdrop_type));
if (FAILED(result))
LOG(WARNING) << "Failed to set background material to " << material;
#endif
}
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 base::Contains(wm_states, sticky_atom);
}
#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;
}
#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_;
}
bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) {
return NonClientHitTest(location) == HTNOWHERE;
}
views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
return new NativeWindowClientView{widget, GetContentsView(), 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
| 35,807 |
[Bug]: Menu Bar Visibility
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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
### What operating system are you using?
Other Linux
### Operating System Version
Fedora 36
### What arch are you using?
x64
### Last Known Working Electron version
19.0.0
### Expected Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
then menu bar will be hidden which is great. But if you spam F11 key, menu bar will become visible again.
### Actual Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
Menu bar shouldn't be visible even while spamming F11.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35807
|
https://github.com/electron/electron/pull/38599
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
|
c8bdd014c87b5c33b77c845f853b7e52bb31de8f
| 2022-09-25T15:23:42Z |
c++
| 2023-06-08T10:19:34Z |
shell/browser/native_window_views.h
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#include "shell/browser/native_window.h"
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "shell/browser/ui/views/root_view.h"
#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include "ui/views/widget/widget_observer.h"
#if defined(USE_OZONE)
#include "ui/ozone/buildflags.h"
#if BUILDFLAG(OZONE_PLATFORM_X11)
#define USE_OZONE_PLATFORM_X11
#endif
#endif
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
namespace electron {
class GlobalMenuBarX11;
class WindowStateWatcher;
#if defined(USE_OZONE_PLATFORM_X11)
class EventDisabler;
#endif
#if BUILDFLAG(IS_WIN)
gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds);
#endif
class NativeWindowViews : public NativeWindow,
public views::WidgetObserver,
public ui::EventHandler {
public:
NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent);
~NativeWindowViews() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate) override;
gfx::Rect GetBounds() override;
gfx::Rect GetContentBounds() override;
gfx::Size GetContentSize() override;
gfx::Rect GetNormalBounds() override;
SkColor GetBackgroundColor() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relativeLevel) override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
bool IsTabletMode() const override;
void SetBackgroundColor(SkColor color) override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void SetMenu(ElectronMenuModel* menu_model) override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetAutoHideMenuBar(bool auto_hide) override;
bool IsMenuBarAutoHide() override;
void SetMenuBarVisibility(bool visible) override;
bool IsMenuBarVisible() override;
void SetBackgroundMaterial(const std::string& type) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetGTKDarkThemeEnabled(bool use_dark_theme) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
void IncrementChildModals();
void DecrementChildModals();
#if BUILDFLAG(IS_WIN)
// Catch-all message handling and filtering. Called before
// HWNDMessageHandler's built-in handling, which may pre-empt some
// expectations in Views/Aura if messages are consumed. Returns true if the
// message was consumed by the delegate and should not be processed further
// by the HWNDMessageHandler. In this case, |result| is returned. |result| is
// not modified otherwise.
bool PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result);
void SetIcon(HICON small_icon, HICON app_icon);
#elif BUILDFLAG(IS_LINUX)
void SetIcon(const gfx::ImageSkia& icon);
#endif
#if BUILDFLAG(IS_WIN)
TaskbarHost& taskbar_host() { return taskbar_host_; }
#endif
#if BUILDFLAG(IS_WIN)
bool IsWindowControlsOverlayEnabled() const {
return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) &&
titlebar_overlay_;
}
SkColor overlay_button_color() const { return overlay_button_color_; }
void set_overlay_button_color(SkColor color) {
overlay_button_color_ = color;
}
SkColor overlay_symbol_color() const { return overlay_symbol_color_; }
void set_overlay_symbol_color(SkColor color) {
overlay_symbol_color_ = color;
}
#endif
private:
// views::WidgetObserver:
void OnWidgetActivationChanged(views::Widget* widget, bool active) override;
void OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& bounds) override;
void OnWidgetDestroying(views::Widget* widget) override;
void OnWidgetDestroyed(views::Widget* widget) override;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override;
bool CanMaximize() const override;
bool CanMinimize() const override;
std::u16string GetWindowTitle() const override;
views::View* GetContentsView() override;
bool ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) override;
views::ClientView* CreateClientView(views::Widget* widget) override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
void OnWidgetMove() override;
#if BUILDFLAG(IS_WIN)
bool ExecuteWindowsCommand(int command_id) override;
#endif
#if BUILDFLAG(IS_WIN)
void HandleSizeEvent(WPARAM w_param, LPARAM l_param);
void ResetWindowControls();
void SetForwardMouseMessages(bool forward);
static LRESULT CALLBACK SubclassProc(HWND hwnd,
UINT msg,
WPARAM w_param,
LPARAM l_param,
UINT_PTR subclass_id,
DWORD_PTR ref_data);
static LRESULT CALLBACK MouseHookProc(int n_code,
WPARAM w_param,
LPARAM l_param);
#endif
// Enable/disable:
bool ShouldBeEnabled();
void SetEnabledInternal(bool enabled);
// NativeWindow:
void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) override;
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override;
// Returns the restore state for the window.
ui::WindowShowState GetRestoredState();
// Maintain window placement.
void MoveBehindTaskBarIfNeeded();
RootView root_view_{this};
// The view should be focused by default.
raw_ptr<views::View> focused_view_ = nullptr;
// The "resizable" flag on Linux is implemented by setting size constraints,
// we need to make sure size constraints are restored when window becomes
// resizable again. This is also used on Windows, to keep taskbar resize
// events from resizing the window.
extensions::SizeConstraints old_size_constraints_;
#if defined(USE_OZONE)
std::unique_ptr<GlobalMenuBarX11> global_menu_bar_;
#endif
#if defined(USE_OZONE_PLATFORM_X11)
// To disable the mouse events.
std::unique_ptr<EventDisabler> event_disabler_;
#endif
#if BUILDFLAG(IS_WIN)
ui::WindowShowState last_window_state_;
gfx::Rect last_normal_placement_bounds_;
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
// Memoized version of a11y check
bool checked_for_a11y_support_ = false;
// Whether to show the WS_THICKFRAME style.
bool thick_frame_ = true;
// The bounds of window before maximize/fullscreen.
gfx::Rect restore_bounds_;
// The icons of window and taskbar.
base::win::ScopedHICON window_icon_;
base::win::ScopedHICON app_icon_;
// The set of windows currently forwarding mouse messages.
static std::set<NativeWindowViews*> forwarding_windows_;
static HHOOK mouse_hook_;
bool forwarding_mouse_messages_ = false;
HWND legacy_window_ = NULL;
bool layered_ = false;
// Set to true if the window is always on top and behind the task bar.
bool behind_task_bar_ = false;
// Whether we want to set window placement without side effect.
bool is_setting_window_placement_ = false;
// Whether the window is currently being resized.
bool is_resizing_ = false;
// Whether the window is currently being moved.
bool is_moving_ = false;
absl::optional<gfx::Rect> pending_bounds_change_;
// The color to use as the theme and symbol colors respectively for Window
// Controls Overlay if enabled on Windows.
SkColor overlay_button_color_;
SkColor overlay_symbol_color_;
#endif
// Handles unhandled keyboard messages coming back from the renderer process.
views::UnhandledKeyboardEventHandler keyboard_event_handler_;
// Whether the window should be enabled based on user calls to SetEnabled()
bool is_enabled_ = true;
// How many modal children this window has;
// used to determine enabled state
unsigned int num_modal_children_ = 0;
bool use_content_size_ = false;
bool movable_ = true;
bool resizable_ = true;
bool maximizable_ = true;
bool minimizable_ = true;
bool fullscreenable_ = true;
std::string title_;
gfx::Size widget_size_;
double opacity_ = 1.0;
bool widget_destroyed_ = false;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,807 |
[Bug]: Menu Bar Visibility
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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
### What operating system are you using?
Other Linux
### Operating System Version
Fedora 36
### What arch are you using?
x64
### Last Known Working Electron version
19.0.0
### Expected Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
then menu bar will be hidden which is great. But if you spam F11 key, menu bar will become visible again.
### Actual Behavior
If I specify:
```js
win.setMenuBarVisibility(false);
```
Menu bar shouldn't be visible even while spamming F11.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35807
|
https://github.com/electron/electron/pull/38599
|
5ee890fb6f7c6acbcfd8e6e765334e6f9aa61850
|
c8bdd014c87b5c33b77c845f853b7e52bb31de8f
| 2022-09-25T15:23:42Z |
c++
| 2023-06-08T10:19:34Z |
spec/api-browser-window-spec.ts
|
import { expect } from 'chai';
import * as childProcess from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
import * as qs from 'querystring';
import * as http from 'http';
import * as os from 'os';
import { AddressInfo } from 'net';
import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main';
import { emittedUntil, emittedNTimes } from './lib/events-helpers';
import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers';
import { once } from 'events';
import { setTimeout } from 'timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixtures = path.resolve(__dirname, 'fixtures');
const mainFixtures = path.resolve(__dirname, 'fixtures');
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
const { scaleFactor } = screen.getPrimaryDisplay();
// Return true if scale factor is non-integer value
if (Math.round(scaleFactor) !== scaleFactor) return true;
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1;
};
const expectBoundsEqual = (actual: any, expected: any) => {
if (!isScaleFactorRounding()) {
expect(expected).to.deep.equal(actual);
} else if (Array.isArray(actual)) {
expect(actual[0]).to.be.closeTo(expected[0], 1);
expect(actual[1]).to.be.closeTo(expected[1], 1);
} else {
expect(actual.x).to.be.closeTo(expected.x, 1);
expect(actual.y).to.be.closeTo(expected.y, 1);
expect(actual.width).to.be.closeTo(expected.width, 1);
expect(actual.height).to.be.closeTo(expected.height, 1);
}
};
const isBeforeUnload = (event: Event, level: number, message: string) => {
return (message === 'beforeunload');
};
describe('BrowserWindow module', () => {
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
expect(() => {
const w = new BrowserWindow({
show: false,
// apparently void 0 had different behaviour from undefined in the
// issue that this test is supposed to catch.
webContents: void 0 // eslint-disable-line no-void
} as any);
w.destroy();
}).not.to.throw();
});
ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
const appProcess = childProcess.spawn(process.execPath, [appPath]);
await once(appProcess, 'exit');
});
it('does not crash or throw when passed an invalid icon', async () => {
expect(() => {
const w = new BrowserWindow({
icon: undefined
} as any);
w.destroy();
}).not.to.throw();
});
});
describe('garbage collection', () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
afterEach(closeAllWindows);
it('window does not get garbage collected when opened', async () => {
const w = new BrowserWindow({ show: false });
// Keep a weak reference to the window.
const wr = new WeakRef(w);
await setTimeout();
// Do garbage collection, since |w| is not referenced in this closure
// it would be gone after next call if there is no other reference.
v8Util.requestGarbageCollectionForTesting();
await setTimeout();
expect(wr.deref()).to.not.be.undefined();
});
});
describe('BrowserWindow.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should work if called when a messageBox is showing', async () => {
const closed = once(w, 'closed');
dialog.showMessageBox(w, { message: 'Hello Error' });
w.close();
await closed;
});
it('closes window without rounded corners', async () => {
await closeWindow(w);
w = new BrowserWindow({ show: false, frame: false, roundedCorners: false });
const closed = once(w, 'closed');
w.close();
await closed;
});
it('should not crash if called after webContents is destroyed', () => {
w.webContents.destroy();
w.webContents.on('destroyed', () => w.close());
});
it('should allow access to id after destruction', async () => {
const closed = once(w, 'closed');
w.destroy();
await closed;
expect(w.id).to.be.a('number');
});
it('should emit unload handler', async () => {
await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
const closed = once(w, 'closed');
w.close();
await closed;
const test = path.join(fixtures, 'api', 'unload');
const content = fs.readFileSync(test);
fs.unlinkSync(test);
expect(String(content)).to.equal('unload');
});
it('should emit beforeunload handler', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'before-unload-fired');
});
it('should not crash when keyboard event is sent before closing', async () => {
await w.loadURL('data:text/html,pls no crash');
const closed = once(w, 'closed');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
w.close();
await closed;
});
describe('when invoked synchronously inside navigation observer', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/301':
response.statusCode = 301;
response.setHeader('Location', '/200');
response.end();
break;
case '/200':
response.statusCode = 200;
response.end('hello');
break;
case '/title':
response.statusCode = 200;
response.end('<title>Hello</title>');
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', path: '/200' },
{ name: 'dom-ready', path: '/200' },
{ name: 'page-title-updated', path: '/title' },
{ name: 'did-stop-loading', path: '/200' },
{ name: 'did-finish-load', path: '/200' },
{ name: 'did-frame-finish-load', path: '/200' },
{ name: 'did-fail-load', path: '/net-error' }
];
for (const { name, path } of events) {
it(`should not crash when closed during ${name}`, async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once((name as any), () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.webContents.loadURL(url + path);
await destroyed;
});
}
});
});
describe('window.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload event', async () => {
w.loadFile(path.join(fixtures, 'api', 'close.html'));
await once(w, 'closed');
const test = path.join(fixtures, 'api', 'close');
const content = fs.readFileSync(test).toString();
fs.unlinkSync(test);
expect(content).to.equal('close');
});
it('should emit beforeunload event', async function () {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.webContents.executeJavaScript('window.close()', true);
await once(w.webContents, 'before-unload-fired');
});
});
describe('BrowserWindow.destroy()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('prevents users to access methods of webContents', async () => {
const contents = w.webContents;
w.destroy();
await new Promise(setImmediate);
expect(() => {
contents.getProcessId();
}).to.throw('Object has been destroyed');
});
it('should not crash when destroying windows with pending events', () => {
const focusListener = () => { };
app.on('browser-window-focus', focusListener);
const windowCount = 3;
const windowOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show());
windows.forEach(win => win.focus());
windows.forEach(win => win.destroy());
app.removeListener('browser-window-focus', focusListener);
});
});
describe('BrowserWindow.loadURL(url)', () => {
let w: BrowserWindow;
const scheme = 'other';
const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
callback(srcPath);
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
let server: http.Server;
let url: string;
let postData = null as any;
before(async () => {
const filePath = path.join(fixtures, 'pages', 'a.html');
const fileStats = fs.statSync(filePath);
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
];
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
let body = '';
req.on('data', (data) => {
if (data) body += data;
});
req.on('end', () => {
const parsedData = qs.parse(body);
fs.readFile(filePath, (err, data) => {
if (err) return;
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end();
}
});
});
} else if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
}
setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond);
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('should emit did-start-loading event', async () => {
const didStartLoading = once(w.webContents, 'did-start-loading');
w.loadURL('about:blank');
await didStartLoading;
});
it('should emit ready-to-show event', async () => {
const readyToShow = once(w, 'ready-to-show');
w.loadURL('about:blank');
await readyToShow;
});
// DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
// changed and adjust the test.
it('should emit did-fail-load event for files that do not exist', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('file://a.txt');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(code).to.equal(-6);
expect(desc).to.equal('ERR_FILE_NOT_FOUND');
expect(isMainFrame).to.equal(true);
});
it('should emit did-fail-load event for invalid URL', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('http://example:port');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should not emit did-fail-load for a successfully loaded media file', async () => {
w.webContents.on('did-fail-load', () => {
expect.fail('did-fail-load should not emit on media file loads');
});
const mediaStarted = once(w.webContents, 'media-started-playing');
w.loadFile(path.join(fixtures, 'cat-spin.mp4'));
await mediaStarted;
});
it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
const [,,,, isMainFrame] = await didFailLoad;
expect(isMainFrame).to.equal(false);
});
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
w.loadURL('http://127.0.0.1:11111');
done();
});
w.loadURL('http://127.0.0.1:11111');
});
it('should emit did-fail-load event for URL exceeding character limit', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL(`data:image/png;base64,${data}`);
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should return a promise', () => {
const p = w.loadURL('about:blank');
expect(p).to.have.property('then');
});
it('should return a promise that resolves', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('should return a promise that rejects on a load failure', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const p = w.loadURL(`data:image/png;base64,${data}`);
await expect(p).to.eventually.be.rejected;
});
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
await expect(p).to.eventually.be.fulfilled;
});
describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
it('supports specifying POST data', async () => {
await w.loadURL(url, { postData });
});
it('sets the content type header on URL encoded forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
});
it('sets the content type header on multi part forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
});
});
it('should support base url for data urls', async () => {
await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
});
});
for (const sandbox of [false, true]) {
describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('will-navigate event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-navigate');
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
await event;
w.close();
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame);
let initiator: WebFrameMain | undefined;
w.webContents.on('will-navigate', (e) => {
initiator = e.initiator;
});
const subframe = w.webContents.mainFrame.frames[0];
subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true);
await once(w.webContents, 'did-navigate');
expect(initiator).not.to.be.undefined();
expect(initiator).to.equal(subframe);
});
});
describe('will-frame-navigate event', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else if (req.url === '/navigate-iframe') {
res.end('<a href="/test">navigate iframe</a>');
} else if (req.url === '/navigate-iframe?navigated') {
res.end('Successfully navigated');
} else if (req.url === '/navigate-iframe-immediately') {
res.end(`
<script type="text/javascript" charset="utf-8">
location.href += '?navigated'
</script>
`);
} else if (req.url === '/navigate-iframe-immediately?navigated') {
res.end('Successfully navigated');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-frame-navigate', () => {
w.close();
done();
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented when navigating subframe', (done) => {
let willNavigate = false;
w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
if (isMainFrame) return;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(frame).to.not.be.undefined();
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
});
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`);
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await setTimeout(1000);
let willFrameNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willFrameNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willFrameNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.true();
});
it('is triggered when a cross-origin iframe navigates itself', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`);
await setTimeout(1000);
let willNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-frame-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.false();
});
it('can cancel when a cross-origin iframe navigates itself', async () => {
});
});
describe('will-redirect event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else if (req.url === '/navigate-302') {
res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
} else {
res.end();
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is emitted on redirects', async () => {
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
});
it('is emitted after will-navigate on redirects', async () => {
let navigateCalled = false;
w.webContents.on('will-navigate', () => {
navigateCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/navigate-302`);
await willRedirect;
expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
});
it('is emitted before did-stop-loading on redirects', async () => {
let stopCalled = false;
w.webContents.on('did-stop-loading', () => {
stopCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await event;
w.close();
});
it('can be prevented', (done) => {
w.webContents.once('will-redirect', (event) => {
event.preventDefault();
});
w.webContents.on('will-navigate', (e, u) => {
expect(u).to.equal(`${url}/302`);
});
w.webContents.on('did-stop-loading', () => {
try {
expect(w.webContents.getURL()).to.equal(
`${url}/navigate-302`,
'url should not have changed after navigation event'
);
done();
} catch (e) {
done(e);
}
});
w.webContents.on('will-redirect', (e, u) => {
try {
expect(u).to.equal(`${url}/200`);
} catch (e) {
done(e);
}
});
w.loadURL(`${url}/navigate-302`);
});
});
describe('ordering', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
const navigationEvents = [
'did-start-navigation',
'did-navigate-in-page',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate') {
res.end('<a href="/">navigate</a>');
} else if (req.url === '/redirect') {
res.end('<a href="/redirect2">redirect</a>');
} else if (req.url === '/redirect2') {
res.statusCode = 302;
res.setHeader('location', url);
res.end();
} else if (req.url === '/in-page') {
res.end('<a href="#in-page">redirect</a><div id="in-page"></div>');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
it('for initial navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-frame-navigate',
'did-navigate'
];
const allEvents = Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const timeout = setTimeout(1000);
w.loadURL(url);
await Promise.race([allEvents, timeout]);
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('for second navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}navigate`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating with redirection, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}redirect`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating in-page, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-navigate-in-page'
];
w.loadURL(`${url}in-page`);
await once(w.webContents, 'did-navigate');
await setTimeout(1000);
navigationEvents.forEach(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
);
const navigationFinished = once(w.webContents, 'did-navigate-in-page');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
});
});
}
describe('focus and visibility', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.show()', () => {
it('should focus on window', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isFocused()).to.equal(true);
});
it('should make the window visible', async () => {
const p = once(w, 'focus');
w.show();
await p;
expect(w.isVisible()).to.equal(true);
});
it('emits when window is shown', async () => {
const show = once(w, 'show');
w.show();
await show;
expect(w.isVisible()).to.equal(true);
});
});
describe('BrowserWindow.hide()', () => {
it('should defocus on window', () => {
w.hide();
expect(w.isFocused()).to.equal(false);
});
it('should make the window not visible', () => {
w.show();
w.hide();
expect(w.isVisible()).to.equal(false);
});
it('emits when window is hidden', async () => {
const shown = once(w, 'show');
w.show();
await shown;
const hidden = once(w, 'hide');
w.hide();
await hidden;
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.minimize()', () => {
// TODO(codebytere): Enable for Linux once maximize/minimize events work in CI.
ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => {
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMinimized()).to.equal(true);
expect(w.isVisible()).to.equal(false);
});
});
describe('BrowserWindow.showInactive()', () => {
it('should not focus on window', () => {
w.showInactive();
expect(w.isFocused()).to.equal(false);
});
// TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests
ifit(process.platform !== 'linux')('should not restore maximized windows', async () => {
const maximize = once(w, 'maximize');
const shown = once(w, 'show');
w.maximize();
// TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden
if (process.platform !== 'darwin') {
await maximize;
} else {
await setTimeout(1000);
}
w.showInactive();
await shown;
expect(w.isMaximized()).to.equal(true);
});
});
describe('BrowserWindow.focus()', () => {
it('does not make the window become visible', () => {
expect(w.isVisible()).to.equal(false);
w.focus();
expect(w.isVisible()).to.equal(false);
});
ifit(process.platform !== 'win32')('focuses a blurred window', async () => {
{
const isBlurred = once(w, 'blur');
const isShown = once(w, 'show');
w.show();
w.blur();
await isShown;
await isBlurred;
}
expect(w.isFocused()).to.equal(false);
w.focus();
expect(w.isFocused()).to.equal(true);
});
ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w1.focus();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w2.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w3.focus();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
// TODO(RaisinTen): Make this work on Windows too.
// Refs: https://github.com/electron/electron/issues/20464.
ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => {
it('removes focus from window', async () => {
{
const isFocused = once(w, 'focus');
const isShown = once(w, 'show');
w.show();
await isShown;
await isFocused;
}
expect(w.isFocused()).to.equal(true);
w.blur();
expect(w.isFocused()).to.equal(false);
});
ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => {
const w1 = new BrowserWindow({ show: false });
const w2 = new BrowserWindow({ show: false });
const w3 = new BrowserWindow({ show: false });
{
const isFocused3 = once(w3, 'focus');
const isShown1 = once(w1, 'show');
const isShown2 = once(w2, 'show');
const isShown3 = once(w3, 'show');
w1.show();
w2.show();
w3.show();
await isShown1;
await isShown2;
await isShown3;
await isFocused3;
}
// TODO(RaisinTen): Investigate why this assertion fails only on Linux.
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
w3.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(true);
expect(w3.isFocused()).to.equal(false);
w2.blur();
expect(w1.isFocused()).to.equal(true);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(false);
w1.blur();
expect(w1.isFocused()).to.equal(false);
expect(w2.isFocused()).to.equal(false);
expect(w3.isFocused()).to.equal(true);
{
const isClosed1 = once(w1, 'closed');
const isClosed2 = once(w2, 'closed');
const isClosed3 = once(w3, 'closed');
w1.destroy();
w2.destroy();
w3.destroy();
await isClosed1;
await isClosed2;
await isClosed3;
}
});
});
describe('BrowserWindow.getFocusedWindow()', () => {
it('returns the opener window when dev tools window is focused', async () => {
const p = once(w, 'focus');
w.show();
await p;
w.webContents.openDevTools({ mode: 'undocked' });
await once(w.webContents, 'devtools-focused');
expect(BrowserWindow.getFocusedWindow()).to.equal(w);
});
});
describe('BrowserWindow.moveTop()', () => {
it('should not steal focus', async () => {
const posDelta = 50;
const wShownInactive = once(w, 'show');
w.showInactive();
await wShownInactive;
expect(w.isFocused()).to.equal(false);
const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
const otherWindowShown = once(otherWindow, 'show');
const otherWindowFocused = once(otherWindow, 'focus');
otherWindow.show();
await otherWindowShown;
await otherWindowFocused;
expect(otherWindow.isFocused()).to.equal(true);
w.moveTop();
const wPos = w.getPosition();
const wMoving = once(w, 'move');
w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
await wMoving;
expect(w.isFocused()).to.equal(false);
expect(otherWindow.isFocused()).to.equal(true);
const wFocused = once(w, 'focus');
const otherWindowBlurred = once(otherWindow, 'blur');
w.focus();
await wFocused;
await otherWindowBlurred;
expect(w.isFocused()).to.equal(true);
otherWindow.moveTop();
const otherWindowPos = otherWindow.getPosition();
const otherWindowMoving = once(otherWindow, 'move');
otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
await otherWindowMoving;
expect(otherWindow.isFocused()).to.equal(false);
expect(w.isFocused()).to.equal(true);
await closeWindow(otherWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
});
});
describe('BrowserWindow.moveAbove(mediaSourceId)', () => {
it('should throw an exception if wrong formatting', async () => {
const fakeSourceIds = [
'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should throw an exception if wrong type', async () => {
const fakeSourceIds = [null as any, 123 as any];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Error processing argument at index 0 */);
});
});
it('should throw an exception if invalid window', async () => {
// It is very unlikely that these window id exist.
const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
'window:123456:9'];
fakeSourceIds.forEach((sourceId) => {
expect(() => {
w.moveAbove(sourceId);
}).to.throw(/Invalid media source id/);
});
});
it('should not throw an exception', async () => {
const w2 = new BrowserWindow({ show: false, title: 'window2' });
const w2Shown = once(w2, 'show');
w2.show();
await w2Shown;
expect(() => {
w.moveAbove(w2.getMediaSourceId());
}).to.not.throw();
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.setFocusable()', () => {
it('can set unfocusable window to focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
const w2Focused = once(w2, 'focus');
w2.setFocusable(true);
w2.focus();
await w2Focused;
await closeWindow(w2, { assertNotWindows: false });
});
});
describe('BrowserWindow.isFocusable()', () => {
it('correctly returns whether a window is focusable', async () => {
const w2 = new BrowserWindow({ focusable: false });
expect(w2.isFocusable()).to.be.false();
w2.setFocusable(true);
expect(w2.isFocusable()).to.be.true();
await closeWindow(w2, { assertNotWindows: false });
});
});
});
describe('sizing', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, width: 400, height: 400 });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.setBounds(bounds[, animate])', () => {
it('sets the window bounds with full bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
expectBoundsEqual(w.getBounds(), fullBounds);
});
it('sets the window bounds with partial bounds', () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds);
const boundsUpdate = { width: 200 };
w.setBounds(boundsUpdate as any);
const expectedBounds = { ...fullBounds, ...boundsUpdate };
expectBoundsEqual(w.getBounds(), expectedBounds);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
w.setBounds(fullBounds, true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setSize(width, height)', () => {
it('sets the window size', async () => {
const size = [300, 400];
const resized = once(w, 'resize');
w.setSize(size[0], size[1]);
await resized;
expectBoundsEqual(w.getSize(), size);
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('emits \'resized\' event after animating', async () => {
const size = [300, 400];
w.setSize(size[0], size[1], true);
await expect(once(w, 'resized')).to.eventually.be.fulfilled();
});
});
});
describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
it('sets the maximum and minimum size of the window', () => {
expect(w.getMinimumSize()).to.deep.equal([0, 0]);
expect(w.getMaximumSize()).to.deep.equal([0, 0]);
w.setMinimumSize(100, 100);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [0, 0]);
w.setMaximumSize(900, 600);
expectBoundsEqual(w.getMinimumSize(), [100, 100]);
expectBoundsEqual(w.getMaximumSize(), [900, 600]);
});
});
describe('BrowserWindow.setAspectRatio(ratio)', () => {
it('resets the behaviour when passing in 0', async () => {
const size = [300, 400];
w.setAspectRatio(1 / 2);
w.setAspectRatio(0);
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getSize(), size);
});
it('doesn\'t change bounds when maximum size is set', () => {
w.setMenu(null);
w.setMaximumSize(400, 400);
// Without https://github.com/electron/electron/pull/29101
// following call would shrink the window to 384x361.
// There would be also DCHECK in resize_utils.cc on
// debug build.
w.setAspectRatio(1.0);
expectBoundsEqual(w.getSize(), [400, 400]);
});
});
describe('BrowserWindow.setPosition(x, y)', () => {
it('sets the window position', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expect(w.getPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setContentSize(width, height)', () => {
it('sets the content size', async () => {
// NB. The CI server has a very small screen. Attempting to size the window
// larger than the screen will limit the window's size to the screen and
// cause the test to fail.
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400
});
const size = [456, 567];
w.setContentSize(size[0], size[1]);
await new Promise(setImmediate);
const after = w.getContentSize();
expect(after).to.deep.equal(size);
});
});
describe('BrowserWindow.setContentBounds(bounds)', () => {
it('sets the content size and position', async () => {
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
it('works for a frameless window', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300
});
const bounds = { x: 10, y: 10, width: 250, height: 250 };
const resize = once(w, 'resize');
w.setContentBounds(bounds);
await resize;
await setTimeout();
expectBoundsEqual(w.getContentBounds(), bounds);
});
});
describe('BrowserWindow.getBackgroundColor()', () => {
it('returns default value if no backgroundColor is set', () => {
w.destroy();
w = new BrowserWindow({});
expect(w.getBackgroundColor()).to.equal('#FFFFFF');
});
it('returns correct value if backgroundColor is set', () => {
const backgroundColor = '#BBAAFF';
w.destroy();
w = new BrowserWindow({
backgroundColor: backgroundColor
});
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct value from setBackgroundColor()', () => {
const backgroundColor = '#AABBFF';
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor(backgroundColor);
expect(w.getBackgroundColor()).to.equal(backgroundColor);
});
it('returns correct color with multiple passed formats', () => {
w.destroy();
w = new BrowserWindow({});
w.setBackgroundColor('#AABBFF');
expect(w.getBackgroundColor()).to.equal('#AABBFF');
w.setBackgroundColor('blueviolet');
expect(w.getBackgroundColor()).to.equal('#8A2BE2');
w.setBackgroundColor('rgb(255, 0, 185)');
expect(w.getBackgroundColor()).to.equal('#FF00B9');
w.setBackgroundColor('rgba(245, 40, 145, 0.8)');
expect(w.getBackgroundColor()).to.equal('#F52891');
w.setBackgroundColor('hsl(155, 100%, 50%)');
expect(w.getBackgroundColor()).to.equal('#00FF95');
});
});
describe('BrowserWindow.getNormalBounds()', () => {
describe('Normal state', () => {
it('checks normal bounds after resize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
it('checks normal bounds after move', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
expectBoundsEqual(w.getNormalBounds(), w.getBounds());
});
});
ifdescribe(process.platform !== 'linux')('Maximized state', () => {
it('checks normal bounds when maximized', async () => {
const bounds = w.getBounds();
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and maximize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and maximize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unmaximized', async () => {
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly reports maximized state after maximizing then minimizing', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
expect(w.isMinimized()).to.equal(true);
});
it('correctly reports maximized state after maximizing then fullscreening', async () => {
w.destroy();
w = new BrowserWindow({ show: false });
w.show();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
expect(w.isMaximized()).to.equal(false);
expect(w.isFullScreen()).to.equal(true);
});
it('checks normal bounds for maximized transparent window', async () => {
w.destroy();
w = new BrowserWindow({
transparent: true,
show: false
});
w.show();
const bounds = w.getNormalBounds();
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('maximize', () => {
w.unmaximize();
});
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await unmaximize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('correctly checks transparent window maximization state', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
width: 300,
height: 300,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
const unmaximize = once(w, 'unmaximize');
w.unmaximize();
await unmaximize;
expect(w.isMaximized()).to.equal(false);
});
it('returns the correct value for windows with an aspect ratio', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
fullscreenable: false
});
w.setAspectRatio(16 / 11);
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
expect(w.isMaximized()).to.equal(true);
w.resizable = false;
expect(w.isMaximized()).to.equal(true);
});
});
ifdescribe(process.platform !== 'linux')('Minimized state', () => {
it('checks normal bounds when minimized', async () => {
const bounds = w.getBounds();
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after move and minimize', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('updates normal bounds after resize and minimize', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
const normal = w.getNormalBounds();
expect(original).to.deep.equal(normal);
expectBoundsEqual(normal, w.getBounds());
});
it('checks normal bounds when restored', async () => {
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('does not change size for a frameless window with min size', async () => {
w.destroy();
w = new BrowserWindow({
show: false,
frame: false,
width: 300,
height: 300,
minWidth: 300,
minHeight: 300
});
const bounds = w.getBounds();
w.once('minimize', () => {
w.restore();
});
const restore = once(w, 'restore');
w.show();
w.minimize();
await restore;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
it('with properties', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.fullScreen).to.be.true();
});
it('does not go fullscreen if roundedCorners are enabled', async () => {
w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true });
expect(w.fullScreen).to.be.false();
});
it('can be changed', () => {
w.fullScreen = false;
expect(w.fullScreen).to.be.false();
w.fullScreen = true;
expect(w.fullScreen).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
const enterFullScreen = once(w, 'enter-full-screen');
w.show();
w.fullScreen = true;
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.fullScreen = true;
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.once('enter-full-screen', () => {
w.fullScreen = false;
});
const leaveFullScreen = once(w, 'leave-full-screen');
w.show();
w.fullScreen = true;
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
it('with functions', () => {
it('can be set with the fullscreen constructor option', () => {
w = new BrowserWindow({ fullscreen: true });
expect(w.isFullScreen()).to.be.true();
});
it('can be changed', () => {
w.setFullScreen(false);
expect(w.isFullScreen()).to.be.false();
w.setFullScreen(true);
expect(w.isFullScreen()).to.be.true();
});
it('checks normal bounds when fullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
it('updates normal bounds after resize and fullscreen', async () => {
const size = [300, 400];
const resize = once(w, 'resize');
w.setSize(size[0], size[1]);
await resize;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('updates normal bounds after move and fullscreen', async () => {
const pos = [10, 10];
const move = once(w, 'move');
w.setPosition(pos[0], pos[1]);
await move;
const original = w.getBounds();
const fsc = once(w, 'enter-full-screen');
w.setFullScreen(true);
await fsc;
const normal = w.getNormalBounds();
const bounds = w.getBounds();
expect(normal).to.deep.equal(original);
expect(normal).to.not.deep.equal(bounds);
const close = once(w, 'close');
w.close();
await close;
});
it('checks normal bounds when unfullscreen\'ed', async () => {
const bounds = w.getBounds();
w.show();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expectBoundsEqual(w.getNormalBounds(), bounds);
});
});
});
});
});
ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('BrowserWindow.selectPreviousTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectPreviousTab();
}).to.not.throw();
});
});
describe('BrowserWindow.selectNextTab()', () => {
it('does not throw', () => {
expect(() => {
w.selectNextTab();
}).to.not.throw();
});
});
describe('BrowserWindow.mergeAllWindows()', () => {
it('does not throw', () => {
expect(() => {
w.mergeAllWindows();
}).to.not.throw();
});
});
describe('BrowserWindow.moveTabToNewWindow()', () => {
it('does not throw', () => {
expect(() => {
w.moveTabToNewWindow();
}).to.not.throw();
});
});
describe('BrowserWindow.toggleTabBar()', () => {
it('does not throw', () => {
expect(() => {
w.toggleTabBar();
}).to.not.throw();
});
});
describe('BrowserWindow.addTabbedWindow()', () => {
it('does not throw', async () => {
const tabbedWindow = new BrowserWindow({});
expect(() => {
w.addTabbedWindow(tabbedWindow);
}).to.not.throw();
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
await closeWindow(tabbedWindow, { assertNotWindows: false });
expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
});
it('throws when called on itself', () => {
expect(() => {
w.addTabbedWindow(w);
}).to.throw('AddTabbedWindow cannot be called by a window on itself.');
});
});
});
describe('autoHideMenuBar state', () => {
afterEach(closeAllWindows);
it('for properties', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
w.autoHideMenuBar = true;
expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
w.autoHideMenuBar = false;
expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
});
});
it('for functions', () => {
it('can be set with autoHideMenuBar constructor option', () => {
const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
w.setAutoHideMenuBar(true);
expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
w.setAutoHideMenuBar(false);
expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
});
});
});
describe('BrowserWindow.capturePage(rect)', () => {
afterEach(closeAllWindows);
it('returns a Promise with a Buffer', async () => {
const w = new BrowserWindow({ show: false });
const image = await w.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => {
const w = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true });
const visible = await w.webContents.executeJavaScript('document.visibilityState');
expect(visible).to.equal('hidden');
});
it('resolves after the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
w.show();
const visibleImage = await w.capturePage();
expect(visibleImage.isEmpty()).to.equal(false);
w.hide();
const hiddenImage = await w.capturePage();
const isEmpty = process.platform !== 'darwin';
expect(hiddenImage.isEmpty()).to.equal(isEmpty);
});
it('resolves after the window is hidden and capturer count is non-zero', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
w.loadFile(path.join(fixtures, 'pages', 'a.html'));
await once(w, 'ready-to-show');
const image = await w.capturePage();
expect(image.isEmpty()).to.equal(false);
});
it('preserves transparency', async () => {
const w = new BrowserWindow({ show: false, transparent: true });
w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
await once(w, 'ready-to-show');
w.show();
const image = await w.capturePage();
const imgBuffer = image.toPNG();
// Check the 25th byte in the PNG.
// Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
expect(imgBuffer[25]).to.equal(6);
});
});
describe('BrowserWindow.setProgressBar(progress)', () => {
let w: BrowserWindow;
before(() => {
w = new BrowserWindow({ show: false });
});
after(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('sets the progress', () => {
expect(() => {
if (process.platform === 'darwin') {
app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
}
w.setProgressBar(0.5);
if (process.platform === 'darwin') {
app.dock.setIcon(null as any);
}
w.setProgressBar(-1);
}).to.not.throw();
});
it('sets the progress using "paused" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'paused' });
}).to.not.throw();
});
it('sets the progress using "error" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'error' });
}).to.not.throw();
});
it('sets the progress using "normal" mode', () => {
expect(() => {
w.setProgressBar(0.5, { mode: 'normal' });
}).to.not.throw();
});
});
describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
let w: BrowserWindow;
afterEach(closeAllWindows);
beforeEach(() => {
w = new BrowserWindow({ show: true });
});
it('sets the window as always on top', () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
w.setAlwaysOnTop(false);
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => {
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
});
it('causes the right value to be emitted on `always-on-top-changed`', async () => {
const alwaysOnTopChanged = once(w, 'always-on-top-changed');
expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
w.setAlwaysOnTop(true);
const [, alwaysOnTop] = await alwaysOnTopChanged;
expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
});
ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ parent: w });
c.setAlwaysOnTop(true, 'screen-saver');
expect(w.isAlwaysOnTop()).to.be.false();
expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver');
});
});
describe('preconnect feature', () => {
let w: BrowserWindow;
let server: http.Server;
let url: string;
let connections = 0;
beforeEach(async () => {
connections = 0;
server = http.createServer((req, res) => {
if (req.url === '/link') {
res.setHeader('Content-type', 'text/html');
res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
return;
}
res.end();
});
server.on('connection', () => { connections++; });
url = (await listen(server)).url;
});
afterEach(async () => {
server.close();
await closeWindow(w);
w = null as unknown as BrowserWindow;
server = null as unknown as http.Server;
});
it('calling preconnect() connects to the server', async () => {
w = new BrowserWindow({ show: false });
w.webContents.on('did-start-navigation', (event, url) => {
w.webContents.session.preconnect({ url, numSockets: 4 });
});
await w.loadURL(url);
expect(connections).to.equal(4);
});
it('does not preconnect unless requested', async () => {
w = new BrowserWindow({ show: false });
await w.loadURL(url);
expect(connections).to.equal(1);
});
it('parses <link rel=preconnect>', async () => {
w = new BrowserWindow({ show: true });
const p = once(w.webContents.session, 'preconnect');
w.loadURL(url + '/link');
const [, preconnectUrl, allowCredentials] = await p;
expect(preconnectUrl).to.equal('http://example.com/');
expect(allowCredentials).to.be.true('allowCredentials');
});
});
describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
ifit(process.platform === 'darwin')('on macOS', () => {
it('allows changing cursor auto-hiding', () => {
expect(() => {
w.setAutoHideCursor(false);
w.setAutoHideCursor(true);
}).to.not.throw();
});
});
ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
it('is not available', () => {
expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
});
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setWindowButtonVisibility(true);
w.setWindowButtonVisibility(false);
}).to.not.throw();
});
it('changes window button visibility for normal window', () => {
const w = new BrowserWindow({ show: false });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('changes window button visibility for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('changes window button visibility for hiddenInset window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
// Buttons of customButtonsOnHover are always hidden unless hovered.
it('does not change window button visibility for customButtonsOnHover window', () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(false);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
});
it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
expect(w._getWindowButtonVisibility()).to.equal(true);
w.setWindowButtonVisibility(false);
expect(w._getWindowButtonVisibility()).to.equal(false);
const enterFS = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFS;
const leaveFS = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFS;
w.setWindowButtonVisibility(true);
expect(w._getWindowButtonVisibility()).to.equal(true);
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
afterEach(closeAllWindows);
it('allows setting, changing, and removing the vibrancy', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('light');
w.setVibrancy('dark');
w.setVibrancy(null);
w.setVibrancy('ultra-dark');
w.setVibrancy('' as any);
}).to.not.throw();
});
it('does not crash if vibrancy is set to an invalid value', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
}).to.not.throw();
});
});
ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
const pos = { x: 10, y: 10 };
afterEach(closeAllWindows);
describe('BrowserWindow.getWindowButtonPosition(pos)', () => {
it('returns null when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition');
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getWindowButtonPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setWindowButtonPosition(pos)', () => {
it('resets the position when null is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setWindowButtonPosition(null);
expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition');
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setWindowButtonPosition(newPos);
expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
});
});
// The set/getTrafficLightPosition APIs are deprecated.
describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
it('returns { x: 0, y: 0 } when there is no custom position', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('gets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
expect(w.getTrafficLightPosition()).to.deep.equal(pos);
});
});
describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
it('resets the position when { x: 0, y: 0 } is passed', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
w.setTrafficLightPosition({ x: 0, y: 0 });
expect(w.getTrafficLightPosition()).to.deep.equal({ x: 0, y: 0 });
});
it('sets position property for "hidden" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
const newPos = { x: 20, y: 20 };
w.setTrafficLightPosition(newPos);
expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
});
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
afterEach(closeAllWindows);
it('supports setting the app details', () => {
const w = new BrowserWindow({ show: false });
const iconPath = path.join(fixtures, 'assets', 'icon.ico');
expect(() => {
w.setAppDetails({ appId: 'my.app.id' });
w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
w.setAppDetails({ appIconPath: iconPath });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
w.setAppDetails({ relaunchDisplayName: 'My app name' });
w.setAppDetails({
appId: 'my.app.id',
appIconPath: iconPath,
appIconIndex: 0,
relaunchCommand: 'my-app.exe arg1 arg2',
relaunchDisplayName: 'My app name'
});
w.setAppDetails({});
}).to.not.throw();
expect(() => {
(w.setAppDetails as any)();
}).to.throw('Insufficient number of arguments.');
});
});
describe('BrowserWindow.fromId(id)', () => {
afterEach(closeAllWindows);
it('returns the window with id', () => {
const w = new BrowserWindow({ show: false });
expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
});
});
describe('Opening a BrowserWindow from a link', () => {
let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('can properly open and load a new window from a link', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
appProcess = childProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
});
describe('BrowserWindow.fromWebContents(webContents)', () => {
afterEach(closeAllWindows);
it('returns the window with the webContents', () => {
const w = new BrowserWindow({ show: false });
const found = BrowserWindow.fromWebContents(w.webContents);
expect(found!.id).to.equal(w.id);
});
it('returns null for webContents without a BrowserWindow', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
try {
expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
} finally {
contents.destroy();
}
});
it('returns the correct window for a BrowserView webcontents', async () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
await bv.webContents.loadURL('about:blank');
expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
});
it('returns the correct window for a WebView webcontents', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
// NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
// https://github.com/electron/electron/issues/25413, and is not integral
// to the test.
const p = once(w.webContents, 'did-attach-webview');
const [, webviewContents] = await once(app, 'web-contents-created');
expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
await p;
});
it('is usable immediately on browser-window-created', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.open(""); null');
const [win, winFromWebContents] = await new Promise<any>((resolve) => {
app.once('browser-window-created', (e, win) => {
resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
});
});
expect(winFromWebContents).to.equal(win);
});
});
describe('BrowserWindow.openDevTools()', () => {
afterEach(closeAllWindows);
it('does not crash for frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
w.webContents.openDevTools();
});
});
describe('BrowserWindow.fromBrowserView(browserView)', () => {
afterEach(closeAllWindows);
it('returns the window with the BrowserView', () => {
const w = new BrowserWindow({ show: false });
const bv = new BrowserView();
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
});
it('returns the window when there are multiple BrowserViews', () => {
const w = new BrowserWindow({ show: false });
const bv1 = new BrowserView();
w.addBrowserView(bv1);
const bv2 = new BrowserView();
w.addBrowserView(bv2);
defer(() => {
w.removeBrowserView(bv1);
w.removeBrowserView(bv2);
bv1.webContents.destroy();
bv2.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
});
it('returns undefined if not attached', () => {
const bv = new BrowserView();
defer(() => {
bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
});
});
describe('BrowserWindow.setOpacity(opacity)', () => {
afterEach(closeAllWindows);
ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
it('make window with initial opacity', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
expect(w.getOpacity()).to.equal(0.5);
});
it('allows setting the opacity', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setOpacity(0.0);
expect(w.getOpacity()).to.equal(0.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(0.5);
w.setOpacity(1.0);
expect(w.getOpacity()).to.equal(1.0);
}).to.not.throw();
});
it('clamps opacity to [0.0...1.0]', () => {
const w = new BrowserWindow({ show: false, opacity: 0.5 });
w.setOpacity(100);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(-100);
expect(w.getOpacity()).to.equal(0.0);
});
});
ifdescribe(process.platform === 'linux')(('Linux'), () => {
it('sets 1 regardless of parameter', () => {
const w = new BrowserWindow({ show: false });
w.setOpacity(0);
expect(w.getOpacity()).to.equal(1.0);
w.setOpacity(0.5);
expect(w.getOpacity()).to.equal(1.0);
});
});
});
describe('BrowserWindow.setShape(rects)', () => {
afterEach(closeAllWindows);
it('allows setting shape', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.setShape([]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
w.setShape([]);
}).to.not.throw();
});
});
describe('"useContentSize" option', () => {
afterEach(closeAllWindows);
it('make window created with content size when used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('make window created with window size when not used', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400
});
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
it('works for a frameless window', () => {
const w = new BrowserWindow({
show: false,
frame: false,
width: 400,
height: 400,
useContentSize: true
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
const size = w.getSize();
expect(size).to.deep.equal([400, 400]);
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => {
const testWindowsOverlay = async (style: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: style,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: true
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRect.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRect.x).to.be.greaterThan(0);
} else {
expect(overlayRect.x).to.equal(0);
}
expect(overlayRect.width).to.be.greaterThan(0);
expect(overlayRect.height).to.be.greaterThan(0);
const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
expect(cssOverlayRect).to.deep.equal(overlayRect);
const geometryChange = once(ipcMain, 'geometrychange');
w.setBounds({ width: 800 });
const [, newOverlayRect] = await geometryChange;
expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('creates browser window with hidden title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hiddenInset'
});
const contentSize = w.getContentSize();
expect(contentSize).to.deep.equal([400, 400]);
});
it('sets Window Control Overlay with hidden title bar', async () => {
await testWindowsOverlay('hidden');
});
ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
await testWindowsOverlay('hiddenInset');
});
ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
});
afterEach(async () => {
await closeAllWindows();
});
it('does not crash changing minimizability ', () => {
expect(() => {
w.setMinimizable(false);
}).to.not.throw();
});
it('does not crash changing maximizability', () => {
expect(() => {
w.setMaximizable(false);
}).to.not.throw();
});
});
});
ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => {
const testWindowsOverlayHeight = async (size: any) => {
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: size
}
});
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
if (process.platform === 'darwin') {
await w.loadFile(overlayHTML);
} else {
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(overlayRectPreMax.y).to.equal(0);
if (process.platform === 'darwin') {
expect(overlayRectPreMax.x).to.be.greaterThan(0);
} else {
expect(overlayRectPreMax.x).to.equal(0);
}
expect(overlayRectPreMax.width).to.be.greaterThan(0);
expect(overlayRectPreMax.height).to.equal(size);
// Confirm that maximization only affected the height of the buttons and not the title bar
expect(overlayRectPostMax.height).to.equal(size);
};
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('sets Window Control Overlay with title bar height of 40', async () => {
await testWindowsOverlayHeight(40);
});
});
ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => {
afterEach(async () => {
await closeAllWindows();
ipcMain.removeAllListeners('geometrychange');
});
it('does not crash when an invalid titleBarStyle was initially set', () => {
const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
color: '#0000f0',
symbolColor: '#ffffff'
},
titleBarStyle: 'hiddenInset'
});
expect(() => {
win.setTitleBarOverlay({
color: '#000000'
});
}).to.not.throw();
});
it('correctly updates the height of the overlay', async () => {
const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
const overlayReady = once(ipcMain, 'geometrychange');
await w.loadFile(overlayHTML);
if (firstRun) {
await overlayReady;
}
const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
expect(overlayEnabled).to.be.true('overlayEnabled');
const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
if (!w.isMaximized()) {
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
}
expect(w.isMaximized()).to.be.true('not maximized');
const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
expect(x).to.equal(0);
expect(y).to.equal(0);
expect(width).to.be.greaterThan(0);
expect(height).to.equal(size);
expect(preMaxHeight).to.equal(size);
};
const INITIAL_SIZE = 40;
const w = new BrowserWindow({
show: false,
width: 400,
height: 400,
titleBarStyle: 'hidden',
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
titleBarOverlay: {
height: INITIAL_SIZE
}
});
await testOverlay(w, INITIAL_SIZE, true);
w.setTitleBarOverlay({
height: INITIAL_SIZE + 10
});
await testOverlay(w, INITIAL_SIZE + 10, false);
});
});
ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
afterEach(closeAllWindows);
it('can move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, 50);
const after = w.getPosition();
expect(after).to.deep.equal([-10, 50]);
});
it('cannot move the window behind menu bar', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can move the window behind menu bar if it has no frame', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[0]).to.be.equal(-10);
expect(after[1]).to.be.equal(-10);
});
it('without it, cannot move the window out of screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
w.setPosition(-10, -10);
const after = w.getPosition();
expect(after[1]).to.be.at.least(0);
});
it('can set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expectBoundsEqual(w.getSize(), [size.width, size.height]);
});
it('without it, cannot set the window larger than screen', () => {
const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
const size = screen.getPrimaryDisplay().size;
size.width += 100;
size.height += 100;
w.setSize(size.width, size.height);
expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
});
});
ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
afterEach(closeAllWindows);
it('sets the window width to the page width when used', () => {
const w = new BrowserWindow({
show: false,
width: 500,
height: 400,
zoomToPageWidth: true
});
w.maximize();
expect(w.getSize()[0]).to.equal(500);
});
});
describe('"tabbingIdentifier" option', () => {
afterEach(closeAllWindows);
it('can be set on a window', () => {
expect(() => {
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group1'
});
/* eslint-disable-next-line no-new */
new BrowserWindow({
tabbingIdentifier: 'group2',
frame: false
});
}).not.to.throw();
});
});
describe('"webPreferences" option', () => {
afterEach(() => { ipcMain.removeAllListeners('answer'); });
afterEach(closeAllWindows);
describe('"preload" option', () => {
const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
it(name, async () => {
const w = new BrowserWindow({
webPreferences: {
...webPrefs,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
const [, result] = await once(ipcMain, 'leak-result');
expect(result).to.have.property('require', 'undefined');
expect(result).to.have.property('exports', 'undefined');
expect(result).to.have.property('windowExports', 'undefined');
expect(result).to.have.property('windowPreload', 'undefined');
expect(result).to.have.property('windowRequire', 'undefined');
});
};
doesNotLeakSpec('does not leak require', {
nodeIntegration: false,
sandbox: false,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when sandbox is enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: false
});
doesNotLeakSpec('does not leak require when context isolation is enabled', {
nodeIntegration: false,
sandbox: false,
contextIsolation: true
});
doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
nodeIntegration: false,
sandbox: true,
contextIsolation: true
});
it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
let w = new BrowserWindow({
webPreferences: {
contextIsolation: false,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, notIsolated] = await once(ipcMain, 'leak-result');
expect(notIsolated).to.have.property('globals');
w.destroy();
w = new BrowserWindow({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.resolve(fixtures, 'module', 'empty.js')
},
show: false
});
w.loadFile(path.join(fixtures, 'api', 'globals.html'));
const [, isolated] = await once(ipcMain, 'leak-result');
expect(isolated).to.have.property('globals');
const notIsolatedGlobals = new Set(notIsolated.globals);
for (const isolatedGlobal of isolated.globals) {
notIsolatedGlobals.delete(isolatedGlobal);
}
expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
});
it('loads the script before other scripts in window', async () => {
const preload = path.join(fixtures, 'module', 'set-global.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.eql('preload');
});
it('has synchronous access to all eventual window APIs', async () => {
const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.be.an('object');
expect(test.atPreload).to.be.an('array');
expect(test.atLoad).to.be.an('array');
expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
});
});
describe('session preload scripts', function () {
const preloads = [
path.join(fixtures, 'module', 'set-global-preload-1.js'),
path.join(fixtures, 'module', 'set-global-preload-2.js'),
path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
];
const defaultSession = session.defaultSession;
beforeEach(() => {
expect(defaultSession.getPreloads()).to.deep.equal([]);
defaultSession.setPreloads(preloads);
});
afterEach(() => {
defaultSession.setPreloads([]);
});
it('can set multiple session preload script', () => {
expect(defaultSession.getPreloads()).to.deep.equal(preloads);
});
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('loads the script before other scripts in window including normal preloads', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload: path.join(fixtures, 'module', 'get-global-preload.js'),
contextIsolation: false
}
});
w.loadURL('about:blank');
const [, preload1, preload2, preload3] = await once(ipcMain, 'vars');
expect(preload1).to.equal('preload-1');
expect(preload2).to.equal('preload-1-2');
expect(preload3).to.be.undefined('preload 3');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('"additionalArguments" option', () => {
it('adds extra args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg');
});
it('adds extra value args to process.argv in the renderer process', async () => {
const preload = path.join(fixtures, 'module', 'check-arguments.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
preload,
additionalArguments: ['--my-magic-arg=foo']
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, argv] = await once(ipcMain, 'answer');
expect(argv).to.include('--my-magic-arg=foo');
});
});
describe('"node-integration" option', () => {
it('disables node integration by default', async () => {
const preload = path.join(fixtures, 'module', 'send-later.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'blank.html'));
const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer');
expect(typeofProcess).to.equal('undefined');
expect(typeofBuffer).to.equal('undefined');
});
});
describe('"sandbox" option', () => {
const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/cross-site':
response.end(`<html><body><h1>${request.url}</h1></body></html>`);
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('exposes ipcRenderer to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes ipcRenderer to preload script (path has special chars)', async () => {
const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: preloadSpecialChars,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test).to.equal('preload');
});
it('exposes "loaded" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload
}
});
w.loadURL('about:blank');
await once(ipcMain, 'process-loaded');
});
it('exposes "exit" event to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
const pageUrl = 'file://' + htmlPath;
w.loadURL(pageUrl);
const [, url] = await once(ipcMain, 'answer');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
});
it('exposes full EventEmitter object to preload script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
}
});
w.loadURL('about:blank');
const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer');
const { EventEmitter } = require('events');
const emitter = new EventEmitter();
const browserEventEmitterProperties = [];
let currentObj = emitter;
do {
browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
} while ((currentObj = Object.getPrototypeOf(currentObj)));
expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
});
it('should open windows in same domain with cross-scripting enabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
const pageUrl = 'file://' + htmlPath;
const answer = once(ipcMain, 'answer');
w.loadURL(pageUrl);
const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window');
const expectedUrl = process.platform === 'win32'
? 'file:///' + htmlPath.replace(/\\/g, '/')
: pageUrl;
expect(url).to.equal(expectedUrl);
expect(frameName).to.equal('popup!');
expect(options.width).to.equal(500);
expect(options.height).to.equal(600);
const [, html] = await answer;
expect(html).to.equal('<h1>scripting from opener</h1>');
});
it('should open windows in another domain with cross-scripting disabled', async () => {
const w = new BrowserWindow({
show: true,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload
}
}
}));
w.loadFile(
path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
{ search: 'window-open-external' }
);
// Wait for a message from the main window saying that it's ready.
await once(ipcMain, 'opener-loaded');
// Ask the opener to open a popup with window.opener.
const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
w.webContents.send('open-the-popup', expectedPopupUrl);
// The page is going to open a popup that it won't be able to close.
// We have to close it from here later.
const [, popupWindow] = await once(app, 'browser-window-created');
// Ask the popup window for details.
const detailsAnswer = once(ipcMain, 'child-loaded');
popupWindow.webContents.send('provide-details');
const [, openerIsNull, , locationHref] = await detailsAnswer;
expect(openerIsNull).to.be.false('window.opener is null');
expect(locationHref).to.equal(expectedPopupUrl);
// Ask the page to access the popup.
const touchPopupResult = once(ipcMain, 'answer');
w.webContents.send('touch-the-popup');
const [, popupAccessMessage] = await touchPopupResult;
// Ask the popup to access the opener.
const touchOpenerResult = once(ipcMain, 'answer');
popupWindow.webContents.send('touch-the-opener');
const [, openerAccessMessage] = await touchOpenerResult;
// We don't need the popup anymore, and its parent page can't close it,
// so let's close it from here before we run any checks.
await closeWindow(popupWindow, { assertNotWindows: false });
expect(popupAccessMessage).to.be.a('string',
'child\'s .document is accessible from its parent window');
expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
expect(openerAccessMessage).to.be.a('string',
'opener .document is accessible from a popup window');
expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
});
it('should inherit the sandbox setting in opened windows', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [, { argv }] = await once(ipcMain, 'answer');
expect(argv).to.include('--enable-sandbox');
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
it('should set ipc event sender correctly', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
let childWc: WebContents | null = null;
w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
w.webContents.on('did-create-window', (win) => {
childWc = win.webContents;
expect(w.webContents).to.not.equal(childWc);
});
ipcMain.once('parent-ready', function (event) {
expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
event.sender.send('verified');
});
ipcMain.once('child-ready', function (event) {
expect(childWc).to.not.be.null('child webcontents should be available');
expect(event.sender).to.equal(childWc, 'sender should be the child');
event.sender.send('verified');
});
const done = Promise.all([
'parent-answer',
'child-answer'
].map(name => once(ipcMain, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
await done;
});
describe('event handling', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
});
it('works for window events', async () => {
const pageTitleUpdated = once(w, 'page-title-updated');
w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
await pageTitleUpdated;
});
it('works for stop events', async () => {
const done = Promise.all([
'did-navigate',
'did-fail-load',
'did-stop-loading'
].map(name => once(w.webContents, name)));
w.loadURL('data:text/html,<script>stop()</script>');
await done;
});
it('works for web contents events', async () => {
const done = Promise.all([
'did-finish-load',
'did-frame-finish-load',
'did-navigate-in-page',
'will-navigate',
'did-start-loading',
'did-stop-loading',
'did-frame-finish-load',
'dom-ready'
].map(name => once(w.webContents, name)));
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
await done;
});
});
it('validates process APIs access in sandboxed renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
contextIsolation: false
}
});
w.webContents.once('preload-error', (event, preloadPath, error) => {
throw error;
});
process.env.sandboxmain = 'foo';
w.loadFile(path.join(fixtures, 'api', 'preload.html'));
const [, test] = await once(ipcMain, 'answer');
expect(test.hasCrash).to.be.true('has crash');
expect(test.hasHang).to.be.true('has hang');
expect(test.heapStatistics).to.be.an('object');
expect(test.blinkMemoryInfo).to.be.an('object');
expect(test.processMemoryInfo).to.be.an('object');
expect(test.systemVersion).to.be.a('string');
expect(test.cpuUsage).to.be.an('object');
expect(test.ioCounters).to.be.an('object');
expect(test.uptime).to.be.a('number');
expect(test.arch).to.equal(process.arch);
expect(test.platform).to.equal(process.platform);
expect(test.env).to.deep.equal(process.env);
expect(test.execPath).to.equal(process.helperExecPath);
expect(test.sandboxed).to.be.true('sandboxed');
expect(test.contextIsolated).to.be.false('contextIsolated');
expect(test.type).to.equal('renderer');
expect(test.version).to.equal(process.version);
expect(test.versions).to.deep.equal(process.versions);
expect(test.contextId).to.be.a('string');
if (process.platform === 'linux' && test.osSandbox) {
expect(test.creationTime).to.be.null('creation time');
expect(test.systemMemoryInfo).to.be.null('system memory info');
} else {
expect(test.creationTime).to.be.a('number');
expect(test.systemMemoryInfo).to.be.an('object');
}
});
it('webview in sandbox renderer', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
preload,
webviewTag: true,
contextIsolation: false
}
});
const didAttachWebview = once(w.webContents, 'did-attach-webview');
const webviewDomReady = once(ipcMain, 'webview-dom-ready');
w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
const [, webContents] = await didAttachWebview;
const [, id] = await webviewDomReady;
expect(webContents.id).to.equal(id);
});
});
describe('child windows', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
// tests relies on preloads in opened windows
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
it('opens window of about:blank with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window of same domain with cross-scripting enabled', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('blocks accessing cross-origin frames', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
const [, content] = await answer;
expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
});
it('opens window from <iframe> tags', async () => {
const answer = once(ipcMain, 'answer');
w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
const [, content] = await answer;
expect(content).to.equal('Hello');
});
it('opens window with cross-scripting enabled from isolated context', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
}
});
w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('Hello');
});
ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
w.reload();
{
const [, content] = await once(ipcMain, 'answer');
expect(content).to.equal('function');
}
});
it('<webview> works in a scriptable popup', async () => {
const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegrationInSubFrames: true,
webviewTag: true,
contextIsolation: false,
preload
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
show: false,
webPreferences: {
contextIsolation: false,
webviewTag: true,
nodeIntegrationInSubFrames: true,
preload
}
}
}));
const webviewLoaded = once(ipcMain, 'webview-loaded');
w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
await webviewLoaded;
});
it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: preloadPath,
contextIsolation: false
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
const [[, childWebContents]] = await Promise.all([
once(app, 'web-contents-created'),
once(ipcMain, 'answer')
]);
const webPreferences = childWebContents.getLastWebPreferences();
expect(webPreferences.contextIsolation).to.equal(false);
});
describe('window.location', () => {
const protocols = [
['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
];
beforeEach(() => {
for (const [scheme, path] of protocols) {
protocol.registerBufferProtocol(scheme, (request, callback) => {
callback({
mimeType: 'text/html',
data: fs.readFileSync(path)
});
});
}
});
afterEach(() => {
for (const [scheme] of protocols) {
protocol.unregisterProtocol(scheme);
}
});
it('retains the original web preferences when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
contextIsolation: false,
nodeIntegrationInSubFrames: true
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer');
expect(nodeIntegration).to.be.false();
expect(typeofProcess).to.eql('undefined');
});
it('window.opener is not null when window.location is changed to a new origin', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
// test relies on preloads in opened window
nodeIntegrationInSubFrames: true
}
});
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
}
}
}));
w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer');
expect(windowOpenerIsNull).to.be.false('window.opener is null');
});
});
});
describe('"disableHtmlFullscreenWindowResize" option', () => {
it('prevents window from resizing when set', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
disableHtmlFullscreenWindowResize: true
}
});
await w.loadURL('about:blank');
const size = w.getSize();
const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen');
w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await enterHtmlFullScreen;
expect(w.getSize()).to.deep.equal(size);
});
});
describe('"defaultFontFamily" option', () => {
it('can change the standard font family', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
defaultFontFamily: {
standard: 'Impact'
}
}
});
await w.loadFile(path.join(fixtures, 'pages', 'content.html'));
const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true);
expect(fontFamily).to.equal('Impact');
});
});
});
describe('beforeunload handler', function () {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(closeAllWindows);
it('returning undefined would not prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('returning false would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('returning empty string would prevent close', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
w.close();
const [, proceed] = await once(w.webContents, 'before-unload-fired');
expect(proceed).to.equal(false);
});
it('emits for each close attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const destroyListener = () => { expect.fail('Close was not prevented'); };
w.webContents.once('destroyed', destroyListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.close();
await once(w.webContents, 'before-unload-fired');
w.close();
await once(w.webContents, 'before-unload-fired');
w.webContents.removeListener('destroyed', destroyListener);
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits for each reload attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.reload();
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.reload();
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
w.reload();
await once(w.webContents, 'did-finish-load');
});
it('emits for each navigation attempt', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
const navigationListener = () => { expect.fail('Reload was not prevented'); };
w.webContents.once('did-start-navigation', navigationListener);
w.webContents.executeJavaScript('installBeforeUnload(2)', true);
// The renderer needs to report the status of beforeunload handler
// back to main process, so wait for next console message, which means
// the SuddenTerminationStatus message have been flushed.
await once(w.webContents, 'console-message');
w.loadURL('about:blank');
// Chromium does not emit 'before-unload-fired' on WebContents for
// navigations, so we have to use other ways to know if beforeunload
// is fired.
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.loadURL('about:blank');
await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
w.webContents.removeListener('did-start-navigation', navigationListener);
await w.loadURL('about:blank');
});
});
describe('document.visibilityState/hidden', () => {
afterEach(closeAllWindows);
it('visibilityState is initially visible despite window being hidden', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let readyToShow = false;
w.once('ready-to-show', () => {
readyToShow = true;
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(readyToShow).to.be.false('ready to show');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.hide();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.show();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
if (process.platform === 'darwin') {
// See https://github.com/electron/electron/issues/8664
await once(w, 'show');
}
w.hide();
w.showInactive();
const [, visibilityState] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
});
// TODO(nornagon): figure out why this is failing on windows
ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
const w = new BrowserWindow({
width: 100,
height: 100,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
w.minimize();
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('hidden');
expect(hidden).to.be.true('hidden');
}
});
// DISABLED-FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
// when we introduced the compositor recycling patch. Should figure out how to fix this
it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
const w = new BrowserWindow({
show: false,
width: 100,
height: 100,
webPreferences: {
backgroundThrottling: false,
nodeIntegration: true
}
});
w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
{
const [, visibilityState, hidden] = await once(ipcMain, 'pong');
expect(visibilityState).to.equal('visible');
expect(hidden).to.be.false('hidden');
}
ipcMain.once('pong', (event, visibilityState, hidden) => {
throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
});
try {
const shown1 = once(w, 'show');
w.show();
await shown1;
const hidden = once(w, 'hide');
w.hide();
await hidden;
const shown2 = once(w, 'show');
w.show();
await shown2;
} finally {
ipcMain.removeAllListeners('pong');
}
});
});
ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
afterEach(closeAllWindows);
it('emits an event when window is maximized', async () => {
const w = new BrowserWindow({ show: false });
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits an event when a transparent window is maximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.show();
w.maximize();
await maximize;
});
it('emits only one event when frameless window is maximized', () => {
const w = new BrowserWindow({ show: false, frame: false });
let emitted = 0;
w.on('maximize', () => emitted++);
w.show();
w.maximize();
expect(emitted).to.equal(1);
});
it('emits an event when window is unmaximized', async () => {
const w = new BrowserWindow({ show: false });
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
w.unmaximize();
await unmaximize;
});
it('emits an event when a transparent window is unmaximized', async () => {
const w = new BrowserWindow({
show: false,
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
const unmaximize = once(w, 'unmaximize');
w.show();
w.maximize();
await maximize;
w.unmaximize();
await unmaximize;
});
it('emits an event when window is minimized', async () => {
const w = new BrowserWindow({ show: false });
const minimize = once(w, 'minimize');
w.show();
w.minimize();
await minimize;
});
});
describe('beginFrameSubscription method', () => {
it('does not crash when callback returns nothing', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function () {
// This callback might be called twice.
if (called) return;
called = true;
// Pending endFrameSubscription to next tick can reliably reproduce
// a crash which happens when nothing is returned in the callback.
setTimeout().then(() => {
w.webContents.endFrameSubscription();
done();
});
});
});
});
it('subscribes to frame updates', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
w.webContents.on('dom-ready', () => {
w.webContents.beginFrameSubscription(function (data) {
// This callback might be called twice.
if (called) return;
called = true;
try {
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
});
it('subscribes to frame updates (only dirty rectangle)', (done) => {
const w = new BrowserWindow({ show: false });
let called = false;
let gotInitialFullSizeFrame = false;
const [contentWidth, contentHeight] = w.getContentSize();
w.webContents.on('did-finish-load', () => {
w.webContents.beginFrameSubscription(true, (image, rect) => {
if (image.isEmpty()) {
// Chromium sometimes sends a 0x0 frame at the beginning of the
// page load.
return;
}
if (rect.height === contentHeight && rect.width === contentWidth &&
!gotInitialFullSizeFrame) {
// The initial frame is full-size, but we're looking for a call
// with just the dirty-rect. The next frame should be a smaller
// rect.
gotInitialFullSizeFrame = true;
return;
}
// This callback might be called twice.
if (called) return;
// We asked for just the dirty rectangle, so we expect to receive a
// rect smaller than the full size.
// TODO(jeremy): this is failing on windows currently; investigate.
// assert(rect.width < contentWidth || rect.height < contentHeight)
called = true;
try {
const expectedSize = rect.width * rect.height * 4;
expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
done();
} catch (e) {
done(e);
} finally {
w.webContents.endFrameSubscription();
}
});
});
w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
});
it('throws error when subscriber is not well defined', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.beginFrameSubscription(true, true as any);
// TODO(zcbenz): gin is weak at guessing parameter types, we should
// upstream native_mate's implementation to gin.
}).to.throw('Error processing argument at index 1, conversion failure from ');
});
});
describe('savePage method', () => {
const savePageDir = path.join(fixtures, 'save_page');
const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
afterEach(() => {
closeAllWindows();
try {
fs.unlinkSync(savePageCssPath);
fs.unlinkSync(savePageJsPath);
fs.unlinkSync(savePageHtmlPath);
fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
fs.rmdirSync(savePageDir);
} catch {}
});
it('should throw when passing relative paths', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await expect(
w.webContents.savePage('save_page.html', 'HTMLComplete')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'HTMLOnly')
).to.eventually.be.rejectedWith('Path must be absolute');
await expect(
w.webContents.savePage('save_page.html', 'MHTML')
).to.eventually.be.rejectedWith('Path must be absolute');
});
it('should save page to disk with HTMLOnly', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
});
it('should save page to disk with MHTML', async () => {
/* Use temp directory for saving MHTML file since the write handle
* gets passed to untrusted process and chromium will deny exec access to
* the path. To perform this task, chromium requires that the path is one
* of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416
*/
const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-'));
const savePageMHTMLPath = path.join(tmpDir, 'save_page.html');
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageMHTMLPath, 'MHTML');
expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
try {
await fs.promises.unlink(savePageMHTMLPath);
await fs.promises.rmdir(tmpDir);
} catch {}
});
it('should save page to disk with HTMLComplete', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
});
});
describe('BrowserWindow options argument is optional', () => {
afterEach(closeAllWindows);
it('should create a window with default size (800x600)', () => {
const w = new BrowserWindow();
expect(w.getSize()).to.deep.equal([800, 600]);
});
});
describe('BrowserWindow.restore()', () => {
afterEach(closeAllWindows);
it('should restore the previous window size', () => {
const w = new BrowserWindow({
minWidth: 800,
width: 800
});
const initialSize = w.getSize();
w.minimize();
w.restore();
expectBoundsEqual(w.getSize(), initialSize);
});
it('does not crash when restoring hidden minimized window', () => {
const w = new BrowserWindow({});
w.minimize();
w.hide();
w.show();
});
// TODO(zcbenz):
// This test does not run on Linux CI. See:
// https://github.com/electron/electron/issues/28699
ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => {
const w = new BrowserWindow({});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.equal(false);
const restore = once(w, 'restore');
w.restore();
await restore;
expect(w.isMaximized()).to.equal(true);
});
});
// TODO(dsanders11): Enable once maximize event works on Linux again on CI
ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
afterEach(closeAllWindows);
it('should show the window if it is not currently shown', async () => {
const w = new BrowserWindow({ show: false });
const hidden = once(w, 'hide');
let shown = once(w, 'show');
const maximize = once(w, 'maximize');
expect(w.isVisible()).to.be.false('visible');
w.maximize();
await maximize;
await shown;
expect(w.isMaximized()).to.be.true('maximized');
expect(w.isVisible()).to.be.true('visible');
// Even if the window is already maximized
w.hide();
await hidden;
expect(w.isVisible()).to.be.false('visible');
shown = once(w, 'show');
w.maximize();
await shown;
expect(w.isVisible()).to.be.true('visible');
});
});
describe('BrowserWindow.unmaximize()', () => {
afterEach(closeAllWindows);
it('should restore the previous window position', () => {
const w = new BrowserWindow();
const initialPosition = w.getPosition();
w.maximize();
w.unmaximize();
expectBoundsEqual(w.getPosition(), initialPosition);
});
// TODO(dsanders11): Enable once minimize event works on Linux again.
// See https://github.com/electron/electron/issues/28699
ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
const w = new BrowserWindow();
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
w.unmaximize();
await setTimeout(1000);
expect(w.isMinimized()).to.be.true();
});
it('should not change the size or position of a normal window', async () => {
const w = new BrowserWindow();
const initialSize = w.getSize();
const initialPosition = w.getPosition();
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getSize(), initialSize);
expectBoundsEqual(w.getPosition(), initialPosition);
});
ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
const { workArea } = screen.getPrimaryDisplay();
const bounds = {
x: workArea.x,
y: workArea.y,
width: workArea.width,
height: workArea.height
};
const w = new BrowserWindow(bounds);
w.unmaximize();
await setTimeout(1000);
expectBoundsEqual(w.getBounds(), bounds);
});
});
describe('setFullScreen(false)', () => {
afterEach(closeAllWindows);
// only applicable to windows: https://github.com/electron/electron/issues/6036
ifdescribe(process.platform === 'win32')('on windows', () => {
it('should restore a normal visible window from a fullscreen startup state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const shown = once(w, 'show');
// start fullscreen and hidden
w.setFullScreen(true);
w.show();
await shown;
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.true('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
it('should keep window hidden if already in hidden state', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const leftFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leftFullScreen;
expect(w.isVisible()).to.be.false('visible');
expect(w.isFullScreen()).to.be.false('fullscreen');
});
});
ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
it('exits HTML fullscreen when window leaves fullscreen', async () => {
const w = new BrowserWindow();
await w.loadURL('about:blank');
await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
await once(w, 'enter-full-screen');
// Wait a tick for the full-screen state to 'stick'
await setTimeout();
w.setFullScreen(false);
await once(w, 'leave-html-full-screen');
});
});
});
describe('parent window', () => {
afterEach(closeAllWindows);
ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
const w = new BrowserWindow();
const sheetBegin = once(w, 'sheet-begin');
// eslint-disable-next-line no-new
new BrowserWindow({
modal: true,
parent: w
});
await sheetBegin;
});
ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
const w = new BrowserWindow();
const sheet = new BrowserWindow({
modal: true,
parent: w
});
const sheetEnd = once(w, 'sheet-end');
sheet.close();
await sheetEnd;
});
describe('parent option', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.getParentWindow()).to.equal(w);
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(w.getChildWindows()).to.deep.equal([c]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
it('can handle child window close and reparent multiple times', async () => {
const w = new BrowserWindow({ show: false });
let c: BrowserWindow | null;
for (let i = 0; i < 5; i++) {
c = new BrowserWindow({ show: false, parent: w });
const closed = once(c, 'closed');
c.close();
await closed;
}
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(w, 'minimize');
w.minimize();
await minimized;
expect(w.isVisible()).to.be.false('parent is visible');
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(w, 'restore');
w.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
const wShow = once(w, 'show');
const cShow = once(c, 'show');
w.show();
c.show();
await Promise.all([wShow, cShow]);
const minimized = once(c, 'minimize');
c.minimize();
await minimized;
expect(c.isVisible()).to.be.false('child is visible');
const restored = once(c, 'restore');
c.restore();
await restored;
expect(w.isVisible()).to.be.true('parent is visible');
expect(c.isVisible()).to.be.true('child is visible');
});
it('closes a grandchild window when a middle child window is destroyed', (done) => {
const w = new BrowserWindow();
w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
w.webContents.executeJavaScript('window.open("")');
w.webContents.on('did-create-window', async (window) => {
const childWindow = new BrowserWindow({ parent: window });
await setTimeout();
window.close();
childWindow.on('closed', () => {
expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
done();
});
});
});
it('should not affect the show option', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w });
expect(c.isVisible()).to.be.false('child is visible');
expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
});
});
describe('win.setParentWindow(parent)', () => {
it('sets parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getParentWindow()).to.be.null('w.parent');
expect(c.getParentWindow()).to.be.null('c.parent');
c.setParentWindow(w);
expect(c.getParentWindow()).to.equal(w);
c.setParentWindow(null);
expect(c.getParentWindow()).to.be.null('c.parent');
});
it('adds window to child windows of parent', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
expect(w.getChildWindows()).to.deep.equal([]);
c.setParentWindow(w);
expect(w.getChildWindows()).to.deep.equal([c]);
c.setParentWindow(null);
expect(w.getChildWindows()).to.deep.equal([]);
});
it('removes from child windows of parent when window is closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false });
const closed = once(c, 'closed');
c.setParentWindow(w);
c.close();
await closed;
// The child window list is not immediately cleared, so wait a tick until it's ready.
await setTimeout();
expect(w.getChildWindows().length).to.equal(0);
});
});
describe('modal option', () => {
it('does not freeze or crash', async () => {
const parentWindow = new BrowserWindow();
const createTwo = async () => {
const two = new BrowserWindow({
width: 300,
height: 200,
parent: parentWindow,
modal: true,
show: false
});
const twoShown = once(two, 'show');
two.show();
await twoShown;
setTimeout(500).then(() => two.close());
await once(two, 'closed');
};
const one = new BrowserWindow({
width: 600,
height: 400,
parent: parentWindow,
modal: true,
show: false
});
const oneShown = once(one, 'show');
one.show();
await oneShown;
setTimeout(500).then(() => one.destroy());
await once(one, 'closed');
await createTwo();
});
ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
const w = new BrowserWindow({ show: false });
w.setEnabled(false);
expect(w.isEnabled()).to.be.false('w.isEnabled()');
w.setEnabled(true);
expect(w.isEnabled()).to.be.true('!w.isEnabled()');
});
ifit(process.platform !== 'darwin')('disables parent window', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
expect(w.isEnabled()).to.be.true('w.isEnabled');
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const closed = once(c, 'closed');
w.setEnabled(false);
c.show();
c.close();
await closed;
expect(w.isEnabled()).to.be.false('w.isEnabled');
});
ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
const w = new BrowserWindow({ show: false });
const c = new BrowserWindow({ show: false, parent: w, modal: true });
const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
c.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.show();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c.destroy();
expect(w.isEnabled()).to.be.false('w.isEnabled');
c2.destroy();
expect(w.isEnabled()).to.be.true('w.isEnabled');
});
});
});
describe('window states', () => {
afterEach(closeAllWindows);
it('does not resize frameless windows when states change', () => {
const w = new BrowserWindow({
frame: false,
width: 300,
height: 200,
show: false
});
w.minimizable = false;
w.minimizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.resizable = false;
w.resizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.maximizable = false;
w.maximizable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.fullScreenable = false;
w.fullScreenable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
w.closable = false;
w.closable = true;
expect(w.getSize()).to.deep.equal([300, 200]);
});
describe('resizable state', () => {
it('with properties', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.resizable).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.maximizable).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
w.resizable = false;
expect(w.resizable).to.be.false('resizable');
w.resizable = true;
expect(w.resizable).to.be.true('resizable');
});
});
it('with functions', () => {
it('can be set with resizable constructor option', () => {
const w = new BrowserWindow({ show: false, resizable: false });
expect(w.isResizable()).to.be.false('resizable');
if (process.platform === 'darwin') {
expect(w.isMaximizable()).to.to.true('maximizable');
}
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isResizable()).to.be.true('resizable');
w.setResizable(false);
expect(w.isResizable()).to.be.false('resizable');
w.setResizable(true);
expect(w.isResizable()).to.be.true('resizable');
});
});
it('works for a frameless window', () => {
const w = new BrowserWindow({ show: false, frame: false });
expect(w.resizable).to.be.true('resizable');
if (process.platform === 'win32') {
const w = new BrowserWindow({ show: false, thickFrame: false });
expect(w.resizable).to.be.false('resizable');
}
});
// On Linux there is no "resizable" property of a window.
ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
const w = new BrowserWindow({ show: false });
expect(w.resizable).to.be.true('resizable');
expect(w.maximizable).to.be.true('maximizable');
w.resizable = false;
expect(w.maximizable).to.be.false('not maximizable');
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
const w = new BrowserWindow({
show: false,
frame: false,
resizable: false,
transparent: true
});
w.setContentSize(60, 60);
expectBoundsEqual(w.getContentSize(), [60, 60]);
w.setContentSize(30, 30);
expectBoundsEqual(w.getContentSize(), [30, 30]);
w.setContentSize(10, 10);
expectBoundsEqual(w.getContentSize(), [10, 10]);
});
});
describe('loading main frame state', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is true when the main frame is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(serverUrl);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
it('is false when only a subframe is loading', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/page2'
document.body.appendChild(iframe)
`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
});
it('is true when navigating to pages from the same origin', async () => {
const w = new BrowserWindow({ show: false });
const didStopLoading = once(w.webContents, 'did-stop-loading');
w.webContents.loadURL(serverUrl);
await didStopLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
const didStartLoading = once(w.webContents, 'did-start-loading');
w.webContents.loadURL(`${serverUrl}/page2`);
await didStartLoading;
expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
});
});
});
ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
// Not implemented on Linux.
afterEach(closeAllWindows);
describe('movable state', () => {
it('with properties', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.movable).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.movable).to.be.true('movable');
w.movable = false;
expect(w.movable).to.be.false('movable');
w.movable = true;
expect(w.movable).to.be.true('movable');
});
});
it('with functions', () => {
it('can be set with movable constructor option', () => {
const w = new BrowserWindow({ show: false, movable: false });
expect(w.isMovable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMovable()).to.be.true('movable');
w.setMovable(false);
expect(w.isMovable()).to.be.false('movable');
w.setMovable(true);
expect(w.isMovable()).to.be.true('movable');
});
});
});
describe('visibleOnAllWorkspaces state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.visibleOnAllWorkspaces).to.be.false();
w.visibleOnAllWorkspaces = true;
expect(w.visibleOnAllWorkspaces).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isVisibleOnAllWorkspaces()).to.be.false();
w.setVisibleOnAllWorkspaces(true);
expect(w.isVisibleOnAllWorkspaces()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.documentEdited).to.be.false();
w.documentEdited = true;
expect(w.documentEdited).to.be.true();
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isDocumentEdited()).to.be.false();
w.setDocumentEdited(true);
expect(w.isDocumentEdited()).to.be.true();
});
});
});
ifdescribe(process.platform === 'darwin')('representedFilename', () => {
it('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.representedFilename).to.eql('');
w.representedFilename = 'a name';
expect(w.representedFilename).to.eql('a name');
});
});
it('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getRepresentedFilename()).to.eql('');
w.setRepresentedFilename('a name');
expect(w.getRepresentedFilename()).to.eql('a name');
});
});
});
describe('native window title', () => {
it('with properties', () => {
it('can be set with title constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.title).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.title).to.eql('Electron Test Main');
w.title = 'NEW TITLE';
expect(w.title).to.eql('NEW TITLE');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
expect(w.getTitle()).to.eql('mYtItLe');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.getTitle()).to.eql('Electron Test Main');
w.setTitle('NEW TITLE');
expect(w.getTitle()).to.eql('NEW TITLE');
});
});
});
describe('minimizable state', () => {
it('with properties', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.minimizable).to.be.false('minimizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.minimizable).to.be.true('minimizable');
w.minimizable = false;
expect(w.minimizable).to.be.false('minimizable');
w.minimizable = true;
expect(w.minimizable).to.be.true('minimizable');
});
});
it('with functions', () => {
it('can be set with minimizable constructor option', () => {
const w = new BrowserWindow({ show: false, minimizable: false });
expect(w.isMinimizable()).to.be.false('movable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMinimizable()).to.be.true('isMinimizable');
w.setMinimizable(false);
expect(w.isMinimizable()).to.be.false('isMinimizable');
w.setMinimizable(true);
expect(w.isMinimizable()).to.be.true('isMinimizable');
});
});
});
describe('maximizable state (property)', () => {
it('with properties', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.maximizable).to.be.false('maximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.maximizable).to.be.true('maximizable');
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.minimizable = false;
expect(w.maximizable).to.be.false('maximizable');
w.closable = false;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
expect(w.maximizable).to.be.true('maximizable');
w.closable = true;
expect(w.maximizable).to.be.true('maximizable');
w.fullScreenable = false;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('can be set with maximizable constructor option', () => {
const w = new BrowserWindow({ show: false, maximizable: false });
expect(w.isMaximizable()).to.be.false('isMaximizable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
it('is not affected when changing other states', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMinimizable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setClosable(false);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setClosable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
w.setFullScreenable(false);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform === 'win32')('maximizable state', () => {
it('with properties', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.maximizable = false;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.false('maximizable');
w.maximizable = true;
w.resizable = false;
w.resizable = true;
expect(w.maximizable).to.be.true('maximizable');
});
});
it('with functions', () => {
it('is reset to its former state', () => {
const w = new BrowserWindow({ show: false });
w.setMaximizable(false);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.false('isMaximizable');
w.setMaximizable(true);
w.setResizable(false);
w.setResizable(true);
expect(w.isMaximizable()).to.be.true('isMaximizable');
});
});
});
ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
describe('with properties', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.menuBarVisible).to.be.true();
w.menuBarVisible = false;
expect(w.menuBarVisible).to.be.false();
w.menuBarVisible = true;
expect(w.menuBarVisible).to.be.true();
});
});
describe('with functions', () => {
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
w.setMenuBarVisibility(false);
expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
w.setMenuBarVisibility(true);
expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
it('with functions', () => {
it('can be set with fullscreenable constructor option', () => {
const w = new BrowserWindow({ show: false, fullscreenable: false });
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
w.setFullScreenable(false);
expect(w.isFullScreenable()).to.be.false('isFullScreenable');
w.setFullScreenable(true);
expect(w.isFullScreenable()).to.be.true('isFullScreenable');
});
});
});
ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => {
it('with functions', () => {
it('can be set with ignoreMissionControl constructor option', () => {
const w = new BrowserWindow({ show: false, hiddenInMissionControl: true });
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
w.setHiddenInMissionControl(true);
expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
w.setHiddenInMissionControl(false);
expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
});
});
});
// fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
ifdescribe(process.platform === 'darwin')('kiosk state', () => {
it('with properties', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.kiosk).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.kiosk = true;
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.kiosk = false;
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
it('with functions', () => {
it('can be set with a constructor property', () => {
const w = new BrowserWindow({ kiosk: true });
expect(w.isKiosk()).to.be.true();
});
it('can be changed ', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
expect(w.isKiosk()).to.be.true('isKiosk');
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
expect(w.isKiosk()).to.be.false('isKiosk');
await leaveFullScreen;
});
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
it('resizable flag should be set to false and restored', async () => {
const w = new BrowserWindow({ resizable: false });
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.false('resizable');
});
it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.resizable).to.be.false('resizable');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.resizable).to.be.true('resizable');
});
});
ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
it('should not cause a crash if called when exiting fullscreen', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('should be able to load a URL while transitioning to fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true });
w.loadFile(path.join(fixtures, 'pages', 'c.html'));
const load = once(w.webContents, 'did-finish-load');
const enterFS = once(w, 'enter-full-screen');
await Promise.all([enterFS, load]);
expect(w.fullScreen).to.be.true();
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
});
it('can be changed with setFullScreen method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('handles several transitions starting with fullscreen', async () => {
const w = new BrowserWindow({ fullscreen: true, show: true });
expect(w.isFullScreen()).to.be.true('not fullscreen');
w.setFullScreen(false);
w.setFullScreen(true);
const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('not fullscreen');
await setTimeout();
const leaveFullScreen = once(w, 'leave-full-screen');
w.setFullScreen(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several HTML fullscreen transitions', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFullScreen = once(w, 'enter-full-screen');
const leaveFullScreen = once(w, 'leave-full-screen');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
await setTimeout();
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await enterFullScreen;
await w.webContents.executeJavaScript('document.exitFullscreen()', true);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('is fullscreen');
});
it('handles several transitions in close proximity', async () => {
const w = new BrowserWindow();
expect(w.isFullScreen()).to.be.false('is fullscreen');
const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
w.setFullScreen(true);
w.setFullScreen(false);
w.setFullScreen(true);
w.setFullScreen(false);
await Promise.all([enterFS, leaveFS]);
expect(w.isFullScreen()).to.be.false('not fullscreen');
});
it('handles several chromium-initiated transitions in close proximity', async () => {
const w = new BrowserWindow();
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>(resolve => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', () => {
enterCount++;
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await done;
});
it('handles HTML fullscreen transitions when fullscreenable is false', async () => {
const w = new BrowserWindow({ fullscreenable: false });
await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
expect(w.isFullScreen()).to.be.false('is fullscreen');
let enterCount = 0;
let exitCount = 0;
const done = new Promise<void>((resolve, reject) => {
const checkDone = () => {
if (enterCount === 2 && exitCount === 2) resolve();
};
w.webContents.on('enter-html-full-screen', async () => {
enterCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement');
if (!isFS) reject(new Error('Document should have fullscreen element'));
checkDone();
});
w.webContents.on('leave-html-full-screen', () => {
exitCount++;
if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
checkDone();
});
});
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
await w.webContents.executeJavaScript('document.exitFullscreen()');
await expect(done).to.eventually.be.fulfilled();
});
it('does not crash when exiting simpleFullScreen (properties)', async () => {
const w = new BrowserWindow();
w.setSimpleFullScreen(true);
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('does not crash when exiting simpleFullScreen (functions)', async () => {
const w = new BrowserWindow();
w.simpleFullScreen = true;
await setTimeout(1000);
w.setFullScreen(!w.isFullScreen());
});
it('should not be changed by setKiosk method', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setKiosk(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
const leaveFullScreen = once(w, 'leave-full-screen');
w.setKiosk(false);
await leaveFullScreen;
expect(w.isFullScreen()).to.be.false('isFullScreen');
});
it('should stay fullscreen if fullscreen before kiosk', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
w.setKiosk(true);
w.setKiosk(false);
// Wait enough time for a fullscreen change to take effect.
await setTimeout(2000);
expect(w.isFullScreen()).to.be.true('isFullScreen');
});
it('multiple windows inherit correct fullscreen state', async () => {
const w = new BrowserWindow();
const enterFullScreen = once(w, 'enter-full-screen');
w.setFullScreen(true);
await enterFullScreen;
expect(w.isFullScreen()).to.be.true('isFullScreen');
await setTimeout(1000);
const w2 = new BrowserWindow({ show: false });
const enterFullScreen2 = once(w2, 'enter-full-screen');
w2.show();
await enterFullScreen2;
expect(w2.isFullScreen()).to.be.true('isFullScreen');
});
});
describe('closable state', () => {
it('with properties', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.closable).to.be.false('closable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.closable).to.be.true('closable');
w.closable = false;
expect(w.closable).to.be.false('closable');
w.closable = true;
expect(w.closable).to.be.true('closable');
});
});
it('with functions', () => {
it('can be set with closable constructor option', () => {
const w = new BrowserWindow({ show: false, closable: false });
expect(w.isClosable()).to.be.false('isClosable');
});
it('can be changed', () => {
const w = new BrowserWindow({ show: false });
expect(w.isClosable()).to.be.true('isClosable');
w.setClosable(false);
expect(w.isClosable()).to.be.false('isClosable');
w.setClosable(true);
expect(w.isClosable()).to.be.true('isClosable');
});
});
});
describe('hasShadow state', () => {
it('with properties', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
expect(w.shadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.shadow).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
w.shadow = true;
expect(w.shadow).to.be.true('hasShadow');
w.shadow = false;
expect(w.shadow).to.be.false('hasShadow');
});
});
describe('with functions', () => {
it('returns a boolean on all platforms', () => {
const w = new BrowserWindow({ show: false });
const hasShadow = w.hasShadow();
expect(hasShadow).to.be.a('boolean');
});
// On Windows there's no shadow by default & it can't be changed dynamically.
it('can be changed with hasShadow option', () => {
const hasShadow = process.platform !== 'darwin';
const w = new BrowserWindow({ show: false, hasShadow });
expect(w.hasShadow()).to.equal(hasShadow);
});
it('can be changed with setHasShadow method', () => {
const w = new BrowserWindow({ show: false });
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
w.setHasShadow(true);
expect(w.hasShadow()).to.be.true('hasShadow');
w.setHasShadow(false);
expect(w.hasShadow()).to.be.false('hasShadow');
});
});
});
});
describe('window.getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns valid source id', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
// Check format 'window:1234:0'.
const sourceId = w.getMediaSourceId();
expect(sourceId).to.match(/^window:\d+:\d+$/);
});
});
ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
afterEach(closeAllWindows);
it('returns valid handle', () => {
const w = new BrowserWindow({ show: false });
// The module's source code is hosted at
// https://github.com/electron/node-is-valid-window
const isValidWindow = require('is-valid-window');
expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
});
});
ifdescribe(process.platform === 'darwin')('previewFile', () => {
afterEach(closeAllWindows);
it('opens the path in Quick Look on macOS', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.previewFile(__filename);
w.closeFilePreview();
}).to.not.throw();
});
it('should not call BrowserWindow show event', async () => {
const w = new BrowserWindow({ show: false });
const shown = once(w, 'show');
w.show();
await shown;
let showCalled = false;
w.on('show', () => {
showCalled = true;
});
w.previewFile(__filename);
await setTimeout(500);
expect(showCalled).to.equal(false, 'should not have called show twice');
});
});
// TODO (jkleinsc) renable these tests on mas arm64
ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
const expectedContextData = {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
};
afterEach(closeAllWindows);
it('separates the page context from the Electron/preload context', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
iw.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('enables context isolation on child windows', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const browserWindowCreated = once(app, 'browser-window-created');
iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
const [, window] = await browserWindowCreated;
expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
});
it('separates the page context from the Electron/preload context with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const [, data] = await p;
expect(data).to.deep.equal(expectedContextData);
});
it('recreates the contexts on reload with sandbox on', async () => {
const ws = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
const isolatedWorld = once(ipcMain, 'isolated-world');
ws.webContents.reload();
const [, data] = await isolatedWorld;
expect(data).to.deep.equal(expectedContextData);
});
it('supports fetch api', async () => {
const fetchWindow = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
}
});
const p = once(ipcMain, 'isolated-fetch-error');
fetchWindow.loadURL('about:blank');
const [, error] = await p;
expect(error).to.equal('Failed to fetch');
});
it('doesn\'t break ipc serialization', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-preload.js')
}
});
const p = once(ipcMain, 'isolated-world');
iw.loadURL('about:blank');
iw.webContents.executeJavaScript(`
const opened = window.open()
openedLocation = opened.location.href
opened.close()
window.postMessage({openedLocation}, '*')
`);
const [, data] = await p;
expect(data.pageContext.openedLocation).to.equal('about:blank');
});
it('reports process.contextIsolated', async () => {
const iw = new BrowserWindow({
show: false,
webPreferences: {
contextIsolation: true,
preload: path.join(fixtures, 'api', 'isolated-process.js')
}
});
const p = once(ipcMain, 'context-isolation');
iw.loadURL('about:blank');
const [, contextIsolation] = await p;
expect(contextIsolation).to.be.true('contextIsolation');
});
});
it('reloading does not cause Node.js module API hangs after reload', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
let count = 0;
ipcMain.on('async-node-api-done', () => {
if (count === 3) {
ipcMain.removeAllListeners('async-node-api-done');
done();
} else {
count++;
w.reload();
}
});
w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
});
describe('window.webContents.focus()', () => {
afterEach(closeAllWindows);
it('focuses window', async () => {
const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
w1.loadURL('about:blank');
const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
w2.loadURL('about:blank');
const w1Focused = once(w1, 'focus');
w1.webContents.focus();
await w1Focused;
expect(w1.webContents.isFocused()).to.be.true('focuses window');
});
});
ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
let w: BrowserWindow;
beforeEach(function () {
w = new BrowserWindow({
width: 100,
height: 100,
show: false,
webPreferences: {
backgroundThrottling: false,
offscreen: true
}
});
});
afterEach(closeAllWindows);
it('creates offscreen window with correct size', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
const [,, data] = await paint;
expect(data.constructor.name).to.equal('NativeImage');
expect(data.isEmpty()).to.be.false('data is empty');
const size = data.getSize();
const { scaleFactor } = screen.getPrimaryDisplay();
expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
});
it('does not crash after navigation', () => {
w.webContents.loadURL('about:blank');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
});
describe('window.webContents.isOffscreen()', () => {
it('is true for offscreen type', () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
});
it('is false for regular window', () => {
const c = new BrowserWindow({ show: false });
expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
c.destroy();
});
});
describe('window.webContents.isPainting()', () => {
it('returns whether is currently painting', async () => {
const paint = once(w.webContents, 'paint');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await paint;
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('window.webContents.stopPainting()', () => {
it('stops painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
expect(w.webContents.isPainting()).to.be.false('isPainting');
});
});
describe('window.webContents.startPainting()', () => {
it('starts painting', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.stopPainting();
w.webContents.startPainting();
await once(w.webContents, 'paint');
expect(w.webContents.isPainting()).to.be.true('isPainting');
});
});
describe('frameRate APIs', () => {
it('has default frame rate (function)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(60);
});
it('has default frame rate (property)', async () => {
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(60);
});
it('sets custom frame rate (function)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.setFrameRate(30);
await once(w.webContents, 'paint');
expect(w.webContents.getFrameRate()).to.equal(30);
});
it('sets custom frame rate (property)', async () => {
const domReady = once(w.webContents, 'dom-ready');
w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
await domReady;
w.webContents.frameRate = 30;
await once(w.webContents, 'paint');
expect(w.webContents.frameRate).to.equal(30);
});
});
});
describe('"transparent" option', () => {
afterEach(closeAllWindows);
ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => {
const w = new BrowserWindow({
frame: false,
transparent: true
});
const maximize = once(w, 'maximize');
w.maximize();
await maximize;
const minimize = once(w, 'minimize');
w.minimize();
await minimize;
expect(w.isMaximized()).to.be.false();
expect(w.isMinimized()).to.be.true();
});
// Only applicable on Windows where transparent windows can't be maximized.
ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
show: true
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
expect(w.isMaximized()).to.be.true();
// Fails when the transparent HWND is in an invalid maximized state.
expect(w.getBounds()).to.deep.equal(display.workArea);
const newBounds = { width: 256, height: 256, x: 0, y: 0 };
w.setBounds(newBounds);
expect(w.getBounds()).to.deep.equal(newBounds);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.GREEN,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
show: true,
transparent: true,
frame: false,
hasShadow: false
});
const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html');
await foregroundWindow.loadFile(colorFile);
await setTimeout(1000);
const screenCapture = await captureScreen();
const leftHalfColor = getPixelColor(screenCapture, {
x: display.size.width / 4,
y: display.size.height / 2
});
const rightHalfColor = getPixelColor(screenCapture, {
x: display.size.width - (display.size.width / 4),
y: display.size.height / 2
});
expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true();
expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true();
});
ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => {
const display = screen.getPrimaryDisplay();
const backgroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
backgroundColor: HexColors.PURPLE,
hasShadow: false
});
await backgroundWindow.loadURL('about:blank');
const foregroundWindow = new BrowserWindow({
...display.bounds,
frame: false,
transparent: true,
hasShadow: false,
webPreferences: {
contextIsolation: false,
nodeIntegration: true
}
});
foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html'));
await once(ipcMain, 'set-transparent');
await setTimeout();
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => {
const display = screen.getPrimaryDisplay();
for (const transparent of [false, undefined]) {
const window = new BrowserWindow({
...display.bounds,
transparent
});
await once(window, 'show');
await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>');
await setTimeout(500);
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
window.close();
// color-scheme is set to dark so background should not be white
expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false();
}
});
});
describe('"backgroundColor" option', () => {
afterEach(closeAllWindows);
// Linux/WOA doesn't return any capture sources.
ifit(process.platform === 'darwin')('should display the set color', async () => {
const display = screen.getPrimaryDisplay();
const w = new BrowserWindow({
...display.bounds,
show: true,
backgroundColor: HexColors.BLUE
});
w.loadURL('about:blank');
await once(w, 'ready-to-show');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true();
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
docs/tutorial/window-customization.md
|
# Window Customization
The `BrowserWindow` module is the foundation of your Electron application, and it exposes
many APIs that can change the look and behavior of your browser windows. In this
tutorial, we will be going over the various use-cases for window customization on
macOS, Windows, and Linux.
## Create frameless windows
A frameless window is a window that has no [chrome][]. Not to be confused with the Google
Chrome browser, window _chrome_ refers to the parts of the window (e.g. toolbars, controls)
that are not a part of the web page.
To create a frameless window, you need to set `frame` to `false` in the `BrowserWindow`
constructor.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ frame: false })
```
## Apply custom title bar styles _macOS_ _Windows_
Title bar styles allow you to hide most of a BrowserWindow's chrome while keeping the
system's native window controls intact and can be configured with the `titleBarStyle`
option in the `BrowserWindow` constructor.
Applying the `hidden` title bar style results in a hidden title bar and a full-size
content window.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'hidden' })
```
### Control the traffic lights _macOS_
On macOS, applying the `hidden` title bar style will still expose the standard window
controls (“traffic lights”) in the top left.
#### Customize the look of your traffic lights _macOS_
The `customButtonsOnHover` title bar style will hide the traffic lights until you hover
over them. This is useful if you want to create custom traffic lights in your HTML but still
use the native UI to control the window.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'customButtonsOnHover' })
```
#### Customize the traffic light position _macOS_
To modify the position of the traffic light window controls, there are two configuration
options available.
Applying `hiddenInset` title bar style will shift the vertical inset of the traffic lights
by a fixed amount.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'hiddenInset' })
```
If you need more granular control over the positioning of the traffic lights, you can pass
a set of coordinates to the `trafficLightPosition` option in the `BrowserWindow`
constructor.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
trafficLightPosition: { x: 10, y: 10 }
})
```
#### Show and hide the traffic lights programmatically _macOS_
You can also show and hide the traffic lights programmatically from the main process.
The `win.setWindowButtonVisibility` forces traffic lights to be show or hidden depending
on the value of its boolean parameter.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
// hides the traffic lights
win.setWindowButtonVisibility(false)
```
> Note: Given the number of APIs available, there are many ways of achieving this. For instance,
> combining `frame: false` with `win.setWindowButtonVisibility(true)` will yield the same
> layout outcome as setting `titleBarStyle: 'hidden'`.
## Window Controls Overlay _macOS_ _Windows_
The [Window Controls Overlay API][] is a web standard that gives web apps the ability to
customize their title bar region when installed on desktop. Electron exposes this API
through the `BrowserWindow` constructor option `titleBarOverlay`.
This option only works whenever a custom `titlebarStyle` is applied on macOS or Windows.
When `titleBarOverlay` is enabled, the window controls become exposed in their default
position, and DOM elements cannot use the area underneath this region.
The `titleBarOverlay` option accepts two different value formats.
Specifying `true` on either platform will result in an overlay region with default
system colors:
```javascript title='main.js'
// on macOS or Windows
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
titleBarOverlay: true
})
```
On either platform `titleBarOverlay` can also be an object. On both macOS and Windows, the height of the overlay can be specified with the `height` property. On Windows, the color of the overlay and its symbols can be specified using the `color` and `symbolColor` properties respectively.
If a color option is not specified, the color will default to its system color for the window control buttons. Similarly, if the height option is not specified it will default to the default height:
```javascript title='main.js'
// on Windows
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#2f3241',
symbolColor: '#74b1be',
height: 60
}
})
```
> Note: Once your title bar overlay is enabled from the main process, you can access the overlay's
> color and dimension values from a renderer using a set of readonly
> [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars].
### Limitations
* Transparent colors are currently not supported. Progress updates for this feature can be found in PR [#33567](https://github.com/electron/electron/issues/33567).
## Create transparent windows
By setting the `transparent` option to `true`, you can make a fully transparent window.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ transparent: true })
```
### Limitations
* You cannot click through the transparent area. See
[#1335](https://github.com/electron/electron/issues/1335) for details.
* Transparent windows are not resizable. Setting `resizable` to `true` may make
a transparent window stop working on some platforms.
* The CSS [`blur()`][] filter only applies to the window's web contents, so there is no way to apply
blur effect to the content below the window (i.e. other applications open on
the user's system).
* The window will not be transparent when DevTools is opened.
* On _Windows_:
* Transparent windows will not work when DWM is disabled.
* Transparent windows can not be maximized using the Windows system menu or by double
clicking the title bar. The reasoning behind this can be seen on
PR [#28207](https://github.com/electron/electron/pull/28207).
* On _macOS_:
* The native window shadow will not be shown on a transparent window.
## Create click-through windows
To create a click-through window, i.e. making the window ignore all mouse
events, you can call the [win.setIgnoreMouseEvents(ignore)][ignore-mouse-events]
API:
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.setIgnoreMouseEvents(true)
```
### Forward mouse events _macOS_ _Windows_
Ignoring mouse messages makes the web contents oblivious to mouse movement,
meaning that mouse movement events will not be emitted. On Windows and macOS, an
optional parameter can be used to forward mouse move messages to the web page,
allowing events such as `mouseleave` to be emitted:
```javascript title='main.js'
const { BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
ipcMain.on('set-ignore-mouse-events', (event, ignore, options) => {
const win = BrowserWindow.fromWebContents(event.sender)
win.setIgnoreMouseEvents(ignore, options)
})
```
```javascript title='preload.js'
window.addEventListener('DOMContentLoaded', () => {
const el = document.getElementById('clickThroughElement')
el.addEventListener('mouseenter', () => {
ipcRenderer.send('set-ignore-mouse-events', true, { forward: true })
})
el.addEventListener('mouseleave', () => {
ipcRenderer.send('set-ignore-mouse-events', false)
})
})
```
This makes the web page click-through when over the `#clickThroughElement` element,
and returns to normal outside it.
## Set custom draggable region
By default, the frameless window is non-draggable. Apps need to specify
`-webkit-app-region: drag` in CSS to tell Electron which regions are draggable
(like the OS's standard titlebar), and apps can also use
`-webkit-app-region: no-drag` to exclude the non-draggable area from the
draggable region. Note that only rectangular shapes are currently supported.
To make the whole window draggable, you can add `-webkit-app-region: drag` as
`body`'s style:
```css title='styles.css'
body {
-webkit-app-region: drag;
}
```
And note that if you have made the whole window draggable, you must also mark
buttons as non-draggable, otherwise it would be impossible for users to click on
them:
```css title='styles.css'
button {
-webkit-app-region: no-drag;
}
```
If you're only setting a custom titlebar as draggable, you also need to make all
buttons in titlebar non-draggable.
### Tip: disable text selection
When creating a draggable region, the dragging behavior may conflict with text selection.
For example, when you drag the titlebar, you may accidentally select its text contents.
To prevent this, you need to disable text selection within a draggable area like this:
```css
.titlebar {
-webkit-user-select: none;
-webkit-app-region: drag;
}
```
### Tip: disable context menus
On some platforms, the draggable area will be treated as a non-client frame, so
when you right click on it, a system menu will pop up. To make the context menu
behave correctly on all platforms, you should never use a custom context menu on
draggable areas.
[`blur()`]: https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/blur()
[chrome]: https://developer.mozilla.org/en-US/docs/Glossary/Chrome
[ignore-mouse-events]: ../api/browser-window.md#winsetignoremouseeventsignore-options
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
[Window Controls Overlay API]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
shell/browser/ui/views/win_caption_button_container.cc
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Modified from
// chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc
#include "shell/browser/ui/views/win_caption_button_container.h"
#include <memory>
#include <utility>
#include "shell/browser/ui/views/win_caption_button.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/view_class_properties.h"
namespace electron {
namespace {
std::unique_ptr<WinCaptionButton> CreateCaptionButton(
views::Button::PressedCallback callback,
WinFrameView* frame_view,
ViewID button_type,
int accessible_name_resource_id) {
return std::make_unique<WinCaptionButton>(
std::move(callback), frame_view, button_type,
l10n_util::GetStringUTF16(accessible_name_resource_id));
}
bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) {
return button && button->GetVisible() && button->bounds().Contains(point);
}
} // anonymous namespace
WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view)
: frame_view_(frame_view),
minimize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Minimize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MINIMIZE_BUTTON,
IDS_APP_ACCNAME_MINIMIZE))),
maximize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Maximize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MAXIMIZE_BUTTON,
IDS_APP_ACCNAME_MAXIMIZE))),
restore_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Restore,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_RESTORE_BUTTON,
IDS_APP_ACCNAME_RESTORE))),
close_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::CloseWithReason,
base::Unretained(frame_view_->frame()),
views::Widget::ClosedReason::kCloseButtonClicked),
frame_view_,
VIEW_ID_CLOSE_BUTTON,
IDS_APP_ACCNAME_CLOSE))) {
// Layout is horizontal, with buttons placed at the trailing end of the view.
// This allows the container to expand to become a faux titlebar/drag handle.
auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetMainAxisAlignment(views::LayoutAlignment::kEnd)
.SetCrossAxisAlignment(views::LayoutAlignment::kStart)
.SetDefault(
views::kFlexBehaviorKey,
views::FlexSpecification(views::LayoutOrientation::kHorizontal,
views::MinimumFlexSizeRule::kPreferred,
views::MaximumFlexSizeRule::kPreferred,
/* adjust_width_for_height */ false,
views::MinimumFlexSizeRule::kScaleToZero));
}
WinCaptionButtonContainer::~WinCaptionButtonContainer() {}
int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const {
DCHECK(HitTestPoint(point))
<< "should only be called with a point inside this view's bounds";
if (HitTestCaptionButton(minimize_button_, point)) {
return HTMINBUTTON;
}
if (HitTestCaptionButton(maximize_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(restore_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(close_button_, point)) {
return HTCLOSE;
}
return HTCAPTION;
}
gfx::Size WinCaptionButtonContainer::GetButtonSize() const {
// Close button size is set the same as all the buttons
return close_button_->GetSize();
}
void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) {
minimize_button_->SetSize(size);
maximize_button_->SetSize(size);
restore_button_->SetSize(size);
close_button_->SetSize(size);
}
void WinCaptionButtonContainer::ResetWindowControls() {
minimize_button_->SetState(views::Button::STATE_NORMAL);
maximize_button_->SetState(views::Button::STATE_NORMAL);
restore_button_->SetState(views::Button::STATE_NORMAL);
close_button_->SetState(views::Button::STATE_NORMAL);
InvalidateLayout();
}
void WinCaptionButtonContainer::AddedToWidget() {
views::Widget* const widget = GetWidget();
DCHECK(!widget_observation_.IsObserving());
widget_observation_.Observe(widget);
UpdateButtons();
if (frame_view_->window()->IsWindowControlsOverlayEnabled()) {
SetBackground(views::CreateSolidBackground(
frame_view_->window()->overlay_button_color()));
SetPaintToLayer();
}
}
void WinCaptionButtonContainer::RemovedFromWidget() {
DCHECK(widget_observation_.IsObserving());
widget_observation_.Reset();
}
void WinCaptionButtonContainer::OnWidgetBoundsChanged(
views::Widget* widget,
const gfx::Rect& new_bounds) {
UpdateButtons();
}
void WinCaptionButtonContainer::UpdateButtons() {
const bool is_maximized = frame_view_->frame()->IsMaximized();
restore_button_->SetVisible(is_maximized);
maximize_button_->SetVisible(!is_maximized);
const bool minimizable = frame_view_->window()->IsMinimizable();
minimize_button_->SetEnabled(minimizable);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled.
const bool is_touch = ui::TouchUiController::Get()->touch_ui();
restore_button_->SetEnabled(!is_touch);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled, unless the window is not
// maximized.
const bool maximizable = frame_view_->window()->IsMaximizable();
maximize_button_->SetEnabled(!(is_touch && is_maximized) && maximizable);
const bool closable = frame_view_->window()->IsClosable();
close_button_->SetEnabled(closable);
// If all three of closable, maximizable, and minimizable are disabled,
// Windows natively only shows the disabled closable button. Copy that
// behavior here.
if (!maximizable && !closable && !minimizable) {
minimize_button_->SetVisible(false);
maximize_button_->SetVisible(false);
}
InvalidateLayout();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
shell/browser/ui/views/win_caption_button_container.h
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Modified from
// chrome/browser/ui/views/frame/glass_browser_caption_button_container.h
#ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
#define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
#include "base/scoped_observation.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/pointer/touch_ui_controller.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace electron {
class WinFrameView;
class WinCaptionButton;
// Provides a container for Windows 10 caption buttons that can be moved between
// frame and browser window as needed. When extended horizontally, becomes a
// grab bar for moving the window.
class WinCaptionButtonContainer : public views::View,
public views::WidgetObserver {
public:
explicit WinCaptionButtonContainer(WinFrameView* frame_view);
~WinCaptionButtonContainer() override;
// Tests to see if the specified |point| (which is expressed in this view's
// coordinates and which must be within this view's bounds) is within one of
// the caption buttons. Returns one of HitTestCompat enum defined in
// ui/base/hit_test.h, HTCAPTION if the area hit would be part of the window's
// drag handle, and HTNOWHERE otherwise.
// See also ClientView::NonClientHitTest.
int NonClientHitTest(const gfx::Point& point) const;
gfx::Size GetButtonSize() const;
void SetButtonSize(gfx::Size size);
// Sets caption button visibility and enabled state based on window state.
// Only one of maximize or restore button should ever be visible at the same
// time, and both are disabled in tablet UI mode.
void UpdateButtons();
// Reset window button states to STATE_NORMAL.
void ResetWindowControls();
private:
// views::View:
void AddedToWidget() override;
void RemovedFromWidget() override;
// views::WidgetObserver:
void OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& new_bounds) override;
WinFrameView* const frame_view_;
WinCaptionButton* const minimize_button_;
WinCaptionButton* const maximize_button_;
WinCaptionButton* const restore_button_;
WinCaptionButton* const close_button_;
base::ScopedObservation<views::Widget, views::WidgetObserver>
widget_observation_{this};
base::CallbackListSubscription subscription_ =
ui::TouchUiController::Get()->RegisterCallback(
base::BindRepeating(&WinCaptionButtonContainer::UpdateButtons,
base::Unretained(this)));
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
shell/browser/ui/views/win_frame_view.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
//
// Portions of this file are sourced from
// chrome/browser/ui/views/frame/glass_browser_frame_view.cc,
// Copyright (c) 2012 The Chromium Authors,
// which is governed by a BSD-style license
#include "shell/browser/ui/views/win_frame_view.h"
#include <dwmapi.h>
#include <memory>
#include "base/win/windows_version.h"
#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/win_caption_button_container.h"
#include "ui/base/win/hwnd_metrics.h"
#include "ui/display/win/dpi.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/views/background.h"
#include "ui/views/widget/widget.h"
#include "ui/views/win/hwnd_util.h"
namespace electron {
const char WinFrameView::kViewClassName[] = "WinFrameView";
WinFrameView::WinFrameView() = default;
WinFrameView::~WinFrameView() = default;
void WinFrameView::Init(NativeWindowViews* window, views::Widget* frame) {
window_ = window;
frame_ = frame;
if (window->IsWindowControlsOverlayEnabled()) {
caption_button_container_ =
AddChildView(std::make_unique<WinCaptionButtonContainer>(this));
} else {
caption_button_container_ = nullptr;
}
}
SkColor WinFrameView::GetReadableFeatureColor(SkColor background_color) {
// color_utils::GetColorWithMaxContrast()/IsDark() aren't used here because
// they switch based on the Chrome light/dark endpoints, while we want to use
// the system native behavior below.
const auto windows_luma = [](SkColor c) {
return 0.25f * SkColorGetR(c) + 0.625f * SkColorGetG(c) +
0.125f * SkColorGetB(c);
};
return windows_luma(background_color) <= 128.0f ? SK_ColorWHITE
: SK_ColorBLACK;
}
void WinFrameView::InvalidateCaptionButtons() {
if (!caption_button_container_)
return;
caption_button_container_->SetBackground(
views::CreateSolidBackground(window()->overlay_button_color()));
caption_button_container_->InvalidateLayout();
caption_button_container_->SchedulePaint();
}
gfx::Rect WinFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return views::GetWindowBoundsForClientBounds(
static_cast<views::View*>(const_cast<WinFrameView*>(this)),
client_bounds);
}
int WinFrameView::FrameBorderThickness() const {
return (IsMaximized() || frame()->IsFullscreen())
? 0
: display::win::ScreenWin::GetSystemMetricsInDIP(SM_CXSIZEFRAME);
}
views::View* WinFrameView::TargetForRect(views::View* root,
const gfx::Rect& rect) {
if (NonClientHitTest(rect.origin()) != HTCLIENT) {
// Custom system titlebar returns non HTCLIENT value, however event should
// be handled by the view, not by the system, because there are no system
// buttons underneath.
if (!ShouldCustomDrawSystemTitlebar()) {
return this;
}
auto local_point = rect.origin();
ConvertPointToTarget(parent(), caption_button_container_, &local_point);
if (!caption_button_container_->HitTestPoint(local_point)) {
return this;
}
}
return NonClientFrameView::TargetForRect(root, rect);
}
int WinFrameView::NonClientHitTest(const gfx::Point& point) {
if (window_->has_frame())
return frame_->client_view()->NonClientHitTest(point);
if (ShouldCustomDrawSystemTitlebar()) {
// See if the point is within any of the window controls.
if (caption_button_container_) {
gfx::Point local_point = point;
ConvertPointToTarget(parent(), caption_button_container_, &local_point);
if (caption_button_container_->HitTestPoint(local_point)) {
const int hit_test_result =
caption_button_container_->NonClientHitTest(local_point);
if (hit_test_result != HTNOWHERE)
return hit_test_result;
}
}
// On Windows 8+, the caption buttons are almost butted up to the top right
// corner of the window. This code ensures the mouse isn't set to a size
// cursor while hovering over the caption buttons, thus giving the incorrect
// impression that the user can resize the window.
RECT button_bounds = {0};
if (SUCCEEDED(DwmGetWindowAttribute(
views::HWNDForWidget(frame()), DWMWA_CAPTION_BUTTON_BOUNDS,
&button_bounds, sizeof(button_bounds)))) {
gfx::RectF button_bounds_in_dips = gfx::ConvertRectToDips(
gfx::Rect(button_bounds), display::win::GetDPIScale());
// TODO(crbug.com/1131681): GetMirroredRect() requires an integer rect,
// but the size in DIPs may not be an integer with a fractional device
// scale factor. If we want to keep using integers, the choice to use
// ToFlooredRectDeprecated() seems to be doing the wrong thing given the
// comment below about insetting 1 DIP instead of 1 physical pixel. We
// should probably use ToEnclosedRect() and then we could have inset 1
// physical pixel here.
gfx::Rect buttons =
GetMirroredRect(gfx::ToFlooredRectDeprecated(button_bounds_in_dips));
// There is a small one-pixel strip right above the caption buttons in
// which the resize border "peeks" through.
constexpr int kCaptionButtonTopInset = 1;
// The sizing region at the window edge above the caption buttons is
// 1 px regardless of scale factor. If we inset by 1 before converting
// to DIPs, the precision loss might eliminate this region entirely. The
// best we can do is to inset after conversion. This guarantees we'll
// show the resize cursor when resizing is possible. The cost of which
// is also maybe showing it over the portion of the DIP that isn't the
// outermost pixel.
buttons.Inset(gfx::Insets::TLBR(0, kCaptionButtonTopInset, 0, 0));
if (buttons.Contains(point))
return HTNOWHERE;
}
int top_border_thickness = FrameTopBorderThickness(false);
// At the window corners the resize area is not actually bigger, but the 16
// pixels at the end of the top and bottom edges trigger diagonal resizing.
constexpr int kResizeCornerWidth = 16;
int window_component = GetHTComponentForFrame(
point, gfx::Insets::TLBR(top_border_thickness, 0, 0, 0),
top_border_thickness, kResizeCornerWidth - FrameBorderThickness(),
frame()->widget_delegate()->CanResize());
if (window_component != HTNOWHERE)
return window_component;
}
// Use the parent class's hittest last
return FramelessView::NonClientHitTest(point);
}
const char* WinFrameView::GetClassName() const {
return kViewClassName;
}
bool WinFrameView::IsMaximized() const {
return frame()->IsMaximized();
}
bool WinFrameView::ShouldCustomDrawSystemTitlebar() const {
return window()->IsWindowControlsOverlayEnabled();
}
void WinFrameView::Layout() {
LayoutCaptionButtons();
if (window()->IsWindowControlsOverlayEnabled()) {
LayoutWindowControlsOverlay();
}
NonClientFrameView::Layout();
}
int WinFrameView::FrameTopBorderThickness(bool restored) const {
// Mouse and touch locations are floored but GetSystemMetricsInDIP is rounded,
// so we need to floor instead or else the difference will cause the hittest
// to fail when it ought to succeed.
return std::floor(
FrameTopBorderThicknessPx(restored) /
display::win::ScreenWin::GetScaleFactorForHWND(HWNDForView(this)));
}
int WinFrameView::FrameTopBorderThicknessPx(bool restored) const {
// Distinct from FrameBorderThickness() because we can't inset the top
// border, otherwise Windows will give us a standard titlebar.
// For maximized windows this is not true, and the top border must be
// inset in order to avoid overlapping the monitor above.
// See comments in BrowserDesktopWindowTreeHostWin::GetClientAreaInsets().
const bool needs_no_border =
(ShouldCustomDrawSystemTitlebar() && frame()->IsMaximized()) ||
frame()->IsFullscreen();
if (needs_no_border && !restored)
return 0;
// Note that this method assumes an equal resize handle thickness on all
// sides of the window.
// TODO(dfried): Consider having it return a gfx::Insets object instead.
return ui::GetFrameThickness(
MonitorFromWindow(HWNDForView(this), MONITOR_DEFAULTTONEAREST));
}
int WinFrameView::TitlebarMaximizedVisualHeight() const {
int maximized_height =
display::win::ScreenWin::GetSystemMetricsInDIP(SM_CYCAPTION);
return maximized_height;
}
// NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium
int WinFrameView::TitlebarHeight(int custom_height) const {
if (frame()->IsFullscreen() && !IsMaximized())
return 0;
int height = TitlebarMaximizedVisualHeight() +
FrameTopBorderThickness(false) - WindowTopY();
if (custom_height > TitlebarMaximizedVisualHeight())
height = custom_height - WindowTopY();
return height;
}
// NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium
int WinFrameView::WindowTopY() const {
// The window top is SM_CYSIZEFRAME pixels when maximized (see the comment in
// FrameTopBorderThickness()) and floor(system dsf) pixels when restored.
// Unfortunately we can't represent either of those at hidpi without using
// non-integral dips, so we return the closest reasonable values instead.
if (IsMaximized())
return FrameTopBorderThickness(false);
return 1;
}
void WinFrameView::LayoutCaptionButtons() {
if (!caption_button_container_)
return;
// Non-custom system titlebar already contains caption buttons.
if (!ShouldCustomDrawSystemTitlebar()) {
caption_button_container_->SetVisible(false);
return;
}
caption_button_container_->SetVisible(true);
const gfx::Size preferred_size =
caption_button_container_->GetPreferredSize();
int custom_height = window()->titlebar_overlay_height();
int height = TitlebarHeight(custom_height);
// TODO(mlaurencin): This -1 creates a 1 pixel margin between the right
// edge of the button container and the edge of the window, allowing for this
// edge portion to return the correct hit test and be manually resized
// properly. Alternatives can be explored, but the differences in view
// structures between Electron and Chromium may result in this as the best
// option.
int variable_width =
IsMaximized() ? preferred_size.width() : preferred_size.width() - 1;
caption_button_container_->SetBounds(width() - preferred_size.width(),
WindowTopY(), variable_width, height);
// Needed for heights larger than default
caption_button_container_->SetButtonSize(gfx::Size(0, height));
}
void WinFrameView::LayoutWindowControlsOverlay() {
int overlay_height = window()->titlebar_overlay_height();
if (overlay_height == 0) {
// Accounting for the 1 pixel margin at the top of the button container
overlay_height = IsMaximized()
? caption_button_container_->size().height()
: caption_button_container_->size().height() + 1;
}
int overlay_width = caption_button_container_->size().width();
int bounding_rect_width = width() - overlay_width;
auto bounding_rect =
GetMirroredRect(gfx::Rect(0, 0, bounding_rect_width, overlay_height));
window()->SetWindowControlsOverlayRect(bounding_rect);
window()->NotifyLayoutWindowControlsOverlay();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
docs/tutorial/window-customization.md
|
# Window Customization
The `BrowserWindow` module is the foundation of your Electron application, and it exposes
many APIs that can change the look and behavior of your browser windows. In this
tutorial, we will be going over the various use-cases for window customization on
macOS, Windows, and Linux.
## Create frameless windows
A frameless window is a window that has no [chrome][]. Not to be confused with the Google
Chrome browser, window _chrome_ refers to the parts of the window (e.g. toolbars, controls)
that are not a part of the web page.
To create a frameless window, you need to set `frame` to `false` in the `BrowserWindow`
constructor.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ frame: false })
```
## Apply custom title bar styles _macOS_ _Windows_
Title bar styles allow you to hide most of a BrowserWindow's chrome while keeping the
system's native window controls intact and can be configured with the `titleBarStyle`
option in the `BrowserWindow` constructor.
Applying the `hidden` title bar style results in a hidden title bar and a full-size
content window.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'hidden' })
```
### Control the traffic lights _macOS_
On macOS, applying the `hidden` title bar style will still expose the standard window
controls (“traffic lights”) in the top left.
#### Customize the look of your traffic lights _macOS_
The `customButtonsOnHover` title bar style will hide the traffic lights until you hover
over them. This is useful if you want to create custom traffic lights in your HTML but still
use the native UI to control the window.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'customButtonsOnHover' })
```
#### Customize the traffic light position _macOS_
To modify the position of the traffic light window controls, there are two configuration
options available.
Applying `hiddenInset` title bar style will shift the vertical inset of the traffic lights
by a fixed amount.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ titleBarStyle: 'hiddenInset' })
```
If you need more granular control over the positioning of the traffic lights, you can pass
a set of coordinates to the `trafficLightPosition` option in the `BrowserWindow`
constructor.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
trafficLightPosition: { x: 10, y: 10 }
})
```
#### Show and hide the traffic lights programmatically _macOS_
You can also show and hide the traffic lights programmatically from the main process.
The `win.setWindowButtonVisibility` forces traffic lights to be show or hidden depending
on the value of its boolean parameter.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
// hides the traffic lights
win.setWindowButtonVisibility(false)
```
> Note: Given the number of APIs available, there are many ways of achieving this. For instance,
> combining `frame: false` with `win.setWindowButtonVisibility(true)` will yield the same
> layout outcome as setting `titleBarStyle: 'hidden'`.
## Window Controls Overlay _macOS_ _Windows_
The [Window Controls Overlay API][] is a web standard that gives web apps the ability to
customize their title bar region when installed on desktop. Electron exposes this API
through the `BrowserWindow` constructor option `titleBarOverlay`.
This option only works whenever a custom `titlebarStyle` is applied on macOS or Windows.
When `titleBarOverlay` is enabled, the window controls become exposed in their default
position, and DOM elements cannot use the area underneath this region.
The `titleBarOverlay` option accepts two different value formats.
Specifying `true` on either platform will result in an overlay region with default
system colors:
```javascript title='main.js'
// on macOS or Windows
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
titleBarOverlay: true
})
```
On either platform `titleBarOverlay` can also be an object. On both macOS and Windows, the height of the overlay can be specified with the `height` property. On Windows, the color of the overlay and its symbols can be specified using the `color` and `symbolColor` properties respectively.
If a color option is not specified, the color will default to its system color for the window control buttons. Similarly, if the height option is not specified it will default to the default height:
```javascript title='main.js'
// on Windows
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({
titleBarStyle: 'hidden',
titleBarOverlay: {
color: '#2f3241',
symbolColor: '#74b1be',
height: 60
}
})
```
> Note: Once your title bar overlay is enabled from the main process, you can access the overlay's
> color and dimension values from a renderer using a set of readonly
> [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars].
### Limitations
* Transparent colors are currently not supported. Progress updates for this feature can be found in PR [#33567](https://github.com/electron/electron/issues/33567).
## Create transparent windows
By setting the `transparent` option to `true`, you can make a fully transparent window.
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ transparent: true })
```
### Limitations
* You cannot click through the transparent area. See
[#1335](https://github.com/electron/electron/issues/1335) for details.
* Transparent windows are not resizable. Setting `resizable` to `true` may make
a transparent window stop working on some platforms.
* The CSS [`blur()`][] filter only applies to the window's web contents, so there is no way to apply
blur effect to the content below the window (i.e. other applications open on
the user's system).
* The window will not be transparent when DevTools is opened.
* On _Windows_:
* Transparent windows will not work when DWM is disabled.
* Transparent windows can not be maximized using the Windows system menu or by double
clicking the title bar. The reasoning behind this can be seen on
PR [#28207](https://github.com/electron/electron/pull/28207).
* On _macOS_:
* The native window shadow will not be shown on a transparent window.
## Create click-through windows
To create a click-through window, i.e. making the window ignore all mouse
events, you can call the [win.setIgnoreMouseEvents(ignore)][ignore-mouse-events]
API:
```javascript title='main.js'
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.setIgnoreMouseEvents(true)
```
### Forward mouse events _macOS_ _Windows_
Ignoring mouse messages makes the web contents oblivious to mouse movement,
meaning that mouse movement events will not be emitted. On Windows and macOS, an
optional parameter can be used to forward mouse move messages to the web page,
allowing events such as `mouseleave` to be emitted:
```javascript title='main.js'
const { BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const win = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
ipcMain.on('set-ignore-mouse-events', (event, ignore, options) => {
const win = BrowserWindow.fromWebContents(event.sender)
win.setIgnoreMouseEvents(ignore, options)
})
```
```javascript title='preload.js'
window.addEventListener('DOMContentLoaded', () => {
const el = document.getElementById('clickThroughElement')
el.addEventListener('mouseenter', () => {
ipcRenderer.send('set-ignore-mouse-events', true, { forward: true })
})
el.addEventListener('mouseleave', () => {
ipcRenderer.send('set-ignore-mouse-events', false)
})
})
```
This makes the web page click-through when over the `#clickThroughElement` element,
and returns to normal outside it.
## Set custom draggable region
By default, the frameless window is non-draggable. Apps need to specify
`-webkit-app-region: drag` in CSS to tell Electron which regions are draggable
(like the OS's standard titlebar), and apps can also use
`-webkit-app-region: no-drag` to exclude the non-draggable area from the
draggable region. Note that only rectangular shapes are currently supported.
To make the whole window draggable, you can add `-webkit-app-region: drag` as
`body`'s style:
```css title='styles.css'
body {
-webkit-app-region: drag;
}
```
And note that if you have made the whole window draggable, you must also mark
buttons as non-draggable, otherwise it would be impossible for users to click on
them:
```css title='styles.css'
button {
-webkit-app-region: no-drag;
}
```
If you're only setting a custom titlebar as draggable, you also need to make all
buttons in titlebar non-draggable.
### Tip: disable text selection
When creating a draggable region, the dragging behavior may conflict with text selection.
For example, when you drag the titlebar, you may accidentally select its text contents.
To prevent this, you need to disable text selection within a draggable area like this:
```css
.titlebar {
-webkit-user-select: none;
-webkit-app-region: drag;
}
```
### Tip: disable context menus
On some platforms, the draggable area will be treated as a non-client frame, so
when you right click on it, a system menu will pop up. To make the context menu
behave correctly on all platforms, you should never use a custom context menu on
draggable areas.
[`blur()`]: https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/blur()
[chrome]: https://developer.mozilla.org/en-US/docs/Glossary/Chrome
[ignore-mouse-events]: ../api/browser-window.md#winsetignoremouseeventsignore-options
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
[Window Controls Overlay API]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
shell/browser/ui/views/win_caption_button_container.cc
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Modified from
// chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc
#include "shell/browser/ui/views/win_caption_button_container.h"
#include <memory>
#include <utility>
#include "shell/browser/ui/views/win_caption_button.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/view_class_properties.h"
namespace electron {
namespace {
std::unique_ptr<WinCaptionButton> CreateCaptionButton(
views::Button::PressedCallback callback,
WinFrameView* frame_view,
ViewID button_type,
int accessible_name_resource_id) {
return std::make_unique<WinCaptionButton>(
std::move(callback), frame_view, button_type,
l10n_util::GetStringUTF16(accessible_name_resource_id));
}
bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) {
return button && button->GetVisible() && button->bounds().Contains(point);
}
} // anonymous namespace
WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view)
: frame_view_(frame_view),
minimize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Minimize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MINIMIZE_BUTTON,
IDS_APP_ACCNAME_MINIMIZE))),
maximize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Maximize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MAXIMIZE_BUTTON,
IDS_APP_ACCNAME_MAXIMIZE))),
restore_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Restore,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_RESTORE_BUTTON,
IDS_APP_ACCNAME_RESTORE))),
close_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::CloseWithReason,
base::Unretained(frame_view_->frame()),
views::Widget::ClosedReason::kCloseButtonClicked),
frame_view_,
VIEW_ID_CLOSE_BUTTON,
IDS_APP_ACCNAME_CLOSE))) {
// Layout is horizontal, with buttons placed at the trailing end of the view.
// This allows the container to expand to become a faux titlebar/drag handle.
auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetMainAxisAlignment(views::LayoutAlignment::kEnd)
.SetCrossAxisAlignment(views::LayoutAlignment::kStart)
.SetDefault(
views::kFlexBehaviorKey,
views::FlexSpecification(views::LayoutOrientation::kHorizontal,
views::MinimumFlexSizeRule::kPreferred,
views::MaximumFlexSizeRule::kPreferred,
/* adjust_width_for_height */ false,
views::MinimumFlexSizeRule::kScaleToZero));
}
WinCaptionButtonContainer::~WinCaptionButtonContainer() {}
int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const {
DCHECK(HitTestPoint(point))
<< "should only be called with a point inside this view's bounds";
if (HitTestCaptionButton(minimize_button_, point)) {
return HTMINBUTTON;
}
if (HitTestCaptionButton(maximize_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(restore_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(close_button_, point)) {
return HTCLOSE;
}
return HTCAPTION;
}
gfx::Size WinCaptionButtonContainer::GetButtonSize() const {
// Close button size is set the same as all the buttons
return close_button_->GetSize();
}
void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) {
minimize_button_->SetSize(size);
maximize_button_->SetSize(size);
restore_button_->SetSize(size);
close_button_->SetSize(size);
}
void WinCaptionButtonContainer::ResetWindowControls() {
minimize_button_->SetState(views::Button::STATE_NORMAL);
maximize_button_->SetState(views::Button::STATE_NORMAL);
restore_button_->SetState(views::Button::STATE_NORMAL);
close_button_->SetState(views::Button::STATE_NORMAL);
InvalidateLayout();
}
void WinCaptionButtonContainer::AddedToWidget() {
views::Widget* const widget = GetWidget();
DCHECK(!widget_observation_.IsObserving());
widget_observation_.Observe(widget);
UpdateButtons();
if (frame_view_->window()->IsWindowControlsOverlayEnabled()) {
SetBackground(views::CreateSolidBackground(
frame_view_->window()->overlay_button_color()));
SetPaintToLayer();
}
}
void WinCaptionButtonContainer::RemovedFromWidget() {
DCHECK(widget_observation_.IsObserving());
widget_observation_.Reset();
}
void WinCaptionButtonContainer::OnWidgetBoundsChanged(
views::Widget* widget,
const gfx::Rect& new_bounds) {
UpdateButtons();
}
void WinCaptionButtonContainer::UpdateButtons() {
const bool is_maximized = frame_view_->frame()->IsMaximized();
restore_button_->SetVisible(is_maximized);
maximize_button_->SetVisible(!is_maximized);
const bool minimizable = frame_view_->window()->IsMinimizable();
minimize_button_->SetEnabled(minimizable);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled.
const bool is_touch = ui::TouchUiController::Get()->touch_ui();
restore_button_->SetEnabled(!is_touch);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled, unless the window is not
// maximized.
const bool maximizable = frame_view_->window()->IsMaximizable();
maximize_button_->SetEnabled(!(is_touch && is_maximized) && maximizable);
const bool closable = frame_view_->window()->IsClosable();
close_button_->SetEnabled(closable);
// If all three of closable, maximizable, and minimizable are disabled,
// Windows natively only shows the disabled closable button. Copy that
// behavior here.
if (!maximizable && !closable && !minimizable) {
minimize_button_->SetVisible(false);
maximize_button_->SetVisible(false);
}
InvalidateLayout();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
shell/browser/ui/views/win_caption_button_container.h
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Modified from
// chrome/browser/ui/views/frame/glass_browser_caption_button_container.h
#ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
#define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
#include "base/scoped_observation.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/pointer/touch_ui_controller.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace electron {
class WinFrameView;
class WinCaptionButton;
// Provides a container for Windows 10 caption buttons that can be moved between
// frame and browser window as needed. When extended horizontally, becomes a
// grab bar for moving the window.
class WinCaptionButtonContainer : public views::View,
public views::WidgetObserver {
public:
explicit WinCaptionButtonContainer(WinFrameView* frame_view);
~WinCaptionButtonContainer() override;
// Tests to see if the specified |point| (which is expressed in this view's
// coordinates and which must be within this view's bounds) is within one of
// the caption buttons. Returns one of HitTestCompat enum defined in
// ui/base/hit_test.h, HTCAPTION if the area hit would be part of the window's
// drag handle, and HTNOWHERE otherwise.
// See also ClientView::NonClientHitTest.
int NonClientHitTest(const gfx::Point& point) const;
gfx::Size GetButtonSize() const;
void SetButtonSize(gfx::Size size);
// Sets caption button visibility and enabled state based on window state.
// Only one of maximize or restore button should ever be visible at the same
// time, and both are disabled in tablet UI mode.
void UpdateButtons();
// Reset window button states to STATE_NORMAL.
void ResetWindowControls();
private:
// views::View:
void AddedToWidget() override;
void RemovedFromWidget() override;
// views::WidgetObserver:
void OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& new_bounds) override;
WinFrameView* const frame_view_;
WinCaptionButton* const minimize_button_;
WinCaptionButton* const maximize_button_;
WinCaptionButton* const restore_button_;
WinCaptionButton* const close_button_;
base::ScopedObservation<views::Widget, views::WidgetObserver>
widget_observation_{this};
base::CallbackListSubscription subscription_ =
ui::TouchUiController::Get()->RegisterCallback(
base::BindRepeating(&WinCaptionButtonContainer::UpdateButtons,
base::Unretained(this)));
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 33,567 |
[Feature Request]: Transparent background color support for WCO on Windows
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
Window Controls Overlay (WCO) allows for integrated titlebars can be styled to fit the look and feel of any app. But they are styled from the Electron main process, rather than in CSS, which means that there is no simple way to blend them into web content which is always changing.
Authors can set background and symbol colours which match a specific app configuration, but these colours have to be adjusted whenever the page styles change, e.g. due to theme changes, in-app navigation, or dimming caused by modals.
### Proposed Solution
Allow `color: undefined` or `color: "transparent"` to be set in `BrowserWindowOptions.titleBarOverlay`.
### Alternatives Considered
It is possible to style window controls at any time using `BrowserWindow#setTitleBarOverlay` (https://github.com/electron/electron/pull/33066). But web content in some apps is too dynamic for this solution to be practical -- any style change within the titlebar region would need a lifecycle event and IPC, just to simulate transparency at all times,
And because the overlay colour needs to be solid and opaque, there is no way to have the titlebar blend into all possible web content.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/33567
|
https://github.com/electron/electron/pull/38693
|
d95ae19edf08f8df15357925abf4b7c0c6769c88
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
| 2022-04-01T03:14:06Z |
c++
| 2023-06-09T16:57:57Z |
shell/browser/ui/views/win_frame_view.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
//
// Portions of this file are sourced from
// chrome/browser/ui/views/frame/glass_browser_frame_view.cc,
// Copyright (c) 2012 The Chromium Authors,
// which is governed by a BSD-style license
#include "shell/browser/ui/views/win_frame_view.h"
#include <dwmapi.h>
#include <memory>
#include "base/win/windows_version.h"
#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/win_caption_button_container.h"
#include "ui/base/win/hwnd_metrics.h"
#include "ui/display/win/dpi.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/views/background.h"
#include "ui/views/widget/widget.h"
#include "ui/views/win/hwnd_util.h"
namespace electron {
const char WinFrameView::kViewClassName[] = "WinFrameView";
WinFrameView::WinFrameView() = default;
WinFrameView::~WinFrameView() = default;
void WinFrameView::Init(NativeWindowViews* window, views::Widget* frame) {
window_ = window;
frame_ = frame;
if (window->IsWindowControlsOverlayEnabled()) {
caption_button_container_ =
AddChildView(std::make_unique<WinCaptionButtonContainer>(this));
} else {
caption_button_container_ = nullptr;
}
}
SkColor WinFrameView::GetReadableFeatureColor(SkColor background_color) {
// color_utils::GetColorWithMaxContrast()/IsDark() aren't used here because
// they switch based on the Chrome light/dark endpoints, while we want to use
// the system native behavior below.
const auto windows_luma = [](SkColor c) {
return 0.25f * SkColorGetR(c) + 0.625f * SkColorGetG(c) +
0.125f * SkColorGetB(c);
};
return windows_luma(background_color) <= 128.0f ? SK_ColorWHITE
: SK_ColorBLACK;
}
void WinFrameView::InvalidateCaptionButtons() {
if (!caption_button_container_)
return;
caption_button_container_->SetBackground(
views::CreateSolidBackground(window()->overlay_button_color()));
caption_button_container_->InvalidateLayout();
caption_button_container_->SchedulePaint();
}
gfx::Rect WinFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return views::GetWindowBoundsForClientBounds(
static_cast<views::View*>(const_cast<WinFrameView*>(this)),
client_bounds);
}
int WinFrameView::FrameBorderThickness() const {
return (IsMaximized() || frame()->IsFullscreen())
? 0
: display::win::ScreenWin::GetSystemMetricsInDIP(SM_CXSIZEFRAME);
}
views::View* WinFrameView::TargetForRect(views::View* root,
const gfx::Rect& rect) {
if (NonClientHitTest(rect.origin()) != HTCLIENT) {
// Custom system titlebar returns non HTCLIENT value, however event should
// be handled by the view, not by the system, because there are no system
// buttons underneath.
if (!ShouldCustomDrawSystemTitlebar()) {
return this;
}
auto local_point = rect.origin();
ConvertPointToTarget(parent(), caption_button_container_, &local_point);
if (!caption_button_container_->HitTestPoint(local_point)) {
return this;
}
}
return NonClientFrameView::TargetForRect(root, rect);
}
int WinFrameView::NonClientHitTest(const gfx::Point& point) {
if (window_->has_frame())
return frame_->client_view()->NonClientHitTest(point);
if (ShouldCustomDrawSystemTitlebar()) {
// See if the point is within any of the window controls.
if (caption_button_container_) {
gfx::Point local_point = point;
ConvertPointToTarget(parent(), caption_button_container_, &local_point);
if (caption_button_container_->HitTestPoint(local_point)) {
const int hit_test_result =
caption_button_container_->NonClientHitTest(local_point);
if (hit_test_result != HTNOWHERE)
return hit_test_result;
}
}
// On Windows 8+, the caption buttons are almost butted up to the top right
// corner of the window. This code ensures the mouse isn't set to a size
// cursor while hovering over the caption buttons, thus giving the incorrect
// impression that the user can resize the window.
RECT button_bounds = {0};
if (SUCCEEDED(DwmGetWindowAttribute(
views::HWNDForWidget(frame()), DWMWA_CAPTION_BUTTON_BOUNDS,
&button_bounds, sizeof(button_bounds)))) {
gfx::RectF button_bounds_in_dips = gfx::ConvertRectToDips(
gfx::Rect(button_bounds), display::win::GetDPIScale());
// TODO(crbug.com/1131681): GetMirroredRect() requires an integer rect,
// but the size in DIPs may not be an integer with a fractional device
// scale factor. If we want to keep using integers, the choice to use
// ToFlooredRectDeprecated() seems to be doing the wrong thing given the
// comment below about insetting 1 DIP instead of 1 physical pixel. We
// should probably use ToEnclosedRect() and then we could have inset 1
// physical pixel here.
gfx::Rect buttons =
GetMirroredRect(gfx::ToFlooredRectDeprecated(button_bounds_in_dips));
// There is a small one-pixel strip right above the caption buttons in
// which the resize border "peeks" through.
constexpr int kCaptionButtonTopInset = 1;
// The sizing region at the window edge above the caption buttons is
// 1 px regardless of scale factor. If we inset by 1 before converting
// to DIPs, the precision loss might eliminate this region entirely. The
// best we can do is to inset after conversion. This guarantees we'll
// show the resize cursor when resizing is possible. The cost of which
// is also maybe showing it over the portion of the DIP that isn't the
// outermost pixel.
buttons.Inset(gfx::Insets::TLBR(0, kCaptionButtonTopInset, 0, 0));
if (buttons.Contains(point))
return HTNOWHERE;
}
int top_border_thickness = FrameTopBorderThickness(false);
// At the window corners the resize area is not actually bigger, but the 16
// pixels at the end of the top and bottom edges trigger diagonal resizing.
constexpr int kResizeCornerWidth = 16;
int window_component = GetHTComponentForFrame(
point, gfx::Insets::TLBR(top_border_thickness, 0, 0, 0),
top_border_thickness, kResizeCornerWidth - FrameBorderThickness(),
frame()->widget_delegate()->CanResize());
if (window_component != HTNOWHERE)
return window_component;
}
// Use the parent class's hittest last
return FramelessView::NonClientHitTest(point);
}
const char* WinFrameView::GetClassName() const {
return kViewClassName;
}
bool WinFrameView::IsMaximized() const {
return frame()->IsMaximized();
}
bool WinFrameView::ShouldCustomDrawSystemTitlebar() const {
return window()->IsWindowControlsOverlayEnabled();
}
void WinFrameView::Layout() {
LayoutCaptionButtons();
if (window()->IsWindowControlsOverlayEnabled()) {
LayoutWindowControlsOverlay();
}
NonClientFrameView::Layout();
}
int WinFrameView::FrameTopBorderThickness(bool restored) const {
// Mouse and touch locations are floored but GetSystemMetricsInDIP is rounded,
// so we need to floor instead or else the difference will cause the hittest
// to fail when it ought to succeed.
return std::floor(
FrameTopBorderThicknessPx(restored) /
display::win::ScreenWin::GetScaleFactorForHWND(HWNDForView(this)));
}
int WinFrameView::FrameTopBorderThicknessPx(bool restored) const {
// Distinct from FrameBorderThickness() because we can't inset the top
// border, otherwise Windows will give us a standard titlebar.
// For maximized windows this is not true, and the top border must be
// inset in order to avoid overlapping the monitor above.
// See comments in BrowserDesktopWindowTreeHostWin::GetClientAreaInsets().
const bool needs_no_border =
(ShouldCustomDrawSystemTitlebar() && frame()->IsMaximized()) ||
frame()->IsFullscreen();
if (needs_no_border && !restored)
return 0;
// Note that this method assumes an equal resize handle thickness on all
// sides of the window.
// TODO(dfried): Consider having it return a gfx::Insets object instead.
return ui::GetFrameThickness(
MonitorFromWindow(HWNDForView(this), MONITOR_DEFAULTTONEAREST));
}
int WinFrameView::TitlebarMaximizedVisualHeight() const {
int maximized_height =
display::win::ScreenWin::GetSystemMetricsInDIP(SM_CYCAPTION);
return maximized_height;
}
// NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium
int WinFrameView::TitlebarHeight(int custom_height) const {
if (frame()->IsFullscreen() && !IsMaximized())
return 0;
int height = TitlebarMaximizedVisualHeight() +
FrameTopBorderThickness(false) - WindowTopY();
if (custom_height > TitlebarMaximizedVisualHeight())
height = custom_height - WindowTopY();
return height;
}
// NOTE(@mlaurencin): Usage of IsWebUITabStrip simplified out from Chromium
int WinFrameView::WindowTopY() const {
// The window top is SM_CYSIZEFRAME pixels when maximized (see the comment in
// FrameTopBorderThickness()) and floor(system dsf) pixels when restored.
// Unfortunately we can't represent either of those at hidpi without using
// non-integral dips, so we return the closest reasonable values instead.
if (IsMaximized())
return FrameTopBorderThickness(false);
return 1;
}
void WinFrameView::LayoutCaptionButtons() {
if (!caption_button_container_)
return;
// Non-custom system titlebar already contains caption buttons.
if (!ShouldCustomDrawSystemTitlebar()) {
caption_button_container_->SetVisible(false);
return;
}
caption_button_container_->SetVisible(true);
const gfx::Size preferred_size =
caption_button_container_->GetPreferredSize();
int custom_height = window()->titlebar_overlay_height();
int height = TitlebarHeight(custom_height);
// TODO(mlaurencin): This -1 creates a 1 pixel margin between the right
// edge of the button container and the edge of the window, allowing for this
// edge portion to return the correct hit test and be manually resized
// properly. Alternatives can be explored, but the differences in view
// structures between Electron and Chromium may result in this as the best
// option.
int variable_width =
IsMaximized() ? preferred_size.width() : preferred_size.width() - 1;
caption_button_container_->SetBounds(width() - preferred_size.width(),
WindowTopY(), variable_width, height);
// Needed for heights larger than default
caption_button_container_->SetButtonSize(gfx::Size(0, height));
}
void WinFrameView::LayoutWindowControlsOverlay() {
int overlay_height = window()->titlebar_overlay_height();
if (overlay_height == 0) {
// Accounting for the 1 pixel margin at the top of the button container
overlay_height = IsMaximized()
? caption_button_container_->size().height()
: caption_button_container_->size().height() + 1;
}
int overlay_width = caption_button_container_->size().width();
int bounding_rect_width = width() - overlay_width;
auto bounding_rect =
GetMirroredRect(gfx::Rect(0, 0, bounding_rect_width, overlay_height));
window()->SetWindowControlsOverlayRect(bounding_rect);
window()->NotifyLayoutWindowControlsOverlay();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,598 |
[Bug]: webContents.print fails with unspecified options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.1
### Expected Behavior
Calling `webContents.print()`, `webContents.print({})`, or `webContents.print(null)` will result in the system print dialog to appearing.
### Actual Behavior
If `print()` or `print({})` are called, the call will never invoke the provided callback (at least not within 5 minutes, which was the longest I let it sit), nor will it throw any exceptions catchable by a try-catch block. When running the provided gist in Electron Fiddle, I see the following console log: "[19232:0605/173028.939:ERROR:device_event_log_impl.cc(222)] [17:30:28.939] Printer: print_view_manager_base.cc:352 Printer settings invalid for \\epic-print1\vca2cpy-Revenge (destination type kLocal): content size is empty; page size is empty; printable area is empty"
If `print(null)` is called, an exception will be thrown with the error message: "Cannot read properties of null (reading 'pageSize')".
### Testcase Gist URL
https://gist.github.com/mgalla10/7710e8f22830f1122cfe0d98dd99ab08
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38598
|
https://github.com/electron/electron/pull/38614
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
|
c0d9764de9d00968a8c9d5ab74ef3b9840aebc09
| 2023-06-05T22:43:02Z |
c++
| 2023-06-09T19:41:01Z |
lib/browser/api/web-contents.ts
|
import { app, ipcMain, session, webFrameMain } from 'electron/main';
import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main';
import * as url from 'url';
import * as path from 'path';
import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager';
import { parseFeatures } from '@electron/internal/browser/parse-features-string';
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
import { MessagePortMain } from '@electron/internal/browser/message-port-main';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl';
import * as deprecate from '@electron/internal/common/deprecate';
// session is not used here, the purpose is to make sure session is initialized
// before the webContents module.
// eslint-disable-next-line no-unused-expressions
session;
const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main');
let nextId = 0;
const getNextId = function () {
return ++nextId;
};
type PostData = LoadURLOptions['postData']
// Stock page sizes
const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = {
Letter: {
custom_display_name: 'Letter',
height_microns: 279400,
name: 'NA_LETTER',
width_microns: 215900
},
Legal: {
custom_display_name: 'Legal',
height_microns: 355600,
name: 'NA_LEGAL',
width_microns: 215900
},
Tabloid: {
height_microns: 431800,
name: 'NA_LEDGER',
width_microns: 279400,
custom_display_name: 'Tabloid'
},
A0: {
custom_display_name: 'A0',
height_microns: 1189000,
name: 'ISO_A0',
width_microns: 841000
},
A1: {
custom_display_name: 'A1',
height_microns: 841000,
name: 'ISO_A1',
width_microns: 594000
},
A2: {
custom_display_name: 'A2',
height_microns: 594000,
name: 'ISO_A2',
width_microns: 420000
},
A3: {
custom_display_name: 'A3',
height_microns: 420000,
name: 'ISO_A3',
width_microns: 297000
},
A4: {
custom_display_name: 'A4',
height_microns: 297000,
name: 'ISO_A4',
is_default: 'true',
width_microns: 210000
},
A5: {
custom_display_name: 'A5',
height_microns: 210000,
name: 'ISO_A5',
width_microns: 148000
},
A6: {
custom_display_name: 'A6',
height_microns: 148000,
name: 'ISO_A6',
width_microns: 105000
}
} as const;
const paperFormats: Record<string, ElectronInternal.PageSize> = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
} as const;
// The minimum micron size Chromium accepts is that where:
// Per printing/units.h:
// * kMicronsPerInch - Length of an inch in 0.001mm unit.
// * kPointsPerInch - Length of an inch in CSS's 1pt unit.
//
// Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
//
// Practically, this means microns need to be > 352 microns.
// We therefore need to verify this or it will silently fail.
const isValidCustomPageSize = (width: number, height: number) => {
return [width, height].every(x => x > 352);
};
// JavaScript implementations of WebContents.
const binding = process._linkedBinding('electron_browser_web_contents');
const printing = process._linkedBinding('electron_browser_printing');
const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } };
WebContents.prototype.postMessage = function (...args) {
return this.mainFrame.postMessage(...args);
};
WebContents.prototype.send = function (channel, ...args) {
return this.mainFrame.send(channel, ...args);
};
WebContents.prototype._sendInternal = function (channel, ...args) {
return this.mainFrame._sendInternal(channel, ...args);
};
function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) {
if (typeof frame === 'number') {
return webFrameMain.fromId(contents.mainFrame.processId, frame);
} else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) {
return webFrameMain.fromId(frame[0], frame[1]);
} else {
throw new Error('Missing required frame argument (must be number or [processId, frameId])');
}
}
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
const frame = getWebFrame(this, frameId);
if (!frame) return false;
frame.send(channel, ...args);
return true;
};
// Following methods are mapped to webFrame.
const webFrameMethods = [
'insertCSS',
'insertText',
'removeInsertedCSS',
'setVisualZoomLevelLimits'
] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[];
for (const method of webFrameMethods) {
WebContents.prototype[method] = function (...args: any[]): Promise<any> {
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args);
};
}
const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => {
if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
return new Promise<void>((resolve) => {
webContents.once('did-stop-loading', () => {
resolve();
});
});
};
// Make sure WebContents::executeJavaScript would run the code only when the
// WebContents has been loaded.
WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture);
};
WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture);
};
// Translate the options of printToPDF.
let pendingPromise: Promise<any> | undefined;
WebContents.prototype.printToPDF = async function (options) {
const printSettings: Record<string, any> = {
requestID: getNextId(),
landscape: false,
displayHeaderFooter: false,
headerTemplate: '',
footerTemplate: '',
printBackground: false,
scale: 1.0,
paperWidth: 8.5,
paperHeight: 11.0,
marginTop: 0.4,
marginBottom: 0.4,
marginLeft: 0.4,
marginRight: 0.4,
pageRanges: '',
preferCSSPageSize: false
};
if (options.landscape !== undefined) {
if (typeof options.landscape !== 'boolean') {
return Promise.reject(new Error('landscape must be a Boolean'));
}
printSettings.landscape = options.landscape;
}
if (options.displayHeaderFooter !== undefined) {
if (typeof options.displayHeaderFooter !== 'boolean') {
return Promise.reject(new Error('displayHeaderFooter must be a Boolean'));
}
printSettings.displayHeaderFooter = options.displayHeaderFooter;
}
if (options.printBackground !== undefined) {
if (typeof options.printBackground !== 'boolean') {
return Promise.reject(new Error('printBackground must be a Boolean'));
}
printSettings.shouldPrintBackgrounds = options.printBackground;
}
if (options.scale !== undefined) {
if (typeof options.scale !== 'number') {
return Promise.reject(new Error('scale must be a Number'));
}
printSettings.scale = options.scale;
}
const { pageSize } = options;
if (pageSize !== undefined) {
if (typeof pageSize === 'string') {
const format = paperFormats[pageSize.toLowerCase()];
if (!format) {
return Promise.reject(new Error(`Invalid pageSize ${pageSize}`));
}
printSettings.paperWidth = format.width;
printSettings.paperHeight = format.height;
} else if (typeof options.pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
return Promise.reject(new Error('height and width properties are required for pageSize'));
}
printSettings.paperWidth = pageSize.width;
printSettings.paperHeight = pageSize.height;
} else {
return Promise.reject(new Error('pageSize must be a String or Object'));
}
}
const { margins } = options;
if (margins !== undefined) {
if (typeof margins !== 'object') {
return Promise.reject(new Error('margins must be an Object'));
}
if (margins.top !== undefined) {
if (typeof margins.top !== 'number') {
return Promise.reject(new Error('margins.top must be a Number'));
}
printSettings.marginTop = margins.top;
}
if (margins.bottom !== undefined) {
if (typeof margins.bottom !== 'number') {
return Promise.reject(new Error('margins.bottom must be a Number'));
}
printSettings.marginBottom = margins.bottom;
}
if (margins.left !== undefined) {
if (typeof margins.left !== 'number') {
return Promise.reject(new Error('margins.left must be a Number'));
}
printSettings.marginLeft = margins.left;
}
if (margins.right !== undefined) {
if (typeof margins.right !== 'number') {
return Promise.reject(new Error('margins.right must be a Number'));
}
printSettings.marginRight = margins.right;
}
}
if (options.pageRanges !== undefined) {
if (typeof options.pageRanges !== 'string') {
return Promise.reject(new Error('pageRanges must be a String'));
}
printSettings.pageRanges = options.pageRanges;
}
if (options.headerTemplate !== undefined) {
if (typeof options.headerTemplate !== 'string') {
return Promise.reject(new Error('headerTemplate must be a String'));
}
printSettings.headerTemplate = options.headerTemplate;
}
if (options.footerTemplate !== undefined) {
if (typeof options.footerTemplate !== 'string') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.footerTemplate = options.footerTemplate;
}
if (options.preferCSSPageSize !== undefined) {
if (typeof options.preferCSSPageSize !== 'boolean') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.preferCSSPageSize = options.preferCSSPageSize;
}
if (this._printToPDF) {
if (pendingPromise) {
pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
} else {
pendingPromise = this._printToPDF(printSettings);
}
return pendingPromise;
} else {
const error = new Error('Printing feature is disabled');
return Promise.reject(error);
}
};
// TODO(codebytere): deduplicate argument sanitization by moving rest of
// print param logic into new file shared between printToPDF and print
WebContents.prototype.print = function (printOptions: ElectronInternal.WebContentsPrintOptions, callback) {
const options = printOptions ?? {};
if (options.pageSize) {
const pageSize = options.pageSize;
if (typeof pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
throw new Error('height and width properties are required for pageSize');
}
// Dimensions in Microns - 1 meter = 10^6 microns
const height = Math.ceil(pageSize.height);
const width = Math.ceil(pageSize.width);
if (!isValidCustomPageSize(width, height)) {
throw new Error('height and width properties must be minimum 352 microns.');
}
options.mediaSize = {
name: 'CUSTOM',
custom_display_name: 'Custom',
height_microns: height,
width_microns: width
};
} else if (PDFPageSizes[pageSize]) {
options.mediaSize = PDFPageSizes[pageSize];
} else {
throw new Error(`Unsupported pageSize: ${pageSize}`);
}
}
if (this._print) {
if (callback) {
this._print(options, callback);
} else {
this._print(options);
}
} else {
console.error('Error: Printing feature is disabled.');
}
};
WebContents.prototype.getPrinters = function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterList) {
return printing.getPrinterList();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.getPrintersAsync = async function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterListAsync) {
return printing.getPrinterListAsync();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.loadFile = function (filePath, options = {}) {
if (typeof filePath !== 'string') {
throw new Error('Must pass filePath as a string');
}
const { query, search, hash } = options;
return this.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: path.resolve(app.getAppPath(), filePath),
query,
search,
hash
}));
};
WebContents.prototype.loadURL = function (url, options) {
const p = new Promise<void>((resolve, reject) => {
const resolveAndCleanup = () => {
removeListeners();
resolve();
};
const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
Object.assign(err, { errno: errorCode, code: errorDescription, url });
removeListeners();
reject(err);
};
const finishListener = () => {
resolveAndCleanup();
};
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
if (isMainFrame) {
rejectAndCleanup(errorCode, errorDescription, validatedURL);
}
};
let navigationStarted = false;
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
if (isMainFrame) {
if (navigationStarted && !isSameDocument) {
// the webcontents has started another unrelated navigation in the
// main frame (probably from the app calling `loadURL` again); reject
// the promise
// We should only consider the request aborted if the "navigation" is
// actually navigating and not simply transitioning URL state in the
// current context. E.g. pushState and `location.hash` changes are
// considered navigation events but are triggered with isSameDocument.
// We can ignore these to allow virtual routing on page load as long
// as the routing does not leave the document
return rejectAndCleanup(-3, 'ERR_ABORTED', url);
}
navigationStarted = true;
}
};
const stopLoadingListener = () => {
// By the time we get here, either 'finish' or 'fail' should have fired
// if the navigation occurred. However, in some situations (e.g. when
// attempting to load a page with a bad scheme), loading will stop
// without emitting finish or fail. In this case, we reject the promise
// with a generic failure.
// TODO(jeremy): enumerate all the cases in which this can happen. If
// the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
// would be more appropriate.
rejectAndCleanup(-2, 'ERR_FAILED', url);
};
const removeListeners = () => {
this.removeListener('did-finish-load', finishListener);
this.removeListener('did-fail-load', failListener);
this.removeListener('did-navigate-in-page', finishListener);
this.removeListener('did-start-navigation', navigationListener);
this.removeListener('did-stop-loading', stopLoadingListener);
this.removeListener('destroyed', stopLoadingListener);
};
this.on('did-finish-load', finishListener);
this.on('did-fail-load', failListener);
this.on('did-navigate-in-page', finishListener);
this.on('did-start-navigation', navigationListener);
this.on('did-stop-loading', stopLoadingListener);
this.on('destroyed', stopLoadingListener);
});
// Add a no-op rejection handler to silence the unhandled rejection error.
p.catch(() => {});
this._loadURL(url, options ?? {});
return p;
};
WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) {
this._windowOpenHandler = handler;
};
WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} {
const defaultResponse = {
browserWindowConstructorOptions: null,
outlivesOpener: false
};
if (!this._windowOpenHandler) {
return defaultResponse;
}
const response = this._windowOpenHandler(details);
if (typeof response !== 'object') {
event.preventDefault();
console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
return defaultResponse;
}
if (response === null) {
event.preventDefault();
console.error('The window open handler response must be an object, but was instead null.');
return defaultResponse;
}
if (response.action === 'deny') {
event.preventDefault();
return defaultResponse;
} else if (response.action === 'allow') {
return {
browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null,
outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false
};
} else {
event.preventDefault();
console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
return defaultResponse;
}
};
const addReplyToEvent = (event: Electron.IpcMainEvent) => {
const { processId, frameId } = event;
event.reply = (channel: string, ...args: any[]) => {
event.sender.sendToFrame([processId, frameId], channel, ...args);
};
};
const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
event.sender = sender;
const { processId, frameId } = event;
Object.defineProperty(event, 'senderFrame', {
get: () => webFrameMain.fromId(processId, frameId)
});
};
const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
Object.defineProperty(event, 'returnValue', {
set: (value) => event._replyChannel.sendReply(value),
get: () => {}
});
};
const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
if (!event.processId || !event.frameId) return null;
return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId);
};
const commandLine = process._linkedBinding('electron_common_command_line');
const environment = process._linkedBinding('electron_common_environment');
const loggingEnabled = () => {
return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
};
// Add JavaScript wrappers for WebContents class.
WebContents.prototype._init = function () {
const prefs = this.getLastWebPreferences() || {};
if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) {
deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.');
}
// Read off the ID at construction time, so that it's accessible even after
// the underlying C++ WebContents is destroyed.
const id = this.id;
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this._windowOpenHandler = null;
const ipc = new IpcMainImpl();
Object.defineProperty(this, 'ipc', {
get () { return ipc; },
enumerable: true
});
// Dispatch IPC messages to the ipc module.
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
this.emit('ipc-message', event, channel, ...args);
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
const replyWithError = (error: Error) => {
console.error(`Error occurred in handler for '${channel}':`, error);
event._replyChannel.sendReply({ error: error.toString() });
};
const maybeWebFrame = getWebFrameForEvent(event);
const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
if (target) {
const handler = (target as any)._invokeHandlers.get(channel);
try {
replyWithResult(await Promise.resolve(handler(event, ...args)));
} catch (err) {
replyWithError(err as Error);
}
} else {
replyWithError(new Error(`No handler registered for '${channel}'`));
}
});
this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
addReturnValueToEvent(event);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
const maybeWebFrame = getWebFrameForEvent(event);
if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) {
console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
}
this.emit('ipc-message-sync', event, channel, ...args);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
addSenderToEvent(event, this);
event.ports = ports.map(p => new MessagePortMain(p));
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
ipc.emit(channel, event, message);
ipcMain.emit(channel, event, message);
});
this.on('crashed', (event, ...args) => {
app.emit('renderer-process-crashed', event, this, ...args);
});
this.on('render-process-gone', (event, details) => {
app.emit('render-process-gone', event, this, details);
// Log out a hint to help users better debug renderer crashes.
if (loggingEnabled()) {
console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
}
});
// The devtools requests the webContents to reload.
this.on('devtools-reload-page', function (this: Electron.WebContents) {
this.reload();
});
if (this.getType() !== 'remote') {
// Make new windows requested by links behave like "window.open".
this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
referrer,
postBody,
disposition
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
const options = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
openGuestWindow({
embedder: this,
disposition,
referrer,
postData,
overrideBrowserWindowOptions: options || {},
windowOpenArgs: details,
outlivesOpener: result.outlivesOpener
});
}
});
let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
let windowOpenOutlivesOpenerOption: boolean = false;
this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
disposition,
referrer,
postBody
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
windowOpenOutlivesOpenerOption = result.outlivesOpener;
windowOpenOverriddenOptions = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
// Allow setting of backgroundColor as a webPreference even though
// it's technically a BrowserWindowConstructorOptions option because
// we need to access it in the renderer at init time.
backgroundColor: windowOpenOverriddenOptions.backgroundColor,
transparent: windowOpenOverriddenOptions.transparent,
...windowOpenOverriddenOptions.webPreferences
} : undefined;
const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
const webPreferences = makeWebPreferences({
embedder: this,
insecureParsedWebPreferences: parsedWebPreferences,
secureOverrideWebPreferences
});
windowOpenOverriddenOptions = {
...windowOpenOverriddenOptions,
webPreferences
};
this._setNextChildWebPreferences(webPreferences);
}
});
// Create a new browser window for "window.open"
this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
_userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
const overriddenOptions = windowOpenOverriddenOptions || undefined;
const outlivesOpener = windowOpenOutlivesOpenerOption;
windowOpenOverriddenOptions = null;
// false is the default
windowOpenOutlivesOpenerOption = false;
if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
disposition !== 'background-tab')) {
event.preventDefault();
return;
}
openGuestWindow({
embedder: this,
guest: webContents,
overrideBrowserWindowOptions: overriddenOptions,
disposition,
referrer,
postData,
windowOpenArgs: {
url,
frameName,
features: rawFeatures
},
outlivesOpener
});
});
}
this.on('login', (event, ...args) => {
app.emit('login', event, this, ...args);
});
this.on('ready-to-show' as any, () => {
const owner = this.getOwnerBrowserWindow();
if (owner && !owner.isDestroyed()) {
process.nextTick(() => {
owner.emit('ready-to-show');
});
}
});
this.on('select-bluetooth-device', (event, devices, callback) => {
if (this.listenerCount('select-bluetooth-device') === 1) {
// Cancel it if there are no handlers
event.preventDefault();
callback('');
}
});
app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);
// Properties
Object.defineProperty(this, 'audioMuted', {
get: () => this.isAudioMuted(),
set: (muted) => this.setAudioMuted(muted)
});
Object.defineProperty(this, 'userAgent', {
get: () => this.getUserAgent(),
set: (agent) => this.setUserAgent(agent)
});
Object.defineProperty(this, 'zoomLevel', {
get: () => this.getZoomLevel(),
set: (level) => this.setZoomLevel(level)
});
Object.defineProperty(this, 'zoomFactor', {
get: () => this.getZoomFactor(),
set: (factor) => this.setZoomFactor(factor)
});
Object.defineProperty(this, 'frameRate', {
get: () => this.getFrameRate(),
set: (rate) => this.setFrameRate(rate)
});
Object.defineProperty(this, 'backgroundThrottling', {
get: () => this.getBackgroundThrottling(),
set: (allowed) => this.setBackgroundThrottling(allowed)
});
};
// Public APIs.
export function create (options = {}): Electron.WebContents {
return new (WebContents as any)(options);
}
export function fromId (id: string) {
return binding.fromId(id);
}
export function fromFrame (frame: Electron.WebFrameMain) {
return binding.fromFrame(frame);
}
export function fromDevToolsTargetId (targetId: string) {
return binding.fromDevToolsTargetId(targetId);
}
export function getFocusedWebContents () {
let focused = null;
for (const contents of binding.getAllWebContents()) {
if (!contents.isFocused()) continue;
if (focused == null) focused = contents;
// Return webview web contents which may be embedded inside another
// web contents that is also reporting as focused
if (contents.getType() === 'webview') return contents;
}
return focused;
}
export function getAllWebContents () {
return binding.getAllWebContents();
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,598 |
[Bug]: webContents.print fails with unspecified options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.1
### Expected Behavior
Calling `webContents.print()`, `webContents.print({})`, or `webContents.print(null)` will result in the system print dialog to appearing.
### Actual Behavior
If `print()` or `print({})` are called, the call will never invoke the provided callback (at least not within 5 minutes, which was the longest I let it sit), nor will it throw any exceptions catchable by a try-catch block. When running the provided gist in Electron Fiddle, I see the following console log: "[19232:0605/173028.939:ERROR:device_event_log_impl.cc(222)] [17:30:28.939] Printer: print_view_manager_base.cc:352 Printer settings invalid for \\epic-print1\vca2cpy-Revenge (destination type kLocal): content size is empty; page size is empty; printable area is empty"
If `print(null)` is called, an exception will be thrown with the error message: "Cannot read properties of null (reading 'pageSize')".
### Testcase Gist URL
https://gist.github.com/mgalla10/7710e8f22830f1122cfe0d98dd99ab08
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38598
|
https://github.com/electron/electron/pull/38614
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
|
c0d9764de9d00968a8c9d5ab74ef3b9840aebc09
| 2023-06-05T22:43:02Z |
c++
| 2023-06-09T19:41:01Z |
spec/api-web-contents-spec.ts
|
import { expect } from 'chai';
import { AddressInfo } from 'net';
import * as path from 'path';
import * as fs from 'fs';
import * as http from 'http';
import { BrowserWindow, ipcMain, webContents, session, app, BrowserView } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers';
import { once } from 'events';
import { setTimeout } from 'timers/promises';
const pdfjs = require('pdfjs-dist');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const mainFixturesPath = path.resolve(__dirname, 'fixtures');
const features = process._linkedBinding('electron_common_features');
describe('webContents module', () => {
describe('getAllWebContents() API', () => {
afterEach(closeAllWindows);
it('returns an array of web contents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { webviewTag: true }
});
w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
await once(w.webContents, 'did-attach-webview');
w.webContents.openDevTools();
await once(w.webContents, 'devtools-opened');
const all = webContents.getAllWebContents().sort((a, b) => {
return a.id - b.id;
});
expect(all).to.have.length(3);
expect(all[0].getType()).to.equal('window');
expect(all[all.length - 2].getType()).to.equal('webview');
expect(all[all.length - 1].getType()).to.equal('remote');
});
});
describe('fromId()', () => {
it('returns undefined for an unknown id', () => {
expect(webContents.fromId(12345)).to.be.undefined();
});
});
describe('fromFrame()', () => {
it('returns WebContents for mainFrame', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents);
});
it('returns undefined for disposed frame', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const { mainFrame } = contents;
contents.destroy();
await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined');
});
it('throws when passing invalid argument', async () => {
let errored = false;
try {
webContents.fromFrame({} as any);
} catch {
errored = true;
}
expect(errored).to.be.true();
});
});
describe('fromDevToolsTargetId()', () => {
it('returns WebContents for attached DevTools target', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
try {
await w.webContents.debugger.attach('1.3');
const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
} finally {
await w.webContents.debugger.detach();
}
});
it('returns undefined for an unknown id', () => {
expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
});
});
describe('will-prevent-unload event', function () {
afterEach(closeAllWindows);
it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
view.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits if beforeunload returns false in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'will-prevent-unload');
});
it('emits if beforeunload returns false in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(view.webContents, 'will-prevent-unload');
});
it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', event => event.preventDefault());
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
});
describe('webContents.send(channel, args...)', () => {
afterEach(closeAllWindows);
it('throws an error when the channel is missing', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
(w.webContents.send as any)();
}).to.throw('Missing required channel argument');
expect(() => {
w.webContents.send(null as any);
}).to.throw('Missing required channel argument');
});
it('does not block node async APIs when sent before document is ready', (done) => {
// Please reference https://github.com/electron/electron/issues/19368 if
// this test fails.
ipcMain.once('async-node-api-done', () => {
done();
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
setTimeout(50).then(() => {
w.webContents.send('test');
});
});
});
ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('throws when invalid settings are passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print(true);
}).to.throw('webContents.print(): Invalid print settings specified.');
});
it('throws when an invalid callback is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({}, true);
}).to.throw('webContents.print(): Invalid optional callback provided.');
});
it('fails when an invalid deviceName is passed', (done) => {
w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
expect(success).to.equal(false);
expect(reason).to.match(/Invalid deviceName provided/);
done();
});
});
it('throws when an invalid pageSize is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
}).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
});
it('throws when an invalid custom pageSize is passed', () => {
expect(() => {
w.webContents.print({
pageSize: {
width: 100,
height: 200
}
});
}).to.throw('height and width properties must be minimum 352 microns.');
});
it('does not crash with custom margins', () => {
expect(() => {
w.webContents.print({
silent: true,
margins: {
marginType: 'custom',
top: 1,
bottom: 1,
left: 1,
right: 1
}
});
}).to.not.throw();
});
});
describe('webContents.executeJavaScript', () => {
describe('in about:blank', () => {
const expected = 'hello, world!';
const expectedErrorMsg = 'woops!';
const code = `(() => "${expected}")()`;
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
]);
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
await w.loadURL('about:blank');
});
after(closeAllWindows);
it('resolves the returned promise with the result', async () => {
const result = await w.webContents.executeJavaScript(code);
expect(result).to.equal(expected);
});
it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
const result = await w.webContents.executeJavaScript(asyncCode);
expect(result).to.equal(expected);
});
it('rejects the returned promise if an async error is thrown', async () => {
await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
});
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error of errorTypes) {
await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
.to.eventually.be.rejectedWith(error);
}
});
});
describe('on a real page', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('works after page load and during subframe load', async () => {
await w.loadURL(serverUrl);
// initiate a sub-frame load, then try and execute script during it
await w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/slow'
document.body.appendChild(iframe)
null // don't return the iframe
`);
await w.webContents.executeJavaScript('console.log(\'hello\')');
});
it('executes after page load', async () => {
const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
w.loadURL(serverUrl);
const result = await executeJavaScript;
expect(result).to.equal('test');
});
});
});
describe('webContents.executeJavaScriptInIsolatedWorld', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
await w.loadURL('about:blank');
});
it('resolves the returned promise with the result', async () => {
await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
const mainWorldResult = await w.webContents.executeJavaScript('window.X');
expect(isolatedResult).to.equal(123);
expect(mainWorldResult).to.equal(undefined);
});
});
describe('loadURL() promise API', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('resolves when done loading', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('resolves when done loading a file URL', async () => {
await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
});
it('resolves when navigating within the page', async () => {
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await setTimeout();
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
it('rejects when failing to load a file URL', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FILE_NOT_FOUND');
});
// FIXME: Temporarily disable on WOA until
// https://github.com/electron/electron/issues/20008 is resolved
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => {
await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
});
it('rejects when navigation is cancelled due to a bad scheme', async () => {
await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FAILED');
});
it('does not crash when loading a new URL with emulation settings set', async () => {
const setEmulation = async () => {
if (w.webContents) {
w.webContents.debugger.attach('1.3');
const deviceMetrics = {
width: 700,
height: 600,
deviceScaleFactor: 2,
mobile: true,
dontSetVisibleSize: true
};
await w.webContents.debugger.sendCommand(
'Emulation.setDeviceMetricsOverride',
deviceMetrics
);
}
};
try {
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await setEmulation();
await w.loadURL('data:text/html,<h1>HELLO</h1>');
await setEmulation();
} catch (e) {
expect((e as Error).message).to.match(/Debugger is already attached to the target/);
}
});
it('sets appropriate error information on rejection', async () => {
let err: any;
try {
await w.loadURL('file:non-existent');
} catch (e) {
err = e;
}
expect(err).not.to.be.null();
expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
expect(err.errno).to.eql(-6);
expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
});
it('rejects if the load is aborted', async () => {
const s = http.createServer(() => { /* never complete the request */ });
const { port } = await listen(s);
const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
// load a different file before the first load completes, causing the
// first load to be aborted.
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await p;
s.close();
});
it("doesn't reject when a subframe fails to load", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="http://err.name.not.resolved"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.end();
await main;
s.close();
});
it("doesn't resolve when a subframe loads", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="about:blank"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.destroy(); // cause the main request to fail
await expect(main).to.eventually.be.rejected()
.and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
s.close();
});
});
describe('getFocusedWebContents() API', () => {
afterEach(closeAllWindows);
// FIXME
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => {
const w = new BrowserWindow({ show: true });
await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
const devToolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools();
await devToolsOpened;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id);
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
});
it('does not crash when called on a detached dev tools window', async () => {
const w = new BrowserWindow({ show: true });
w.webContents.openDevTools({ mode: 'detach' });
w.webContents.inspectElement(100, 100);
// For some reason we have to wait for two focused events...?
await once(w.webContents, 'devtools-focused');
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
// Work around https://github.com/electron/electron/issues/19985
await setTimeout();
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
});
});
describe('setDevToolsWebContents() API', () => {
afterEach(closeAllWindows);
it('sets arbitrary webContents as devtools', async () => {
const w = new BrowserWindow({ show: false });
const devtools = new BrowserWindow({ show: false });
const promise = once(devtools.webContents, 'dom-ready');
w.webContents.setDevToolsWebContents(devtools.webContents);
w.webContents.openDevTools();
await promise;
expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
expect(result).to.equal('InspectorFrontendHostImpl');
devtools.destroy();
});
});
describe('isFocused() API', () => {
it('returns false when the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(w.isVisible()).to.be.false();
expect(w.webContents.isFocused()).to.be.false();
});
});
describe('isCurrentlyAudible() API', () => {
afterEach(closeAllWindows);
it('returns whether audio is playing', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`
window.context = new AudioContext
// Start in suspended state, because of the
// new web audio api policy.
context.suspend()
window.oscillator = context.createOscillator()
oscillator.connect(context.destination)
oscillator.start()
`);
let p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('context.resume()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.true();
p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('oscillator.stop()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.false();
});
});
describe('openDevTools() API', () => {
afterEach(closeAllWindows);
it('can show window with activation', async () => {
const w = new BrowserWindow({ show: false });
const focused = once(w, 'focus');
w.show();
await focused;
expect(w.isFocused()).to.be.true();
const blurred = once(w, 'blur');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await Promise.all([
once(w.webContents, 'devtools-opened'),
once(w.webContents, 'devtools-focused')
]);
await blurred;
expect(w.isFocused()).to.be.false();
});
it('can show window without activation', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
});
});
describe('before-input-event event', () => {
afterEach(closeAllWindows);
it('can prevent document keyboard events', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
const keyDown = new Promise(resolve => {
ipcMain.once('keydown', (event, key) => resolve(key));
});
w.webContents.once('before-input-event', (event, input) => {
if (input.key === 'a') event.preventDefault();
});
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
expect(await keyDown).to.equal('b');
});
it('has the correct properties', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testBeforeInput = async (opts: any) => {
const modifiers = [];
if (opts.shift) modifiers.push('shift');
if (opts.control) modifiers.push('control');
if (opts.alt) modifiers.push('alt');
if (opts.meta) modifiers.push('meta');
if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
const p = once(w.webContents, 'before-input-event');
w.webContents.sendInputEvent({
type: opts.type,
keyCode: opts.keyCode,
modifiers: modifiers as any
});
const [, input] = await p;
expect(input.type).to.equal(opts.type);
expect(input.key).to.equal(opts.key);
expect(input.code).to.equal(opts.code);
expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
expect(input.shift).to.equal(opts.shift);
expect(input.control).to.equal(opts.control);
expect(input.alt).to.equal(opts.alt);
expect(input.meta).to.equal(opts.meta);
};
await testBeforeInput({
type: 'keyDown',
key: 'A',
code: 'KeyA',
keyCode: 'a',
shift: true,
control: true,
alt: true,
meta: true,
isAutoRepeat: true
});
await testBeforeInput({
type: 'keyUp',
key: '.',
code: 'Period',
keyCode: '.',
shift: false,
control: true,
alt: true,
meta: false,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: '!',
code: 'Digit1',
keyCode: '1',
shift: true,
control: false,
alt: false,
meta: true,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: 'Tab',
code: 'Tab',
keyCode: 'Tab',
shift: false,
control: true,
alt: false,
meta: false,
isAutoRepeat: true
});
});
});
// On Mac, zooming isn't done with the mouse wheel.
ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
afterEach(closeAllWindows);
it('is emitted with the correct zoom-in info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: 1,
wheelTicksX: 0,
wheelTicksY: 1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed');
expect(zoomDirection).to.equal('in');
};
await testZoomChanged();
});
it('is emitted with the correct zoom-out info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: -1,
wheelTicksX: 0,
wheelTicksY: -1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed');
expect(zoomDirection).to.equal('out');
};
await testZoomChanged();
});
});
describe('sendInputEvent(event)', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
});
afterEach(closeAllWindows);
it('can send keydown events', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send keydown events with modifiers', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
it('can send keydown events with special keys', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Tab');
expect(code).to.equal('Tab');
expect(keyCode).to.equal(9);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.true();
});
it('can send char events', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send char events with modifiers', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
});
describe('insertCSS', () => {
afterEach(closeAllWindows);
it('supports inserting CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.webContents.insertCSS('body { background-repeat: round; }');
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const key = await w.webContents.insertCSS('body { background-repeat: round; }');
await w.webContents.removeInsertedCSS(key);
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('repeat');
});
});
describe('inspectElement()', () => {
afterEach(closeAllWindows);
it('supports inspecting an element in the devtools', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const event = once(w.webContents, 'devtools-opened');
w.webContents.inspectElement(10, 10);
await event;
});
});
describe('startDrag({file, icon})', () => {
it('throws errors for a missing file or a missing/empty icon', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
}).to.throw('Must specify either \'file\' or \'files\' option');
expect(() => {
w.webContents.startDrag({ file: __filename } as any);
}).to.throw('\'icon\' parameter is required');
expect(() => {
w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('focus APIs', () => {
describe('focus()', () => {
afterEach(closeAllWindows);
it('does not blur the focused window when the web contents is hidden', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.show();
await w.loadURL('about:blank');
w.focus();
const child = new BrowserWindow({ show: false });
child.loadURL('about:blank');
child.webContents.focus();
const currentFocused = w.isFocused();
const childFocused = child.isFocused();
child.close();
expect(currentFocused).to.be.true();
expect(childFocused).to.be.false();
});
});
const moveFocusToDevTools = async (win: BrowserWindow) => {
const devToolsOpened = once(win.webContents, 'devtools-opened');
win.webContents.openDevTools({ mode: 'right' });
await devToolsOpened;
win.webContents.devToolsWebContents!.focus();
};
describe('focus event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is focused', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await moveFocusToDevTools(w);
const focusPromise = once(w.webContents, 'focus');
w.webContents.focus();
await expect(focusPromise).to.eventually.be.fulfilled();
});
});
describe('blur event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is blurred', async () => {
const w = new BrowserWindow({ show: true });
await w.loadURL('about:blank');
w.webContents.focus();
const blurPromise = once(w.webContents, 'blur');
await moveFocusToDevTools(w);
await expect(blurPromise).to.eventually.be.fulfilled();
});
});
});
describe('getOSProcessId()', () => {
afterEach(closeAllWindows);
it('returns a valid process id', async () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getOSProcessId()).to.equal(0);
await w.loadURL('about:blank');
expect(w.webContents.getOSProcessId()).to.be.above(0);
});
});
describe('getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns a valid stream id', () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
});
});
describe('userAgent APIs', () => {
it('is not empty by default', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
expect(userAgent).to.be.a('string').that.is.not.empty();
});
it('can set the user agent (functions)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
w.webContents.setUserAgent('my-user-agent');
expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
w.webContents.setUserAgent(userAgent);
expect(w.webContents.getUserAgent()).to.equal(userAgent);
});
it('can set the user agent (properties)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.userAgent;
w.webContents.userAgent = 'my-user-agent';
expect(w.webContents.userAgent).to.equal('my-user-agent');
w.webContents.userAgent = userAgent;
expect(w.webContents.userAgent).to.equal(userAgent);
});
});
describe('audioMuted APIs', () => {
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setAudioMuted(true);
expect(w.webContents.isAudioMuted()).to.be.true();
w.webContents.setAudioMuted(false);
expect(w.webContents.isAudioMuted()).to.be.false();
});
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.audioMuted = true;
expect(w.webContents.audioMuted).to.be.true();
w.webContents.audioMuted = false;
expect(w.webContents.audioMuted).to.be.false();
});
});
describe('zoom api', () => {
const hostZoomMap: Record<string, number> = {
host1: 0.3,
host2: 0.7,
host3: 0.2
};
before(() => {
const protocol = session.defaultSession.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
const response = `<script>
const {ipcRenderer} = require('electron')
ipcRenderer.send('set-zoom', window.location.hostname)
ipcRenderer.on(window.location.hostname + '-zoom-set', () => {
ipcRenderer.send(window.location.hostname + '-zoom-level')
})
</script>`;
callback({ data: response, mimeType: 'text/html' });
});
});
after(() => {
const protocol = session.defaultSession.protocol;
protocol.unregisterProtocol(standardScheme);
});
afterEach(closeAllWindows);
it('throws on an invalid zoomFactor', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
w.webContents.setZoomFactor(0.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
expect(() => {
w.webContents.setZoomFactor(-2.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
});
it('can set the correct zoom level (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.getZoomLevel();
expect(zoomLevel).to.eql(0.0);
w.webContents.setZoomLevel(0.5);
const newZoomLevel = w.webContents.getZoomLevel();
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.setZoomLevel(0);
}
});
it('can set the correct zoom level (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.eql(0.0);
w.webContents.zoomLevel = 0.5;
const newZoomLevel = w.webContents.zoomLevel;
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.zoomLevel = 0;
}
});
it('can set the correct zoom factor (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.getZoomFactor();
expect(zoomFactor).to.eql(1.0);
w.webContents.setZoomFactor(0.5);
const newZoomFactor = w.webContents.getZoomFactor();
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.setZoomFactor(1.0);
}
});
it('can set the correct zoom factor (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.zoomFactor;
expect(zoomFactor).to.eql(1.0);
w.webContents.zoomFactor = 0.5;
const newZoomFactor = w.webContents.zoomFactor;
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.zoomFactor = 1.0;
}
});
it('can persist zoom level across navigation', (done) => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
let finalNavigation = false;
ipcMain.on('set-zoom', (e, host) => {
const zoomLevel = hostZoomMap[host];
if (!finalNavigation) w.webContents.zoomLevel = zoomLevel;
e.sender.send(`${host}-zoom-set`);
});
ipcMain.on('host1-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host1;
expect(zoomLevel).to.equal(expectedZoomLevel);
if (finalNavigation) {
done();
} else {
w.loadURL(`${standardScheme}://host2`);
}
} catch (e) {
done(e);
}
});
ipcMain.once('host2-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host2;
expect(zoomLevel).to.equal(expectedZoomLevel);
finalNavigation = true;
w.webContents.goBack();
} catch (e) {
done(e);
}
});
w.loadURL(`${standardScheme}://host1`);
});
it('can propagate zoom level across same session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({ show: false });
defer(() => {
w2.setClosable(true);
w2.close();
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel1).to.equal(zoomLevel2);
});
it('cannot propagate zoom level across different session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({
show: false,
webPreferences: {
partition: 'temp'
}
});
const protocol = w2.webContents.session.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
callback('hello');
});
defer(() => {
w2.setClosable(true);
w2.close();
protocol.unregisterProtocol(standardScheme);
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
it('can persist when it contains iframe', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
setTimeout(200).then(() => {
res.end();
});
});
server.listen(0, '127.0.0.1', () => {
const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
const content = `<iframe src=${url}></iframe>`;
w.webContents.on('did-frame-finish-load', (e, isMainFrame) => {
if (!isMainFrame) {
try {
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(2.0);
w.webContents.zoomLevel = 0;
done();
} catch (e) {
done(e);
} finally {
server.close();
}
}
});
w.webContents.on('dom-ready', () => {
w.webContents.zoomLevel = 2.0;
});
w.loadURL(`data:text/html,${content}`);
});
});
it('cannot propagate when used with webframe', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const w2 = new BrowserWindow({ show: false });
const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set');
w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html'));
await temporaryZoomSet;
const finalZoomLevel = w.webContents.getZoomLevel();
await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html'));
const zoomLevel1 = w.webContents.zoomLevel;
const zoomLevel2 = w2.webContents.zoomLevel;
w2.setClosable(true);
w2.close();
expect(zoomLevel1).to.equal(finalZoomLevel);
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
describe('with unique domains', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
setTimeout().then(() => res.end('hey'));
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
it('cannot persist zoom level after navigation with webFrame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const source = `
const {ipcRenderer, webFrame} = require('electron')
webFrame.setZoomLevel(0.6)
ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel())
`;
const zoomLevelPromise = once(ipcMain, 'zoom-level-set');
await w.loadURL(serverUrl);
await w.webContents.executeJavaScript(source);
let [, zoomLevel] = await zoomLevelPromise;
expect(zoomLevel).to.equal(0.6);
const loadPromise = once(w.webContents, 'did-finish-load');
await w.loadURL(crossSiteUrl);
await loadPromise;
zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(0);
});
});
});
describe('webrtc ip policy api', () => {
afterEach(closeAllWindows);
it('can set and get webrtc ip policies', () => {
const w = new BrowserWindow({ show: false });
const policies = [
'default',
'default_public_interface_only',
'default_public_and_private_interfaces',
'disable_non_proxied_udp'
];
policies.forEach((policy) => {
w.webContents.setWebRTCIPHandlingPolicy(policy as any);
expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
});
});
});
describe('opener api', () => {
afterEach(closeAllWindows);
it('can get opener with window.open()', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript('window.open("about:blank")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener when using "noopener"', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
it('can get opener with a[target=_blank][rel=opener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'opener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener with a[target=_blank][rel=noopener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
});
describe('render view deleted events', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${crossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else if (req.url === '/first-window-open') {
res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
} else if (req.url === '/second-window-open') {
res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
afterEach(closeAllWindows);
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
w.webContents.on('did-finish-load', () => {
w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
});
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const parentWindow = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
let childWindow: BrowserWindow | null = null;
const destroyed = once(parentWindow.webContents, 'destroyed');
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
const childWindowCreated = new Promise<void>((resolve) => {
app.once('browser-window-created', (event, window) => {
childWindow = window;
window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
resolve();
});
});
parentWindow.loadURL(`${serverUrl}/first-window-open`);
await childWindowCreated;
childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
parentWindow.close();
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
});
it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
w.webContents.on('current-render-view-deleted' as any, () => {
currentRenderViewDeletedEmitted = true;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
});
it('emits render-view-deleted if any RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let rvhDeletedCount = 0;
w.webContents.on('render-view-deleted' as any, () => {
rvhDeletedCount++;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
const expectedRenderViewDeletedEventCount = 1;
expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
});
});
describe('setIgnoreMenuShortcuts(ignore)', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.setIgnoreMenuShortcuts(true);
w.webContents.setIgnoreMenuShortcuts(false);
}).to.not.throw();
});
});
const crashPrefs = [
{
nodeIntegration: true
},
{
sandbox: true
}
];
const nicePrefs = (o: any) => {
let s = '';
for (const key of Object.keys(o)) {
s += `${key}=${o[key]}, `;
}
return `(${s.slice(0, s.length - 2)})`;
};
for (const prefs of crashPrefs) {
describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('isCrashed() is false by default', () => {
expect(w.webContents.isCrashed()).to.equal(false);
});
it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
const crashEvent = once(w.webContents, 'render-process-gone');
w.webContents.forcefullyCrashRenderer();
const [, details] = await crashEvent;
expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
expect(w.webContents.isCrashed()).to.equal(true);
});
it('a crashed process is recoverable with reload()', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
w.webContents.forcefullyCrashRenderer();
w.webContents.reload();
expect(w.webContents.isCrashed()).to.equal(false);
});
});
}
// Destroying webContents in its event listener is going to crash when
// Electron is built in Debug mode.
describe('destroy()', () => {
let server: http.Server;
let serverUrl: string;
before((done) => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/200':
response.end();
break;
default:
done('unsupported endpoint');
}
}).listen(0, '127.0.0.1', () => {
serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
done();
});
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', url: '/200' },
{ name: 'dom-ready', url: '/200' },
{ name: 'did-stop-loading', url: '/200' },
{ name: 'did-finish-load', url: '/200' },
// FIXME: Multiple Emit calls inside an observer assume that object
// will be alive till end of the observer. Synchronous `destroy` api
// violates this contract and crashes.
{ name: 'did-frame-finish-load', url: '/200' },
{ name: 'did-fail-load', url: '/net-error' }
];
for (const e of events) {
it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
// This test is flaky on Windows CI and we don't know why, but the
// purpose of this test is to make sure Electron does not crash so it
// is fine to retry this test for a few times.
this.retries(3);
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const originalEmit = contents.emit.bind(contents);
contents.emit = (...args) => { return originalEmit(...args); };
contents.once(e.name as any, () => contents.destroy());
const destroyed = once(contents, 'destroyed');
contents.loadURL(serverUrl + e.url);
await destroyed;
});
}
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('is triggered with correct theme color', (done) => {
const w = new BrowserWindow({ show: true });
let count = 0;
w.webContents.on('did-change-theme-color', (e, color) => {
try {
if (count === 0) {
count += 1;
expect(color).to.equal('#FFEEDD');
w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
} else if (count === 1) {
expect(color).to.be.null();
done();
}
} catch (e) {
done(e);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
});
});
describe('console-message event', () => {
afterEach(closeAllWindows);
it('is triggered with correct log message', (done) => {
const w = new BrowserWindow({ show: true });
w.webContents.on('console-message', (e, level, message) => {
// Don't just assert as Chromium might emit other logs that we should ignore.
if (message === 'a') {
done();
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
});
});
describe('ipc-message event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends an asynchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
w.webContents.executeJavaScript(`
require('electron').ipcRenderer.send('message', 'Hello World!')
`);
const [, channel, message] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
});
});
describe('ipc-message-sync event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends a synchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
const promise: Promise<[string, string]> = new Promise(resolve => {
w.webContents.once('ipc-message-sync', (event, channel, arg) => {
event.returnValue = 'foobar';
resolve([channel, arg]);
});
});
const result = await w.webContents.executeJavaScript(`
require('electron').ipcRenderer.sendSync('message', 'Hello World!')
`);
const [channel, message] = await promise;
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
expect(result).to.equal('foobar');
});
});
describe('referrer', () => {
afterEach(closeAllWindows);
it('propagates referrer information to new target=_blank windows', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
} finally {
server.close();
}
}
res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
});
server.listen(0, '127.0.0.1', () => {
const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/';
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url);
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('a.click()');
});
w.loadURL(url);
});
});
it('propagates referrer information to windows opened with window.open', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
}
}
res.end('');
});
server.listen(0, '127.0.0.1', () => {
const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/';
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url);
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
});
w.loadURL(url);
});
});
});
describe('webframe messages in sandboxed contents', () => {
afterEach(closeAllWindows);
it('responds to executeJavaScript', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const result = await w.webContents.executeJavaScript('37 + 5');
expect(result).to.equal(42);
});
});
describe('preload-error event', () => {
afterEach(closeAllWindows);
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('is triggered when unhandled exception is thrown', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error');
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('Hello World!');
});
it('is triggered on syntax errors', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error');
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('foobar is not defined');
});
it('is triggered when preload script loading fails', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error');
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.contain('preload-invalid.js');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('takeHeapSnapshot()', () => {
afterEach(closeAllWindows);
it('works with sandboxed renderers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
const cleanup = () => {
try {
fs.unlinkSync(filePath);
} catch (e) {
// ignore error
}
};
try {
await w.webContents.takeHeapSnapshot(filePath);
const stats = fs.statSync(filePath);
expect(stats.size).not.to.be.equal(0);
} finally {
cleanup();
}
});
it('fails with invalid file path', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path');
const promise = w.webContents.takeHeapSnapshot(badPath);
return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`);
});
it('fails with invalid render process', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
w.webContents.destroy();
const promise = w.webContents.takeHeapSnapshot(filePath);
return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame');
});
});
describe('setBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('does not crash when allowing', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(true);
});
it('does not crash when called via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
(w as any).setBackgroundThrottling(true);
});
it('does not crash when disallowing', () => {
const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
w.webContents.setBackgroundThrottling(false);
});
});
describe('getBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('works via getter', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
expect(w.webContents.getBackgroundThrottling()).to.equal(false);
w.webContents.setBackgroundThrottling(true);
expect(w.webContents.getBackgroundThrottling()).to.equal(true);
});
it('works via property', () => {
const w = new BrowserWindow({ show: false });
w.webContents.backgroundThrottling = false;
expect(w.webContents.backgroundThrottling).to.equal(false);
w.webContents.backgroundThrottling = true;
expect(w.webContents.backgroundThrottling).to.equal(true);
});
it('works via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
(w as any).setBackgroundThrottling(false);
expect((w as any).getBackgroundThrottling()).to.equal(false);
(w as any).setBackgroundThrottling(true);
expect((w as any).getBackgroundThrottling()).to.equal(true);
});
});
ifdescribe(features.isPrintingEnabled())('getPrinters()', () => {
afterEach(closeAllWindows);
it('can get printer list', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const printers = w.webContents.getPrinters();
expect(printers).to.be.an('array');
});
});
ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
afterEach(closeAllWindows);
it('can get printer list', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const printers = await w.webContents.getPrintersAsync();
expect(printers).to.be.an('array');
});
});
ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
});
afterEach(closeAllWindows);
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
}
});
it('does not crash when called multiple times in parallel', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const promises = [];
for (let i = 0; i < 3; i++) {
promises.push(w.webContents.printToPDF({}));
}
const results = await Promise.all(promises);
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('does not crash when called multiple times in sequence', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const results = [];
for (let i = 0; i < 3; i++) {
const result = await w.webContents.printToPDF({});
results.push(result);
}
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('can print a PDF with default settings', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const data = await w.webContents.printToPDF({});
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
});
it('with custom page sizes', async () => {
const paperFormats: Record<string, ElectronInternal.PageSize> = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
};
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
for (const format of Object.keys(paperFormats)) {
const data = await w.webContents.printToPDF({ pageSize: format });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2] / 72;
const height = page.view[3] / 72;
const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon;
expect(approxEq(width, paperFormats[format].width)).to.be.true();
expect(approxEq(height, paperFormats[format].height)).to.be.true();
}
});
it('with custom header and footer', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({
displayHeaderFooter: true,
headerTemplate: '<div>I\'m a PDF header</div>',
footerTemplate: '<div>I\'m a PDF footer</div>'
});
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
const { items } = await page.getTextContent();
// Check that generated PDF contains a header.
const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text));
expect(containsText(/I'm a PDF header/)).to.be.true();
expect(containsText(/I'm a PDF footer/)).to.be.true();
});
it('in landscape mode', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ landscape: true });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2];
const height = page.view[3];
expect(width).to.be.greaterThan(height);
});
it('with custom page ranges', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html'));
const data = await w.webContents.printToPDF({
pageRanges: '1-3',
landscape: true
});
const doc = await pdfjs.getDocument(data).promise;
// Check that correct # of pages are rendered.
expect(doc.numPages).to.equal(3);
});
});
describe('PictureInPicture video', () => {
afterEach(closeAllWindows);
it('works as expected', async function () {
const w = new BrowserWindow({ webPreferences: { sandbox: true } });
// TODO(codebytere): figure out why this workaround is needed and remove.
// It is not germane to the actual test.
await w.loadFile(path.join(fixturesPath, 'blank.html'));
await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true);
const result = await w.webContents.executeJavaScript('runTest(true)', true);
expect(result).to.be.true();
});
});
describe('Shared Workers', () => {
afterEach(closeAllWindows);
it('can get multiple shared workers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
expect(sharedWorkers).to.have.lengthOf(2);
expect(sharedWorkers[0].url).to.contain('shared-worker');
expect(sharedWorkers[1].url).to.contain('shared-worker');
});
it('can inspect a specific shared worker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
await devtoolsOpened;
const devtoolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devtoolsClosed;
});
});
describe('login event', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
let serverPort: number;
let proxyServer: http.Server;
let proxyServerPort: number;
before(async () => {
server = http.createServer((request, response) => {
if (request.url === '/no-auth') {
return response.end('ok');
}
if (request.headers.authorization) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers.authorization);
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end('401');
});
({ port: serverPort, url: serverUrl } = await listen(server));
});
before(async () => {
proxyServer = http.createServer((request, response) => {
if (request.headers['proxy-authorization']) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers['proxy-authorization']);
}
response
.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
.end();
});
proxyServerPort = (await listen(proxyServer)).port;
});
afterEach(async () => {
await session.defaultSession.clearAuthCache();
});
after(() => {
server.close();
proxyServer.close();
});
it('is emitted when navigating', async () => {
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(serverUrl + '/');
expect(eventAuthInfo.isProxy).to.be.false();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(serverPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('is emitted when a proxy requests authorization', async () => {
const customSession = session.fromPartition(`${Math.random()}`);
await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(`${serverUrl}/no-auth`);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
expect(eventAuthInfo.isProxy).to.be.true();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(proxyServerPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('cancels authentication when callback is called with no arguments', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.on('login', (event, request, authInfo, cb) => {
event.preventDefault();
cb();
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal('401');
});
});
describe('page-title-updated event', () => {
afterEach(closeAllWindows);
it('is emitted with a full title for pages with no navigation', async () => {
const bw = new BrowserWindow({ show: false });
await bw.loadURL('about:blank');
bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
const [, child] = await once(app, 'web-contents-created');
bw.webContents.executeJavaScript('child.document.title = "new title"');
const [, title] = await once(child, 'page-title-updated');
expect(title).to.equal('new title');
});
});
describe('crashed event', () => {
it('does not crash main process when destroying WebContents in it', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true });
const crashEvent = once(contents, 'render-process-gone');
await contents.loadURL('about:blank');
contents.forcefullyCrashRenderer();
await crashEvent;
contents.destroy();
});
});
describe('context-menu event', () => {
afterEach(closeAllWindows);
it('emits when right-clicked in page', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const promise = once(w.webContents, 'context-menu');
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' as any };
w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
const [, params] = await promise;
expect(params.pageURL).to.equal(w.webContents.getURL());
expect(params.frame).to.be.an('object');
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('close() method', () => {
afterEach(closeAllWindows);
it('closes when close() is called', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('closes when close() is called after loading a page', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('can be GCed before loading a page', async () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
let registry: FinalizationRegistry<unknown> | null = null;
const cleanedUp = new Promise<number>(resolve => {
registry = new FinalizationRegistry(resolve as any);
});
(() => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
registry!.register(w, 42);
})();
const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100);
defer(() => clearInterval(i));
expect(await cleanedUp).to.equal(42);
});
it('causes its parent browserwindow to be closed', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const closed = once(w, 'closed');
w.webContents.close();
await closed;
expect(w.isDestroyed()).to.be.true();
});
it('ignores beforeunload if waitForBeforeUnload not specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); });
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('runs beforeunload if waitForBeforeUnload is specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
const willPreventUnload = once(w, 'will-prevent-unload');
w.close({ waitForBeforeUnload: true });
await willPreventUnload;
expect(w.isDestroyed()).to.be.false();
});
it('overriding beforeunload prevention results in webcontents close', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.once('will-prevent-unload', e => e.preventDefault());
const destroyed = once(w, 'destroyed');
w.close({ waitForBeforeUnload: true });
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
});
describe('content-bounds-updated event', () => {
afterEach(closeAllWindows);
it('emits when moveTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.moveTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated');
const { width, height } = w.getBounds();
expect(rect).to.deep.equal({
x: 100,
y: 100,
width,
height
});
await new Promise(setImmediate);
expect(w.getBounds().x).to.equal(100);
expect(w.getBounds().y).to.equal(100);
});
it('emits when resizeTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated');
const { x, y } = w.getBounds();
expect(rect).to.deep.equal({
x,
y,
width: 100,
height: 100
});
await new Promise(setImmediate);
expect({
width: w.getBounds().width,
height: w.getBounds().height
}).to.deep.equal(process.platform === 'win32' ? {
// The width is reported as being larger on Windows? I'm not sure why
// this is.
width: 136,
height: 100
} : {
width: 100,
height: 100
});
});
it('does not change window bounds if cancelled', async () => {
const w = new BrowserWindow({ show: false });
const { width, height } = w.getBounds();
w.loadURL('about:blank');
w.webContents.once('content-bounds-updated', e => e.preventDefault());
await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
await new Promise(setImmediate);
expect(w.getBounds().width).to.equal(width);
expect(w.getBounds().height).to.equal(height);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,598 |
[Bug]: webContents.print fails with unspecified options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.1
### Expected Behavior
Calling `webContents.print()`, `webContents.print({})`, or `webContents.print(null)` will result in the system print dialog to appearing.
### Actual Behavior
If `print()` or `print({})` are called, the call will never invoke the provided callback (at least not within 5 minutes, which was the longest I let it sit), nor will it throw any exceptions catchable by a try-catch block. When running the provided gist in Electron Fiddle, I see the following console log: "[19232:0605/173028.939:ERROR:device_event_log_impl.cc(222)] [17:30:28.939] Printer: print_view_manager_base.cc:352 Printer settings invalid for \\epic-print1\vca2cpy-Revenge (destination type kLocal): content size is empty; page size is empty; printable area is empty"
If `print(null)` is called, an exception will be thrown with the error message: "Cannot read properties of null (reading 'pageSize')".
### Testcase Gist URL
https://gist.github.com/mgalla10/7710e8f22830f1122cfe0d98dd99ab08
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38598
|
https://github.com/electron/electron/pull/38614
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
|
c0d9764de9d00968a8c9d5ab74ef3b9840aebc09
| 2023-06-05T22:43:02Z |
c++
| 2023-06-09T19:41:01Z |
typings/internal-electron.d.ts
|
/// <reference path="../electron.d.ts" />
/**
* This file augments the Electron TS namespace with the internal APIs
* that are not documented but are used by Electron internally
*/
declare namespace Electron {
enum ProcessType {
browser = 'browser',
renderer = 'renderer',
worker = 'worker',
utility = 'utility'
}
interface App {
setVersion(version: string): void;
setDesktopName(name: string): void;
setAppPath(path: string | null): void;
}
type TouchBarItemType = NonNullable<Electron.TouchBarConstructorOptions['items']>[0];
interface BaseWindow {
_init(): void;
}
interface BrowserWindow {
_init(): void;
_touchBar: Electron.TouchBar | null;
_setTouchBarItems: (items: TouchBarItemType[]) => void;
_setEscapeTouchBarItem: (item: TouchBarItemType | {}) => void;
_refreshTouchBarItem: (itemID: string) => void;
_getWindowButtonVisibility: () => boolean;
frameName: string;
on(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
removeListener(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
}
interface BrowserWindowConstructorOptions {
webContents?: WebContents;
}
interface ContextBridge {
internalContextBridge?: {
contextIsolationEnabled: boolean;
overrideGlobalValueFromIsolatedWorld(keys: string[], value: any): void;
overrideGlobalValueWithDynamicPropsFromIsolatedWorld(keys: string[], value: any): void;
overrideGlobalPropertyFromIsolatedWorld(keys: string[], getter: Function, setter?: Function): void;
isInMainWorld(): boolean;
}
}
interface TouchBar {
_removeFromWindow: (win: BrowserWindow) => void;
}
interface WebContents {
_loadURL(url: string, options: ElectronInternal.LoadURLOptions): void;
getOwnerBrowserWindow(): Electron.BrowserWindow | null;
getLastWebPreferences(): Electron.WebPreferences | null;
_getProcessMemoryInfo(): Electron.ProcessMemoryInfo;
_getPreloadPaths(): string[];
equal(other: WebContents): boolean;
browserWindowOptions: BrowserWindowConstructorOptions;
_windowOpenHandler: ((details: Electron.HandlerDetails) => any) | null;
_callWindowOpenHandler(event: any, details: Electron.HandlerDetails): {browserWindowConstructorOptions: Electron.BrowserWindowConstructorOptions | null, outlivesOpener: boolean};
_setNextChildWebPreferences(prefs: Partial<Electron.BrowserWindowConstructorOptions['webPreferences']> & Pick<Electron.BrowserWindowConstructorOptions, 'backgroundColor'>): void;
_send(internal: boolean, channel: string, args: any): boolean;
_sendInternal(channel: string, ...args: any[]): void;
_printToPDF(options: any): Promise<Buffer>;
_print(options: any, callback?: (success: boolean, failureReason: string) => void): void;
_getPrinters(): Electron.PrinterInfo[];
_getPrintersAsync(): Promise<Electron.PrinterInfo[]>;
_init(): void;
canGoToIndex(index: number): boolean;
getActiveIndex(): number;
length(): number;
destroy(): void;
// <webview>
attachToIframe(embedderWebContents: Electron.WebContents, embedderFrameId: number): void;
detachFromOuterFrame(): void;
setEmbedder(embedder: Electron.WebContents): void;
viewInstanceId: number;
}
interface WebFrameMain {
_send(internal: boolean, channel: string, args: any): void;
_sendInternal(channel: string, ...args: any[]): void;
_postMessage(channel: string, message: any, transfer?: any[]): void;
}
interface WebFrame {
_isEvalAllowed(): boolean;
}
interface WebPreferences {
disablePopups?: boolean;
embedder?: Electron.WebContents;
type?: 'backgroundPage' | 'window' | 'browserView' | 'remote' | 'webview' | 'offscreen';
}
interface Menu {
_init(): void;
_isCommandIdChecked(id: string): boolean;
_isCommandIdEnabled(id: string): boolean;
_shouldCommandIdWorkWhenHidden(id: string): boolean;
_isCommandIdVisible(id: string): boolean;
_getAcceleratorForCommandId(id: string, useDefaultAccelerator: boolean): Accelerator | undefined;
_shouldRegisterAcceleratorForCommandId(id: string): boolean;
_getSharingItemForCommandId(id: string): SharingItem | null;
_callMenuWillShow(): void;
_executeCommand(event: KeyboardEvent, id: number): void;
_menuWillShow(): void;
commandsMap: Record<string, MenuItem>;
groupsMap: Record<string, MenuItem[]>;
getItemCount(): number;
popupAt(window: BaseWindow, x: number, y: number, positioning: number, callback: () => void): void;
closePopupAt(id: number): void;
setSublabel(index: number, label: string): void;
setToolTip(index: number, tooltip: string): void;
setIcon(index: number, image: string | NativeImage): void;
setRole(index: number, role: string): void;
insertItem(index: number, commandId: number, label: string): void;
insertCheckItem(index: number, commandId: number, label: string): void;
insertRadioItem(index: number, commandId: number, label: string, groupId: number): void;
insertSeparator(index: number): void;
insertSubMenu(index: number, commandId: number, label: string, submenu?: Menu): void;
delegate?: any;
_getAcceleratorTextAt(index: number): string;
}
interface MenuItem {
overrideReadOnlyProperty(property: string, value: any): void;
groupId: number;
getDefaultRoleAccelerator(): Accelerator | undefined;
getCheckStatus(): boolean;
acceleratorWorksWhenHidden?: boolean;
}
interface ReplyChannel {
sendReply(value: any): void;
}
interface IpcMainEvent {
_replyChannel: ReplyChannel;
}
interface IpcMainInvokeEvent {
_replyChannel: ReplyChannel;
}
class View {}
// Experimental views API
class BaseWindow {
constructor(args: {show: boolean})
setContentView(view: View): void
static fromId(id: number): BaseWindow;
static getAllWindows(): BaseWindow[];
isFocused(): boolean;
static getFocusedWindow(): BaseWindow | undefined;
setMenu(menu: Menu): void;
}
class WebContentsView {
constructor(options: BrowserWindowConstructorOptions)
}
// Deprecated / undocumented BrowserWindow methods
interface BrowserWindow {
getURL(): string;
send(channel: string, ...args: any[]): void;
openDevTools(options?: Electron.OpenDevToolsOptions): void;
closeDevTools(): void;
isDevToolsOpened(): void;
isDevToolsFocused(): void;
toggleDevTools(): void;
inspectElement(x: number, y: number): void;
inspectSharedWorker(): void;
inspectServiceWorker(): void;
getBackgroundThrottling(): void;
setBackgroundThrottling(allowed: boolean): void;
}
interface Protocol {
registerProtocol(scheme: string, handler: any): boolean;
interceptProtocol(scheme: string, handler: any): boolean;
}
namespace Main {
class BaseWindow extends Electron.BaseWindow {}
class View extends Electron.View {}
class WebContentsView extends Electron.WebContentsView {}
}
}
declare namespace ElectronInternal {
interface DesktopCapturer {
startHandling(captureWindow: boolean, captureScreen: boolean, thumbnailSize: Electron.Size, fetchWindowIcons: boolean): void;
_onerror?: (error: string) => void;
_onfinished?: (sources: Electron.DesktopCapturerSource[], fetchWindowIcons: boolean) => void;
}
interface GetSourcesOptions {
captureWindow: boolean;
captureScreen: boolean;
thumbnailSize: Electron.Size;
fetchWindowIcons: boolean;
}
interface GetSourcesResult {
id: string;
name: string;
thumbnail: Electron.NativeImage;
display_id: string;
appIcon: Electron.NativeImage | null;
}
interface IpcRendererInternal extends NodeJS.EventEmitter, Pick<Electron.IpcRenderer, 'send' | 'sendSync' | 'invoke'> {
invoke<T>(channel: string, ...args: any[]): Promise<T>;
}
interface IpcMainInternalEvent extends Omit<Electron.IpcMainEvent, 'reply'> {
}
interface IpcMainInternal extends NodeJS.EventEmitter {
handle(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any): void;
on(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this;
once(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this;
}
interface LoadURLOptions extends Electron.LoadURLOptions {
reloadIgnoringCache?: boolean;
}
interface WebContentsPrintOptions extends Electron.WebContentsPrintOptions {
mediaSize?: MediaSize;
}
type MediaSize = {
name: string,
custom_display_name: string,
height_microns: number,
width_microns: number,
is_default?: 'true',
}
type PageSize = {
width: number,
height: number,
}
type ModuleLoader = () => any;
interface ModuleEntry {
name: string;
loader: ModuleLoader;
}
interface UtilityProcessWrapper extends NodeJS.EventEmitter {
readonly pid: (number) | (undefined);
kill(): boolean;
postMessage(message: any, transfer?: any[]): void;
}
interface ParentPort extends NodeJS.EventEmitter {
start(): void;
pause(): void;
postMessage(message: any): void;
}
class WebViewElement extends HTMLElement {
static observedAttributes: Array<string>;
public contentWindow: Window;
public connectedCallback?(): void;
public attributeChangedCallback?(): void;
public disconnectedCallback?(): void;
// Created in web-view-impl
public getWebContentsId(): number;
public capturePage(rect?: Electron.Rectangle): Promise<Electron.NativeImage>;
}
class WebContents extends Electron.WebContents {
static create(opts?: Electron.WebPreferences): Electron.WebContents;
}
}
declare namespace Chrome {
namespace Tabs {
// https://developer.chrome.com/docs/extensions/tabs#method-executeScript
interface ExecuteScriptDetails {
code?: string;
file?: string;
allFrames?: boolean;
frameId?: number;
matchAboutBlank?: boolean;
runAt?: 'document-start' | 'document-end' | 'document_idle';
cssOrigin: 'author' | 'user';
}
type ExecuteScriptCallback = (result: Array<any>) => void;
// https://developer.chrome.com/docs/extensions/tabs#method-sendMessage
interface SendMessageDetails {
frameId?: number;
}
type SendMessageCallback = (result: any) => void;
}
}
interface Global extends NodeJS.Global {
require: NodeRequire;
module: NodeModule;
__filename: string;
__dirname: string;
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,598 |
[Bug]: webContents.print fails with unspecified options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.1
### Expected Behavior
Calling `webContents.print()`, `webContents.print({})`, or `webContents.print(null)` will result in the system print dialog to appearing.
### Actual Behavior
If `print()` or `print({})` are called, the call will never invoke the provided callback (at least not within 5 minutes, which was the longest I let it sit), nor will it throw any exceptions catchable by a try-catch block. When running the provided gist in Electron Fiddle, I see the following console log: "[19232:0605/173028.939:ERROR:device_event_log_impl.cc(222)] [17:30:28.939] Printer: print_view_manager_base.cc:352 Printer settings invalid for \\epic-print1\vca2cpy-Revenge (destination type kLocal): content size is empty; page size is empty; printable area is empty"
If `print(null)` is called, an exception will be thrown with the error message: "Cannot read properties of null (reading 'pageSize')".
### Testcase Gist URL
https://gist.github.com/mgalla10/7710e8f22830f1122cfe0d98dd99ab08
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38598
|
https://github.com/electron/electron/pull/38614
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
|
c0d9764de9d00968a8c9d5ab74ef3b9840aebc09
| 2023-06-05T22:43:02Z |
c++
| 2023-06-09T19:41:01Z |
lib/browser/api/web-contents.ts
|
import { app, ipcMain, session, webFrameMain } from 'electron/main';
import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main';
import * as url from 'url';
import * as path from 'path';
import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager';
import { parseFeatures } from '@electron/internal/browser/parse-features-string';
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
import { MessagePortMain } from '@electron/internal/browser/message-port-main';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl';
import * as deprecate from '@electron/internal/common/deprecate';
// session is not used here, the purpose is to make sure session is initialized
// before the webContents module.
// eslint-disable-next-line no-unused-expressions
session;
const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main');
let nextId = 0;
const getNextId = function () {
return ++nextId;
};
type PostData = LoadURLOptions['postData']
// Stock page sizes
const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = {
Letter: {
custom_display_name: 'Letter',
height_microns: 279400,
name: 'NA_LETTER',
width_microns: 215900
},
Legal: {
custom_display_name: 'Legal',
height_microns: 355600,
name: 'NA_LEGAL',
width_microns: 215900
},
Tabloid: {
height_microns: 431800,
name: 'NA_LEDGER',
width_microns: 279400,
custom_display_name: 'Tabloid'
},
A0: {
custom_display_name: 'A0',
height_microns: 1189000,
name: 'ISO_A0',
width_microns: 841000
},
A1: {
custom_display_name: 'A1',
height_microns: 841000,
name: 'ISO_A1',
width_microns: 594000
},
A2: {
custom_display_name: 'A2',
height_microns: 594000,
name: 'ISO_A2',
width_microns: 420000
},
A3: {
custom_display_name: 'A3',
height_microns: 420000,
name: 'ISO_A3',
width_microns: 297000
},
A4: {
custom_display_name: 'A4',
height_microns: 297000,
name: 'ISO_A4',
is_default: 'true',
width_microns: 210000
},
A5: {
custom_display_name: 'A5',
height_microns: 210000,
name: 'ISO_A5',
width_microns: 148000
},
A6: {
custom_display_name: 'A6',
height_microns: 148000,
name: 'ISO_A6',
width_microns: 105000
}
} as const;
const paperFormats: Record<string, ElectronInternal.PageSize> = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
} as const;
// The minimum micron size Chromium accepts is that where:
// Per printing/units.h:
// * kMicronsPerInch - Length of an inch in 0.001mm unit.
// * kPointsPerInch - Length of an inch in CSS's 1pt unit.
//
// Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
//
// Practically, this means microns need to be > 352 microns.
// We therefore need to verify this or it will silently fail.
const isValidCustomPageSize = (width: number, height: number) => {
return [width, height].every(x => x > 352);
};
// JavaScript implementations of WebContents.
const binding = process._linkedBinding('electron_browser_web_contents');
const printing = process._linkedBinding('electron_browser_printing');
const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } };
WebContents.prototype.postMessage = function (...args) {
return this.mainFrame.postMessage(...args);
};
WebContents.prototype.send = function (channel, ...args) {
return this.mainFrame.send(channel, ...args);
};
WebContents.prototype._sendInternal = function (channel, ...args) {
return this.mainFrame._sendInternal(channel, ...args);
};
function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) {
if (typeof frame === 'number') {
return webFrameMain.fromId(contents.mainFrame.processId, frame);
} else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) {
return webFrameMain.fromId(frame[0], frame[1]);
} else {
throw new Error('Missing required frame argument (must be number or [processId, frameId])');
}
}
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
const frame = getWebFrame(this, frameId);
if (!frame) return false;
frame.send(channel, ...args);
return true;
};
// Following methods are mapped to webFrame.
const webFrameMethods = [
'insertCSS',
'insertText',
'removeInsertedCSS',
'setVisualZoomLevelLimits'
] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[];
for (const method of webFrameMethods) {
WebContents.prototype[method] = function (...args: any[]): Promise<any> {
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args);
};
}
const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => {
if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
return new Promise<void>((resolve) => {
webContents.once('did-stop-loading', () => {
resolve();
});
});
};
// Make sure WebContents::executeJavaScript would run the code only when the
// WebContents has been loaded.
WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture);
};
WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture);
};
// Translate the options of printToPDF.
let pendingPromise: Promise<any> | undefined;
WebContents.prototype.printToPDF = async function (options) {
const printSettings: Record<string, any> = {
requestID: getNextId(),
landscape: false,
displayHeaderFooter: false,
headerTemplate: '',
footerTemplate: '',
printBackground: false,
scale: 1.0,
paperWidth: 8.5,
paperHeight: 11.0,
marginTop: 0.4,
marginBottom: 0.4,
marginLeft: 0.4,
marginRight: 0.4,
pageRanges: '',
preferCSSPageSize: false
};
if (options.landscape !== undefined) {
if (typeof options.landscape !== 'boolean') {
return Promise.reject(new Error('landscape must be a Boolean'));
}
printSettings.landscape = options.landscape;
}
if (options.displayHeaderFooter !== undefined) {
if (typeof options.displayHeaderFooter !== 'boolean') {
return Promise.reject(new Error('displayHeaderFooter must be a Boolean'));
}
printSettings.displayHeaderFooter = options.displayHeaderFooter;
}
if (options.printBackground !== undefined) {
if (typeof options.printBackground !== 'boolean') {
return Promise.reject(new Error('printBackground must be a Boolean'));
}
printSettings.shouldPrintBackgrounds = options.printBackground;
}
if (options.scale !== undefined) {
if (typeof options.scale !== 'number') {
return Promise.reject(new Error('scale must be a Number'));
}
printSettings.scale = options.scale;
}
const { pageSize } = options;
if (pageSize !== undefined) {
if (typeof pageSize === 'string') {
const format = paperFormats[pageSize.toLowerCase()];
if (!format) {
return Promise.reject(new Error(`Invalid pageSize ${pageSize}`));
}
printSettings.paperWidth = format.width;
printSettings.paperHeight = format.height;
} else if (typeof options.pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
return Promise.reject(new Error('height and width properties are required for pageSize'));
}
printSettings.paperWidth = pageSize.width;
printSettings.paperHeight = pageSize.height;
} else {
return Promise.reject(new Error('pageSize must be a String or Object'));
}
}
const { margins } = options;
if (margins !== undefined) {
if (typeof margins !== 'object') {
return Promise.reject(new Error('margins must be an Object'));
}
if (margins.top !== undefined) {
if (typeof margins.top !== 'number') {
return Promise.reject(new Error('margins.top must be a Number'));
}
printSettings.marginTop = margins.top;
}
if (margins.bottom !== undefined) {
if (typeof margins.bottom !== 'number') {
return Promise.reject(new Error('margins.bottom must be a Number'));
}
printSettings.marginBottom = margins.bottom;
}
if (margins.left !== undefined) {
if (typeof margins.left !== 'number') {
return Promise.reject(new Error('margins.left must be a Number'));
}
printSettings.marginLeft = margins.left;
}
if (margins.right !== undefined) {
if (typeof margins.right !== 'number') {
return Promise.reject(new Error('margins.right must be a Number'));
}
printSettings.marginRight = margins.right;
}
}
if (options.pageRanges !== undefined) {
if (typeof options.pageRanges !== 'string') {
return Promise.reject(new Error('pageRanges must be a String'));
}
printSettings.pageRanges = options.pageRanges;
}
if (options.headerTemplate !== undefined) {
if (typeof options.headerTemplate !== 'string') {
return Promise.reject(new Error('headerTemplate must be a String'));
}
printSettings.headerTemplate = options.headerTemplate;
}
if (options.footerTemplate !== undefined) {
if (typeof options.footerTemplate !== 'string') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.footerTemplate = options.footerTemplate;
}
if (options.preferCSSPageSize !== undefined) {
if (typeof options.preferCSSPageSize !== 'boolean') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.preferCSSPageSize = options.preferCSSPageSize;
}
if (this._printToPDF) {
if (pendingPromise) {
pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
} else {
pendingPromise = this._printToPDF(printSettings);
}
return pendingPromise;
} else {
const error = new Error('Printing feature is disabled');
return Promise.reject(error);
}
};
// TODO(codebytere): deduplicate argument sanitization by moving rest of
// print param logic into new file shared between printToPDF and print
WebContents.prototype.print = function (printOptions: ElectronInternal.WebContentsPrintOptions, callback) {
const options = printOptions ?? {};
if (options.pageSize) {
const pageSize = options.pageSize;
if (typeof pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
throw new Error('height and width properties are required for pageSize');
}
// Dimensions in Microns - 1 meter = 10^6 microns
const height = Math.ceil(pageSize.height);
const width = Math.ceil(pageSize.width);
if (!isValidCustomPageSize(width, height)) {
throw new Error('height and width properties must be minimum 352 microns.');
}
options.mediaSize = {
name: 'CUSTOM',
custom_display_name: 'Custom',
height_microns: height,
width_microns: width
};
} else if (PDFPageSizes[pageSize]) {
options.mediaSize = PDFPageSizes[pageSize];
} else {
throw new Error(`Unsupported pageSize: ${pageSize}`);
}
}
if (this._print) {
if (callback) {
this._print(options, callback);
} else {
this._print(options);
}
} else {
console.error('Error: Printing feature is disabled.');
}
};
WebContents.prototype.getPrinters = function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterList) {
return printing.getPrinterList();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.getPrintersAsync = async function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterListAsync) {
return printing.getPrinterListAsync();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.loadFile = function (filePath, options = {}) {
if (typeof filePath !== 'string') {
throw new Error('Must pass filePath as a string');
}
const { query, search, hash } = options;
return this.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: path.resolve(app.getAppPath(), filePath),
query,
search,
hash
}));
};
WebContents.prototype.loadURL = function (url, options) {
const p = new Promise<void>((resolve, reject) => {
const resolveAndCleanup = () => {
removeListeners();
resolve();
};
const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
Object.assign(err, { errno: errorCode, code: errorDescription, url });
removeListeners();
reject(err);
};
const finishListener = () => {
resolveAndCleanup();
};
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
if (isMainFrame) {
rejectAndCleanup(errorCode, errorDescription, validatedURL);
}
};
let navigationStarted = false;
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
if (isMainFrame) {
if (navigationStarted && !isSameDocument) {
// the webcontents has started another unrelated navigation in the
// main frame (probably from the app calling `loadURL` again); reject
// the promise
// We should only consider the request aborted if the "navigation" is
// actually navigating and not simply transitioning URL state in the
// current context. E.g. pushState and `location.hash` changes are
// considered navigation events but are triggered with isSameDocument.
// We can ignore these to allow virtual routing on page load as long
// as the routing does not leave the document
return rejectAndCleanup(-3, 'ERR_ABORTED', url);
}
navigationStarted = true;
}
};
const stopLoadingListener = () => {
// By the time we get here, either 'finish' or 'fail' should have fired
// if the navigation occurred. However, in some situations (e.g. when
// attempting to load a page with a bad scheme), loading will stop
// without emitting finish or fail. In this case, we reject the promise
// with a generic failure.
// TODO(jeremy): enumerate all the cases in which this can happen. If
// the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
// would be more appropriate.
rejectAndCleanup(-2, 'ERR_FAILED', url);
};
const removeListeners = () => {
this.removeListener('did-finish-load', finishListener);
this.removeListener('did-fail-load', failListener);
this.removeListener('did-navigate-in-page', finishListener);
this.removeListener('did-start-navigation', navigationListener);
this.removeListener('did-stop-loading', stopLoadingListener);
this.removeListener('destroyed', stopLoadingListener);
};
this.on('did-finish-load', finishListener);
this.on('did-fail-load', failListener);
this.on('did-navigate-in-page', finishListener);
this.on('did-start-navigation', navigationListener);
this.on('did-stop-loading', stopLoadingListener);
this.on('destroyed', stopLoadingListener);
});
// Add a no-op rejection handler to silence the unhandled rejection error.
p.catch(() => {});
this._loadURL(url, options ?? {});
return p;
};
WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) {
this._windowOpenHandler = handler;
};
WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} {
const defaultResponse = {
browserWindowConstructorOptions: null,
outlivesOpener: false
};
if (!this._windowOpenHandler) {
return defaultResponse;
}
const response = this._windowOpenHandler(details);
if (typeof response !== 'object') {
event.preventDefault();
console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
return defaultResponse;
}
if (response === null) {
event.preventDefault();
console.error('The window open handler response must be an object, but was instead null.');
return defaultResponse;
}
if (response.action === 'deny') {
event.preventDefault();
return defaultResponse;
} else if (response.action === 'allow') {
return {
browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null,
outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false
};
} else {
event.preventDefault();
console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
return defaultResponse;
}
};
const addReplyToEvent = (event: Electron.IpcMainEvent) => {
const { processId, frameId } = event;
event.reply = (channel: string, ...args: any[]) => {
event.sender.sendToFrame([processId, frameId], channel, ...args);
};
};
const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
event.sender = sender;
const { processId, frameId } = event;
Object.defineProperty(event, 'senderFrame', {
get: () => webFrameMain.fromId(processId, frameId)
});
};
const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
Object.defineProperty(event, 'returnValue', {
set: (value) => event._replyChannel.sendReply(value),
get: () => {}
});
};
const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
if (!event.processId || !event.frameId) return null;
return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId);
};
const commandLine = process._linkedBinding('electron_common_command_line');
const environment = process._linkedBinding('electron_common_environment');
const loggingEnabled = () => {
return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
};
// Add JavaScript wrappers for WebContents class.
WebContents.prototype._init = function () {
const prefs = this.getLastWebPreferences() || {};
if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) {
deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.');
}
// Read off the ID at construction time, so that it's accessible even after
// the underlying C++ WebContents is destroyed.
const id = this.id;
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this._windowOpenHandler = null;
const ipc = new IpcMainImpl();
Object.defineProperty(this, 'ipc', {
get () { return ipc; },
enumerable: true
});
// Dispatch IPC messages to the ipc module.
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
this.emit('ipc-message', event, channel, ...args);
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
const replyWithError = (error: Error) => {
console.error(`Error occurred in handler for '${channel}':`, error);
event._replyChannel.sendReply({ error: error.toString() });
};
const maybeWebFrame = getWebFrameForEvent(event);
const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
if (target) {
const handler = (target as any)._invokeHandlers.get(channel);
try {
replyWithResult(await Promise.resolve(handler(event, ...args)));
} catch (err) {
replyWithError(err as Error);
}
} else {
replyWithError(new Error(`No handler registered for '${channel}'`));
}
});
this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
addReturnValueToEvent(event);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
const maybeWebFrame = getWebFrameForEvent(event);
if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) {
console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
}
this.emit('ipc-message-sync', event, channel, ...args);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
addSenderToEvent(event, this);
event.ports = ports.map(p => new MessagePortMain(p));
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
ipc.emit(channel, event, message);
ipcMain.emit(channel, event, message);
});
this.on('crashed', (event, ...args) => {
app.emit('renderer-process-crashed', event, this, ...args);
});
this.on('render-process-gone', (event, details) => {
app.emit('render-process-gone', event, this, details);
// Log out a hint to help users better debug renderer crashes.
if (loggingEnabled()) {
console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
}
});
// The devtools requests the webContents to reload.
this.on('devtools-reload-page', function (this: Electron.WebContents) {
this.reload();
});
if (this.getType() !== 'remote') {
// Make new windows requested by links behave like "window.open".
this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
referrer,
postBody,
disposition
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
const options = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
openGuestWindow({
embedder: this,
disposition,
referrer,
postData,
overrideBrowserWindowOptions: options || {},
windowOpenArgs: details,
outlivesOpener: result.outlivesOpener
});
}
});
let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
let windowOpenOutlivesOpenerOption: boolean = false;
this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
disposition,
referrer,
postBody
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
windowOpenOutlivesOpenerOption = result.outlivesOpener;
windowOpenOverriddenOptions = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
// Allow setting of backgroundColor as a webPreference even though
// it's technically a BrowserWindowConstructorOptions option because
// we need to access it in the renderer at init time.
backgroundColor: windowOpenOverriddenOptions.backgroundColor,
transparent: windowOpenOverriddenOptions.transparent,
...windowOpenOverriddenOptions.webPreferences
} : undefined;
const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
const webPreferences = makeWebPreferences({
embedder: this,
insecureParsedWebPreferences: parsedWebPreferences,
secureOverrideWebPreferences
});
windowOpenOverriddenOptions = {
...windowOpenOverriddenOptions,
webPreferences
};
this._setNextChildWebPreferences(webPreferences);
}
});
// Create a new browser window for "window.open"
this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
_userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
const overriddenOptions = windowOpenOverriddenOptions || undefined;
const outlivesOpener = windowOpenOutlivesOpenerOption;
windowOpenOverriddenOptions = null;
// false is the default
windowOpenOutlivesOpenerOption = false;
if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
disposition !== 'background-tab')) {
event.preventDefault();
return;
}
openGuestWindow({
embedder: this,
guest: webContents,
overrideBrowserWindowOptions: overriddenOptions,
disposition,
referrer,
postData,
windowOpenArgs: {
url,
frameName,
features: rawFeatures
},
outlivesOpener
});
});
}
this.on('login', (event, ...args) => {
app.emit('login', event, this, ...args);
});
this.on('ready-to-show' as any, () => {
const owner = this.getOwnerBrowserWindow();
if (owner && !owner.isDestroyed()) {
process.nextTick(() => {
owner.emit('ready-to-show');
});
}
});
this.on('select-bluetooth-device', (event, devices, callback) => {
if (this.listenerCount('select-bluetooth-device') === 1) {
// Cancel it if there are no handlers
event.preventDefault();
callback('');
}
});
app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);
// Properties
Object.defineProperty(this, 'audioMuted', {
get: () => this.isAudioMuted(),
set: (muted) => this.setAudioMuted(muted)
});
Object.defineProperty(this, 'userAgent', {
get: () => this.getUserAgent(),
set: (agent) => this.setUserAgent(agent)
});
Object.defineProperty(this, 'zoomLevel', {
get: () => this.getZoomLevel(),
set: (level) => this.setZoomLevel(level)
});
Object.defineProperty(this, 'zoomFactor', {
get: () => this.getZoomFactor(),
set: (factor) => this.setZoomFactor(factor)
});
Object.defineProperty(this, 'frameRate', {
get: () => this.getFrameRate(),
set: (rate) => this.setFrameRate(rate)
});
Object.defineProperty(this, 'backgroundThrottling', {
get: () => this.getBackgroundThrottling(),
set: (allowed) => this.setBackgroundThrottling(allowed)
});
};
// Public APIs.
export function create (options = {}): Electron.WebContents {
return new (WebContents as any)(options);
}
export function fromId (id: string) {
return binding.fromId(id);
}
export function fromFrame (frame: Electron.WebFrameMain) {
return binding.fromFrame(frame);
}
export function fromDevToolsTargetId (targetId: string) {
return binding.fromDevToolsTargetId(targetId);
}
export function getFocusedWebContents () {
let focused = null;
for (const contents of binding.getAllWebContents()) {
if (!contents.isFocused()) continue;
if (focused == null) focused = contents;
// Return webview web contents which may be embedded inside another
// web contents that is also reporting as focused
if (contents.getType() === 'webview') return contents;
}
return focused;
}
export function getAllWebContents () {
return binding.getAllWebContents();
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,598 |
[Bug]: webContents.print fails with unspecified options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.1
### Expected Behavior
Calling `webContents.print()`, `webContents.print({})`, or `webContents.print(null)` will result in the system print dialog to appearing.
### Actual Behavior
If `print()` or `print({})` are called, the call will never invoke the provided callback (at least not within 5 minutes, which was the longest I let it sit), nor will it throw any exceptions catchable by a try-catch block. When running the provided gist in Electron Fiddle, I see the following console log: "[19232:0605/173028.939:ERROR:device_event_log_impl.cc(222)] [17:30:28.939] Printer: print_view_manager_base.cc:352 Printer settings invalid for \\epic-print1\vca2cpy-Revenge (destination type kLocal): content size is empty; page size is empty; printable area is empty"
If `print(null)` is called, an exception will be thrown with the error message: "Cannot read properties of null (reading 'pageSize')".
### Testcase Gist URL
https://gist.github.com/mgalla10/7710e8f22830f1122cfe0d98dd99ab08
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38598
|
https://github.com/electron/electron/pull/38614
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
|
c0d9764de9d00968a8c9d5ab74ef3b9840aebc09
| 2023-06-05T22:43:02Z |
c++
| 2023-06-09T19:41:01Z |
spec/api-web-contents-spec.ts
|
import { expect } from 'chai';
import { AddressInfo } from 'net';
import * as path from 'path';
import * as fs from 'fs';
import * as http from 'http';
import { BrowserWindow, ipcMain, webContents, session, app, BrowserView } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers';
import { once } from 'events';
import { setTimeout } from 'timers/promises';
const pdfjs = require('pdfjs-dist');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const mainFixturesPath = path.resolve(__dirname, 'fixtures');
const features = process._linkedBinding('electron_common_features');
describe('webContents module', () => {
describe('getAllWebContents() API', () => {
afterEach(closeAllWindows);
it('returns an array of web contents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { webviewTag: true }
});
w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
await once(w.webContents, 'did-attach-webview');
w.webContents.openDevTools();
await once(w.webContents, 'devtools-opened');
const all = webContents.getAllWebContents().sort((a, b) => {
return a.id - b.id;
});
expect(all).to.have.length(3);
expect(all[0].getType()).to.equal('window');
expect(all[all.length - 2].getType()).to.equal('webview');
expect(all[all.length - 1].getType()).to.equal('remote');
});
});
describe('fromId()', () => {
it('returns undefined for an unknown id', () => {
expect(webContents.fromId(12345)).to.be.undefined();
});
});
describe('fromFrame()', () => {
it('returns WebContents for mainFrame', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents);
});
it('returns undefined for disposed frame', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const { mainFrame } = contents;
contents.destroy();
await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined');
});
it('throws when passing invalid argument', async () => {
let errored = false;
try {
webContents.fromFrame({} as any);
} catch {
errored = true;
}
expect(errored).to.be.true();
});
});
describe('fromDevToolsTargetId()', () => {
it('returns WebContents for attached DevTools target', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
try {
await w.webContents.debugger.attach('1.3');
const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
} finally {
await w.webContents.debugger.detach();
}
});
it('returns undefined for an unknown id', () => {
expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
});
});
describe('will-prevent-unload event', function () {
afterEach(closeAllWindows);
it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
view.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits if beforeunload returns false in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'will-prevent-unload');
});
it('emits if beforeunload returns false in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(view.webContents, 'will-prevent-unload');
});
it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', event => event.preventDefault());
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
});
describe('webContents.send(channel, args...)', () => {
afterEach(closeAllWindows);
it('throws an error when the channel is missing', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
(w.webContents.send as any)();
}).to.throw('Missing required channel argument');
expect(() => {
w.webContents.send(null as any);
}).to.throw('Missing required channel argument');
});
it('does not block node async APIs when sent before document is ready', (done) => {
// Please reference https://github.com/electron/electron/issues/19368 if
// this test fails.
ipcMain.once('async-node-api-done', () => {
done();
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
setTimeout(50).then(() => {
w.webContents.send('test');
});
});
});
ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('throws when invalid settings are passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print(true);
}).to.throw('webContents.print(): Invalid print settings specified.');
});
it('throws when an invalid callback is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({}, true);
}).to.throw('webContents.print(): Invalid optional callback provided.');
});
it('fails when an invalid deviceName is passed', (done) => {
w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
expect(success).to.equal(false);
expect(reason).to.match(/Invalid deviceName provided/);
done();
});
});
it('throws when an invalid pageSize is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
}).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
});
it('throws when an invalid custom pageSize is passed', () => {
expect(() => {
w.webContents.print({
pageSize: {
width: 100,
height: 200
}
});
}).to.throw('height and width properties must be minimum 352 microns.');
});
it('does not crash with custom margins', () => {
expect(() => {
w.webContents.print({
silent: true,
margins: {
marginType: 'custom',
top: 1,
bottom: 1,
left: 1,
right: 1
}
});
}).to.not.throw();
});
});
describe('webContents.executeJavaScript', () => {
describe('in about:blank', () => {
const expected = 'hello, world!';
const expectedErrorMsg = 'woops!';
const code = `(() => "${expected}")()`;
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
]);
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
await w.loadURL('about:blank');
});
after(closeAllWindows);
it('resolves the returned promise with the result', async () => {
const result = await w.webContents.executeJavaScript(code);
expect(result).to.equal(expected);
});
it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
const result = await w.webContents.executeJavaScript(asyncCode);
expect(result).to.equal(expected);
});
it('rejects the returned promise if an async error is thrown', async () => {
await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
});
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error of errorTypes) {
await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
.to.eventually.be.rejectedWith(error);
}
});
});
describe('on a real page', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('works after page load and during subframe load', async () => {
await w.loadURL(serverUrl);
// initiate a sub-frame load, then try and execute script during it
await w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/slow'
document.body.appendChild(iframe)
null // don't return the iframe
`);
await w.webContents.executeJavaScript('console.log(\'hello\')');
});
it('executes after page load', async () => {
const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
w.loadURL(serverUrl);
const result = await executeJavaScript;
expect(result).to.equal('test');
});
});
});
describe('webContents.executeJavaScriptInIsolatedWorld', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
await w.loadURL('about:blank');
});
it('resolves the returned promise with the result', async () => {
await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
const mainWorldResult = await w.webContents.executeJavaScript('window.X');
expect(isolatedResult).to.equal(123);
expect(mainWorldResult).to.equal(undefined);
});
});
describe('loadURL() promise API', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('resolves when done loading', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('resolves when done loading a file URL', async () => {
await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
});
it('resolves when navigating within the page', async () => {
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await setTimeout();
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
it('rejects when failing to load a file URL', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FILE_NOT_FOUND');
});
// FIXME: Temporarily disable on WOA until
// https://github.com/electron/electron/issues/20008 is resolved
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => {
await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
});
it('rejects when navigation is cancelled due to a bad scheme', async () => {
await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FAILED');
});
it('does not crash when loading a new URL with emulation settings set', async () => {
const setEmulation = async () => {
if (w.webContents) {
w.webContents.debugger.attach('1.3');
const deviceMetrics = {
width: 700,
height: 600,
deviceScaleFactor: 2,
mobile: true,
dontSetVisibleSize: true
};
await w.webContents.debugger.sendCommand(
'Emulation.setDeviceMetricsOverride',
deviceMetrics
);
}
};
try {
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await setEmulation();
await w.loadURL('data:text/html,<h1>HELLO</h1>');
await setEmulation();
} catch (e) {
expect((e as Error).message).to.match(/Debugger is already attached to the target/);
}
});
it('sets appropriate error information on rejection', async () => {
let err: any;
try {
await w.loadURL('file:non-existent');
} catch (e) {
err = e;
}
expect(err).not.to.be.null();
expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
expect(err.errno).to.eql(-6);
expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
});
it('rejects if the load is aborted', async () => {
const s = http.createServer(() => { /* never complete the request */ });
const { port } = await listen(s);
const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
// load a different file before the first load completes, causing the
// first load to be aborted.
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await p;
s.close();
});
it("doesn't reject when a subframe fails to load", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="http://err.name.not.resolved"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.end();
await main;
s.close();
});
it("doesn't resolve when a subframe loads", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="about:blank"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.destroy(); // cause the main request to fail
await expect(main).to.eventually.be.rejected()
.and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
s.close();
});
});
describe('getFocusedWebContents() API', () => {
afterEach(closeAllWindows);
// FIXME
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => {
const w = new BrowserWindow({ show: true });
await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
const devToolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools();
await devToolsOpened;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id);
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
});
it('does not crash when called on a detached dev tools window', async () => {
const w = new BrowserWindow({ show: true });
w.webContents.openDevTools({ mode: 'detach' });
w.webContents.inspectElement(100, 100);
// For some reason we have to wait for two focused events...?
await once(w.webContents, 'devtools-focused');
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
// Work around https://github.com/electron/electron/issues/19985
await setTimeout();
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
});
});
describe('setDevToolsWebContents() API', () => {
afterEach(closeAllWindows);
it('sets arbitrary webContents as devtools', async () => {
const w = new BrowserWindow({ show: false });
const devtools = new BrowserWindow({ show: false });
const promise = once(devtools.webContents, 'dom-ready');
w.webContents.setDevToolsWebContents(devtools.webContents);
w.webContents.openDevTools();
await promise;
expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
expect(result).to.equal('InspectorFrontendHostImpl');
devtools.destroy();
});
});
describe('isFocused() API', () => {
it('returns false when the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(w.isVisible()).to.be.false();
expect(w.webContents.isFocused()).to.be.false();
});
});
describe('isCurrentlyAudible() API', () => {
afterEach(closeAllWindows);
it('returns whether audio is playing', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`
window.context = new AudioContext
// Start in suspended state, because of the
// new web audio api policy.
context.suspend()
window.oscillator = context.createOscillator()
oscillator.connect(context.destination)
oscillator.start()
`);
let p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('context.resume()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.true();
p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('oscillator.stop()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.false();
});
});
describe('openDevTools() API', () => {
afterEach(closeAllWindows);
it('can show window with activation', async () => {
const w = new BrowserWindow({ show: false });
const focused = once(w, 'focus');
w.show();
await focused;
expect(w.isFocused()).to.be.true();
const blurred = once(w, 'blur');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await Promise.all([
once(w.webContents, 'devtools-opened'),
once(w.webContents, 'devtools-focused')
]);
await blurred;
expect(w.isFocused()).to.be.false();
});
it('can show window without activation', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
});
});
describe('before-input-event event', () => {
afterEach(closeAllWindows);
it('can prevent document keyboard events', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
const keyDown = new Promise(resolve => {
ipcMain.once('keydown', (event, key) => resolve(key));
});
w.webContents.once('before-input-event', (event, input) => {
if (input.key === 'a') event.preventDefault();
});
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
expect(await keyDown).to.equal('b');
});
it('has the correct properties', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testBeforeInput = async (opts: any) => {
const modifiers = [];
if (opts.shift) modifiers.push('shift');
if (opts.control) modifiers.push('control');
if (opts.alt) modifiers.push('alt');
if (opts.meta) modifiers.push('meta');
if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
const p = once(w.webContents, 'before-input-event');
w.webContents.sendInputEvent({
type: opts.type,
keyCode: opts.keyCode,
modifiers: modifiers as any
});
const [, input] = await p;
expect(input.type).to.equal(opts.type);
expect(input.key).to.equal(opts.key);
expect(input.code).to.equal(opts.code);
expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
expect(input.shift).to.equal(opts.shift);
expect(input.control).to.equal(opts.control);
expect(input.alt).to.equal(opts.alt);
expect(input.meta).to.equal(opts.meta);
};
await testBeforeInput({
type: 'keyDown',
key: 'A',
code: 'KeyA',
keyCode: 'a',
shift: true,
control: true,
alt: true,
meta: true,
isAutoRepeat: true
});
await testBeforeInput({
type: 'keyUp',
key: '.',
code: 'Period',
keyCode: '.',
shift: false,
control: true,
alt: true,
meta: false,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: '!',
code: 'Digit1',
keyCode: '1',
shift: true,
control: false,
alt: false,
meta: true,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: 'Tab',
code: 'Tab',
keyCode: 'Tab',
shift: false,
control: true,
alt: false,
meta: false,
isAutoRepeat: true
});
});
});
// On Mac, zooming isn't done with the mouse wheel.
ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
afterEach(closeAllWindows);
it('is emitted with the correct zoom-in info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: 1,
wheelTicksX: 0,
wheelTicksY: 1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed');
expect(zoomDirection).to.equal('in');
};
await testZoomChanged();
});
it('is emitted with the correct zoom-out info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: -1,
wheelTicksX: 0,
wheelTicksY: -1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed');
expect(zoomDirection).to.equal('out');
};
await testZoomChanged();
});
});
describe('sendInputEvent(event)', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
});
afterEach(closeAllWindows);
it('can send keydown events', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send keydown events with modifiers', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
it('can send keydown events with special keys', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Tab');
expect(code).to.equal('Tab');
expect(keyCode).to.equal(9);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.true();
});
it('can send char events', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send char events with modifiers', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
});
describe('insertCSS', () => {
afterEach(closeAllWindows);
it('supports inserting CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.webContents.insertCSS('body { background-repeat: round; }');
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const key = await w.webContents.insertCSS('body { background-repeat: round; }');
await w.webContents.removeInsertedCSS(key);
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('repeat');
});
});
describe('inspectElement()', () => {
afterEach(closeAllWindows);
it('supports inspecting an element in the devtools', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const event = once(w.webContents, 'devtools-opened');
w.webContents.inspectElement(10, 10);
await event;
});
});
describe('startDrag({file, icon})', () => {
it('throws errors for a missing file or a missing/empty icon', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
}).to.throw('Must specify either \'file\' or \'files\' option');
expect(() => {
w.webContents.startDrag({ file: __filename } as any);
}).to.throw('\'icon\' parameter is required');
expect(() => {
w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('focus APIs', () => {
describe('focus()', () => {
afterEach(closeAllWindows);
it('does not blur the focused window when the web contents is hidden', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.show();
await w.loadURL('about:blank');
w.focus();
const child = new BrowserWindow({ show: false });
child.loadURL('about:blank');
child.webContents.focus();
const currentFocused = w.isFocused();
const childFocused = child.isFocused();
child.close();
expect(currentFocused).to.be.true();
expect(childFocused).to.be.false();
});
});
const moveFocusToDevTools = async (win: BrowserWindow) => {
const devToolsOpened = once(win.webContents, 'devtools-opened');
win.webContents.openDevTools({ mode: 'right' });
await devToolsOpened;
win.webContents.devToolsWebContents!.focus();
};
describe('focus event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is focused', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await moveFocusToDevTools(w);
const focusPromise = once(w.webContents, 'focus');
w.webContents.focus();
await expect(focusPromise).to.eventually.be.fulfilled();
});
});
describe('blur event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is blurred', async () => {
const w = new BrowserWindow({ show: true });
await w.loadURL('about:blank');
w.webContents.focus();
const blurPromise = once(w.webContents, 'blur');
await moveFocusToDevTools(w);
await expect(blurPromise).to.eventually.be.fulfilled();
});
});
});
describe('getOSProcessId()', () => {
afterEach(closeAllWindows);
it('returns a valid process id', async () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getOSProcessId()).to.equal(0);
await w.loadURL('about:blank');
expect(w.webContents.getOSProcessId()).to.be.above(0);
});
});
describe('getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns a valid stream id', () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
});
});
describe('userAgent APIs', () => {
it('is not empty by default', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
expect(userAgent).to.be.a('string').that.is.not.empty();
});
it('can set the user agent (functions)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
w.webContents.setUserAgent('my-user-agent');
expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
w.webContents.setUserAgent(userAgent);
expect(w.webContents.getUserAgent()).to.equal(userAgent);
});
it('can set the user agent (properties)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.userAgent;
w.webContents.userAgent = 'my-user-agent';
expect(w.webContents.userAgent).to.equal('my-user-agent');
w.webContents.userAgent = userAgent;
expect(w.webContents.userAgent).to.equal(userAgent);
});
});
describe('audioMuted APIs', () => {
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setAudioMuted(true);
expect(w.webContents.isAudioMuted()).to.be.true();
w.webContents.setAudioMuted(false);
expect(w.webContents.isAudioMuted()).to.be.false();
});
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.audioMuted = true;
expect(w.webContents.audioMuted).to.be.true();
w.webContents.audioMuted = false;
expect(w.webContents.audioMuted).to.be.false();
});
});
describe('zoom api', () => {
const hostZoomMap: Record<string, number> = {
host1: 0.3,
host2: 0.7,
host3: 0.2
};
before(() => {
const protocol = session.defaultSession.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
const response = `<script>
const {ipcRenderer} = require('electron')
ipcRenderer.send('set-zoom', window.location.hostname)
ipcRenderer.on(window.location.hostname + '-zoom-set', () => {
ipcRenderer.send(window.location.hostname + '-zoom-level')
})
</script>`;
callback({ data: response, mimeType: 'text/html' });
});
});
after(() => {
const protocol = session.defaultSession.protocol;
protocol.unregisterProtocol(standardScheme);
});
afterEach(closeAllWindows);
it('throws on an invalid zoomFactor', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(() => {
w.webContents.setZoomFactor(0.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
expect(() => {
w.webContents.setZoomFactor(-2.0);
}).to.throw(/'zoomFactor' must be a double greater than 0.0/);
});
it('can set the correct zoom level (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.getZoomLevel();
expect(zoomLevel).to.eql(0.0);
w.webContents.setZoomLevel(0.5);
const newZoomLevel = w.webContents.getZoomLevel();
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.setZoomLevel(0);
}
});
it('can set the correct zoom level (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.eql(0.0);
w.webContents.zoomLevel = 0.5;
const newZoomLevel = w.webContents.zoomLevel;
expect(newZoomLevel).to.eql(0.5);
} finally {
w.webContents.zoomLevel = 0;
}
});
it('can set the correct zoom factor (functions)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.getZoomFactor();
expect(zoomFactor).to.eql(1.0);
w.webContents.setZoomFactor(0.5);
const newZoomFactor = w.webContents.getZoomFactor();
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.setZoomFactor(1.0);
}
});
it('can set the correct zoom factor (properties)', async () => {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL('about:blank');
const zoomFactor = w.webContents.zoomFactor;
expect(zoomFactor).to.eql(1.0);
w.webContents.zoomFactor = 0.5;
const newZoomFactor = w.webContents.zoomFactor;
expect(newZoomFactor).to.eql(0.5);
} finally {
w.webContents.zoomFactor = 1.0;
}
});
it('can persist zoom level across navigation', (done) => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
let finalNavigation = false;
ipcMain.on('set-zoom', (e, host) => {
const zoomLevel = hostZoomMap[host];
if (!finalNavigation) w.webContents.zoomLevel = zoomLevel;
e.sender.send(`${host}-zoom-set`);
});
ipcMain.on('host1-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host1;
expect(zoomLevel).to.equal(expectedZoomLevel);
if (finalNavigation) {
done();
} else {
w.loadURL(`${standardScheme}://host2`);
}
} catch (e) {
done(e);
}
});
ipcMain.once('host2-zoom-level', (e) => {
try {
const zoomLevel = e.sender.getZoomLevel();
const expectedZoomLevel = hostZoomMap.host2;
expect(zoomLevel).to.equal(expectedZoomLevel);
finalNavigation = true;
w.webContents.goBack();
} catch (e) {
done(e);
}
});
w.loadURL(`${standardScheme}://host1`);
});
it('can propagate zoom level across same session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({ show: false });
defer(() => {
w2.setClosable(true);
w2.close();
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel1).to.equal(zoomLevel2);
});
it('cannot propagate zoom level across different session', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const w2 = new BrowserWindow({
show: false,
webPreferences: {
partition: 'temp'
}
});
const protocol = w2.webContents.session.protocol;
protocol.registerStringProtocol(standardScheme, (request, callback) => {
callback('hello');
});
defer(() => {
w2.setClosable(true);
w2.close();
protocol.unregisterProtocol(standardScheme);
});
await w.loadURL(`${standardScheme}://host3`);
w.webContents.zoomLevel = hostZoomMap.host3;
await w2.loadURL(`${standardScheme}://host3`);
const zoomLevel1 = w.webContents.zoomLevel;
expect(zoomLevel1).to.equal(hostZoomMap.host3);
const zoomLevel2 = w2.webContents.zoomLevel;
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
it('can persist when it contains iframe', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
setTimeout(200).then(() => {
res.end();
});
});
server.listen(0, '127.0.0.1', () => {
const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
const content = `<iframe src=${url}></iframe>`;
w.webContents.on('did-frame-finish-load', (e, isMainFrame) => {
if (!isMainFrame) {
try {
const zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(2.0);
w.webContents.zoomLevel = 0;
done();
} catch (e) {
done(e);
} finally {
server.close();
}
}
});
w.webContents.on('dom-ready', () => {
w.webContents.zoomLevel = 2.0;
});
w.loadURL(`data:text/html,${content}`);
});
});
it('cannot propagate when used with webframe', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const w2 = new BrowserWindow({ show: false });
const temporaryZoomSet = once(ipcMain, 'temporary-zoom-set');
w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html'));
await temporaryZoomSet;
const finalZoomLevel = w.webContents.getZoomLevel();
await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html'));
const zoomLevel1 = w.webContents.zoomLevel;
const zoomLevel2 = w2.webContents.zoomLevel;
w2.setClosable(true);
w2.close();
expect(zoomLevel1).to.equal(finalZoomLevel);
expect(zoomLevel2).to.equal(0);
expect(zoomLevel1).to.not.equal(zoomLevel2);
});
describe('with unique domains', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
setTimeout().then(() => res.end('hey'));
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
it('cannot persist zoom level after navigation with webFrame', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const source = `
const {ipcRenderer, webFrame} = require('electron')
webFrame.setZoomLevel(0.6)
ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel())
`;
const zoomLevelPromise = once(ipcMain, 'zoom-level-set');
await w.loadURL(serverUrl);
await w.webContents.executeJavaScript(source);
let [, zoomLevel] = await zoomLevelPromise;
expect(zoomLevel).to.equal(0.6);
const loadPromise = once(w.webContents, 'did-finish-load');
await w.loadURL(crossSiteUrl);
await loadPromise;
zoomLevel = w.webContents.zoomLevel;
expect(zoomLevel).to.equal(0);
});
});
});
describe('webrtc ip policy api', () => {
afterEach(closeAllWindows);
it('can set and get webrtc ip policies', () => {
const w = new BrowserWindow({ show: false });
const policies = [
'default',
'default_public_interface_only',
'default_public_and_private_interfaces',
'disable_non_proxied_udp'
];
policies.forEach((policy) => {
w.webContents.setWebRTCIPHandlingPolicy(policy as any);
expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy);
});
});
});
describe('opener api', () => {
afterEach(closeAllWindows);
it('can get opener with window.open()', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript('window.open("about:blank")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener when using "noopener"', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript('window.open("about:blank", undefined, "noopener")', true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
it('can get opener with a[target=_blank][rel=opener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'opener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
});
it('has no opener with a[target=_blank][rel=noopener]', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const childPromise = once(w.webContents, 'did-create-window');
w.webContents.executeJavaScript(`(function() {
const a = document.createElement('a');
a.target = '_blank';
a.rel = 'noopener';
a.href = 'about:blank';
a.click();
}())`, true);
const [childWindow] = await childPromise;
expect(childWindow.webContents.opener).to.be.null();
});
});
describe('render view deleted events', () => {
let server: http.Server;
let serverUrl: string;
let crossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${crossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else if (req.url === '/first-window-open') {
res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`);
} else if (req.url === '/second-window-open') {
res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
});
afterEach(closeAllWindows);
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
w.webContents.on('did-finish-load', () => {
w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted');
});
it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => {
const parentWindow = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
let childWindow: BrowserWindow | null = null;
const destroyed = once(parentWindow.webContents, 'destroyed');
const renderViewDeletedHandler = () => {
currentRenderViewDeletedEmitted = true;
};
const childWindowCreated = new Promise<void>((resolve) => {
app.once('browser-window-created', (event, window) => {
childWindow = window;
window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler);
resolve();
});
});
parentWindow.loadURL(`${serverUrl}/first-window-open`);
await childWindowCreated;
childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler);
parentWindow.close();
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed');
});
it('emits current-render-view-deleted if the current RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let currentRenderViewDeletedEmitted = false;
w.webContents.on('current-render-view-deleted' as any, () => {
currentRenderViewDeletedEmitted = true;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted');
});
it('emits render-view-deleted if any RVHs are deleted', async () => {
const w = new BrowserWindow({ show: false });
let rvhDeletedCount = 0;
w.webContents.on('render-view-deleted' as any, () => {
rvhDeletedCount++;
});
w.webContents.on('did-finish-load', () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.loadURL(`${serverUrl}/redirect-cross-site`);
await destroyed;
const expectedRenderViewDeletedEventCount = 1;
expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times');
});
});
describe('setIgnoreMenuShortcuts(ignore)', () => {
afterEach(closeAllWindows);
it('does not throw', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.setIgnoreMenuShortcuts(true);
w.webContents.setIgnoreMenuShortcuts(false);
}).to.not.throw();
});
});
const crashPrefs = [
{
nodeIntegration: true
},
{
sandbox: true
}
];
const nicePrefs = (o: any) => {
let s = '';
for (const key of Object.keys(o)) {
s += `${key}=${o[key]}, `;
}
return `(${s.slice(0, s.length - 2)})`;
};
for (const prefs of crashPrefs) {
describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadURL('about:blank');
});
afterEach(closeAllWindows);
it('isCrashed() is false by default', () => {
expect(w.webContents.isCrashed()).to.equal(false);
});
it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
const crashEvent = once(w.webContents, 'render-process-gone');
w.webContents.forcefullyCrashRenderer();
const [, details] = await crashEvent;
expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed');
expect(w.webContents.isCrashed()).to.equal(true);
});
it('a crashed process is recoverable with reload()', async () => {
expect(w.webContents.isCrashed()).to.equal(false);
w.webContents.forcefullyCrashRenderer();
w.webContents.reload();
expect(w.webContents.isCrashed()).to.equal(false);
});
});
}
// Destroying webContents in its event listener is going to crash when
// Electron is built in Debug mode.
describe('destroy()', () => {
let server: http.Server;
let serverUrl: string;
before((done) => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/200':
response.end();
break;
default:
done('unsupported endpoint');
}
}).listen(0, '127.0.0.1', () => {
serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
done();
});
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', url: '/200' },
{ name: 'dom-ready', url: '/200' },
{ name: 'did-stop-loading', url: '/200' },
{ name: 'did-finish-load', url: '/200' },
// FIXME: Multiple Emit calls inside an observer assume that object
// will be alive till end of the observer. Synchronous `destroy` api
// violates this contract and crashes.
{ name: 'did-frame-finish-load', url: '/200' },
{ name: 'did-fail-load', url: '/net-error' }
];
for (const e of events) {
it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () {
// This test is flaky on Windows CI and we don't know why, but the
// purpose of this test is to make sure Electron does not crash so it
// is fine to retry this test for a few times.
this.retries(3);
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const originalEmit = contents.emit.bind(contents);
contents.emit = (...args) => { return originalEmit(...args); };
contents.once(e.name as any, () => contents.destroy());
const destroyed = once(contents, 'destroyed');
contents.loadURL(serverUrl + e.url);
await destroyed;
});
}
});
describe('did-change-theme-color event', () => {
afterEach(closeAllWindows);
it('is triggered with correct theme color', (done) => {
const w = new BrowserWindow({ show: true });
let count = 0;
w.webContents.on('did-change-theme-color', (e, color) => {
try {
if (count === 0) {
count += 1;
expect(color).to.equal('#FFEEDD');
w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
} else if (count === 1) {
expect(color).to.be.null();
done();
}
} catch (e) {
done(e);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html'));
});
});
describe('console-message event', () => {
afterEach(closeAllWindows);
it('is triggered with correct log message', (done) => {
const w = new BrowserWindow({ show: true });
w.webContents.on('console-message', (e, level, message) => {
// Don't just assert as Chromium might emit other logs that we should ignore.
if (message === 'a') {
done();
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'a.html'));
});
});
describe('ipc-message event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends an asynchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
w.webContents.executeJavaScript(`
require('electron').ipcRenderer.send('message', 'Hello World!')
`);
const [, channel, message] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
});
});
describe('ipc-message-sync event', () => {
afterEach(closeAllWindows);
it('emits when the renderer process sends a synchronous message', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.webContents.loadURL('about:blank');
const promise: Promise<[string, string]> = new Promise(resolve => {
w.webContents.once('ipc-message-sync', (event, channel, arg) => {
event.returnValue = 'foobar';
resolve([channel, arg]);
});
});
const result = await w.webContents.executeJavaScript(`
require('electron').ipcRenderer.sendSync('message', 'Hello World!')
`);
const [channel, message] = await promise;
expect(channel).to.equal('message');
expect(message).to.equal('Hello World!');
expect(result).to.equal('foobar');
});
});
describe('referrer', () => {
afterEach(closeAllWindows);
it('propagates referrer information to new target=_blank windows', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
} finally {
server.close();
}
}
res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>');
});
server.listen(0, '127.0.0.1', () => {
const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/';
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url);
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('a.click()');
});
w.loadURL(url);
});
});
it('propagates referrer information to windows opened with window.open', (done) => {
const w = new BrowserWindow({ show: false });
const server = http.createServer((req, res) => {
if (req.url === '/should_have_referrer') {
try {
expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`);
return done();
} catch (e) {
return done(e);
}
}
res.end('');
});
server.listen(0, '127.0.0.1', () => {
const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/';
w.webContents.once('did-finish-load', () => {
w.webContents.setWindowOpenHandler(details => {
expect(details.referrer.url).to.equal(url);
expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin');
return { action: 'allow' };
});
w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")');
});
w.loadURL(url);
});
});
});
describe('webframe messages in sandboxed contents', () => {
afterEach(closeAllWindows);
it('responds to executeJavaScript', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const result = await w.webContents.executeJavaScript('37 + 5');
expect(result).to.equal(42);
});
});
describe('preload-error event', () => {
afterEach(closeAllWindows);
const generateSpecs = (description: string, sandbox: boolean) => {
describe(description, () => {
it('is triggered when unhandled exception is thrown', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error');
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('Hello World!');
});
it('is triggered on syntax errors', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error');
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.equal('foobar is not defined');
});
it('is triggered when preload script loading fails', async () => {
const preload = path.join(fixturesPath, 'module', 'preload-invalid.js');
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox,
preload
}
});
const promise = once(w.webContents, 'preload-error');
w.loadURL('about:blank');
const [, preloadPath, error] = await promise;
expect(preloadPath).to.equal(preload);
expect(error.message).to.contain('preload-invalid.js');
});
});
};
generateSpecs('without sandbox', false);
generateSpecs('with sandbox', true);
});
describe('takeHeapSnapshot()', () => {
afterEach(closeAllWindows);
it('works with sandboxed renderers', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
const cleanup = () => {
try {
fs.unlinkSync(filePath);
} catch (e) {
// ignore error
}
};
try {
await w.webContents.takeHeapSnapshot(filePath);
const stats = fs.statSync(filePath);
expect(stats.size).not.to.be.equal(0);
} finally {
cleanup();
}
});
it('fails with invalid file path', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
await w.loadURL('about:blank');
const badPath = path.join('i', 'am', 'a', 'super', 'bad', 'path');
const promise = w.webContents.takeHeapSnapshot(badPath);
return expect(promise).to.be.eventually.rejectedWith(Error, `Failed to take heap snapshot with invalid file path ${badPath}`);
});
it('fails with invalid render process', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot');
w.webContents.destroy();
const promise = w.webContents.takeHeapSnapshot(filePath);
return expect(promise).to.be.eventually.rejectedWith(Error, 'Failed to take heap snapshot with nonexistent render frame');
});
});
describe('setBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('does not crash when allowing', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(true);
});
it('does not crash when called via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
(w as any).setBackgroundThrottling(true);
});
it('does not crash when disallowing', () => {
const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } });
w.webContents.setBackgroundThrottling(false);
});
});
describe('getBackgroundThrottling()', () => {
afterEach(closeAllWindows);
it('works via getter', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setBackgroundThrottling(false);
expect(w.webContents.getBackgroundThrottling()).to.equal(false);
w.webContents.setBackgroundThrottling(true);
expect(w.webContents.getBackgroundThrottling()).to.equal(true);
});
it('works via property', () => {
const w = new BrowserWindow({ show: false });
w.webContents.backgroundThrottling = false;
expect(w.webContents.backgroundThrottling).to.equal(false);
w.webContents.backgroundThrottling = true;
expect(w.webContents.backgroundThrottling).to.equal(true);
});
it('works via BrowserWindow', () => {
const w = new BrowserWindow({ show: false });
(w as any).setBackgroundThrottling(false);
expect((w as any).getBackgroundThrottling()).to.equal(false);
(w as any).setBackgroundThrottling(true);
expect((w as any).getBackgroundThrottling()).to.equal(true);
});
});
ifdescribe(features.isPrintingEnabled())('getPrinters()', () => {
afterEach(closeAllWindows);
it('can get printer list', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const printers = w.webContents.getPrinters();
expect(printers).to.be.an('array');
});
});
ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => {
afterEach(closeAllWindows);
it('can get printer list', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
await w.loadURL('about:blank');
const printers = await w.webContents.getPrintersAsync();
expect(printers).to.be.an('array');
});
});
ifdescribe(features.isPrintingEnabled())('printToPDF()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true
}
});
});
afterEach(closeAllWindows);
it('rejects on incorrectly typed parameters', async () => {
const badTypes = {
landscape: [],
displayHeaderFooter: '123',
printBackground: 2,
scale: 'not-a-number',
pageSize: 'IAmAPageSize',
margins: 'terrible',
pageRanges: { oops: 'im-not-the-right-key' },
headerTemplate: [1, 2, 3],
footerTemplate: [4, 5, 6],
preferCSSPageSize: 'no'
};
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
// These will hard crash in Chromium unless we type-check
for (const [key, value] of Object.entries(badTypes)) {
const param = { [key]: value };
await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected();
}
});
it('does not crash when called multiple times in parallel', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const promises = [];
for (let i = 0; i < 3; i++) {
promises.push(w.webContents.printToPDF({}));
}
const results = await Promise.all(promises);
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('does not crash when called multiple times in sequence', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const results = [];
for (let i = 0; i < 3; i++) {
const result = await w.webContents.printToPDF({});
results.push(result);
}
for (const data of results) {
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
}
});
it('can print a PDF with default settings', async () => {
await w.loadURL('data:text/html,<h1>Hello, World!</h1>');
const data = await w.webContents.printToPDF({});
expect(data).to.be.an.instanceof(Buffer).that.is.not.empty();
});
it('with custom page sizes', async () => {
const paperFormats: Record<string, ElectronInternal.PageSize> = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
};
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
for (const format of Object.keys(paperFormats)) {
const data = await w.webContents.printToPDF({ pageSize: format });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2] / 72;
const height = page.view[3] / 72;
const approxEq = (a: number, b: number, epsilon = 0.01) => Math.abs(a - b) <= epsilon;
expect(approxEq(width, paperFormats[format].width)).to.be.true();
expect(approxEq(height, paperFormats[format].height)).to.be.true();
}
});
it('with custom header and footer', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({
displayHeaderFooter: true,
headerTemplate: '<div>I\'m a PDF header</div>',
footerTemplate: '<div>I\'m a PDF footer</div>'
});
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
const { items } = await page.getTextContent();
// Check that generated PDF contains a header.
const containsText = (text: RegExp) => items.some(({ str }: { str: string }) => str.match(text));
expect(containsText(/I'm a PDF header/)).to.be.true();
expect(containsText(/I'm a PDF footer/)).to.be.true();
});
it('in landscape mode', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-small.html'));
const data = await w.webContents.printToPDF({ landscape: true });
const doc = await pdfjs.getDocument(data).promise;
const page = await doc.getPage(1);
// page.view is [top, left, width, height].
const width = page.view[2];
const height = page.view[3];
expect(width).to.be.greaterThan(height);
});
it('with custom page ranges', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf-large.html'));
const data = await w.webContents.printToPDF({
pageRanges: '1-3',
landscape: true
});
const doc = await pdfjs.getDocument(data).promise;
// Check that correct # of pages are rendered.
expect(doc.numPages).to.equal(3);
});
});
describe('PictureInPicture video', () => {
afterEach(closeAllWindows);
it('works as expected', async function () {
const w = new BrowserWindow({ webPreferences: { sandbox: true } });
// TODO(codebytere): figure out why this workaround is needed and remove.
// It is not germane to the actual test.
await w.loadFile(path.join(fixturesPath, 'blank.html'));
await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html'));
await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')', true);
const result = await w.webContents.executeJavaScript('runTest(true)', true);
expect(result).to.be.true();
});
});
describe('Shared Workers', () => {
afterEach(closeAllWindows);
it('can get multiple shared workers', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
expect(sharedWorkers).to.have.lengthOf(2);
expect(sharedWorkers[0].url).to.contain('shared-worker');
expect(sharedWorkers[1].url).to.contain('shared-worker');
});
it('can inspect a specific shared worker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
const ready = once(ipcMain, 'ready');
w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html'));
await ready;
const sharedWorkers = w.webContents.getAllSharedWorkers();
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.inspectSharedWorkerById(sharedWorkers[0].id);
await devtoolsOpened;
const devtoolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devtoolsClosed;
});
});
describe('login event', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
let serverPort: number;
let proxyServer: http.Server;
let proxyServerPort: number;
before(async () => {
server = http.createServer((request, response) => {
if (request.url === '/no-auth') {
return response.end('ok');
}
if (request.headers.authorization) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers.authorization);
}
response
.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
.end('401');
});
({ port: serverPort, url: serverUrl } = await listen(server));
});
before(async () => {
proxyServer = http.createServer((request, response) => {
if (request.headers['proxy-authorization']) {
response.writeHead(200, { 'Content-type': 'text/plain' });
return response.end(request.headers['proxy-authorization']);
}
response
.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' })
.end();
});
proxyServerPort = (await listen(proxyServer)).port;
});
afterEach(async () => {
await session.defaultSession.clearAuthCache();
});
after(() => {
server.close();
proxyServer.close();
});
it('is emitted when navigating', async () => {
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(serverUrl + '/');
expect(eventAuthInfo.isProxy).to.be.false();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(serverPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('is emitted when a proxy requests authorization', async () => {
const customSession = session.fromPartition(`${Math.random()}`);
await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' });
const [user, pass] = ['user', 'pass'];
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
let eventRequest: any;
let eventAuthInfo: any;
w.webContents.on('login', (event, request, authInfo, cb) => {
eventRequest = request;
eventAuthInfo = authInfo;
event.preventDefault();
cb(user, pass);
});
await w.loadURL(`${serverUrl}/no-auth`);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`);
expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`);
expect(eventAuthInfo.isProxy).to.be.true();
expect(eventAuthInfo.scheme).to.equal('basic');
expect(eventAuthInfo.host).to.equal('127.0.0.1');
expect(eventAuthInfo.port).to.equal(proxyServerPort);
expect(eventAuthInfo.realm).to.equal('Foo');
});
it('cancels authentication when callback is called with no arguments', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.on('login', (event, request, authInfo, cb) => {
event.preventDefault();
cb();
});
await w.loadURL(serverUrl);
const body = await w.webContents.executeJavaScript('document.documentElement.textContent');
expect(body).to.equal('401');
});
});
describe('page-title-updated event', () => {
afterEach(closeAllWindows);
it('is emitted with a full title for pages with no navigation', async () => {
const bw = new BrowserWindow({ show: false });
await bw.loadURL('about:blank');
bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null');
const [, child] = await once(app, 'web-contents-created');
bw.webContents.executeJavaScript('child.document.title = "new title"');
const [, title] = await once(child, 'page-title-updated');
expect(title).to.equal('new title');
});
});
describe('crashed event', () => {
it('does not crash main process when destroying WebContents in it', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true });
const crashEvent = once(contents, 'render-process-gone');
await contents.loadURL('about:blank');
contents.forcefullyCrashRenderer();
await crashEvent;
contents.destroy();
});
});
describe('context-menu event', () => {
afterEach(closeAllWindows);
it('emits when right-clicked in page', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const promise = once(w.webContents, 'context-menu');
// Simulate right-click to create context-menu event.
const opts = { x: 0, y: 0, button: 'right' as any };
w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' });
w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' });
const [, params] = await promise;
expect(params.pageURL).to.equal(w.webContents.getURL());
expect(params.frame).to.be.an('object');
expect(params.x).to.be.a('number');
expect(params.y).to.be.a('number');
});
});
describe('close() method', () => {
afterEach(closeAllWindows);
it('closes when close() is called', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('closes when close() is called after loading a page', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('can be GCed before loading a page', async () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
let registry: FinalizationRegistry<unknown> | null = null;
const cleanedUp = new Promise<number>(resolve => {
registry = new FinalizationRegistry(resolve as any);
});
(() => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
registry!.register(w, 42);
})();
const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100);
defer(() => clearInterval(i));
expect(await cleanedUp).to.equal(42);
});
it('causes its parent browserwindow to be closed', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const closed = once(w, 'closed');
w.webContents.close();
await closed;
expect(w.isDestroyed()).to.be.true();
});
it('ignores beforeunload if waitForBeforeUnload not specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); });
const destroyed = once(w, 'destroyed');
w.close();
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
it('runs beforeunload if waitForBeforeUnload is specified', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
const willPreventUnload = once(w, 'will-prevent-unload');
w.close({ waitForBeforeUnload: true });
await willPreventUnload;
expect(w.isDestroyed()).to.be.false();
});
it('overriding beforeunload prevention results in webcontents close', async () => {
const w = (webContents as typeof ElectronInternal.WebContents).create();
await w.loadURL('about:blank');
await w.executeJavaScript('window.onbeforeunload = () => "hello"; null');
w.once('will-prevent-unload', e => e.preventDefault());
const destroyed = once(w, 'destroyed');
w.close({ waitForBeforeUnload: true });
await destroyed;
expect(w.isDestroyed()).to.be.true();
});
});
describe('content-bounds-updated event', () => {
afterEach(closeAllWindows);
it('emits when moveTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.moveTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated');
const { width, height } = w.getBounds();
expect(rect).to.deep.equal({
x: 100,
y: 100,
width,
height
});
await new Promise(setImmediate);
expect(w.getBounds().x).to.equal(100);
expect(w.getBounds().y).to.equal(100);
});
it('emits when resizeTo is called', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
const [, rect] = await once(w.webContents, 'content-bounds-updated');
const { x, y } = w.getBounds();
expect(rect).to.deep.equal({
x,
y,
width: 100,
height: 100
});
await new Promise(setImmediate);
expect({
width: w.getBounds().width,
height: w.getBounds().height
}).to.deep.equal(process.platform === 'win32' ? {
// The width is reported as being larger on Windows? I'm not sure why
// this is.
width: 136,
height: 100
} : {
width: 100,
height: 100
});
});
it('does not change window bounds if cancelled', async () => {
const w = new BrowserWindow({ show: false });
const { width, height } = w.getBounds();
w.loadURL('about:blank');
w.webContents.once('content-bounds-updated', e => e.preventDefault());
await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
await new Promise(setImmediate);
expect(w.getBounds().width).to.equal(width);
expect(w.getBounds().height).to.equal(height);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,598 |
[Bug]: webContents.print fails with unspecified options
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Windows
### Operating System Version
Windows 10 version 21H2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.1
### Expected Behavior
Calling `webContents.print()`, `webContents.print({})`, or `webContents.print(null)` will result in the system print dialog to appearing.
### Actual Behavior
If `print()` or `print({})` are called, the call will never invoke the provided callback (at least not within 5 minutes, which was the longest I let it sit), nor will it throw any exceptions catchable by a try-catch block. When running the provided gist in Electron Fiddle, I see the following console log: "[19232:0605/173028.939:ERROR:device_event_log_impl.cc(222)] [17:30:28.939] Printer: print_view_manager_base.cc:352 Printer settings invalid for \\epic-print1\vca2cpy-Revenge (destination type kLocal): content size is empty; page size is empty; printable area is empty"
If `print(null)` is called, an exception will be thrown with the error message: "Cannot read properties of null (reading 'pageSize')".
### Testcase Gist URL
https://gist.github.com/mgalla10/7710e8f22830f1122cfe0d98dd99ab08
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38598
|
https://github.com/electron/electron/pull/38614
|
e8fd5fd3a8250d44a0665ca18da34cb09ea30677
|
c0d9764de9d00968a8c9d5ab74ef3b9840aebc09
| 2023-06-05T22:43:02Z |
c++
| 2023-06-09T19:41:01Z |
typings/internal-electron.d.ts
|
/// <reference path="../electron.d.ts" />
/**
* This file augments the Electron TS namespace with the internal APIs
* that are not documented but are used by Electron internally
*/
declare namespace Electron {
enum ProcessType {
browser = 'browser',
renderer = 'renderer',
worker = 'worker',
utility = 'utility'
}
interface App {
setVersion(version: string): void;
setDesktopName(name: string): void;
setAppPath(path: string | null): void;
}
type TouchBarItemType = NonNullable<Electron.TouchBarConstructorOptions['items']>[0];
interface BaseWindow {
_init(): void;
}
interface BrowserWindow {
_init(): void;
_touchBar: Electron.TouchBar | null;
_setTouchBarItems: (items: TouchBarItemType[]) => void;
_setEscapeTouchBarItem: (item: TouchBarItemType | {}) => void;
_refreshTouchBarItem: (itemID: string) => void;
_getWindowButtonVisibility: () => boolean;
frameName: string;
on(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
removeListener(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
}
interface BrowserWindowConstructorOptions {
webContents?: WebContents;
}
interface ContextBridge {
internalContextBridge?: {
contextIsolationEnabled: boolean;
overrideGlobalValueFromIsolatedWorld(keys: string[], value: any): void;
overrideGlobalValueWithDynamicPropsFromIsolatedWorld(keys: string[], value: any): void;
overrideGlobalPropertyFromIsolatedWorld(keys: string[], getter: Function, setter?: Function): void;
isInMainWorld(): boolean;
}
}
interface TouchBar {
_removeFromWindow: (win: BrowserWindow) => void;
}
interface WebContents {
_loadURL(url: string, options: ElectronInternal.LoadURLOptions): void;
getOwnerBrowserWindow(): Electron.BrowserWindow | null;
getLastWebPreferences(): Electron.WebPreferences | null;
_getProcessMemoryInfo(): Electron.ProcessMemoryInfo;
_getPreloadPaths(): string[];
equal(other: WebContents): boolean;
browserWindowOptions: BrowserWindowConstructorOptions;
_windowOpenHandler: ((details: Electron.HandlerDetails) => any) | null;
_callWindowOpenHandler(event: any, details: Electron.HandlerDetails): {browserWindowConstructorOptions: Electron.BrowserWindowConstructorOptions | null, outlivesOpener: boolean};
_setNextChildWebPreferences(prefs: Partial<Electron.BrowserWindowConstructorOptions['webPreferences']> & Pick<Electron.BrowserWindowConstructorOptions, 'backgroundColor'>): void;
_send(internal: boolean, channel: string, args: any): boolean;
_sendInternal(channel: string, ...args: any[]): void;
_printToPDF(options: any): Promise<Buffer>;
_print(options: any, callback?: (success: boolean, failureReason: string) => void): void;
_getPrinters(): Electron.PrinterInfo[];
_getPrintersAsync(): Promise<Electron.PrinterInfo[]>;
_init(): void;
canGoToIndex(index: number): boolean;
getActiveIndex(): number;
length(): number;
destroy(): void;
// <webview>
attachToIframe(embedderWebContents: Electron.WebContents, embedderFrameId: number): void;
detachFromOuterFrame(): void;
setEmbedder(embedder: Electron.WebContents): void;
viewInstanceId: number;
}
interface WebFrameMain {
_send(internal: boolean, channel: string, args: any): void;
_sendInternal(channel: string, ...args: any[]): void;
_postMessage(channel: string, message: any, transfer?: any[]): void;
}
interface WebFrame {
_isEvalAllowed(): boolean;
}
interface WebPreferences {
disablePopups?: boolean;
embedder?: Electron.WebContents;
type?: 'backgroundPage' | 'window' | 'browserView' | 'remote' | 'webview' | 'offscreen';
}
interface Menu {
_init(): void;
_isCommandIdChecked(id: string): boolean;
_isCommandIdEnabled(id: string): boolean;
_shouldCommandIdWorkWhenHidden(id: string): boolean;
_isCommandIdVisible(id: string): boolean;
_getAcceleratorForCommandId(id: string, useDefaultAccelerator: boolean): Accelerator | undefined;
_shouldRegisterAcceleratorForCommandId(id: string): boolean;
_getSharingItemForCommandId(id: string): SharingItem | null;
_callMenuWillShow(): void;
_executeCommand(event: KeyboardEvent, id: number): void;
_menuWillShow(): void;
commandsMap: Record<string, MenuItem>;
groupsMap: Record<string, MenuItem[]>;
getItemCount(): number;
popupAt(window: BaseWindow, x: number, y: number, positioning: number, callback: () => void): void;
closePopupAt(id: number): void;
setSublabel(index: number, label: string): void;
setToolTip(index: number, tooltip: string): void;
setIcon(index: number, image: string | NativeImage): void;
setRole(index: number, role: string): void;
insertItem(index: number, commandId: number, label: string): void;
insertCheckItem(index: number, commandId: number, label: string): void;
insertRadioItem(index: number, commandId: number, label: string, groupId: number): void;
insertSeparator(index: number): void;
insertSubMenu(index: number, commandId: number, label: string, submenu?: Menu): void;
delegate?: any;
_getAcceleratorTextAt(index: number): string;
}
interface MenuItem {
overrideReadOnlyProperty(property: string, value: any): void;
groupId: number;
getDefaultRoleAccelerator(): Accelerator | undefined;
getCheckStatus(): boolean;
acceleratorWorksWhenHidden?: boolean;
}
interface ReplyChannel {
sendReply(value: any): void;
}
interface IpcMainEvent {
_replyChannel: ReplyChannel;
}
interface IpcMainInvokeEvent {
_replyChannel: ReplyChannel;
}
class View {}
// Experimental views API
class BaseWindow {
constructor(args: {show: boolean})
setContentView(view: View): void
static fromId(id: number): BaseWindow;
static getAllWindows(): BaseWindow[];
isFocused(): boolean;
static getFocusedWindow(): BaseWindow | undefined;
setMenu(menu: Menu): void;
}
class WebContentsView {
constructor(options: BrowserWindowConstructorOptions)
}
// Deprecated / undocumented BrowserWindow methods
interface BrowserWindow {
getURL(): string;
send(channel: string, ...args: any[]): void;
openDevTools(options?: Electron.OpenDevToolsOptions): void;
closeDevTools(): void;
isDevToolsOpened(): void;
isDevToolsFocused(): void;
toggleDevTools(): void;
inspectElement(x: number, y: number): void;
inspectSharedWorker(): void;
inspectServiceWorker(): void;
getBackgroundThrottling(): void;
setBackgroundThrottling(allowed: boolean): void;
}
interface Protocol {
registerProtocol(scheme: string, handler: any): boolean;
interceptProtocol(scheme: string, handler: any): boolean;
}
namespace Main {
class BaseWindow extends Electron.BaseWindow {}
class View extends Electron.View {}
class WebContentsView extends Electron.WebContentsView {}
}
}
declare namespace ElectronInternal {
interface DesktopCapturer {
startHandling(captureWindow: boolean, captureScreen: boolean, thumbnailSize: Electron.Size, fetchWindowIcons: boolean): void;
_onerror?: (error: string) => void;
_onfinished?: (sources: Electron.DesktopCapturerSource[], fetchWindowIcons: boolean) => void;
}
interface GetSourcesOptions {
captureWindow: boolean;
captureScreen: boolean;
thumbnailSize: Electron.Size;
fetchWindowIcons: boolean;
}
interface GetSourcesResult {
id: string;
name: string;
thumbnail: Electron.NativeImage;
display_id: string;
appIcon: Electron.NativeImage | null;
}
interface IpcRendererInternal extends NodeJS.EventEmitter, Pick<Electron.IpcRenderer, 'send' | 'sendSync' | 'invoke'> {
invoke<T>(channel: string, ...args: any[]): Promise<T>;
}
interface IpcMainInternalEvent extends Omit<Electron.IpcMainEvent, 'reply'> {
}
interface IpcMainInternal extends NodeJS.EventEmitter {
handle(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any): void;
on(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this;
once(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this;
}
interface LoadURLOptions extends Electron.LoadURLOptions {
reloadIgnoringCache?: boolean;
}
interface WebContentsPrintOptions extends Electron.WebContentsPrintOptions {
mediaSize?: MediaSize;
}
type MediaSize = {
name: string,
custom_display_name: string,
height_microns: number,
width_microns: number,
is_default?: 'true',
}
type PageSize = {
width: number,
height: number,
}
type ModuleLoader = () => any;
interface ModuleEntry {
name: string;
loader: ModuleLoader;
}
interface UtilityProcessWrapper extends NodeJS.EventEmitter {
readonly pid: (number) | (undefined);
kill(): boolean;
postMessage(message: any, transfer?: any[]): void;
}
interface ParentPort extends NodeJS.EventEmitter {
start(): void;
pause(): void;
postMessage(message: any): void;
}
class WebViewElement extends HTMLElement {
static observedAttributes: Array<string>;
public contentWindow: Window;
public connectedCallback?(): void;
public attributeChangedCallback?(): void;
public disconnectedCallback?(): void;
// Created in web-view-impl
public getWebContentsId(): number;
public capturePage(rect?: Electron.Rectangle): Promise<Electron.NativeImage>;
}
class WebContents extends Electron.WebContents {
static create(opts?: Electron.WebPreferences): Electron.WebContents;
}
}
declare namespace Chrome {
namespace Tabs {
// https://developer.chrome.com/docs/extensions/tabs#method-executeScript
interface ExecuteScriptDetails {
code?: string;
file?: string;
allFrames?: boolean;
frameId?: number;
matchAboutBlank?: boolean;
runAt?: 'document-start' | 'document-end' | 'document_idle';
cssOrigin: 'author' | 'user';
}
type ExecuteScriptCallback = (result: Array<any>) => void;
// https://developer.chrome.com/docs/extensions/tabs#method-sendMessage
interface SendMessageDetails {
frameId?: number;
}
type SendMessageCallback = (result: any) => void;
}
}
interface Global extends NodeJS.Global {
require: NodeRequire;
module: NodeModule;
__filename: string;
__dirname: string;
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,676 |
[Feature Request]: Document which exact punctuation keys are supported
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
The [docs](https://www.electronjs.org/docs/latest/api/accelerator) are a little vague on the matter, saying:
> `Punctuation like ~, !, @, #, $, etc.`
But like better to be precise with these things. Like presumably `[` is supported, but what happens if I do a `Shift+[`, does that work? Or is that interpreted as a single `{`? And what about weird characters like `§` and `±`, are those supported?
### Proposed Solution
Being very explicit in documenting what exactly the syntax for accelerators is.
### Alternatives Considered
Finding out manually.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38676
|
https://github.com/electron/electron/pull/38740
|
f5869b6fb936ba125071f6560ae8c871e4488777
|
678d1aa37d26548004b0ad5df1ac027626c4ab2a
| 2023-06-08T09:07:52Z |
c++
| 2023-06-13T10:42:55Z |
docs/api/accelerator.md
|
# Accelerator
> Define keyboard shortcuts.
Accelerators are strings that can contain multiple modifiers and a single key code,
combined by the `+` character, and are used to define keyboard shortcuts
throughout your application.
Examples:
* `CommandOrControl+A`
* `CommandOrControl+Shift+Z`
Shortcuts are registered with the [`globalShortcut`](global-shortcut.md) module
using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback)
method, i.e.
```javascript
const { app, globalShortcut } = require('electron')
app.whenReady().then(() => {
// Register a 'CommandOrControl+Y' shortcut listener.
globalShortcut.register('CommandOrControl+Y', () => {
// Do stuff when Y and either Command/Control is pressed.
})
})
```
## Platform notice
On Linux and Windows, the `Command` key does not have any effect so
use `CommandOrControl` which represents `Command` on macOS and `Control` on
Linux and Windows to define some accelerators.
Use `Alt` instead of `Option`. The `Option` key only exists on macOS, whereas
the `Alt` key is available on all platforms.
The `Super` (or `Meta`) key is mapped to the `Windows` key on Windows and Linux and
`Cmd` on macOS.
## Available modifiers
* `Command` (or `Cmd` for short)
* `Control` (or `Ctrl` for short)
* `CommandOrControl` (or `CmdOrCtrl` for short)
* `Alt`
* `Option`
* `AltGr`
* `Shift`
* `Super`
* `Meta`
## Available key codes
* `0` to `9`
* `A` to `Z`
* `F1` to `F24`
* Punctuation like `~`, `!`, `@`, `#`, `$`, etc.
* `Plus`
* `Space`
* `Tab`
* `Capslock`
* `Numlock`
* `Scrolllock`
* `Backspace`
* `Delete`
* `Insert`
* `Return` (or `Enter` as alias)
* `Up`, `Down`, `Left` and `Right`
* `Home` and `End`
* `PageUp` and `PageDown`
* `Escape` (or `Esc` for short)
* `VolumeUp`, `VolumeDown` and `VolumeMute`
* `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` and `MediaPlayPause`
* `PrintScreen`
* NumPad Keys
* `num0` - `num9`
* `numdec` - decimal key
* `numadd` - numpad `+` key
* `numsub` - numpad `-` key
* `nummult` - numpad `*` key
* `numdiv` - numpad `÷` key
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,676 |
[Feature Request]: Document which exact punctuation keys are supported
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
The [docs](https://www.electronjs.org/docs/latest/api/accelerator) are a little vague on the matter, saying:
> `Punctuation like ~, !, @, #, $, etc.`
But like better to be precise with these things. Like presumably `[` is supported, but what happens if I do a `Shift+[`, does that work? Or is that interpreted as a single `{`? And what about weird characters like `§` and `±`, are those supported?
### Proposed Solution
Being very explicit in documenting what exactly the syntax for accelerators is.
### Alternatives Considered
Finding out manually.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38676
|
https://github.com/electron/electron/pull/38740
|
f5869b6fb936ba125071f6560ae8c871e4488777
|
678d1aa37d26548004b0ad5df1ac027626c4ab2a
| 2023-06-08T09:07:52Z |
c++
| 2023-06-13T10:42:55Z |
shell/common/keyboard_util.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 <string>
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "shell/common/keyboard_util.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "ui/events/event_constants.h"
namespace electron {
namespace {
// Return key code represented by |str|.
ui::KeyboardCode KeyboardCodeFromKeyIdentifier(
const std::string& s,
absl::optional<char16_t>* shifted_char) {
std::string str = base::ToLowerASCII(s);
if (str == "ctrl" || str == "control") {
return ui::VKEY_CONTROL;
} else if (str == "super" || str == "cmd" || str == "command" ||
str == "meta") {
return ui::VKEY_COMMAND;
} else if (str == "commandorcontrol" || str == "cmdorctrl") {
#if BUILDFLAG(IS_MAC)
return ui::VKEY_COMMAND;
#else
return ui::VKEY_CONTROL;
#endif
} else if (str == "alt" || str == "option") {
return ui::VKEY_MENU;
} else if (str == "shift") {
return ui::VKEY_SHIFT;
} else if (str == "altgr") {
return ui::VKEY_ALTGR;
} else if (str == "plus") {
shifted_char->emplace('+');
return ui::VKEY_OEM_PLUS;
} else if (str == "capslock") {
return ui::VKEY_CAPITAL;
} else if (str == "numlock") {
return ui::VKEY_NUMLOCK;
} else if (str == "scrolllock") {
return ui::VKEY_SCROLL;
} else if (str == "tab") {
return ui::VKEY_TAB;
} else if (str == "num0") {
return ui::VKEY_NUMPAD0;
} else if (str == "num1") {
return ui::VKEY_NUMPAD1;
} else if (str == "num2") {
return ui::VKEY_NUMPAD2;
} else if (str == "num3") {
return ui::VKEY_NUMPAD3;
} else if (str == "num4") {
return ui::VKEY_NUMPAD4;
} else if (str == "num5") {
return ui::VKEY_NUMPAD5;
} else if (str == "num6") {
return ui::VKEY_NUMPAD6;
} else if (str == "num7") {
return ui::VKEY_NUMPAD7;
} else if (str == "num8") {
return ui::VKEY_NUMPAD8;
} else if (str == "num9") {
return ui::VKEY_NUMPAD9;
} else if (str == "numadd") {
return ui::VKEY_ADD;
} else if (str == "nummult") {
return ui::VKEY_MULTIPLY;
} else if (str == "numdec") {
return ui::VKEY_DECIMAL;
} else if (str == "numsub") {
return ui::VKEY_SUBTRACT;
} else if (str == "numdiv") {
return ui::VKEY_DIVIDE;
} else if (str == "space") {
return ui::VKEY_SPACE;
} else if (str == "backspace") {
return ui::VKEY_BACK;
} else if (str == "delete") {
return ui::VKEY_DELETE;
} else if (str == "insert") {
return ui::VKEY_INSERT;
} else if (str == "enter" || str == "return") {
return ui::VKEY_RETURN;
} else if (str == "up") {
return ui::VKEY_UP;
} else if (str == "down") {
return ui::VKEY_DOWN;
} else if (str == "left") {
return ui::VKEY_LEFT;
} else if (str == "right") {
return ui::VKEY_RIGHT;
} else if (str == "home") {
return ui::VKEY_HOME;
} else if (str == "end") {
return ui::VKEY_END;
} else if (str == "pageup") {
return ui::VKEY_PRIOR;
} else if (str == "pagedown") {
return ui::VKEY_NEXT;
} else if (str == "esc" || str == "escape") {
return ui::VKEY_ESCAPE;
} else if (str == "volumemute") {
return ui::VKEY_VOLUME_MUTE;
} else if (str == "volumeup") {
return ui::VKEY_VOLUME_UP;
} else if (str == "volumedown") {
return ui::VKEY_VOLUME_DOWN;
} else if (str == "medianexttrack") {
return ui::VKEY_MEDIA_NEXT_TRACK;
} else if (str == "mediaprevioustrack") {
return ui::VKEY_MEDIA_PREV_TRACK;
} else if (str == "mediastop") {
return ui::VKEY_MEDIA_STOP;
} else if (str == "mediaplaypause") {
return ui::VKEY_MEDIA_PLAY_PAUSE;
} else if (str == "printscreen") {
return ui::VKEY_SNAPSHOT;
} else if (str.size() > 1 && str[0] == 'f') {
// F1 - F24.
int n;
if (base::StringToInt(str.c_str() + 1, &n) && n > 0 && n < 25) {
return static_cast<ui::KeyboardCode>(ui::VKEY_F1 + n - 1);
} else {
LOG(WARNING) << str << "is not available on keyboard";
return ui::VKEY_UNKNOWN;
}
} else {
if (str.size() > 2)
LOG(WARNING) << "Invalid accelerator token: " << str;
return ui::VKEY_UNKNOWN;
}
}
} // namespace
ui::KeyboardCode KeyboardCodeFromCharCode(char16_t c, bool* shifted) {
c = base::ToLowerASCII(c);
*shifted = false;
switch (c) {
case 0x08:
return ui::VKEY_BACK;
case 0x7F:
return ui::VKEY_DELETE;
case 0x09:
return ui::VKEY_TAB;
case 0x0D:
return ui::VKEY_RETURN;
case 0x1B:
return ui::VKEY_ESCAPE;
case ' ':
return ui::VKEY_SPACE;
case 'a':
return ui::VKEY_A;
case 'b':
return ui::VKEY_B;
case 'c':
return ui::VKEY_C;
case 'd':
return ui::VKEY_D;
case 'e':
return ui::VKEY_E;
case 'f':
return ui::VKEY_F;
case 'g':
return ui::VKEY_G;
case 'h':
return ui::VKEY_H;
case 'i':
return ui::VKEY_I;
case 'j':
return ui::VKEY_J;
case 'k':
return ui::VKEY_K;
case 'l':
return ui::VKEY_L;
case 'm':
return ui::VKEY_M;
case 'n':
return ui::VKEY_N;
case 'o':
return ui::VKEY_O;
case 'p':
return ui::VKEY_P;
case 'q':
return ui::VKEY_Q;
case 'r':
return ui::VKEY_R;
case 's':
return ui::VKEY_S;
case 't':
return ui::VKEY_T;
case 'u':
return ui::VKEY_U;
case 'v':
return ui::VKEY_V;
case 'w':
return ui::VKEY_W;
case 'x':
return ui::VKEY_X;
case 'y':
return ui::VKEY_Y;
case 'z':
return ui::VKEY_Z;
case ')':
*shifted = true;
[[fallthrough]];
case '0':
return ui::VKEY_0;
case '!':
*shifted = true;
[[fallthrough]];
case '1':
return ui::VKEY_1;
case '@':
*shifted = true;
[[fallthrough]];
case '2':
return ui::VKEY_2;
case '#':
*shifted = true;
[[fallthrough]];
case '3':
return ui::VKEY_3;
case '$':
*shifted = true;
[[fallthrough]];
case '4':
return ui::VKEY_4;
case '%':
*shifted = true;
[[fallthrough]];
case '5':
return ui::VKEY_5;
case '^':
*shifted = true;
[[fallthrough]];
case '6':
return ui::VKEY_6;
case '&':
*shifted = true;
[[fallthrough]];
case '7':
return ui::VKEY_7;
case '*':
*shifted = true;
[[fallthrough]];
case '8':
return ui::VKEY_8;
case '(':
*shifted = true;
[[fallthrough]];
case '9':
return ui::VKEY_9;
case ':':
*shifted = true;
[[fallthrough]];
case ';':
return ui::VKEY_OEM_1;
case '+':
*shifted = true;
[[fallthrough]];
case '=':
return ui::VKEY_OEM_PLUS;
case '<':
*shifted = true;
[[fallthrough]];
case ',':
return ui::VKEY_OEM_COMMA;
case '_':
*shifted = true;
[[fallthrough]];
case '-':
return ui::VKEY_OEM_MINUS;
case '>':
*shifted = true;
[[fallthrough]];
case '.':
return ui::VKEY_OEM_PERIOD;
case '?':
*shifted = true;
[[fallthrough]];
case '/':
return ui::VKEY_OEM_2;
case '~':
*shifted = true;
[[fallthrough]];
case '`':
return ui::VKEY_OEM_3;
case '{':
*shifted = true;
[[fallthrough]];
case '[':
return ui::VKEY_OEM_4;
case '|':
*shifted = true;
[[fallthrough]];
case '\\':
return ui::VKEY_OEM_5;
case '}':
*shifted = true;
[[fallthrough]];
case ']':
return ui::VKEY_OEM_6;
case '"':
*shifted = true;
[[fallthrough]];
case '\'':
return ui::VKEY_OEM_7;
default:
return ui::VKEY_UNKNOWN;
}
}
ui::KeyboardCode KeyboardCodeFromStr(const std::string& str,
absl::optional<char16_t>* shifted_char) {
if (str.size() == 1) {
bool shifted = false;
auto ret = KeyboardCodeFromCharCode(str[0], &shifted);
if (shifted)
shifted_char->emplace(str[0]);
return ret;
} else {
return KeyboardCodeFromKeyIdentifier(str, shifted_char);
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,676 |
[Feature Request]: Document which exact punctuation keys are supported
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
The [docs](https://www.electronjs.org/docs/latest/api/accelerator) are a little vague on the matter, saying:
> `Punctuation like ~, !, @, #, $, etc.`
But like better to be precise with these things. Like presumably `[` is supported, but what happens if I do a `Shift+[`, does that work? Or is that interpreted as a single `{`? And what about weird characters like `§` and `±`, are those supported?
### Proposed Solution
Being very explicit in documenting what exactly the syntax for accelerators is.
### Alternatives Considered
Finding out manually.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38676
|
https://github.com/electron/electron/pull/38740
|
f5869b6fb936ba125071f6560ae8c871e4488777
|
678d1aa37d26548004b0ad5df1ac027626c4ab2a
| 2023-06-08T09:07:52Z |
c++
| 2023-06-13T10:42:55Z |
docs/api/accelerator.md
|
# Accelerator
> Define keyboard shortcuts.
Accelerators are strings that can contain multiple modifiers and a single key code,
combined by the `+` character, and are used to define keyboard shortcuts
throughout your application.
Examples:
* `CommandOrControl+A`
* `CommandOrControl+Shift+Z`
Shortcuts are registered with the [`globalShortcut`](global-shortcut.md) module
using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback)
method, i.e.
```javascript
const { app, globalShortcut } = require('electron')
app.whenReady().then(() => {
// Register a 'CommandOrControl+Y' shortcut listener.
globalShortcut.register('CommandOrControl+Y', () => {
// Do stuff when Y and either Command/Control is pressed.
})
})
```
## Platform notice
On Linux and Windows, the `Command` key does not have any effect so
use `CommandOrControl` which represents `Command` on macOS and `Control` on
Linux and Windows to define some accelerators.
Use `Alt` instead of `Option`. The `Option` key only exists on macOS, whereas
the `Alt` key is available on all platforms.
The `Super` (or `Meta`) key is mapped to the `Windows` key on Windows and Linux and
`Cmd` on macOS.
## Available modifiers
* `Command` (or `Cmd` for short)
* `Control` (or `Ctrl` for short)
* `CommandOrControl` (or `CmdOrCtrl` for short)
* `Alt`
* `Option`
* `AltGr`
* `Shift`
* `Super`
* `Meta`
## Available key codes
* `0` to `9`
* `A` to `Z`
* `F1` to `F24`
* Punctuation like `~`, `!`, `@`, `#`, `$`, etc.
* `Plus`
* `Space`
* `Tab`
* `Capslock`
* `Numlock`
* `Scrolllock`
* `Backspace`
* `Delete`
* `Insert`
* `Return` (or `Enter` as alias)
* `Up`, `Down`, `Left` and `Right`
* `Home` and `End`
* `PageUp` and `PageDown`
* `Escape` (or `Esc` for short)
* `VolumeUp`, `VolumeDown` and `VolumeMute`
* `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` and `MediaPlayPause`
* `PrintScreen`
* NumPad Keys
* `num0` - `num9`
* `numdec` - decimal key
* `numadd` - numpad `+` key
* `numsub` - numpad `-` key
* `nummult` - numpad `*` key
* `numdiv` - numpad `÷` key
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,676 |
[Feature Request]: Document which exact punctuation keys are supported
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
The [docs](https://www.electronjs.org/docs/latest/api/accelerator) are a little vague on the matter, saying:
> `Punctuation like ~, !, @, #, $, etc.`
But like better to be precise with these things. Like presumably `[` is supported, but what happens if I do a `Shift+[`, does that work? Or is that interpreted as a single `{`? And what about weird characters like `§` and `±`, are those supported?
### Proposed Solution
Being very explicit in documenting what exactly the syntax for accelerators is.
### Alternatives Considered
Finding out manually.
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38676
|
https://github.com/electron/electron/pull/38740
|
f5869b6fb936ba125071f6560ae8c871e4488777
|
678d1aa37d26548004b0ad5df1ac027626c4ab2a
| 2023-06-08T09:07:52Z |
c++
| 2023-06-13T10:42:55Z |
shell/common/keyboard_util.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 <string>
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "shell/common/keyboard_util.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "ui/events/event_constants.h"
namespace electron {
namespace {
// Return key code represented by |str|.
ui::KeyboardCode KeyboardCodeFromKeyIdentifier(
const std::string& s,
absl::optional<char16_t>* shifted_char) {
std::string str = base::ToLowerASCII(s);
if (str == "ctrl" || str == "control") {
return ui::VKEY_CONTROL;
} else if (str == "super" || str == "cmd" || str == "command" ||
str == "meta") {
return ui::VKEY_COMMAND;
} else if (str == "commandorcontrol" || str == "cmdorctrl") {
#if BUILDFLAG(IS_MAC)
return ui::VKEY_COMMAND;
#else
return ui::VKEY_CONTROL;
#endif
} else if (str == "alt" || str == "option") {
return ui::VKEY_MENU;
} else if (str == "shift") {
return ui::VKEY_SHIFT;
} else if (str == "altgr") {
return ui::VKEY_ALTGR;
} else if (str == "plus") {
shifted_char->emplace('+');
return ui::VKEY_OEM_PLUS;
} else if (str == "capslock") {
return ui::VKEY_CAPITAL;
} else if (str == "numlock") {
return ui::VKEY_NUMLOCK;
} else if (str == "scrolllock") {
return ui::VKEY_SCROLL;
} else if (str == "tab") {
return ui::VKEY_TAB;
} else if (str == "num0") {
return ui::VKEY_NUMPAD0;
} else if (str == "num1") {
return ui::VKEY_NUMPAD1;
} else if (str == "num2") {
return ui::VKEY_NUMPAD2;
} else if (str == "num3") {
return ui::VKEY_NUMPAD3;
} else if (str == "num4") {
return ui::VKEY_NUMPAD4;
} else if (str == "num5") {
return ui::VKEY_NUMPAD5;
} else if (str == "num6") {
return ui::VKEY_NUMPAD6;
} else if (str == "num7") {
return ui::VKEY_NUMPAD7;
} else if (str == "num8") {
return ui::VKEY_NUMPAD8;
} else if (str == "num9") {
return ui::VKEY_NUMPAD9;
} else if (str == "numadd") {
return ui::VKEY_ADD;
} else if (str == "nummult") {
return ui::VKEY_MULTIPLY;
} else if (str == "numdec") {
return ui::VKEY_DECIMAL;
} else if (str == "numsub") {
return ui::VKEY_SUBTRACT;
} else if (str == "numdiv") {
return ui::VKEY_DIVIDE;
} else if (str == "space") {
return ui::VKEY_SPACE;
} else if (str == "backspace") {
return ui::VKEY_BACK;
} else if (str == "delete") {
return ui::VKEY_DELETE;
} else if (str == "insert") {
return ui::VKEY_INSERT;
} else if (str == "enter" || str == "return") {
return ui::VKEY_RETURN;
} else if (str == "up") {
return ui::VKEY_UP;
} else if (str == "down") {
return ui::VKEY_DOWN;
} else if (str == "left") {
return ui::VKEY_LEFT;
} else if (str == "right") {
return ui::VKEY_RIGHT;
} else if (str == "home") {
return ui::VKEY_HOME;
} else if (str == "end") {
return ui::VKEY_END;
} else if (str == "pageup") {
return ui::VKEY_PRIOR;
} else if (str == "pagedown") {
return ui::VKEY_NEXT;
} else if (str == "esc" || str == "escape") {
return ui::VKEY_ESCAPE;
} else if (str == "volumemute") {
return ui::VKEY_VOLUME_MUTE;
} else if (str == "volumeup") {
return ui::VKEY_VOLUME_UP;
} else if (str == "volumedown") {
return ui::VKEY_VOLUME_DOWN;
} else if (str == "medianexttrack") {
return ui::VKEY_MEDIA_NEXT_TRACK;
} else if (str == "mediaprevioustrack") {
return ui::VKEY_MEDIA_PREV_TRACK;
} else if (str == "mediastop") {
return ui::VKEY_MEDIA_STOP;
} else if (str == "mediaplaypause") {
return ui::VKEY_MEDIA_PLAY_PAUSE;
} else if (str == "printscreen") {
return ui::VKEY_SNAPSHOT;
} else if (str.size() > 1 && str[0] == 'f') {
// F1 - F24.
int n;
if (base::StringToInt(str.c_str() + 1, &n) && n > 0 && n < 25) {
return static_cast<ui::KeyboardCode>(ui::VKEY_F1 + n - 1);
} else {
LOG(WARNING) << str << "is not available on keyboard";
return ui::VKEY_UNKNOWN;
}
} else {
if (str.size() > 2)
LOG(WARNING) << "Invalid accelerator token: " << str;
return ui::VKEY_UNKNOWN;
}
}
} // namespace
ui::KeyboardCode KeyboardCodeFromCharCode(char16_t c, bool* shifted) {
c = base::ToLowerASCII(c);
*shifted = false;
switch (c) {
case 0x08:
return ui::VKEY_BACK;
case 0x7F:
return ui::VKEY_DELETE;
case 0x09:
return ui::VKEY_TAB;
case 0x0D:
return ui::VKEY_RETURN;
case 0x1B:
return ui::VKEY_ESCAPE;
case ' ':
return ui::VKEY_SPACE;
case 'a':
return ui::VKEY_A;
case 'b':
return ui::VKEY_B;
case 'c':
return ui::VKEY_C;
case 'd':
return ui::VKEY_D;
case 'e':
return ui::VKEY_E;
case 'f':
return ui::VKEY_F;
case 'g':
return ui::VKEY_G;
case 'h':
return ui::VKEY_H;
case 'i':
return ui::VKEY_I;
case 'j':
return ui::VKEY_J;
case 'k':
return ui::VKEY_K;
case 'l':
return ui::VKEY_L;
case 'm':
return ui::VKEY_M;
case 'n':
return ui::VKEY_N;
case 'o':
return ui::VKEY_O;
case 'p':
return ui::VKEY_P;
case 'q':
return ui::VKEY_Q;
case 'r':
return ui::VKEY_R;
case 's':
return ui::VKEY_S;
case 't':
return ui::VKEY_T;
case 'u':
return ui::VKEY_U;
case 'v':
return ui::VKEY_V;
case 'w':
return ui::VKEY_W;
case 'x':
return ui::VKEY_X;
case 'y':
return ui::VKEY_Y;
case 'z':
return ui::VKEY_Z;
case ')':
*shifted = true;
[[fallthrough]];
case '0':
return ui::VKEY_0;
case '!':
*shifted = true;
[[fallthrough]];
case '1':
return ui::VKEY_1;
case '@':
*shifted = true;
[[fallthrough]];
case '2':
return ui::VKEY_2;
case '#':
*shifted = true;
[[fallthrough]];
case '3':
return ui::VKEY_3;
case '$':
*shifted = true;
[[fallthrough]];
case '4':
return ui::VKEY_4;
case '%':
*shifted = true;
[[fallthrough]];
case '5':
return ui::VKEY_5;
case '^':
*shifted = true;
[[fallthrough]];
case '6':
return ui::VKEY_6;
case '&':
*shifted = true;
[[fallthrough]];
case '7':
return ui::VKEY_7;
case '*':
*shifted = true;
[[fallthrough]];
case '8':
return ui::VKEY_8;
case '(':
*shifted = true;
[[fallthrough]];
case '9':
return ui::VKEY_9;
case ':':
*shifted = true;
[[fallthrough]];
case ';':
return ui::VKEY_OEM_1;
case '+':
*shifted = true;
[[fallthrough]];
case '=':
return ui::VKEY_OEM_PLUS;
case '<':
*shifted = true;
[[fallthrough]];
case ',':
return ui::VKEY_OEM_COMMA;
case '_':
*shifted = true;
[[fallthrough]];
case '-':
return ui::VKEY_OEM_MINUS;
case '>':
*shifted = true;
[[fallthrough]];
case '.':
return ui::VKEY_OEM_PERIOD;
case '?':
*shifted = true;
[[fallthrough]];
case '/':
return ui::VKEY_OEM_2;
case '~':
*shifted = true;
[[fallthrough]];
case '`':
return ui::VKEY_OEM_3;
case '{':
*shifted = true;
[[fallthrough]];
case '[':
return ui::VKEY_OEM_4;
case '|':
*shifted = true;
[[fallthrough]];
case '\\':
return ui::VKEY_OEM_5;
case '}':
*shifted = true;
[[fallthrough]];
case ']':
return ui::VKEY_OEM_6;
case '"':
*shifted = true;
[[fallthrough]];
case '\'':
return ui::VKEY_OEM_7;
default:
return ui::VKEY_UNKNOWN;
}
}
ui::KeyboardCode KeyboardCodeFromStr(const std::string& str,
absl::optional<char16_t>* shifted_char) {
if (str.size() == 1) {
bool shifted = false;
auto ret = KeyboardCodeFromCharCode(str[0], &shifted);
if (shifted)
shifted_char->emplace(str[0]);
return ret;
} else {
return KeyboardCodeFromKeyIdentifier(str, shifted_char);
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,751 |
[Bug]: webContens.printPDF preferCSSPageSize throws an error exception message
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.2.10
### What operating system are you using?
Windows
### Operating System Version
win 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Error preferCSSPageSize Indicates a preferCSSPageSize error
### Actual Behavior

This is electron source code, path: /lib/browser/api/web-contents.ts/printToPDF
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38751
|
https://github.com/electron/electron/pull/38761
|
dc2e822dc7cd4554ba08bbb67e68e377ac936251
|
10852b3fd50865c00e5a62fa934b96973ba5c643
| 2023-06-13T02:13:03Z |
c++
| 2023-06-14T14:49:00Z |
lib/browser/api/web-contents.ts
|
import { app, ipcMain, session, webFrameMain } from 'electron/main';
import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main';
import * as url from 'url';
import * as path from 'path';
import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager';
import { parseFeatures } from '@electron/internal/browser/parse-features-string';
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
import { MessagePortMain } from '@electron/internal/browser/message-port-main';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl';
import * as deprecate from '@electron/internal/common/deprecate';
// session is not used here, the purpose is to make sure session is initialized
// before the webContents module.
// eslint-disable-next-line no-unused-expressions
session;
const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main');
let nextId = 0;
const getNextId = function () {
return ++nextId;
};
type PostData = LoadURLOptions['postData']
// Stock page sizes
const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = {
Letter: {
custom_display_name: 'Letter',
height_microns: 279400,
name: 'NA_LETTER',
width_microns: 215900
},
Legal: {
custom_display_name: 'Legal',
height_microns: 355600,
name: 'NA_LEGAL',
width_microns: 215900
},
Tabloid: {
height_microns: 431800,
name: 'NA_LEDGER',
width_microns: 279400,
custom_display_name: 'Tabloid'
},
A0: {
custom_display_name: 'A0',
height_microns: 1189000,
name: 'ISO_A0',
width_microns: 841000
},
A1: {
custom_display_name: 'A1',
height_microns: 841000,
name: 'ISO_A1',
width_microns: 594000
},
A2: {
custom_display_name: 'A2',
height_microns: 594000,
name: 'ISO_A2',
width_microns: 420000
},
A3: {
custom_display_name: 'A3',
height_microns: 420000,
name: 'ISO_A3',
width_microns: 297000
},
A4: {
custom_display_name: 'A4',
height_microns: 297000,
name: 'ISO_A4',
is_default: 'true',
width_microns: 210000
},
A5: {
custom_display_name: 'A5',
height_microns: 210000,
name: 'ISO_A5',
width_microns: 148000
},
A6: {
custom_display_name: 'A6',
height_microns: 148000,
name: 'ISO_A6',
width_microns: 105000
}
} as const;
const paperFormats: Record<string, ElectronInternal.PageSize> = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
} as const;
// The minimum micron size Chromium accepts is that where:
// Per printing/units.h:
// * kMicronsPerInch - Length of an inch in 0.001mm unit.
// * kPointsPerInch - Length of an inch in CSS's 1pt unit.
//
// Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
//
// Practically, this means microns need to be > 352 microns.
// We therefore need to verify this or it will silently fail.
const isValidCustomPageSize = (width: number, height: number) => {
return [width, height].every(x => x > 352);
};
// JavaScript implementations of WebContents.
const binding = process._linkedBinding('electron_browser_web_contents');
const printing = process._linkedBinding('electron_browser_printing');
const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } };
WebContents.prototype.postMessage = function (...args) {
return this.mainFrame.postMessage(...args);
};
WebContents.prototype.send = function (channel, ...args) {
return this.mainFrame.send(channel, ...args);
};
WebContents.prototype._sendInternal = function (channel, ...args) {
return this.mainFrame._sendInternal(channel, ...args);
};
function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) {
if (typeof frame === 'number') {
return webFrameMain.fromId(contents.mainFrame.processId, frame);
} else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) {
return webFrameMain.fromId(frame[0], frame[1]);
} else {
throw new Error('Missing required frame argument (must be number or [processId, frameId])');
}
}
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
const frame = getWebFrame(this, frameId);
if (!frame) return false;
frame.send(channel, ...args);
return true;
};
// Following methods are mapped to webFrame.
const webFrameMethods = [
'insertCSS',
'insertText',
'removeInsertedCSS',
'setVisualZoomLevelLimits'
] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[];
for (const method of webFrameMethods) {
WebContents.prototype[method] = function (...args: any[]): Promise<any> {
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args);
};
}
const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => {
if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
return new Promise<void>((resolve) => {
webContents.once('did-stop-loading', () => {
resolve();
});
});
};
// Make sure WebContents::executeJavaScript would run the code only when the
// WebContents has been loaded.
WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture);
};
WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture);
};
// Translate the options of printToPDF.
let pendingPromise: Promise<any> | undefined;
WebContents.prototype.printToPDF = async function (options) {
const printSettings: Record<string, any> = {
requestID: getNextId(),
landscape: false,
displayHeaderFooter: false,
headerTemplate: '',
footerTemplate: '',
printBackground: false,
scale: 1.0,
paperWidth: 8.5,
paperHeight: 11.0,
marginTop: 0.4,
marginBottom: 0.4,
marginLeft: 0.4,
marginRight: 0.4,
pageRanges: '',
preferCSSPageSize: false
};
if (options.landscape !== undefined) {
if (typeof options.landscape !== 'boolean') {
return Promise.reject(new Error('landscape must be a Boolean'));
}
printSettings.landscape = options.landscape;
}
if (options.displayHeaderFooter !== undefined) {
if (typeof options.displayHeaderFooter !== 'boolean') {
return Promise.reject(new Error('displayHeaderFooter must be a Boolean'));
}
printSettings.displayHeaderFooter = options.displayHeaderFooter;
}
if (options.printBackground !== undefined) {
if (typeof options.printBackground !== 'boolean') {
return Promise.reject(new Error('printBackground must be a Boolean'));
}
printSettings.shouldPrintBackgrounds = options.printBackground;
}
if (options.scale !== undefined) {
if (typeof options.scale !== 'number') {
return Promise.reject(new Error('scale must be a Number'));
}
printSettings.scale = options.scale;
}
const { pageSize } = options;
if (pageSize !== undefined) {
if (typeof pageSize === 'string') {
const format = paperFormats[pageSize.toLowerCase()];
if (!format) {
return Promise.reject(new Error(`Invalid pageSize ${pageSize}`));
}
printSettings.paperWidth = format.width;
printSettings.paperHeight = format.height;
} else if (typeof options.pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
return Promise.reject(new Error('height and width properties are required for pageSize'));
}
printSettings.paperWidth = pageSize.width;
printSettings.paperHeight = pageSize.height;
} else {
return Promise.reject(new Error('pageSize must be a String or Object'));
}
}
const { margins } = options;
if (margins !== undefined) {
if (typeof margins !== 'object') {
return Promise.reject(new Error('margins must be an Object'));
}
if (margins.top !== undefined) {
if (typeof margins.top !== 'number') {
return Promise.reject(new Error('margins.top must be a Number'));
}
printSettings.marginTop = margins.top;
}
if (margins.bottom !== undefined) {
if (typeof margins.bottom !== 'number') {
return Promise.reject(new Error('margins.bottom must be a Number'));
}
printSettings.marginBottom = margins.bottom;
}
if (margins.left !== undefined) {
if (typeof margins.left !== 'number') {
return Promise.reject(new Error('margins.left must be a Number'));
}
printSettings.marginLeft = margins.left;
}
if (margins.right !== undefined) {
if (typeof margins.right !== 'number') {
return Promise.reject(new Error('margins.right must be a Number'));
}
printSettings.marginRight = margins.right;
}
}
if (options.pageRanges !== undefined) {
if (typeof options.pageRanges !== 'string') {
return Promise.reject(new Error('pageRanges must be a String'));
}
printSettings.pageRanges = options.pageRanges;
}
if (options.headerTemplate !== undefined) {
if (typeof options.headerTemplate !== 'string') {
return Promise.reject(new Error('headerTemplate must be a String'));
}
printSettings.headerTemplate = options.headerTemplate;
}
if (options.footerTemplate !== undefined) {
if (typeof options.footerTemplate !== 'string') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.footerTemplate = options.footerTemplate;
}
if (options.preferCSSPageSize !== undefined) {
if (typeof options.preferCSSPageSize !== 'boolean') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.preferCSSPageSize = options.preferCSSPageSize;
}
if (this._printToPDF) {
if (pendingPromise) {
pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
} else {
pendingPromise = this._printToPDF(printSettings);
}
return pendingPromise;
} else {
const error = new Error('Printing feature is disabled');
return Promise.reject(error);
}
};
// TODO(codebytere): deduplicate argument sanitization by moving rest of
// print param logic into new file shared between printToPDF and print
WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions, callback) {
if (typeof options === 'object') {
const pageSize = options.pageSize ?? 'A4';
if (typeof pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
throw new Error('height and width properties are required for pageSize');
}
// Dimensions in Microns - 1 meter = 10^6 microns
const height = Math.ceil(pageSize.height);
const width = Math.ceil(pageSize.width);
if (!isValidCustomPageSize(width, height)) {
throw new Error('height and width properties must be minimum 352 microns.');
}
options.mediaSize = {
name: 'CUSTOM',
custom_display_name: 'Custom',
height_microns: height,
width_microns: width,
imageable_area_left_microns: 0,
imageable_area_bottom_microns: 0,
imageable_area_right_microns: width,
imageable_area_top_microns: height
};
} else if (typeof pageSize === 'string' && PDFPageSizes[pageSize]) {
const mediaSize = PDFPageSizes[pageSize];
options.mediaSize = {
...mediaSize,
imageable_area_left_microns: 0,
imageable_area_bottom_microns: 0,
imageable_area_right_microns: mediaSize.width_microns,
imageable_area_top_microns: mediaSize.height_microns
};
} else {
throw new Error(`Unsupported pageSize: ${pageSize}`);
}
}
if (this._print) {
if (callback) {
this._print(options, callback);
} else {
this._print(options);
}
} else {
console.error('Error: Printing feature is disabled.');
}
};
WebContents.prototype.getPrinters = function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterList) {
return printing.getPrinterList();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.getPrintersAsync = async function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterListAsync) {
return printing.getPrinterListAsync();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.loadFile = function (filePath, options = {}) {
if (typeof filePath !== 'string') {
throw new Error('Must pass filePath as a string');
}
const { query, search, hash } = options;
return this.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: path.resolve(app.getAppPath(), filePath),
query,
search,
hash
}));
};
WebContents.prototype.loadURL = function (url, options) {
const p = new Promise<void>((resolve, reject) => {
const resolveAndCleanup = () => {
removeListeners();
resolve();
};
const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
Object.assign(err, { errno: errorCode, code: errorDescription, url });
removeListeners();
reject(err);
};
const finishListener = () => {
resolveAndCleanup();
};
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
if (isMainFrame) {
rejectAndCleanup(errorCode, errorDescription, validatedURL);
}
};
let navigationStarted = false;
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
if (isMainFrame) {
if (navigationStarted && !isSameDocument) {
// the webcontents has started another unrelated navigation in the
// main frame (probably from the app calling `loadURL` again); reject
// the promise
// We should only consider the request aborted if the "navigation" is
// actually navigating and not simply transitioning URL state in the
// current context. E.g. pushState and `location.hash` changes are
// considered navigation events but are triggered with isSameDocument.
// We can ignore these to allow virtual routing on page load as long
// as the routing does not leave the document
return rejectAndCleanup(-3, 'ERR_ABORTED', url);
}
navigationStarted = true;
}
};
const stopLoadingListener = () => {
// By the time we get here, either 'finish' or 'fail' should have fired
// if the navigation occurred. However, in some situations (e.g. when
// attempting to load a page with a bad scheme), loading will stop
// without emitting finish or fail. In this case, we reject the promise
// with a generic failure.
// TODO(jeremy): enumerate all the cases in which this can happen. If
// the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
// would be more appropriate.
rejectAndCleanup(-2, 'ERR_FAILED', url);
};
const removeListeners = () => {
this.removeListener('did-finish-load', finishListener);
this.removeListener('did-fail-load', failListener);
this.removeListener('did-navigate-in-page', finishListener);
this.removeListener('did-start-navigation', navigationListener);
this.removeListener('did-stop-loading', stopLoadingListener);
this.removeListener('destroyed', stopLoadingListener);
};
this.on('did-finish-load', finishListener);
this.on('did-fail-load', failListener);
this.on('did-navigate-in-page', finishListener);
this.on('did-start-navigation', navigationListener);
this.on('did-stop-loading', stopLoadingListener);
this.on('destroyed', stopLoadingListener);
});
// Add a no-op rejection handler to silence the unhandled rejection error.
p.catch(() => {});
this._loadURL(url, options ?? {});
return p;
};
WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) {
this._windowOpenHandler = handler;
};
WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} {
const defaultResponse = {
browserWindowConstructorOptions: null,
outlivesOpener: false
};
if (!this._windowOpenHandler) {
return defaultResponse;
}
const response = this._windowOpenHandler(details);
if (typeof response !== 'object') {
event.preventDefault();
console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
return defaultResponse;
}
if (response === null) {
event.preventDefault();
console.error('The window open handler response must be an object, but was instead null.');
return defaultResponse;
}
if (response.action === 'deny') {
event.preventDefault();
return defaultResponse;
} else if (response.action === 'allow') {
return {
browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null,
outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false
};
} else {
event.preventDefault();
console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
return defaultResponse;
}
};
const addReplyToEvent = (event: Electron.IpcMainEvent) => {
const { processId, frameId } = event;
event.reply = (channel: string, ...args: any[]) => {
event.sender.sendToFrame([processId, frameId], channel, ...args);
};
};
const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
event.sender = sender;
const { processId, frameId } = event;
Object.defineProperty(event, 'senderFrame', {
get: () => webFrameMain.fromId(processId, frameId)
});
};
const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
Object.defineProperty(event, 'returnValue', {
set: (value) => event._replyChannel.sendReply(value),
get: () => {}
});
};
const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
if (!event.processId || !event.frameId) return null;
return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId);
};
const commandLine = process._linkedBinding('electron_common_command_line');
const environment = process._linkedBinding('electron_common_environment');
const loggingEnabled = () => {
return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
};
// Add JavaScript wrappers for WebContents class.
WebContents.prototype._init = function () {
const prefs = this.getLastWebPreferences() || {};
if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) {
deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.');
}
// Read off the ID at construction time, so that it's accessible even after
// the underlying C++ WebContents is destroyed.
const id = this.id;
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this._windowOpenHandler = null;
const ipc = new IpcMainImpl();
Object.defineProperty(this, 'ipc', {
get () { return ipc; },
enumerable: true
});
// Dispatch IPC messages to the ipc module.
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
this.emit('ipc-message', event, channel, ...args);
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
const replyWithError = (error: Error) => {
console.error(`Error occurred in handler for '${channel}':`, error);
event._replyChannel.sendReply({ error: error.toString() });
};
const maybeWebFrame = getWebFrameForEvent(event);
const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
if (target) {
const handler = (target as any)._invokeHandlers.get(channel);
try {
replyWithResult(await Promise.resolve(handler(event, ...args)));
} catch (err) {
replyWithError(err as Error);
}
} else {
replyWithError(new Error(`No handler registered for '${channel}'`));
}
});
this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
addReturnValueToEvent(event);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
const maybeWebFrame = getWebFrameForEvent(event);
if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) {
console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
}
this.emit('ipc-message-sync', event, channel, ...args);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
addSenderToEvent(event, this);
event.ports = ports.map(p => new MessagePortMain(p));
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
ipc.emit(channel, event, message);
ipcMain.emit(channel, event, message);
});
this.on('crashed', (event, ...args) => {
app.emit('renderer-process-crashed', event, this, ...args);
});
this.on('render-process-gone', (event, details) => {
app.emit('render-process-gone', event, this, details);
// Log out a hint to help users better debug renderer crashes.
if (loggingEnabled()) {
console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
}
});
// The devtools requests the webContents to reload.
this.on('devtools-reload-page', function (this: Electron.WebContents) {
this.reload();
});
if (this.getType() !== 'remote') {
// Make new windows requested by links behave like "window.open".
this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
referrer,
postBody,
disposition
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
const options = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
openGuestWindow({
embedder: this,
disposition,
referrer,
postData,
overrideBrowserWindowOptions: options || {},
windowOpenArgs: details,
outlivesOpener: result.outlivesOpener
});
}
});
let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
let windowOpenOutlivesOpenerOption: boolean = false;
this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
disposition,
referrer,
postBody
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
windowOpenOutlivesOpenerOption = result.outlivesOpener;
windowOpenOverriddenOptions = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
// Allow setting of backgroundColor as a webPreference even though
// it's technically a BrowserWindowConstructorOptions option because
// we need to access it in the renderer at init time.
backgroundColor: windowOpenOverriddenOptions.backgroundColor,
transparent: windowOpenOverriddenOptions.transparent,
...windowOpenOverriddenOptions.webPreferences
} : undefined;
const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
const webPreferences = makeWebPreferences({
embedder: this,
insecureParsedWebPreferences: parsedWebPreferences,
secureOverrideWebPreferences
});
windowOpenOverriddenOptions = {
...windowOpenOverriddenOptions,
webPreferences
};
this._setNextChildWebPreferences(webPreferences);
}
});
// Create a new browser window for "window.open"
this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
_userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
const overriddenOptions = windowOpenOverriddenOptions || undefined;
const outlivesOpener = windowOpenOutlivesOpenerOption;
windowOpenOverriddenOptions = null;
// false is the default
windowOpenOutlivesOpenerOption = false;
if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
disposition !== 'background-tab')) {
event.preventDefault();
return;
}
openGuestWindow({
embedder: this,
guest: webContents,
overrideBrowserWindowOptions: overriddenOptions,
disposition,
referrer,
postData,
windowOpenArgs: {
url,
frameName,
features: rawFeatures
},
outlivesOpener
});
});
}
this.on('login', (event, ...args) => {
app.emit('login', event, this, ...args);
});
this.on('ready-to-show' as any, () => {
const owner = this.getOwnerBrowserWindow();
if (owner && !owner.isDestroyed()) {
process.nextTick(() => {
owner.emit('ready-to-show');
});
}
});
this.on('select-bluetooth-device', (event, devices, callback) => {
if (this.listenerCount('select-bluetooth-device') === 1) {
// Cancel it if there are no handlers
event.preventDefault();
callback('');
}
});
app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);
// Properties
Object.defineProperty(this, 'audioMuted', {
get: () => this.isAudioMuted(),
set: (muted) => this.setAudioMuted(muted)
});
Object.defineProperty(this, 'userAgent', {
get: () => this.getUserAgent(),
set: (agent) => this.setUserAgent(agent)
});
Object.defineProperty(this, 'zoomLevel', {
get: () => this.getZoomLevel(),
set: (level) => this.setZoomLevel(level)
});
Object.defineProperty(this, 'zoomFactor', {
get: () => this.getZoomFactor(),
set: (factor) => this.setZoomFactor(factor)
});
Object.defineProperty(this, 'frameRate', {
get: () => this.getFrameRate(),
set: (rate) => this.setFrameRate(rate)
});
Object.defineProperty(this, 'backgroundThrottling', {
get: () => this.getBackgroundThrottling(),
set: (allowed) => this.setBackgroundThrottling(allowed)
});
};
// Public APIs.
export function create (options = {}): Electron.WebContents {
return new (WebContents as any)(options);
}
export function fromId (id: string) {
return binding.fromId(id);
}
export function fromFrame (frame: Electron.WebFrameMain) {
return binding.fromFrame(frame);
}
export function fromDevToolsTargetId (targetId: string) {
return binding.fromDevToolsTargetId(targetId);
}
export function getFocusedWebContents () {
let focused = null;
for (const contents of binding.getAllWebContents()) {
if (!contents.isFocused()) continue;
if (focused == null) focused = contents;
// Return webview web contents which may be embedded inside another
// web contents that is also reporting as focused
if (contents.getType() === 'webview') return contents;
}
return focused;
}
export function getAllWebContents () {
return binding.getAllWebContents();
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,751 |
[Bug]: webContens.printPDF preferCSSPageSize throws an error exception message
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.2.10
### What operating system are you using?
Windows
### Operating System Version
win 11
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
Error preferCSSPageSize Indicates a preferCSSPageSize error
### Actual Behavior

This is electron source code, path: /lib/browser/api/web-contents.ts/printToPDF
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38751
|
https://github.com/electron/electron/pull/38761
|
dc2e822dc7cd4554ba08bbb67e68e377ac936251
|
10852b3fd50865c00e5a62fa934b96973ba5c643
| 2023-06-13T02:13:03Z |
c++
| 2023-06-14T14:49:00Z |
lib/browser/api/web-contents.ts
|
import { app, ipcMain, session, webFrameMain } from 'electron/main';
import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main';
import * as url from 'url';
import * as path from 'path';
import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager';
import { parseFeatures } from '@electron/internal/browser/parse-features-string';
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils';
import { MessagePortMain } from '@electron/internal/browser/message-port-main';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
import { IpcMainImpl } from '@electron/internal/browser/ipc-main-impl';
import * as deprecate from '@electron/internal/common/deprecate';
// session is not used here, the purpose is to make sure session is initialized
// before the webContents module.
// eslint-disable-next-line no-unused-expressions
session;
const webFrameMainBinding = process._linkedBinding('electron_browser_web_frame_main');
let nextId = 0;
const getNextId = function () {
return ++nextId;
};
type PostData = LoadURLOptions['postData']
// Stock page sizes
const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = {
Letter: {
custom_display_name: 'Letter',
height_microns: 279400,
name: 'NA_LETTER',
width_microns: 215900
},
Legal: {
custom_display_name: 'Legal',
height_microns: 355600,
name: 'NA_LEGAL',
width_microns: 215900
},
Tabloid: {
height_microns: 431800,
name: 'NA_LEDGER',
width_microns: 279400,
custom_display_name: 'Tabloid'
},
A0: {
custom_display_name: 'A0',
height_microns: 1189000,
name: 'ISO_A0',
width_microns: 841000
},
A1: {
custom_display_name: 'A1',
height_microns: 841000,
name: 'ISO_A1',
width_microns: 594000
},
A2: {
custom_display_name: 'A2',
height_microns: 594000,
name: 'ISO_A2',
width_microns: 420000
},
A3: {
custom_display_name: 'A3',
height_microns: 420000,
name: 'ISO_A3',
width_microns: 297000
},
A4: {
custom_display_name: 'A4',
height_microns: 297000,
name: 'ISO_A4',
is_default: 'true',
width_microns: 210000
},
A5: {
custom_display_name: 'A5',
height_microns: 210000,
name: 'ISO_A5',
width_microns: 148000
},
A6: {
custom_display_name: 'A6',
height_microns: 148000,
name: 'ISO_A6',
width_microns: 105000
}
} as const;
const paperFormats: Record<string, ElectronInternal.PageSize> = {
letter: { width: 8.5, height: 11 },
legal: { width: 8.5, height: 14 },
tabloid: { width: 11, height: 17 },
ledger: { width: 17, height: 11 },
a0: { width: 33.1, height: 46.8 },
a1: { width: 23.4, height: 33.1 },
a2: { width: 16.54, height: 23.4 },
a3: { width: 11.7, height: 16.54 },
a4: { width: 8.27, height: 11.7 },
a5: { width: 5.83, height: 8.27 },
a6: { width: 4.13, height: 5.83 }
} as const;
// The minimum micron size Chromium accepts is that where:
// Per printing/units.h:
// * kMicronsPerInch - Length of an inch in 0.001mm unit.
// * kPointsPerInch - Length of an inch in CSS's 1pt unit.
//
// Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1
//
// Practically, this means microns need to be > 352 microns.
// We therefore need to verify this or it will silently fail.
const isValidCustomPageSize = (width: number, height: number) => {
return [width, height].every(x => x > 352);
};
// JavaScript implementations of WebContents.
const binding = process._linkedBinding('electron_browser_web_contents');
const printing = process._linkedBinding('electron_browser_printing');
const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } };
WebContents.prototype.postMessage = function (...args) {
return this.mainFrame.postMessage(...args);
};
WebContents.prototype.send = function (channel, ...args) {
return this.mainFrame.send(channel, ...args);
};
WebContents.prototype._sendInternal = function (channel, ...args) {
return this.mainFrame._sendInternal(channel, ...args);
};
function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) {
if (typeof frame === 'number') {
return webFrameMain.fromId(contents.mainFrame.processId, frame);
} else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) {
return webFrameMain.fromId(frame[0], frame[1]);
} else {
throw new Error('Missing required frame argument (must be number or [processId, frameId])');
}
}
WebContents.prototype.sendToFrame = function (frameId, channel, ...args) {
const frame = getWebFrame(this, frameId);
if (!frame) return false;
frame.send(channel, ...args);
return true;
};
// Following methods are mapped to webFrame.
const webFrameMethods = [
'insertCSS',
'insertText',
'removeInsertedCSS',
'setVisualZoomLevelLimits'
] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[];
for (const method of webFrameMethods) {
WebContents.prototype[method] = function (...args: any[]): Promise<any> {
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args);
};
}
const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => {
if (webContents.getURL() && !webContents.isLoadingMainFrame()) return;
return new Promise<void>((resolve) => {
webContents.once('did-stop-loading', () => {
resolve();
});
});
};
// Make sure WebContents::executeJavaScript would run the code only when the
// WebContents has been loaded.
WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture);
};
WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) {
await waitTillCanExecuteJavaScript(this);
return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture);
};
// Translate the options of printToPDF.
let pendingPromise: Promise<any> | undefined;
WebContents.prototype.printToPDF = async function (options) {
const printSettings: Record<string, any> = {
requestID: getNextId(),
landscape: false,
displayHeaderFooter: false,
headerTemplate: '',
footerTemplate: '',
printBackground: false,
scale: 1.0,
paperWidth: 8.5,
paperHeight: 11.0,
marginTop: 0.4,
marginBottom: 0.4,
marginLeft: 0.4,
marginRight: 0.4,
pageRanges: '',
preferCSSPageSize: false
};
if (options.landscape !== undefined) {
if (typeof options.landscape !== 'boolean') {
return Promise.reject(new Error('landscape must be a Boolean'));
}
printSettings.landscape = options.landscape;
}
if (options.displayHeaderFooter !== undefined) {
if (typeof options.displayHeaderFooter !== 'boolean') {
return Promise.reject(new Error('displayHeaderFooter must be a Boolean'));
}
printSettings.displayHeaderFooter = options.displayHeaderFooter;
}
if (options.printBackground !== undefined) {
if (typeof options.printBackground !== 'boolean') {
return Promise.reject(new Error('printBackground must be a Boolean'));
}
printSettings.shouldPrintBackgrounds = options.printBackground;
}
if (options.scale !== undefined) {
if (typeof options.scale !== 'number') {
return Promise.reject(new Error('scale must be a Number'));
}
printSettings.scale = options.scale;
}
const { pageSize } = options;
if (pageSize !== undefined) {
if (typeof pageSize === 'string') {
const format = paperFormats[pageSize.toLowerCase()];
if (!format) {
return Promise.reject(new Error(`Invalid pageSize ${pageSize}`));
}
printSettings.paperWidth = format.width;
printSettings.paperHeight = format.height;
} else if (typeof options.pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
return Promise.reject(new Error('height and width properties are required for pageSize'));
}
printSettings.paperWidth = pageSize.width;
printSettings.paperHeight = pageSize.height;
} else {
return Promise.reject(new Error('pageSize must be a String or Object'));
}
}
const { margins } = options;
if (margins !== undefined) {
if (typeof margins !== 'object') {
return Promise.reject(new Error('margins must be an Object'));
}
if (margins.top !== undefined) {
if (typeof margins.top !== 'number') {
return Promise.reject(new Error('margins.top must be a Number'));
}
printSettings.marginTop = margins.top;
}
if (margins.bottom !== undefined) {
if (typeof margins.bottom !== 'number') {
return Promise.reject(new Error('margins.bottom must be a Number'));
}
printSettings.marginBottom = margins.bottom;
}
if (margins.left !== undefined) {
if (typeof margins.left !== 'number') {
return Promise.reject(new Error('margins.left must be a Number'));
}
printSettings.marginLeft = margins.left;
}
if (margins.right !== undefined) {
if (typeof margins.right !== 'number') {
return Promise.reject(new Error('margins.right must be a Number'));
}
printSettings.marginRight = margins.right;
}
}
if (options.pageRanges !== undefined) {
if (typeof options.pageRanges !== 'string') {
return Promise.reject(new Error('pageRanges must be a String'));
}
printSettings.pageRanges = options.pageRanges;
}
if (options.headerTemplate !== undefined) {
if (typeof options.headerTemplate !== 'string') {
return Promise.reject(new Error('headerTemplate must be a String'));
}
printSettings.headerTemplate = options.headerTemplate;
}
if (options.footerTemplate !== undefined) {
if (typeof options.footerTemplate !== 'string') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.footerTemplate = options.footerTemplate;
}
if (options.preferCSSPageSize !== undefined) {
if (typeof options.preferCSSPageSize !== 'boolean') {
return Promise.reject(new Error('footerTemplate must be a String'));
}
printSettings.preferCSSPageSize = options.preferCSSPageSize;
}
if (this._printToPDF) {
if (pendingPromise) {
pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings));
} else {
pendingPromise = this._printToPDF(printSettings);
}
return pendingPromise;
} else {
const error = new Error('Printing feature is disabled');
return Promise.reject(error);
}
};
// TODO(codebytere): deduplicate argument sanitization by moving rest of
// print param logic into new file shared between printToPDF and print
WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions, callback) {
if (typeof options === 'object') {
const pageSize = options.pageSize ?? 'A4';
if (typeof pageSize === 'object') {
if (!pageSize.height || !pageSize.width) {
throw new Error('height and width properties are required for pageSize');
}
// Dimensions in Microns - 1 meter = 10^6 microns
const height = Math.ceil(pageSize.height);
const width = Math.ceil(pageSize.width);
if (!isValidCustomPageSize(width, height)) {
throw new Error('height and width properties must be minimum 352 microns.');
}
options.mediaSize = {
name: 'CUSTOM',
custom_display_name: 'Custom',
height_microns: height,
width_microns: width,
imageable_area_left_microns: 0,
imageable_area_bottom_microns: 0,
imageable_area_right_microns: width,
imageable_area_top_microns: height
};
} else if (typeof pageSize === 'string' && PDFPageSizes[pageSize]) {
const mediaSize = PDFPageSizes[pageSize];
options.mediaSize = {
...mediaSize,
imageable_area_left_microns: 0,
imageable_area_bottom_microns: 0,
imageable_area_right_microns: mediaSize.width_microns,
imageable_area_top_microns: mediaSize.height_microns
};
} else {
throw new Error(`Unsupported pageSize: ${pageSize}`);
}
}
if (this._print) {
if (callback) {
this._print(options, callback);
} else {
this._print(options);
}
} else {
console.error('Error: Printing feature is disabled.');
}
};
WebContents.prototype.getPrinters = function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterList) {
return printing.getPrinterList();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.getPrintersAsync = async function () {
// TODO(nornagon): this API has nothing to do with WebContents and should be
// moved.
if (printing.getPrinterListAsync) {
return printing.getPrinterListAsync();
} else {
console.error('Error: Printing feature is disabled.');
return [];
}
};
WebContents.prototype.loadFile = function (filePath, options = {}) {
if (typeof filePath !== 'string') {
throw new Error('Must pass filePath as a string');
}
const { query, search, hash } = options;
return this.loadURL(url.format({
protocol: 'file',
slashes: true,
pathname: path.resolve(app.getAppPath(), filePath),
query,
search,
hash
}));
};
WebContents.prototype.loadURL = function (url, options) {
const p = new Promise<void>((resolve, reject) => {
const resolveAndCleanup = () => {
removeListeners();
resolve();
};
const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => {
const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`);
Object.assign(err, { errno: errorCode, code: errorDescription, url });
removeListeners();
reject(err);
};
const finishListener = () => {
resolveAndCleanup();
};
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
if (isMainFrame) {
rejectAndCleanup(errorCode, errorDescription, validatedURL);
}
};
let navigationStarted = false;
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
if (isMainFrame) {
if (navigationStarted && !isSameDocument) {
// the webcontents has started another unrelated navigation in the
// main frame (probably from the app calling `loadURL` again); reject
// the promise
// We should only consider the request aborted if the "navigation" is
// actually navigating and not simply transitioning URL state in the
// current context. E.g. pushState and `location.hash` changes are
// considered navigation events but are triggered with isSameDocument.
// We can ignore these to allow virtual routing on page load as long
// as the routing does not leave the document
return rejectAndCleanup(-3, 'ERR_ABORTED', url);
}
navigationStarted = true;
}
};
const stopLoadingListener = () => {
// By the time we get here, either 'finish' or 'fail' should have fired
// if the navigation occurred. However, in some situations (e.g. when
// attempting to load a page with a bad scheme), loading will stop
// without emitting finish or fail. In this case, we reject the promise
// with a generic failure.
// TODO(jeremy): enumerate all the cases in which this can happen. If
// the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT
// would be more appropriate.
rejectAndCleanup(-2, 'ERR_FAILED', url);
};
const removeListeners = () => {
this.removeListener('did-finish-load', finishListener);
this.removeListener('did-fail-load', failListener);
this.removeListener('did-navigate-in-page', finishListener);
this.removeListener('did-start-navigation', navigationListener);
this.removeListener('did-stop-loading', stopLoadingListener);
this.removeListener('destroyed', stopLoadingListener);
};
this.on('did-finish-load', finishListener);
this.on('did-fail-load', failListener);
this.on('did-navigate-in-page', finishListener);
this.on('did-start-navigation', navigationListener);
this.on('did-stop-loading', stopLoadingListener);
this.on('destroyed', stopLoadingListener);
});
// Add a no-op rejection handler to silence the unhandled rejection error.
p.catch(() => {});
this._loadURL(url, options ?? {});
return p;
};
WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, outlivesOpener?: boolean})) {
this._windowOpenHandler = handler;
};
WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): {browserWindowConstructorOptions: BrowserWindowConstructorOptions | null, outlivesOpener: boolean} {
const defaultResponse = {
browserWindowConstructorOptions: null,
outlivesOpener: false
};
if (!this._windowOpenHandler) {
return defaultResponse;
}
const response = this._windowOpenHandler(details);
if (typeof response !== 'object') {
event.preventDefault();
console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`);
return defaultResponse;
}
if (response === null) {
event.preventDefault();
console.error('The window open handler response must be an object, but was instead null.');
return defaultResponse;
}
if (response.action === 'deny') {
event.preventDefault();
return defaultResponse;
} else if (response.action === 'allow') {
return {
browserWindowConstructorOptions: typeof response.overrideBrowserWindowOptions === 'object' ? response.overrideBrowserWindowOptions : null,
outlivesOpener: typeof response.outlivesOpener === 'boolean' ? response.outlivesOpener : false
};
} else {
event.preventDefault();
console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.');
return defaultResponse;
}
};
const addReplyToEvent = (event: Electron.IpcMainEvent) => {
const { processId, frameId } = event;
event.reply = (channel: string, ...args: any[]) => {
event.sender.sendToFrame([processId, frameId], channel, ...args);
};
};
const addSenderToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent, sender: Electron.WebContents) => {
event.sender = sender;
const { processId, frameId } = event;
Object.defineProperty(event, 'senderFrame', {
get: () => webFrameMain.fromId(processId, frameId)
});
};
const addReturnValueToEvent = (event: Electron.IpcMainEvent) => {
Object.defineProperty(event, 'returnValue', {
set: (value) => event._replyChannel.sendReply(value),
get: () => {}
});
};
const getWebFrameForEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => {
if (!event.processId || !event.frameId) return null;
return webFrameMainBinding.fromIdOrNull(event.processId, event.frameId);
};
const commandLine = process._linkedBinding('electron_common_command_line');
const environment = process._linkedBinding('electron_common_environment');
const loggingEnabled = () => {
return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging');
};
// Add JavaScript wrappers for WebContents class.
WebContents.prototype._init = function () {
const prefs = this.getLastWebPreferences() || {};
if (!prefs.nodeIntegration && prefs.preload != null && prefs.sandbox == null) {
deprecate.log('The default sandbox option for windows without nodeIntegration is changing. Presently, by default, when a window has a preload script, it defaults to being unsandboxed. In Electron 20, this default will be changing, and all windows that have nodeIntegration: false (which is the default) will be sandboxed by default. If your preload script doesn\'t use Node, no action is needed. If your preload script does use Node, either refactor it to move Node usage to the main process, or specify sandbox: false in your WebPreferences.');
}
// Read off the ID at construction time, so that it's accessible even after
// the underlying C++ WebContents is destroyed.
const id = this.id;
Object.defineProperty(this, 'id', {
value: id,
writable: false
});
this._windowOpenHandler = null;
const ipc = new IpcMainImpl();
Object.defineProperty(this, 'ipc', {
get () { return ipc; },
enumerable: true
});
// Dispatch IPC messages to the ipc module.
this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
this.emit('ipc-message', event, channel, ...args);
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-invoke' as any, async function (this: Electron.WebContents, event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
const replyWithResult = (result: any) => event._replyChannel.sendReply({ result });
const replyWithError = (error: Error) => {
console.error(`Error occurred in handler for '${channel}':`, error);
event._replyChannel.sendReply({ error: error.toString() });
};
const maybeWebFrame = getWebFrameForEvent(event);
const targets: (ElectronInternal.IpcMainInternal| undefined)[] = internal ? [ipcMainInternal] : [maybeWebFrame?.ipc, ipc, ipcMain];
const target = targets.find(target => target && (target as any)._invokeHandlers.has(channel));
if (target) {
const handler = (target as any)._invokeHandlers.get(channel);
try {
replyWithResult(await Promise.resolve(handler(event, ...args)));
} catch (err) {
replyWithError(err as Error);
}
} else {
replyWithError(new Error(`No handler registered for '${channel}'`));
}
});
this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) {
addSenderToEvent(event, this);
addReturnValueToEvent(event);
if (internal) {
ipcMainInternal.emit(channel, event, ...args);
} else {
addReplyToEvent(event);
const maybeWebFrame = getWebFrameForEvent(event);
if (this.listenerCount('ipc-message-sync') === 0 && ipc.listenerCount(channel) === 0 && ipcMain.listenerCount(channel) === 0 && (!maybeWebFrame || maybeWebFrame.ipc.listenerCount(channel) === 0)) {
console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`);
}
this.emit('ipc-message-sync', event, channel, ...args);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, ...args);
ipc.emit(channel, event, ...args);
ipcMain.emit(channel, event, ...args);
}
});
this.on('-ipc-ports' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) {
addSenderToEvent(event, this);
event.ports = ports.map(p => new MessagePortMain(p));
const maybeWebFrame = getWebFrameForEvent(event);
maybeWebFrame && maybeWebFrame.ipc.emit(channel, event, message);
ipc.emit(channel, event, message);
ipcMain.emit(channel, event, message);
});
this.on('crashed', (event, ...args) => {
app.emit('renderer-process-crashed', event, this, ...args);
});
this.on('render-process-gone', (event, details) => {
app.emit('render-process-gone', event, this, details);
// Log out a hint to help users better debug renderer crashes.
if (loggingEnabled()) {
console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`);
}
});
// The devtools requests the webContents to reload.
this.on('devtools-reload-page', function (this: Electron.WebContents) {
this.reload();
});
if (this.getType() !== 'remote') {
// Make new windows requested by links behave like "window.open".
this.on('-new-window' as any, (event: Electron.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'],
rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
referrer,
postBody,
disposition
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
const options = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
openGuestWindow({
embedder: this,
disposition,
referrer,
postData,
overrideBrowserWindowOptions: options || {},
windowOpenArgs: details,
outlivesOpener: result.outlivesOpener
});
}
});
let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null;
let windowOpenOutlivesOpenerOption: boolean = false;
this.on('-will-add-new-contents' as any, (event: Electron.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => {
const postBody = postData ? {
data: postData,
...parseContentTypeFormat(postData)
} : undefined;
const details: Electron.HandlerDetails = {
url,
frameName,
features: rawFeatures,
disposition,
referrer,
postBody
};
let result: ReturnType<typeof this._callWindowOpenHandler>;
try {
result = this._callWindowOpenHandler(event, details);
} catch (err) {
event.preventDefault();
throw err;
}
windowOpenOutlivesOpenerOption = result.outlivesOpener;
windowOpenOverriddenOptions = result.browserWindowConstructorOptions;
if (!event.defaultPrevented) {
const secureOverrideWebPreferences = windowOpenOverriddenOptions ? {
// Allow setting of backgroundColor as a webPreference even though
// it's technically a BrowserWindowConstructorOptions option because
// we need to access it in the renderer at init time.
backgroundColor: windowOpenOverriddenOptions.backgroundColor,
transparent: windowOpenOverriddenOptions.transparent,
...windowOpenOverriddenOptions.webPreferences
} : undefined;
const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures);
const webPreferences = makeWebPreferences({
embedder: this,
insecureParsedWebPreferences: parsedWebPreferences,
secureOverrideWebPreferences
});
windowOpenOverriddenOptions = {
...windowOpenOverriddenOptions,
webPreferences
};
this._setNextChildWebPreferences(webPreferences);
}
});
// Create a new browser window for "window.open"
this.on('-add-new-contents' as any, (event: Electron.Event, webContents: Electron.WebContents, disposition: string,
_userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string,
referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => {
const overriddenOptions = windowOpenOverriddenOptions || undefined;
const outlivesOpener = windowOpenOutlivesOpenerOption;
windowOpenOverriddenOptions = null;
// false is the default
windowOpenOutlivesOpenerOption = false;
if ((disposition !== 'foreground-tab' && disposition !== 'new-window' &&
disposition !== 'background-tab')) {
event.preventDefault();
return;
}
openGuestWindow({
embedder: this,
guest: webContents,
overrideBrowserWindowOptions: overriddenOptions,
disposition,
referrer,
postData,
windowOpenArgs: {
url,
frameName,
features: rawFeatures
},
outlivesOpener
});
});
}
this.on('login', (event, ...args) => {
app.emit('login', event, this, ...args);
});
this.on('ready-to-show' as any, () => {
const owner = this.getOwnerBrowserWindow();
if (owner && !owner.isDestroyed()) {
process.nextTick(() => {
owner.emit('ready-to-show');
});
}
});
this.on('select-bluetooth-device', (event, devices, callback) => {
if (this.listenerCount('select-bluetooth-device') === 1) {
// Cancel it if there are no handlers
event.preventDefault();
callback('');
}
});
app.emit('web-contents-created', { sender: this, preventDefault () {}, get defaultPrevented () { return false; } }, this);
// Properties
Object.defineProperty(this, 'audioMuted', {
get: () => this.isAudioMuted(),
set: (muted) => this.setAudioMuted(muted)
});
Object.defineProperty(this, 'userAgent', {
get: () => this.getUserAgent(),
set: (agent) => this.setUserAgent(agent)
});
Object.defineProperty(this, 'zoomLevel', {
get: () => this.getZoomLevel(),
set: (level) => this.setZoomLevel(level)
});
Object.defineProperty(this, 'zoomFactor', {
get: () => this.getZoomFactor(),
set: (factor) => this.setZoomFactor(factor)
});
Object.defineProperty(this, 'frameRate', {
get: () => this.getFrameRate(),
set: (rate) => this.setFrameRate(rate)
});
Object.defineProperty(this, 'backgroundThrottling', {
get: () => this.getBackgroundThrottling(),
set: (allowed) => this.setBackgroundThrottling(allowed)
});
};
// Public APIs.
export function create (options = {}): Electron.WebContents {
return new (WebContents as any)(options);
}
export function fromId (id: string) {
return binding.fromId(id);
}
export function fromFrame (frame: Electron.WebFrameMain) {
return binding.fromFrame(frame);
}
export function fromDevToolsTargetId (targetId: string) {
return binding.fromDevToolsTargetId(targetId);
}
export function getFocusedWebContents () {
let focused = null;
for (const contents of binding.getAllWebContents()) {
if (!contents.isFocused()) continue;
if (focused == null) focused = contents;
// Return webview web contents which may be embedded inside another
// web contents that is also reporting as focused
if (contents.getType() === 'webview') return contents;
}
return focused;
}
export function getAllWebContents () {
return binding.getAllWebContents();
}
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,996 |
[Bug]: Errors about silent printing
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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.17
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro 21H2
### What arch are you using?
x64
### Last Known Working Electron version
18.3.15
### Expected Behavior
I want to use contents.print ({silent: true}) to execute the print task only once
### Actual Behavior
Use contents.Print({silent: true}) will be executed twice.
Use the following code to monitor the actual printing times.
```js
window. onbeforeprint = (event) => {
console. log('before print');
};
window. onafterprint = (event) => {
console. log('After print');
};
```
This phenomenon will appear in 19 and later versions.
### Testcase Gist URL
https://gist.github.com/feddc9ddf37da270efc034d6ff6431b9
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35996
|
https://github.com/electron/electron/pull/38741
|
d78f37ec8faae9a3677037e1b40baea81fc93b6c
|
46fb0d8f5f3a33c5b9bba2329ac5de946cd66a3c
| 2022-10-12T04:43:34Z |
c++
| 2023-06-15T14:46:38Z |
patches/chromium/printing.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Shelley Vohr <[email protected]>
Date: Fri, 7 Jun 2019 13:59:37 -0700
Subject: printing.patch
Add changeset that was previously applied to sources in chromium_src. The
majority of changes originally come from these PRs:
* https://github.com/electron/electron/pull/1835
* https://github.com/electron/electron/pull/8596
This patch also fixes callback for manual user cancellation and success.
diff --git a/BUILD.gn b/BUILD.gn
index b8b5fddffbff56a83c6315b6d1aad2ad8fad0276..c4aed9336a783f4af3205b359eb5f09a8446e512 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -968,7 +968,6 @@ if (is_win) {
"//media:media_unittests",
"//media/midi:midi_unittests",
"//net:net_unittests",
- "//printing:printing_unittests",
"//sql:sql_unittests",
"//third_party/breakpad:symupload($host_toolchain)",
"//ui/base:ui_base_unittests",
@@ -977,6 +976,10 @@ if (is_win) {
"//ui/views:views_unittests",
"//url:url_unittests",
]
+
+ if (enable_printing) {
+ deps += [ "//printing:printing_unittests" ]
+ }
}
}
diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc
index 3a66a52b8d3c6da9cd8d7e9afdc8d59f528ec3d5..facaa6fbca8ee7c04f83607e62b81b9594727ada 100644
--- a/chrome/browser/printing/print_job.cc
+++ b/chrome/browser/printing/print_job.cc
@@ -93,6 +93,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) {
return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization);
}
+#if 0
PrefService* GetPrefsForWebContents(content::WebContents* web_contents) {
// TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely
// because `web_contents` was null. As a result, this section has many more
@@ -107,6 +108,7 @@ content::WebContents* GetWebContents(content::GlobalRenderFrameHostId rfh_id) {
auto* rfh = content::RenderFrameHost::FromID(rfh_id);
return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr;
}
+#endif
#endif // BUILDFLAG(IS_WIN)
@@ -147,10 +149,8 @@ void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query,
#if BUILDFLAG(IS_WIN)
pdf_page_mapping_ = PageNumber::GetPages(settings->ranges(), page_count);
- PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_));
- if (prefs && prefs->IsManagedPreference(prefs::kPdfUseSkiaRendererEnabled)) {
- use_skia_ = prefs->GetBoolean(prefs::kPdfUseSkiaRendererEnabled);
- }
+ // TODO(codebytere): should we enable this later?
+ use_skia_ = false;
#endif
auto new_doc = base::MakeRefCounted<PrintedDocument>(std::move(settings),
@@ -374,8 +374,10 @@ void PrintJob::StartPdfToEmfConversion(
const PrintSettings& settings = document()->settings();
+#if 0
PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_));
- bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs);
+#endif
+ bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr);
using RenderMode = PdfRenderSettings::Mode;
RenderMode mode = print_with_reduced_rasterization
@@ -465,8 +467,10 @@ void PrintJob::StartPdfToPostScriptConversion(
if (ps_level2) {
mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2;
} else {
+#if 0
PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_));
- mode = PrintWithPostScriptType42Fonts(prefs)
+#endif
+ mode = PrintWithPostScriptType42Fonts(nullptr)
? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS
: PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3;
}
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc
index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffdd4ff2077 100644
--- a/chrome/browser/printing/print_view_manager_base.cc
+++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -23,7 +23,9 @@
#include "chrome/browser/bad_message.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
+#if 0 // Electron does not use Chrome error dialogs
#include "chrome/browser/printing/print_error_dialog.h"
+#endif
#include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_view_manager_common.h"
@@ -83,6 +85,20 @@ namespace printing {
namespace {
+std::string PrintReasonFromPrintStatus(PrintViewManager::PrintStatus status) {
+ if (status == PrintViewManager::PrintStatus::kInvalid) {
+ return "Invalid printer settings";
+ } else if (status == PrintViewManager::PrintStatus::kCanceled) {
+ return "Print job canceled";
+ } else if (status == PrintViewManager::PrintStatus::kFailed) {
+ return "Print job failed";
+ }
+ return "";
+}
+
+using PrintSettingsCallback =
+ base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>;
+
void OnDidGetDefaultPrintSettings(
scoped_refptr<PrintQueriesQueue> queue,
bool want_pdf_settings,
@@ -91,9 +107,11 @@ void OnDidGetDefaultPrintSettings(
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (printer_query->last_status() != mojom::ResultCode::kSuccess) {
+#if 0 // Electron does not use Chrome error dialogs
if (!want_pdf_settings) {
ShowPrintErrorDialogForInvalidPrinterError();
}
+#endif
std::move(callback).Run(nullptr);
return;
}
@@ -103,9 +121,11 @@ void OnDidGetDefaultPrintSettings(
params->document_cookie = printer_query->cookie();
if (!PrintMsgPrintParamsIsValid(*params)) {
+#if 0 // Electron does not use Chrome error dialogs
if (!want_pdf_settings) {
ShowPrintErrorDialogForInvalidPrinterError();
}
+#endif
std::move(callback).Run(nullptr);
return;
}
@@ -122,7 +142,8 @@ void OnDidScriptedPrint(
if (printer_query->last_status() != mojom::ResultCode::kSuccess ||
!printer_query->settings().dpi()) {
- std::move(callback).Run(nullptr);
+ bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled;
+ std::move(callback).Run(nullptr, canceled);
return;
}
@@ -132,12 +153,12 @@ void OnDidScriptedPrint(
params->params.get());
params->params->document_cookie = printer_query->cookie();
if (!PrintMsgPrintParamsIsValid(*params->params)) {
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
params->pages = printer_query->settings().ranges();
- std::move(callback).Run(std::move(params));
+ std::move(callback).Run(std::move(params), false);
queue->QueuePrinterQuery(std::move(printer_query));
}
@@ -174,9 +195,11 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents)
: PrintManager(web_contents),
queue_(g_browser_process->print_job_manager()->queue()) {
DCHECK(queue_);
+#if 0 // Printing is always enabled.
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
- printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs());
+ printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs());
+#endif
}
PrintViewManagerBase::~PrintViewManagerBase() {
@@ -199,7 +222,10 @@ void PrintViewManagerBase::DisableThirdPartyBlocking() {
}
#endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
-bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) {
+bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh,
+ bool silent,
+ base::Value::Dict settings,
+ CompletionCallback callback) {
// Remember the ID for `rfh`, to enable checking that the `RenderFrameHost`
// is still valid after a possible inner message loop runs in
// `DisconnectFromCurrentPrintJob()`.
@@ -227,7 +253,12 @@ bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) {
#endif
SetPrintingRFH(rfh);
+#if 0
CompletePrintNow(rfh);
+#endif
+ callback_ = std::move(callback);
+
+ GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings));
return true;
}
@@ -451,7 +482,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply(
void PrintViewManagerBase::ScriptedPrintReply(
ScriptedPrintCallback callback,
int process_id,
- mojom::PrintPagesParamsPtr params) {
+ mojom::PrintPagesParamsPtr params,
+ bool canceled) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
#if BUILDFLAG(ENABLE_OOP_PRINTING)
@@ -466,12 +498,15 @@ void PrintViewManagerBase::ScriptedPrintReply(
return;
}
+ if (canceled)
+ UserInitCanceled();
+
if (params) {
set_cookie(params->params->document_cookie);
- std::move(callback).Run(std::move(params));
+ std::move(callback).Run(std::move(params), canceled);
} else {
set_cookie(0);
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
}
}
@@ -608,10 +643,12 @@ void PrintViewManagerBase::DidPrintDocument(
void PrintViewManagerBase::GetDefaultPrintSettings(
GetDefaultPrintSettingsCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+#if 0 // Printing is always enabled.
if (!printing_enabled_.GetValue()) {
GetDefaultPrintSettingsReply(std::move(callback), nullptr);
return;
}
+#endif
#if BUILDFLAG(ENABLE_OOP_PRINTING)
if (printing::features::kEnableOopPrintDriversJobPrint.Get() &&
#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
@@ -662,10 +699,12 @@ void PrintViewManagerBase::UpdatePrintSettings(
base::Value::Dict job_settings,
UpdatePrintSettingsCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+#if 0 // Printing is always enabled.
if (!printing_enabled_.GetValue()) {
std::move(callback).Run(nullptr);
return;
}
+#endif // Printing is always enabled.
absl::optional<int> printer_type_value =
job_settings.FindInt(kSettingPrinterType);
@@ -676,6 +715,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
mojom::PrinterType printer_type =
static_cast<mojom::PrinterType>(*printer_type_value);
+#if 0 // Printing is always enabled.
if (printer_type != mojom::PrinterType::kExtension &&
printer_type != mojom::PrinterType::kPdf &&
printer_type != mojom::PrinterType::kLocal) {
@@ -695,6 +735,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
if (value > 0)
job_settings.Set(kSettingRasterizePdfDpi, value);
}
+#endif // Printing is always enabled.
std::unique_ptr<PrintSettings> print_settings =
PrintSettingsFromJobSettings(job_settings);
@@ -744,7 +785,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
void PrintViewManagerBase::IsPrintingEnabled(
IsPrintingEnabledCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- std::move(callback).Run(printing_enabled_.GetValue());
+ std::move(callback).Run(true);
}
void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
@@ -760,14 +801,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
// didn't happen for some reason.
bad_message::ReceivedBadMessage(
render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME);
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
#if BUILDFLAG(ENABLE_OOP_PRINTING)
if (printing::features::kEnableOopPrintDriversJobPrint.Get() &&
!query_with_ui_client_id_.has_value()) {
// Renderer process has requested settings outside of the expected setup.
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
#endif
@@ -802,6 +843,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
PrintManager::PrintingFailed(cookie, reason);
+#if 0 // Electron does not use Chromium error dialogs
// `PrintingFailed()` can occur because asynchronous compositing results
// don't complete until after a print job has already failed and been
// destroyed. In such cases the error notification to the user will
@@ -811,7 +853,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
print_job_->document()->cookie() == cookie) {
ShowPrintErrorDialogForGenericError();
}
-
+#endif
ReleasePrinterQuery();
}
@@ -823,15 +865,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) {
test_observers_.RemoveObserver(&observer);
}
+void PrintViewManagerBase::ShowInvalidPrinterSettingsError() {
+ if (!callback_.is_null()) {
+ printing_status_ = PrintStatus::kInvalid;
+ TerminatePrintJob(true);
+ }
+}
+
void PrintViewManagerBase::RenderFrameHostStateChanged(
content::RenderFrameHost* render_frame_host,
content::RenderFrameHost::LifecycleState /*old_state*/,
content::RenderFrameHost::LifecycleState new_state) {
+#if 0
if (new_state == content::RenderFrameHost::LifecycleState::kActive &&
render_frame_host->GetProcess()->IsPdf() &&
!render_frame_host->GetMainFrame()->GetParentOrOuterDocument()) {
GetPrintRenderFrame(render_frame_host)->ConnectToPdfRenderer();
}
+#endif
}
void PrintViewManagerBase::RenderFrameDeleted(
@@ -883,7 +934,12 @@ void PrintViewManagerBase::OnJobDone() {
// Printing is done, we don't need it anymore.
// print_job_->is_job_pending() may still be true, depending on the order
// of object registration.
- printing_succeeded_ = true;
+ printing_status_ = PrintStatus::kSucceeded;
+ ReleasePrintJob();
+}
+
+void PrintViewManagerBase::UserInitCanceled() {
+ printing_status_ = PrintStatus::kCanceled;
ReleasePrintJob();
}
@@ -892,9 +948,10 @@ void PrintViewManagerBase::OnCanceling() {
}
void PrintViewManagerBase::OnFailed() {
+#if 0 // Electron does not use Chromium error dialogs
if (!canceling_job_)
ShowPrintErrorDialogForGenericError();
-
+#endif
TerminatePrintJob(true);
}
@@ -904,7 +961,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() {
// Is the document already complete?
if (print_job_->document() && print_job_->document()->IsComplete()) {
- printing_succeeded_ = true;
+ printing_status_ = PrintStatus::kSucceeded;
return true;
}
@@ -952,7 +1009,10 @@ bool PrintViewManagerBase::CreateNewPrintJob(
// Disconnect the current `print_job_`.
auto weak_this = weak_ptr_factory_.GetWeakPtr();
- DisconnectFromCurrentPrintJob();
+ if (callback_.is_null()) {
+ // Disconnect the current |print_job_| only when calling window.print()
+ DisconnectFromCurrentPrintJob();
+ }
if (!weak_this)
return false;
@@ -973,7 +1033,7 @@ bool PrintViewManagerBase::CreateNewPrintJob(
#endif
print_job_->AddObserver(*this);
- printing_succeeded_ = false;
+ printing_status_ = PrintStatus::kFailed;
return true;
}
@@ -1041,6 +1101,11 @@ void PrintViewManagerBase::ReleasePrintJob() {
}
#endif
+ if (!callback_.is_null()) {
+ bool success = printing_status_ == PrintStatus::kSucceeded;
+ std::move(callback_).Run(success, PrintReasonFromPrintStatus(printing_status_));
+ }
+
if (!print_job_)
return;
@@ -1048,7 +1113,7 @@ void PrintViewManagerBase::ReleasePrintJob() {
// printing_rfh_ should only ever point to a RenderFrameHost with a live
// RenderFrame.
DCHECK(rfh->IsRenderFrameLive());
- GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_);
+ GetPrintRenderFrame(rfh)->PrintingDone(printing_status_ == PrintStatus::kSucceeded);
}
print_job_->RemoveObserver(*this);
@@ -1090,7 +1155,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() {
}
bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) {
- if (print_job_)
+ if (print_job_ && print_job_->document())
return true;
if (!cookie) {
@@ -1199,7 +1264,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
}
void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) {
- GetPrintRenderFrame(rfh)->PrintRequestedPages();
+ GetPrintRenderFrame(rfh)->PrintRequestedPages(/*silent=*/true, /*job_settings=*/base::Value::Dict());
for (auto& observer : GetTestObservers()) {
observer.OnPrintNow(rfh);
@@ -1249,7 +1314,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis(
set_analyzing_content(/*analyzing*/ false);
if (!allowed || !printing_rfh_ || IsCrashed() ||
!printing_rfh_->IsRenderFrameLive()) {
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
CompleteScriptedPrint(printing_rfh_, std::move(params), std::move(callback));
diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h
index 8af22e511701a595b77bea31da096caedc2e47ce..d1e3bc5ea012de1f1155546ef66c5e3e1c6b11de 100644
--- a/chrome/browser/printing/print_view_manager_base.h
+++ b/chrome/browser/printing/print_view_manager_base.h
@@ -47,6 +47,8 @@ namespace printing {
class PrintQueriesQueue;
class PrinterQuery;
+using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>;
+
// Base class for managing the print commands for a WebContents.
class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
public:
@@ -80,7 +82,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// Prints the current document immediately. Since the rendering is
// asynchronous, the actual printing will not be completed on the return of
// this function. Returns false if printing is impossible at the moment.
- virtual bool PrintNow(content::RenderFrameHost* rfh);
+ virtual bool PrintNow(content::RenderFrameHost* rfh,
+ bool silent = true,
+ base::Value::Dict settings = {},
+ CompletionCallback callback = {});
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
// Prints the document in `print_data` with settings specified in
@@ -132,8 +137,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
void IsPrintingEnabled(IsPrintingEnabledCallback callback) override;
void ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
ScriptedPrintCallback callback) override;
+ void ShowInvalidPrinterSettingsError() override;
void PrintingFailed(int32_t cookie,
mojom::PrintFailureReason reason) override;
+ void UserInitCanceled();
// Adds and removes observers for `PrintViewManagerBase` events. The order in
// which notifications are sent to observers is undefined. Observers must be
@@ -141,6 +148,14 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
void AddTestObserver(TestObserver& observer);
void RemoveTestObserver(TestObserver& observer);
+ enum class PrintStatus {
+ kSucceeded,
+ kCanceled,
+ kFailed,
+ kInvalid,
+ kUnknown
+ };
+
protected:
explicit PrintViewManagerBase(content::WebContents* web_contents);
@@ -293,7 +308,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// Runs `callback` with `params` to reply to ScriptedPrint().
void ScriptedPrintReply(ScriptedPrintCallback callback,
int process_id,
- mojom::PrintPagesParamsPtr params);
+ mojom::PrintPagesParamsPtr params,
+ bool canceled);
// Requests the RenderView to render all the missing pages for the print job.
// No-op if no print job is pending. Returns true if at least one page has
@@ -363,8 +379,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// The current RFH that is printing with a system printing dialog.
raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr;
+ // Respond with success of the print job.
+ CompletionCallback callback_;
+
// Indication of success of the print job.
- bool printing_succeeded_ = false;
+ PrintStatus printing_status_ = PrintStatus::kUnknown;
// Indication that the job is getting canceled.
bool canceling_job_ = false;
diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc
index 0b6ff160cc0537d4e75ecfdc3ab3fc881888bbc9..8ca904943942de2d5ff4b194976e606a60ced16c 100644
--- a/chrome/browser/printing/printer_query.cc
+++ b/chrome/browser/printing/printer_query.cc
@@ -355,17 +355,19 @@ void PrinterQuery::UpdatePrintSettings(base::Value::Dict new_settings,
#endif // BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS)
}
- mojom::ResultCode result;
{
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
base::ScopedAllowBlocking allow_blocking;
#endif
- result = printing_context_->UpdatePrintSettings(std::move(new_settings));
+ // Reset settings from previous print job
+ printing_context_->ResetSettings();
+ mojom::ResultCode result_code = printing_context_->UseDefaultSettings();
+ if (result_code == mojom::ResultCode::kSuccess)
+ result_code = printing_context_->UpdatePrintSettings(std::move(new_settings));
+ InvokeSettingsCallback(std::move(callback), result_code);
}
-
- InvokeSettingsCallback(std::move(callback), result);
}
#if BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
index e83cf407beebcec5ccf7eaa991f43d4d3713833b..5e770a6a840b48e07ff056fe038aad54e526429e 100644
--- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
+++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
@@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame(
FakePrintRenderFrame::~FakePrintRenderFrame() = default;
-void FakePrintRenderFrame::PrintRequestedPages() {}
+void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value::Dict /*settings*/) {}
void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params,
PrintWithParamsCallback callback) {
diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
index 32403bb077dcbbffe6a3a862feff619e980c5f93..af773c93ab969a5dc483cc63384851ff62cf51ec 100644
--- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
+++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
@@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame {
private:
// printing::mojom::PrintRenderFrame:
- void PrintRequestedPages() override;
+ void PrintRequestedPages(bool silent, ::base::Value::Dict settings) override;
void PrintWithParams(mojom::PrintPagesParamsPtr params,
PrintWithParamsCallback callback) override;
void PrintForSystemDialog() override;
diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc
index 21c81377d32ae8d4185598a7eba88ed1d2063ef0..0767f4e9369e926b1cea99178c1a1975941f1765 100644
--- a/components/printing/browser/print_manager.cc
+++ b/components/printing/browser/print_manager.cc
@@ -47,6 +47,8 @@ void PrintManager::IsPrintingEnabled(IsPrintingEnabledCallback callback) {
std::move(callback).Run(true);
}
+void PrintManager::ShowInvalidPrinterSettingsError() {}
+
void PrintManager::PrintingFailed(int32_t cookie,
mojom::PrintFailureReason reason) {
// Note: Not redundant with cookie checks in the same method in other parts of
diff --git a/components/printing/browser/print_manager.h b/components/printing/browser/print_manager.h
index ca71560874a0189068dd11fbc039f5673bf6bd96..a8551d95e64da2afbc1685b2df8f1fc377c7117b 100644
--- a/components/printing/browser/print_manager.h
+++ b/components/printing/browser/print_manager.h
@@ -48,6 +48,7 @@ class PrintManager : public content::WebContentsObserver,
DidPrintDocumentCallback callback) override;
void IsPrintingEnabled(IsPrintingEnabledCallback callback) override;
void DidShowPrintDialog() override;
+ void ShowInvalidPrinterSettingsError() override;
void PrintingFailed(int32_t cookie,
mojom::PrintFailureReason reason) override;
diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom
index cd0f1c1d118cafc4ce12faeb531c38dc12153632..095130068f245dbbc3b7b536892eff9f10456e8c 100644
--- a/components/printing/common/print.mojom
+++ b/components/printing/common/print.mojom
@@ -296,7 +296,7 @@ union PrintWithParamsResult {
interface PrintRenderFrame {
// Tells the RenderFrame to switch the CSS to print media type, render every
// requested page, and then switch back the CSS to display media type.
- PrintRequestedPages();
+ PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings);
// Requests the frame to be printed with specified parameters. This is used
// to programmatically produce PDF by request from the browser (e.g. over
@@ -390,7 +390,10 @@ interface PrintManagerHost {
// UI to the user to select the final print settings. If the user cancels or
// an error occurs, return null.
[Sync]
- ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings);
+ ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings, bool canceled);
+
+ // Tells the browser that there are invalid printer settings.
+ ShowInvalidPrinterSettingsError();
// Tells the browser printing failed.
PrintingFailed(int32 cookie, PrintFailureReason reason);
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc
index 4c31c8a926f89ed10fce2ce497c249f0707db9e5..0e4913a5d99aee139014467e848003be16261587 100644
--- a/components/printing/renderer/print_render_frame_helper.cc
+++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -45,6 +45,7 @@
#include "printing/mojom/print.mojom.h"
#include "printing/page_number.h"
#include "printing/print_job_constants.h"
+#include "printing/print_settings.h"
#include "printing/units.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
@@ -1345,7 +1346,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) {
if (!weak_this)
return;
- Print(web_frame, blink::WebNode(), PrintRequestType::kScripted);
+ Print(web_frame, blink::WebNode(), PrintRequestType::kScripted,
+ false /* silent */, base::Value::Dict() /* new_settings */);
if (!weak_this)
return;
@@ -1376,7 +1378,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver(
receivers_.Add(this, std::move(receiver));
}
-void PrintRenderFrameHelper::PrintRequestedPages() {
+void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value::Dict settings) {
ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr());
if (ipc_nesting_level_ > kAllowedIpcDepthForPrint)
return;
@@ -1391,7 +1393,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() {
// plugin node and print that instead.
auto plugin = delegate_->GetPdfElement(frame);
- Print(frame, plugin, PrintRequestType::kRegular);
+ Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings));
if (!render_frame_gone_)
frame->DispatchAfterPrintEvent();
@@ -1470,7 +1472,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() {
}
Print(frame, print_preview_context_.source_node(),
- PrintRequestType::kRegular);
+ PrintRequestType::kRegular, false,
+ base::Value::Dict());
if (!render_frame_gone_)
print_preview_context_.DispatchAfterPrintEvent();
// WARNING: |this| may be gone at this point. Do not do any more work here and
@@ -1521,6 +1524,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value::Dict settings) {
if (ipc_nesting_level_ > kAllowedIpcDepthForPrint)
return;
+ blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
+ print_preview_context_.InitWithFrame(frame);
print_preview_context_.OnPrintPreview();
#if BUILDFLAG(IS_CHROMEOS_ASH)
@@ -2142,7 +2147,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) {
return;
Print(duplicate_node.GetDocument().GetFrame(), duplicate_node,
- PrintRequestType::kRegular);
+ PrintRequestType::kRegular, false /* silent */,
+ base::Value::Dict() /* new_settings */);
// Check if |this| is still valid.
if (!weak_this)
return;
@@ -2157,7 +2163,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) {
void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame,
const blink::WebNode& node,
- PrintRequestType print_request_type) {
+ PrintRequestType print_request_type,
+ bool silent,
+ base::Value::Dict settings) {
// If still not finished with earlier print request simply ignore.
if (prep_frame_view_)
return;
@@ -2165,7 +2173,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame,
FrameReference frame_ref(frame);
uint32_t expected_page_count = 0;
- if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
+ if (!CalculateNumberOfPages(frame, node, &expected_page_count, std::move(settings))) {
DidFinishPrinting(FAIL_PRINT_INIT);
return; // Failed to init print page settings.
}
@@ -2184,8 +2192,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame,
print_pages_params_->params->print_scaling_option;
auto self = weak_ptr_factory_.GetWeakPtr();
- mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser(
+ mojom::PrintPagesParamsPtr print_settings;
+
+ if (silent) {
+ print_settings = mojom::PrintPagesParams::New();
+ print_settings->params = print_pages_params_->params->Clone();
+ } else {
+ print_settings = GetPrintSettingsFromUser(
frame_ref.GetFrame(), node, expected_page_count, print_request_type);
+ }
// Check if |this| is still valid.
if (!self)
return;
@@ -2418,35 +2433,47 @@ void PrintRenderFrameHelper::IPCProcessed() {
}
}
-bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) {
+bool PrintRenderFrameHelper::InitPrintSettings(
+ bool fit_to_paper_size,
+ base::Value::Dict new_settings) {
// Reset to default values.
ignore_css_margins_ = false;
- mojom::PrintPagesParams settings;
- GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params);
+ mojom::PrintPagesParamsPtr settings;
+ if (new_settings.empty()) {
+ settings = mojom::PrintPagesParams::New();
+ settings->params = mojom::PrintParams::New();
+ GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params);
+ } else {
+ GetPrintManagerHost()->UpdatePrintSettings(
+ std::move(new_settings), &settings);
+ }
// Check if the printer returned any settings, if the settings are null,
// assume there are no printer drivers configured. So safely terminate.
- if (!settings.params) {
+ if (!settings || !settings->params) {
// Caller will reset `print_pages_params_`.
return false;
}
- settings.params->print_scaling_option =
+ settings->params->print_scaling_option =
fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea
: mojom::PrintScalingOption::kSourceSize;
- SetPrintPagesParams(settings);
+ SetPrintPagesParams(*settings);
return true;
}
-bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame,
- const blink::WebNode& node,
- uint32_t* number_of_pages) {
+bool PrintRenderFrameHelper::CalculateNumberOfPages(
+ blink::WebLocalFrame* frame,
+ const blink::WebNode& node,
+ uint32_t* number_of_pages,
+ base::Value::Dict settings) {
DCHECK(frame);
bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node);
- if (!InitPrintSettings(fit_to_paper_size)) {
+ if (!InitPrintSettings(fit_to_paper_size, std::move(settings))) {
// Browser triggered this code path. It already knows about the failure.
notify_browser_of_print_failure_ = false;
+ GetPrintManagerHost()->ShowInvalidPrinterSettingsError();
return false;
}
@@ -2550,7 +2577,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser(
std::move(params),
base::BindOnce(
[](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output,
- mojom::PrintPagesParamsPtr input) {
+ mojom::PrintPagesParamsPtr input, bool canceled) {
*output = std::move(input);
std::move(quit_closure).Run();
},
diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h
index d971e446859507456da153a9d59f3ed4857b66cb..9ab75731a941e7065dfaa481508cfa47dbcf7d0b 100644
--- a/components/printing/renderer/print_render_frame_helper.h
+++ b/components/printing/renderer/print_render_frame_helper.h
@@ -245,7 +245,7 @@ class PrintRenderFrameHelper
mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver);
// printing::mojom::PrintRenderFrame:
- void PrintRequestedPages() override;
+ void PrintRequestedPages(bool silent, base::Value::Dict settings) override;
void PrintWithParams(mojom::PrintPagesParamsPtr params,
PrintWithParamsCallback callback) override;
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
@@ -322,7 +322,9 @@ class PrintRenderFrameHelper
// WARNING: |this| may be gone after this method returns.
void Print(blink::WebLocalFrame* frame,
const blink::WebNode& node,
- PrintRequestType print_request_type);
+ PrintRequestType print_request_type,
+ bool silent,
+ base::Value::Dict settings);
// Notification when printing is done - signal tear-down/free resources.
void DidFinishPrinting(PrintingResult result);
@@ -331,12 +333,14 @@ class PrintRenderFrameHelper
// Initialize print page settings with default settings.
// Used only for native printing workflow.
- bool InitPrintSettings(bool fit_to_paper_size);
+ bool InitPrintSettings(bool fit_to_paper_size,
+ base::Value::Dict new_settings);
// Calculate number of pages in source document.
bool CalculateNumberOfPages(blink::WebLocalFrame* frame,
const blink::WebNode& node,
- uint32_t* number_of_pages);
+ uint32_t* number_of_pages,
+ base::Value::Dict settings);
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
// Set options for print preset from source PDF document.
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn
index cc47fb1a2a3d6a6fe15448ebdba25c29b4b88aa0..e6125b6af20434f3ec3171c044d515b8c120a7b5 100644
--- a/content/browser/BUILD.gn
+++ b/content/browser/BUILD.gn
@@ -2901,8 +2901,9 @@ source_set("browser") {
"//ppapi/shared_impl",
]
- assert(enable_printing)
- deps += [ "//printing" ]
+ if (enable_printing) {
+ deps += [ "//printing" ]
+ }
if (is_chromeos) {
sources += [
diff --git a/printing/printing_context.cc b/printing/printing_context.cc
index 370dedfb4b4649f85a02b3a50ee16f525f57f44a..256666b64d8ffb5b50c9424c40ae1bb4050da6fb 100644
--- a/printing/printing_context.cc
+++ b/printing/printing_context.cc
@@ -143,7 +143,6 @@ void PrintingContext::UsePdfSettings() {
mojom::ResultCode PrintingContext::UpdatePrintSettings(
base::Value::Dict job_settings) {
- ResetSettings();
{
std::unique_ptr<PrintSettings> settings =
PrintSettingsFromJobSettings(job_settings);
diff --git a/printing/printing_context.h b/printing/printing_context.h
index 2fb3aef0797f204f08c20e48987cd8c2703185de..75a70e331f8b539027748dad3252912cb85e8797 100644
--- a/printing/printing_context.h
+++ b/printing/printing_context.h
@@ -178,6 +178,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext {
bool PrintingAborted() const { return abort_printing_; }
+ // Reinitializes the settings for object reuse.
+ void ResetSettings();
+
int job_id() const { return job_id_; }
protected:
@@ -188,9 +191,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext {
static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate,
bool skip_system_calls);
- // Reinitializes the settings for object reuse.
- void ResetSettings();
-
// Determine if system calls should be skipped by this instance.
bool skip_system_calls() const {
#if BUILDFLAG(ENABLE_OOP_PRINTING)
diff --git a/sandbox/policy/mac/sandbox_mac.mm b/sandbox/policy/mac/sandbox_mac.mm
index cc0e9b58d2686c45f8471eccdde7d9c5b03b4cae..d0ad07b3205aa7e9dcb8cc6217426a1bde22a15f 100644
--- a/sandbox/policy/mac/sandbox_mac.mm
+++ b/sandbox/policy/mac/sandbox_mac.mm
@@ -41,6 +41,10 @@
#error "This file requires ARC support."
#endif
+#if BUILDFLAG(ENABLE_PRINTING)
+#include "sandbox/policy/mac/print_backend.sb.h"
+#endif
+
namespace sandbox::policy {
base::FilePath GetCanonicalPath(const base::FilePath& path) {
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,996 |
[Bug]: Errors about silent printing
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue 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.17
### What operating system are you using?
Windows
### Operating System Version
Windows 10 Pro 21H2
### What arch are you using?
x64
### Last Known Working Electron version
18.3.15
### Expected Behavior
I want to use contents.print ({silent: true}) to execute the print task only once
### Actual Behavior
Use contents.Print({silent: true}) will be executed twice.
Use the following code to monitor the actual printing times.
```js
window. onbeforeprint = (event) => {
console. log('before print');
};
window. onafterprint = (event) => {
console. log('After print');
};
```
This phenomenon will appear in 19 and later versions.
### Testcase Gist URL
https://gist.github.com/feddc9ddf37da270efc034d6ff6431b9
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/35996
|
https://github.com/electron/electron/pull/38741
|
d78f37ec8faae9a3677037e1b40baea81fc93b6c
|
46fb0d8f5f3a33c5b9bba2329ac5de946cd66a3c
| 2022-10-12T04:43:34Z |
c++
| 2023-06-15T14:46:38Z |
patches/chromium/printing.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Shelley Vohr <[email protected]>
Date: Fri, 7 Jun 2019 13:59:37 -0700
Subject: printing.patch
Add changeset that was previously applied to sources in chromium_src. The
majority of changes originally come from these PRs:
* https://github.com/electron/electron/pull/1835
* https://github.com/electron/electron/pull/8596
This patch also fixes callback for manual user cancellation and success.
diff --git a/BUILD.gn b/BUILD.gn
index b8b5fddffbff56a83c6315b6d1aad2ad8fad0276..c4aed9336a783f4af3205b359eb5f09a8446e512 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -968,7 +968,6 @@ if (is_win) {
"//media:media_unittests",
"//media/midi:midi_unittests",
"//net:net_unittests",
- "//printing:printing_unittests",
"//sql:sql_unittests",
"//third_party/breakpad:symupload($host_toolchain)",
"//ui/base:ui_base_unittests",
@@ -977,6 +976,10 @@ if (is_win) {
"//ui/views:views_unittests",
"//url:url_unittests",
]
+
+ if (enable_printing) {
+ deps += [ "//printing:printing_unittests" ]
+ }
}
}
diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc
index 3a66a52b8d3c6da9cd8d7e9afdc8d59f528ec3d5..facaa6fbca8ee7c04f83607e62b81b9594727ada 100644
--- a/chrome/browser/printing/print_job.cc
+++ b/chrome/browser/printing/print_job.cc
@@ -93,6 +93,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) {
return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization);
}
+#if 0
PrefService* GetPrefsForWebContents(content::WebContents* web_contents) {
// TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely
// because `web_contents` was null. As a result, this section has many more
@@ -107,6 +108,7 @@ content::WebContents* GetWebContents(content::GlobalRenderFrameHostId rfh_id) {
auto* rfh = content::RenderFrameHost::FromID(rfh_id);
return rfh ? content::WebContents::FromRenderFrameHost(rfh) : nullptr;
}
+#endif
#endif // BUILDFLAG(IS_WIN)
@@ -147,10 +149,8 @@ void PrintJob::Initialize(std::unique_ptr<PrinterQuery> query,
#if BUILDFLAG(IS_WIN)
pdf_page_mapping_ = PageNumber::GetPages(settings->ranges(), page_count);
- PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_));
- if (prefs && prefs->IsManagedPreference(prefs::kPdfUseSkiaRendererEnabled)) {
- use_skia_ = prefs->GetBoolean(prefs::kPdfUseSkiaRendererEnabled);
- }
+ // TODO(codebytere): should we enable this later?
+ use_skia_ = false;
#endif
auto new_doc = base::MakeRefCounted<PrintedDocument>(std::move(settings),
@@ -374,8 +374,10 @@ void PrintJob::StartPdfToEmfConversion(
const PrintSettings& settings = document()->settings();
+#if 0
PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_));
- bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs);
+#endif
+ bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr);
using RenderMode = PdfRenderSettings::Mode;
RenderMode mode = print_with_reduced_rasterization
@@ -465,8 +467,10 @@ void PrintJob::StartPdfToPostScriptConversion(
if (ps_level2) {
mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2;
} else {
+#if 0
PrefService* prefs = GetPrefsForWebContents(GetWebContents(rfh_id_));
- mode = PrintWithPostScriptType42Fonts(prefs)
+#endif
+ mode = PrintWithPostScriptType42Fonts(nullptr)
? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS
: PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3;
}
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc
index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffdd4ff2077 100644
--- a/chrome/browser/printing/print_view_manager_base.cc
+++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -23,7 +23,9 @@
#include "chrome/browser/bad_message.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
+#if 0 // Electron does not use Chrome error dialogs
#include "chrome/browser/printing/print_error_dialog.h"
+#endif
#include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/print_view_manager_common.h"
@@ -83,6 +85,20 @@ namespace printing {
namespace {
+std::string PrintReasonFromPrintStatus(PrintViewManager::PrintStatus status) {
+ if (status == PrintViewManager::PrintStatus::kInvalid) {
+ return "Invalid printer settings";
+ } else if (status == PrintViewManager::PrintStatus::kCanceled) {
+ return "Print job canceled";
+ } else if (status == PrintViewManager::PrintStatus::kFailed) {
+ return "Print job failed";
+ }
+ return "";
+}
+
+using PrintSettingsCallback =
+ base::OnceCallback<void(std::unique_ptr<PrinterQuery>)>;
+
void OnDidGetDefaultPrintSettings(
scoped_refptr<PrintQueriesQueue> queue,
bool want_pdf_settings,
@@ -91,9 +107,11 @@ void OnDidGetDefaultPrintSettings(
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (printer_query->last_status() != mojom::ResultCode::kSuccess) {
+#if 0 // Electron does not use Chrome error dialogs
if (!want_pdf_settings) {
ShowPrintErrorDialogForInvalidPrinterError();
}
+#endif
std::move(callback).Run(nullptr);
return;
}
@@ -103,9 +121,11 @@ void OnDidGetDefaultPrintSettings(
params->document_cookie = printer_query->cookie();
if (!PrintMsgPrintParamsIsValid(*params)) {
+#if 0 // Electron does not use Chrome error dialogs
if (!want_pdf_settings) {
ShowPrintErrorDialogForInvalidPrinterError();
}
+#endif
std::move(callback).Run(nullptr);
return;
}
@@ -122,7 +142,8 @@ void OnDidScriptedPrint(
if (printer_query->last_status() != mojom::ResultCode::kSuccess ||
!printer_query->settings().dpi()) {
- std::move(callback).Run(nullptr);
+ bool canceled = printer_query->last_status() == mojom::ResultCode::kCanceled;
+ std::move(callback).Run(nullptr, canceled);
return;
}
@@ -132,12 +153,12 @@ void OnDidScriptedPrint(
params->params.get());
params->params->document_cookie = printer_query->cookie();
if (!PrintMsgPrintParamsIsValid(*params->params)) {
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
params->pages = printer_query->settings().ranges();
- std::move(callback).Run(std::move(params));
+ std::move(callback).Run(std::move(params), false);
queue->QueuePrinterQuery(std::move(printer_query));
}
@@ -174,9 +195,11 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents)
: PrintManager(web_contents),
queue_(g_browser_process->print_job_manager()->queue()) {
DCHECK(queue_);
+#if 0 // Printing is always enabled.
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
- printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs());
+ printing_enabled_.Init(prefs::kPrintingEnabled, profile->GetPrefs());
+#endif
}
PrintViewManagerBase::~PrintViewManagerBase() {
@@ -199,7 +222,10 @@ void PrintViewManagerBase::DisableThirdPartyBlocking() {
}
#endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
-bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) {
+bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh,
+ bool silent,
+ base::Value::Dict settings,
+ CompletionCallback callback) {
// Remember the ID for `rfh`, to enable checking that the `RenderFrameHost`
// is still valid after a possible inner message loop runs in
// `DisconnectFromCurrentPrintJob()`.
@@ -227,7 +253,12 @@ bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) {
#endif
SetPrintingRFH(rfh);
+#if 0
CompletePrintNow(rfh);
+#endif
+ callback_ = std::move(callback);
+
+ GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings));
return true;
}
@@ -451,7 +482,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply(
void PrintViewManagerBase::ScriptedPrintReply(
ScriptedPrintCallback callback,
int process_id,
- mojom::PrintPagesParamsPtr params) {
+ mojom::PrintPagesParamsPtr params,
+ bool canceled) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
#if BUILDFLAG(ENABLE_OOP_PRINTING)
@@ -466,12 +498,15 @@ void PrintViewManagerBase::ScriptedPrintReply(
return;
}
+ if (canceled)
+ UserInitCanceled();
+
if (params) {
set_cookie(params->params->document_cookie);
- std::move(callback).Run(std::move(params));
+ std::move(callback).Run(std::move(params), canceled);
} else {
set_cookie(0);
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
}
}
@@ -608,10 +643,12 @@ void PrintViewManagerBase::DidPrintDocument(
void PrintViewManagerBase::GetDefaultPrintSettings(
GetDefaultPrintSettingsCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+#if 0 // Printing is always enabled.
if (!printing_enabled_.GetValue()) {
GetDefaultPrintSettingsReply(std::move(callback), nullptr);
return;
}
+#endif
#if BUILDFLAG(ENABLE_OOP_PRINTING)
if (printing::features::kEnableOopPrintDriversJobPrint.Get() &&
#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
@@ -662,10 +699,12 @@ void PrintViewManagerBase::UpdatePrintSettings(
base::Value::Dict job_settings,
UpdatePrintSettingsCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+#if 0 // Printing is always enabled.
if (!printing_enabled_.GetValue()) {
std::move(callback).Run(nullptr);
return;
}
+#endif // Printing is always enabled.
absl::optional<int> printer_type_value =
job_settings.FindInt(kSettingPrinterType);
@@ -676,6 +715,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
mojom::PrinterType printer_type =
static_cast<mojom::PrinterType>(*printer_type_value);
+#if 0 // Printing is always enabled.
if (printer_type != mojom::PrinterType::kExtension &&
printer_type != mojom::PrinterType::kPdf &&
printer_type != mojom::PrinterType::kLocal) {
@@ -695,6 +735,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
if (value > 0)
job_settings.Set(kSettingRasterizePdfDpi, value);
}
+#endif // Printing is always enabled.
std::unique_ptr<PrintSettings> print_settings =
PrintSettingsFromJobSettings(job_settings);
@@ -744,7 +785,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
void PrintViewManagerBase::IsPrintingEnabled(
IsPrintingEnabledCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
- std::move(callback).Run(printing_enabled_.GetValue());
+ std::move(callback).Run(true);
}
void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
@@ -760,14 +801,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
// didn't happen for some reason.
bad_message::ReceivedBadMessage(
render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME);
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
#if BUILDFLAG(ENABLE_OOP_PRINTING)
if (printing::features::kEnableOopPrintDriversJobPrint.Get() &&
!query_with_ui_client_id_.has_value()) {
// Renderer process has requested settings outside of the expected setup.
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
#endif
@@ -802,6 +843,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
PrintManager::PrintingFailed(cookie, reason);
+#if 0 // Electron does not use Chromium error dialogs
// `PrintingFailed()` can occur because asynchronous compositing results
// don't complete until after a print job has already failed and been
// destroyed. In such cases the error notification to the user will
@@ -811,7 +853,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
print_job_->document()->cookie() == cookie) {
ShowPrintErrorDialogForGenericError();
}
-
+#endif
ReleasePrinterQuery();
}
@@ -823,15 +865,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) {
test_observers_.RemoveObserver(&observer);
}
+void PrintViewManagerBase::ShowInvalidPrinterSettingsError() {
+ if (!callback_.is_null()) {
+ printing_status_ = PrintStatus::kInvalid;
+ TerminatePrintJob(true);
+ }
+}
+
void PrintViewManagerBase::RenderFrameHostStateChanged(
content::RenderFrameHost* render_frame_host,
content::RenderFrameHost::LifecycleState /*old_state*/,
content::RenderFrameHost::LifecycleState new_state) {
+#if 0
if (new_state == content::RenderFrameHost::LifecycleState::kActive &&
render_frame_host->GetProcess()->IsPdf() &&
!render_frame_host->GetMainFrame()->GetParentOrOuterDocument()) {
GetPrintRenderFrame(render_frame_host)->ConnectToPdfRenderer();
}
+#endif
}
void PrintViewManagerBase::RenderFrameDeleted(
@@ -883,7 +934,12 @@ void PrintViewManagerBase::OnJobDone() {
// Printing is done, we don't need it anymore.
// print_job_->is_job_pending() may still be true, depending on the order
// of object registration.
- printing_succeeded_ = true;
+ printing_status_ = PrintStatus::kSucceeded;
+ ReleasePrintJob();
+}
+
+void PrintViewManagerBase::UserInitCanceled() {
+ printing_status_ = PrintStatus::kCanceled;
ReleasePrintJob();
}
@@ -892,9 +948,10 @@ void PrintViewManagerBase::OnCanceling() {
}
void PrintViewManagerBase::OnFailed() {
+#if 0 // Electron does not use Chromium error dialogs
if (!canceling_job_)
ShowPrintErrorDialogForGenericError();
-
+#endif
TerminatePrintJob(true);
}
@@ -904,7 +961,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() {
// Is the document already complete?
if (print_job_->document() && print_job_->document()->IsComplete()) {
- printing_succeeded_ = true;
+ printing_status_ = PrintStatus::kSucceeded;
return true;
}
@@ -952,7 +1009,10 @@ bool PrintViewManagerBase::CreateNewPrintJob(
// Disconnect the current `print_job_`.
auto weak_this = weak_ptr_factory_.GetWeakPtr();
- DisconnectFromCurrentPrintJob();
+ if (callback_.is_null()) {
+ // Disconnect the current |print_job_| only when calling window.print()
+ DisconnectFromCurrentPrintJob();
+ }
if (!weak_this)
return false;
@@ -973,7 +1033,7 @@ bool PrintViewManagerBase::CreateNewPrintJob(
#endif
print_job_->AddObserver(*this);
- printing_succeeded_ = false;
+ printing_status_ = PrintStatus::kFailed;
return true;
}
@@ -1041,6 +1101,11 @@ void PrintViewManagerBase::ReleasePrintJob() {
}
#endif
+ if (!callback_.is_null()) {
+ bool success = printing_status_ == PrintStatus::kSucceeded;
+ std::move(callback_).Run(success, PrintReasonFromPrintStatus(printing_status_));
+ }
+
if (!print_job_)
return;
@@ -1048,7 +1113,7 @@ void PrintViewManagerBase::ReleasePrintJob() {
// printing_rfh_ should only ever point to a RenderFrameHost with a live
// RenderFrame.
DCHECK(rfh->IsRenderFrameLive());
- GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_);
+ GetPrintRenderFrame(rfh)->PrintingDone(printing_status_ == PrintStatus::kSucceeded);
}
print_job_->RemoveObserver(*this);
@@ -1090,7 +1155,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() {
}
bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) {
- if (print_job_)
+ if (print_job_ && print_job_->document())
return true;
if (!cookie) {
@@ -1199,7 +1264,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
}
void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) {
- GetPrintRenderFrame(rfh)->PrintRequestedPages();
+ GetPrintRenderFrame(rfh)->PrintRequestedPages(/*silent=*/true, /*job_settings=*/base::Value::Dict());
for (auto& observer : GetTestObservers()) {
observer.OnPrintNow(rfh);
@@ -1249,7 +1314,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis(
set_analyzing_content(/*analyzing*/ false);
if (!allowed || !printing_rfh_ || IsCrashed() ||
!printing_rfh_->IsRenderFrameLive()) {
- std::move(callback).Run(nullptr);
+ std::move(callback).Run(nullptr, false);
return;
}
CompleteScriptedPrint(printing_rfh_, std::move(params), std::move(callback));
diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h
index 8af22e511701a595b77bea31da096caedc2e47ce..d1e3bc5ea012de1f1155546ef66c5e3e1c6b11de 100644
--- a/chrome/browser/printing/print_view_manager_base.h
+++ b/chrome/browser/printing/print_view_manager_base.h
@@ -47,6 +47,8 @@ namespace printing {
class PrintQueriesQueue;
class PrinterQuery;
+using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>;
+
// Base class for managing the print commands for a WebContents.
class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
public:
@@ -80,7 +82,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// Prints the current document immediately. Since the rendering is
// asynchronous, the actual printing will not be completed on the return of
// this function. Returns false if printing is impossible at the moment.
- virtual bool PrintNow(content::RenderFrameHost* rfh);
+ virtual bool PrintNow(content::RenderFrameHost* rfh,
+ bool silent = true,
+ base::Value::Dict settings = {},
+ CompletionCallback callback = {});
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
// Prints the document in `print_data` with settings specified in
@@ -132,8 +137,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
void IsPrintingEnabled(IsPrintingEnabledCallback callback) override;
void ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
ScriptedPrintCallback callback) override;
+ void ShowInvalidPrinterSettingsError() override;
void PrintingFailed(int32_t cookie,
mojom::PrintFailureReason reason) override;
+ void UserInitCanceled();
// Adds and removes observers for `PrintViewManagerBase` events. The order in
// which notifications are sent to observers is undefined. Observers must be
@@ -141,6 +148,14 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
void AddTestObserver(TestObserver& observer);
void RemoveTestObserver(TestObserver& observer);
+ enum class PrintStatus {
+ kSucceeded,
+ kCanceled,
+ kFailed,
+ kInvalid,
+ kUnknown
+ };
+
protected:
explicit PrintViewManagerBase(content::WebContents* web_contents);
@@ -293,7 +308,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// Runs `callback` with `params` to reply to ScriptedPrint().
void ScriptedPrintReply(ScriptedPrintCallback callback,
int process_id,
- mojom::PrintPagesParamsPtr params);
+ mojom::PrintPagesParamsPtr params,
+ bool canceled);
// Requests the RenderView to render all the missing pages for the print job.
// No-op if no print job is pending. Returns true if at least one page has
@@ -363,8 +379,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// The current RFH that is printing with a system printing dialog.
raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr;
+ // Respond with success of the print job.
+ CompletionCallback callback_;
+
// Indication of success of the print job.
- bool printing_succeeded_ = false;
+ PrintStatus printing_status_ = PrintStatus::kUnknown;
// Indication that the job is getting canceled.
bool canceling_job_ = false;
diff --git a/chrome/browser/printing/printer_query.cc b/chrome/browser/printing/printer_query.cc
index 0b6ff160cc0537d4e75ecfdc3ab3fc881888bbc9..8ca904943942de2d5ff4b194976e606a60ced16c 100644
--- a/chrome/browser/printing/printer_query.cc
+++ b/chrome/browser/printing/printer_query.cc
@@ -355,17 +355,19 @@ void PrinterQuery::UpdatePrintSettings(base::Value::Dict new_settings,
#endif // BUILDFLAG(IS_LINUX) && BUILDFLAG(USE_CUPS)
}
- mojom::ResultCode result;
{
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
base::ScopedAllowBlocking allow_blocking;
#endif
- result = printing_context_->UpdatePrintSettings(std::move(new_settings));
+ // Reset settings from previous print job
+ printing_context_->ResetSettings();
+ mojom::ResultCode result_code = printing_context_->UseDefaultSettings();
+ if (result_code == mojom::ResultCode::kSuccess)
+ result_code = printing_context_->UpdatePrintSettings(std::move(new_settings));
+ InvokeSettingsCallback(std::move(callback), result_code);
}
-
- InvokeSettingsCallback(std::move(callback), result);
}
#if BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
index e83cf407beebcec5ccf7eaa991f43d4d3713833b..5e770a6a840b48e07ff056fe038aad54e526429e 100644
--- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
+++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.cc
@@ -21,7 +21,7 @@ FakePrintRenderFrame::FakePrintRenderFrame(
FakePrintRenderFrame::~FakePrintRenderFrame() = default;
-void FakePrintRenderFrame::PrintRequestedPages() {}
+void FakePrintRenderFrame::PrintRequestedPages(bool /*silent*/, ::base::Value::Dict /*settings*/) {}
void FakePrintRenderFrame::PrintWithParams(mojom::PrintPagesParamsPtr params,
PrintWithParamsCallback callback) {
diff --git a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
index 32403bb077dcbbffe6a3a862feff619e980c5f93..af773c93ab969a5dc483cc63384851ff62cf51ec 100644
--- a/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
+++ b/chrome/browser/ui/webui/print_preview/fake_print_render_frame.h
@@ -25,7 +25,7 @@ class FakePrintRenderFrame : public mojom::PrintRenderFrame {
private:
// printing::mojom::PrintRenderFrame:
- void PrintRequestedPages() override;
+ void PrintRequestedPages(bool silent, ::base::Value::Dict settings) override;
void PrintWithParams(mojom::PrintPagesParamsPtr params,
PrintWithParamsCallback callback) override;
void PrintForSystemDialog() override;
diff --git a/components/printing/browser/print_manager.cc b/components/printing/browser/print_manager.cc
index 21c81377d32ae8d4185598a7eba88ed1d2063ef0..0767f4e9369e926b1cea99178c1a1975941f1765 100644
--- a/components/printing/browser/print_manager.cc
+++ b/components/printing/browser/print_manager.cc
@@ -47,6 +47,8 @@ void PrintManager::IsPrintingEnabled(IsPrintingEnabledCallback callback) {
std::move(callback).Run(true);
}
+void PrintManager::ShowInvalidPrinterSettingsError() {}
+
void PrintManager::PrintingFailed(int32_t cookie,
mojom::PrintFailureReason reason) {
// Note: Not redundant with cookie checks in the same method in other parts of
diff --git a/components/printing/browser/print_manager.h b/components/printing/browser/print_manager.h
index ca71560874a0189068dd11fbc039f5673bf6bd96..a8551d95e64da2afbc1685b2df8f1fc377c7117b 100644
--- a/components/printing/browser/print_manager.h
+++ b/components/printing/browser/print_manager.h
@@ -48,6 +48,7 @@ class PrintManager : public content::WebContentsObserver,
DidPrintDocumentCallback callback) override;
void IsPrintingEnabled(IsPrintingEnabledCallback callback) override;
void DidShowPrintDialog() override;
+ void ShowInvalidPrinterSettingsError() override;
void PrintingFailed(int32_t cookie,
mojom::PrintFailureReason reason) override;
diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom
index cd0f1c1d118cafc4ce12faeb531c38dc12153632..095130068f245dbbc3b7b536892eff9f10456e8c 100644
--- a/components/printing/common/print.mojom
+++ b/components/printing/common/print.mojom
@@ -296,7 +296,7 @@ union PrintWithParamsResult {
interface PrintRenderFrame {
// Tells the RenderFrame to switch the CSS to print media type, render every
// requested page, and then switch back the CSS to display media type.
- PrintRequestedPages();
+ PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings);
// Requests the frame to be printed with specified parameters. This is used
// to programmatically produce PDF by request from the browser (e.g. over
@@ -390,7 +390,10 @@ interface PrintManagerHost {
// UI to the user to select the final print settings. If the user cancels or
// an error occurs, return null.
[Sync]
- ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings);
+ ScriptedPrint(ScriptedPrintParams params) => (PrintPagesParams? settings, bool canceled);
+
+ // Tells the browser that there are invalid printer settings.
+ ShowInvalidPrinterSettingsError();
// Tells the browser printing failed.
PrintingFailed(int32 cookie, PrintFailureReason reason);
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc
index 4c31c8a926f89ed10fce2ce497c249f0707db9e5..0e4913a5d99aee139014467e848003be16261587 100644
--- a/components/printing/renderer/print_render_frame_helper.cc
+++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -45,6 +45,7 @@
#include "printing/mojom/print.mojom.h"
#include "printing/page_number.h"
#include "printing/print_job_constants.h"
+#include "printing/print_settings.h"
#include "printing/units.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
@@ -1345,7 +1346,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) {
if (!weak_this)
return;
- Print(web_frame, blink::WebNode(), PrintRequestType::kScripted);
+ Print(web_frame, blink::WebNode(), PrintRequestType::kScripted,
+ false /* silent */, base::Value::Dict() /* new_settings */);
if (!weak_this)
return;
@@ -1376,7 +1378,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver(
receivers_.Add(this, std::move(receiver));
}
-void PrintRenderFrameHelper::PrintRequestedPages() {
+void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value::Dict settings) {
ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr());
if (ipc_nesting_level_ > kAllowedIpcDepthForPrint)
return;
@@ -1391,7 +1393,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() {
// plugin node and print that instead.
auto plugin = delegate_->GetPdfElement(frame);
- Print(frame, plugin, PrintRequestType::kRegular);
+ Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings));
if (!render_frame_gone_)
frame->DispatchAfterPrintEvent();
@@ -1470,7 +1472,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() {
}
Print(frame, print_preview_context_.source_node(),
- PrintRequestType::kRegular);
+ PrintRequestType::kRegular, false,
+ base::Value::Dict());
if (!render_frame_gone_)
print_preview_context_.DispatchAfterPrintEvent();
// WARNING: |this| may be gone at this point. Do not do any more work here and
@@ -1521,6 +1524,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value::Dict settings) {
if (ipc_nesting_level_ > kAllowedIpcDepthForPrint)
return;
+ blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
+ print_preview_context_.InitWithFrame(frame);
print_preview_context_.OnPrintPreview();
#if BUILDFLAG(IS_CHROMEOS_ASH)
@@ -2142,7 +2147,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) {
return;
Print(duplicate_node.GetDocument().GetFrame(), duplicate_node,
- PrintRequestType::kRegular);
+ PrintRequestType::kRegular, false /* silent */,
+ base::Value::Dict() /* new_settings */);
// Check if |this| is still valid.
if (!weak_this)
return;
@@ -2157,7 +2163,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) {
void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame,
const blink::WebNode& node,
- PrintRequestType print_request_type) {
+ PrintRequestType print_request_type,
+ bool silent,
+ base::Value::Dict settings) {
// If still not finished with earlier print request simply ignore.
if (prep_frame_view_)
return;
@@ -2165,7 +2173,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame,
FrameReference frame_ref(frame);
uint32_t expected_page_count = 0;
- if (!CalculateNumberOfPages(frame, node, &expected_page_count)) {
+ if (!CalculateNumberOfPages(frame, node, &expected_page_count, std::move(settings))) {
DidFinishPrinting(FAIL_PRINT_INIT);
return; // Failed to init print page settings.
}
@@ -2184,8 +2192,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame,
print_pages_params_->params->print_scaling_option;
auto self = weak_ptr_factory_.GetWeakPtr();
- mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser(
+ mojom::PrintPagesParamsPtr print_settings;
+
+ if (silent) {
+ print_settings = mojom::PrintPagesParams::New();
+ print_settings->params = print_pages_params_->params->Clone();
+ } else {
+ print_settings = GetPrintSettingsFromUser(
frame_ref.GetFrame(), node, expected_page_count, print_request_type);
+ }
// Check if |this| is still valid.
if (!self)
return;
@@ -2418,35 +2433,47 @@ void PrintRenderFrameHelper::IPCProcessed() {
}
}
-bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) {
+bool PrintRenderFrameHelper::InitPrintSettings(
+ bool fit_to_paper_size,
+ base::Value::Dict new_settings) {
// Reset to default values.
ignore_css_margins_ = false;
- mojom::PrintPagesParams settings;
- GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params);
+ mojom::PrintPagesParamsPtr settings;
+ if (new_settings.empty()) {
+ settings = mojom::PrintPagesParams::New();
+ settings->params = mojom::PrintParams::New();
+ GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params);
+ } else {
+ GetPrintManagerHost()->UpdatePrintSettings(
+ std::move(new_settings), &settings);
+ }
// Check if the printer returned any settings, if the settings are null,
// assume there are no printer drivers configured. So safely terminate.
- if (!settings.params) {
+ if (!settings || !settings->params) {
// Caller will reset `print_pages_params_`.
return false;
}
- settings.params->print_scaling_option =
+ settings->params->print_scaling_option =
fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea
: mojom::PrintScalingOption::kSourceSize;
- SetPrintPagesParams(settings);
+ SetPrintPagesParams(*settings);
return true;
}
-bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame,
- const blink::WebNode& node,
- uint32_t* number_of_pages) {
+bool PrintRenderFrameHelper::CalculateNumberOfPages(
+ blink::WebLocalFrame* frame,
+ const blink::WebNode& node,
+ uint32_t* number_of_pages,
+ base::Value::Dict settings) {
DCHECK(frame);
bool fit_to_paper_size = !IsPrintingPdfFrame(frame, node);
- if (!InitPrintSettings(fit_to_paper_size)) {
+ if (!InitPrintSettings(fit_to_paper_size, std::move(settings))) {
// Browser triggered this code path. It already knows about the failure.
notify_browser_of_print_failure_ = false;
+ GetPrintManagerHost()->ShowInvalidPrinterSettingsError();
return false;
}
@@ -2550,7 +2577,7 @@ mojom::PrintPagesParamsPtr PrintRenderFrameHelper::GetPrintSettingsFromUser(
std::move(params),
base::BindOnce(
[](base::OnceClosure quit_closure, mojom::PrintPagesParamsPtr* output,
- mojom::PrintPagesParamsPtr input) {
+ mojom::PrintPagesParamsPtr input, bool canceled) {
*output = std::move(input);
std::move(quit_closure).Run();
},
diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h
index d971e446859507456da153a9d59f3ed4857b66cb..9ab75731a941e7065dfaa481508cfa47dbcf7d0b 100644
--- a/components/printing/renderer/print_render_frame_helper.h
+++ b/components/printing/renderer/print_render_frame_helper.h
@@ -245,7 +245,7 @@ class PrintRenderFrameHelper
mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver);
// printing::mojom::PrintRenderFrame:
- void PrintRequestedPages() override;
+ void PrintRequestedPages(bool silent, base::Value::Dict settings) override;
void PrintWithParams(mojom::PrintPagesParamsPtr params,
PrintWithParamsCallback callback) override;
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
@@ -322,7 +322,9 @@ class PrintRenderFrameHelper
// WARNING: |this| may be gone after this method returns.
void Print(blink::WebLocalFrame* frame,
const blink::WebNode& node,
- PrintRequestType print_request_type);
+ PrintRequestType print_request_type,
+ bool silent,
+ base::Value::Dict settings);
// Notification when printing is done - signal tear-down/free resources.
void DidFinishPrinting(PrintingResult result);
@@ -331,12 +333,14 @@ class PrintRenderFrameHelper
// Initialize print page settings with default settings.
// Used only for native printing workflow.
- bool InitPrintSettings(bool fit_to_paper_size);
+ bool InitPrintSettings(bool fit_to_paper_size,
+ base::Value::Dict new_settings);
// Calculate number of pages in source document.
bool CalculateNumberOfPages(blink::WebLocalFrame* frame,
const blink::WebNode& node,
- uint32_t* number_of_pages);
+ uint32_t* number_of_pages,
+ base::Value::Dict settings);
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
// Set options for print preset from source PDF document.
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn
index cc47fb1a2a3d6a6fe15448ebdba25c29b4b88aa0..e6125b6af20434f3ec3171c044d515b8c120a7b5 100644
--- a/content/browser/BUILD.gn
+++ b/content/browser/BUILD.gn
@@ -2901,8 +2901,9 @@ source_set("browser") {
"//ppapi/shared_impl",
]
- assert(enable_printing)
- deps += [ "//printing" ]
+ if (enable_printing) {
+ deps += [ "//printing" ]
+ }
if (is_chromeos) {
sources += [
diff --git a/printing/printing_context.cc b/printing/printing_context.cc
index 370dedfb4b4649f85a02b3a50ee16f525f57f44a..256666b64d8ffb5b50c9424c40ae1bb4050da6fb 100644
--- a/printing/printing_context.cc
+++ b/printing/printing_context.cc
@@ -143,7 +143,6 @@ void PrintingContext::UsePdfSettings() {
mojom::ResultCode PrintingContext::UpdatePrintSettings(
base::Value::Dict job_settings) {
- ResetSettings();
{
std::unique_ptr<PrintSettings> settings =
PrintSettingsFromJobSettings(job_settings);
diff --git a/printing/printing_context.h b/printing/printing_context.h
index 2fb3aef0797f204f08c20e48987cd8c2703185de..75a70e331f8b539027748dad3252912cb85e8797 100644
--- a/printing/printing_context.h
+++ b/printing/printing_context.h
@@ -178,6 +178,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext {
bool PrintingAborted() const { return abort_printing_; }
+ // Reinitializes the settings for object reuse.
+ void ResetSettings();
+
int job_id() const { return job_id_; }
protected:
@@ -188,9 +191,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext {
static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate,
bool skip_system_calls);
- // Reinitializes the settings for object reuse.
- void ResetSettings();
-
// Determine if system calls should be skipped by this instance.
bool skip_system_calls() const {
#if BUILDFLAG(ENABLE_OOP_PRINTING)
diff --git a/sandbox/policy/mac/sandbox_mac.mm b/sandbox/policy/mac/sandbox_mac.mm
index cc0e9b58d2686c45f8471eccdde7d9c5b03b4cae..d0ad07b3205aa7e9dcb8cc6217426a1bde22a15f 100644
--- a/sandbox/policy/mac/sandbox_mac.mm
+++ b/sandbox/policy/mac/sandbox_mac.mm
@@ -41,6 +41,10 @@
#error "This file requires ARC support."
#endif
+#if BUILDFLAG(ENABLE_PRINTING)
+#include "sandbox/policy/mac/print_backend.sb.h"
+#endif
+
namespace sandbox::policy {
base::FilePath GetCanonicalPath(const base::FilePath& path) {
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/browser/browser.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/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/files/file_util.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/common/chrome_paths.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/login_handler.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/thread_restrictions.h"
namespace electron {
namespace {
// Call |quit| after Chromium is fully started.
//
// This is important for quitting immediately in the "ready" event, when
// certain initialization task may still be pending, and quitting at that time
// could end up with crash on exit.
void RunQuitClosure(base::OnceClosure quit) {
// On Linux/Windows the "ready" event is emitted in "PreMainMessageLoopRun",
// make sure we quit after message loop has run for once.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,
std::move(quit));
}
} // namespace
#if BUILDFLAG(IS_WIN)
Browser::LaunchItem::LaunchItem() = default;
Browser::LaunchItem::~LaunchItem() = default;
Browser::LaunchItem::LaunchItem(const LaunchItem& other) = default;
#endif
Browser::LoginItemSettings::LoginItemSettings() = default;
Browser::LoginItemSettings::~LoginItemSettings() = default;
Browser::LoginItemSettings::LoginItemSettings(const LoginItemSettings& other) =
default;
Browser::Browser() {
WindowList::AddObserver(this);
}
Browser::~Browser() {
WindowList::RemoveObserver(this);
}
// static
Browser* Browser::Get() {
return ElectronBrowserMainParts::Get()->browser();
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
void Browser::Focus(gin::Arguments* args) {
// Focus on the first visible window.
for (auto* const window : WindowList::GetWindows()) {
if (window->IsVisible()) {
window->Focus(true);
break;
}
}
}
#endif
void Browser::Quit() {
if (is_quitting_)
return;
is_quitting_ = HandleBeforeQuit();
if (!is_quitting_)
return;
if (electron::WindowList::IsEmpty())
NotifyAndShutdown();
else
electron::WindowList::CloseAllWindows();
}
void Browser::Exit(gin::Arguments* args) {
int code = 0;
args->GetNext(&code);
if (!ElectronBrowserMainParts::Get()->SetExitCode(code)) {
// Message loop is not ready, quit directly.
exit(code);
} else {
// Prepare to quit when all windows have been closed.
is_quitting_ = true;
// Remember this caller so that we don't emit unrelated events.
is_exiting_ = true;
// Must destroy windows before quitting, otherwise bad things can happen.
if (electron::WindowList::IsEmpty()) {
Shutdown();
} else {
// Unlike Quit(), we do not ask to close window, but destroy the window
// without asking.
electron::WindowList::DestroyAllWindows();
}
}
}
void Browser::Shutdown() {
if (is_shutdown_)
return;
is_shutdown_ = true;
is_quitting_ = true;
for (BrowserObserver& observer : observers_)
observer.OnQuit();
if (quit_main_message_loop_) {
RunQuitClosure(std::move(quit_main_message_loop_));
} else {
// There is no message loop available so we are in early stage, wait until
// the quit_main_message_loop_ is available.
// Exiting now would leave defunct processes behind.
}
}
std::string Browser::GetVersion() const {
std::string ret = OverriddenApplicationVersion();
if (ret.empty())
ret = GetExecutableFileVersion();
return ret;
}
void Browser::SetVersion(const std::string& version) {
OverriddenApplicationVersion() = version;
}
std::string Browser::GetName() const {
std::string ret = OverriddenApplicationName();
if (ret.empty())
ret = GetExecutableFileProductName();
return ret;
}
void Browser::SetName(const std::string& name) {
OverriddenApplicationName() = name;
}
int Browser::GetBadgeCount() {
return badge_count_;
}
bool Browser::OpenFile(const std::string& file_path) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnOpenFile(&prevent_default, file_path);
return prevent_default;
}
void Browser::OpenURL(const std::string& url) {
for (BrowserObserver& observer : observers_)
observer.OnOpenURL(url);
}
void Browser::Activate(bool has_visible_windows) {
for (BrowserObserver& observer : observers_)
observer.OnActivate(has_visible_windows);
}
void Browser::WillFinishLaunching() {
for (BrowserObserver& observer : observers_)
observer.OnWillFinishLaunching();
}
void Browser::DidFinishLaunching(base::Value::Dict launch_info) {
// Make sure the userData directory is created.
ScopedAllowBlockingForElectron allow_blocking;
base::FilePath user_data;
if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data)) {
base::CreateDirectoryAndGetError(user_data, nullptr);
#if BUILDFLAG(IS_WIN)
base::SetExtraNoExecuteAllowedPath(chrome::DIR_USER_DATA);
#endif
}
is_ready_ = true;
if (ready_promise_) {
ready_promise_->Resolve();
}
for (BrowserObserver& observer : observers_)
observer.OnFinishLaunching(launch_info.Clone());
#if BUILDFLAG(IS_MAC)
if (dock_icon_) {
DockSetIconImage(*dock_icon_);
dock_icon_.reset();
}
#endif
}
v8::Local<v8::Value> Browser::WhenReady(v8::Isolate* isolate) {
if (!ready_promise_) {
ready_promise_ = std::make_unique<gin_helper::Promise<void>>(isolate);
if (is_ready()) {
ready_promise_->Resolve();
}
}
return ready_promise_->GetHandle();
}
void Browser::OnAccessibilitySupportChanged() {
for (BrowserObserver& observer : observers_)
observer.OnAccessibilitySupportChanged();
}
void Browser::PreMainMessageLoopRun() {
for (BrowserObserver& observer : observers_) {
observer.OnPreMainMessageLoopRun();
}
}
void Browser::PreCreateThreads() {
for (BrowserObserver& observer : observers_) {
observer.OnPreCreateThreads();
}
}
void Browser::SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure) {
if (is_shutdown_)
RunQuitClosure(std::move(quit_closure));
else
quit_main_message_loop_ = std::move(quit_closure);
}
void Browser::NotifyAndShutdown() {
if (is_shutdown_)
return;
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillQuit(&prevent_default);
if (prevent_default) {
is_quitting_ = false;
return;
}
Shutdown();
}
bool Browser::HandleBeforeQuit() {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnBeforeQuit(&prevent_default);
return !prevent_default;
}
void Browser::OnWindowCloseCancelled(NativeWindow* window) {
if (is_quitting_)
// Once a beforeunload handler has prevented the closing, we think the quit
// is cancelled too.
is_quitting_ = false;
}
void Browser::OnWindowAllClosed() {
if (is_exiting_) {
Shutdown();
} else if (is_quitting_) {
NotifyAndShutdown();
} else {
for (BrowserObserver& observer : observers_)
observer.OnWindowAllClosed();
}
}
#if BUILDFLAG(IS_MAC)
void Browser::NewWindowForTab() {
for (BrowserObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void Browser::DidBecomeActive() {
for (BrowserObserver& observer : observers_)
observer.OnDidBecomeActive();
}
void Browser::DidResignActive() {
for (BrowserObserver& observer : observers_)
observer.OnDidResignActive();
}
#endif
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/browser/browser.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_BROWSER_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
#include "gin/dictionary.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/window_list_observer.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "base/files/file_path.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/cocoa/secure_password_input.h"
#include "ui/gfx/image/image.h"
#endif
namespace base {
class FilePath;
}
namespace gin_helper {
class Arguments;
}
namespace electron {
class ElectronMenuModel;
// This class is used for control application-wide operations.
class Browser : public WindowListObserver {
public:
Browser();
~Browser() override;
// disable copy
Browser(const Browser&) = delete;
Browser& operator=(const Browser&) = delete;
static Browser* Get();
// Try to close all windows and quit the application.
void Quit();
// Exit the application immediately and set exit code.
void Exit(gin::Arguments* args);
// Cleanup everything and shutdown the application gracefully.
void Shutdown();
// Focus the application.
void Focus(gin::Arguments* args);
// Returns the version of the executable (or bundle).
std::string GetVersion() const;
// Overrides the application version.
void SetVersion(const std::string& version);
// Returns the application's name, default is just Electron.
std::string GetName() const;
// Overrides the application name.
void SetName(const std::string& name);
// Add the |path| to recent documents list.
void AddRecentDocument(const base::FilePath& path);
// Clear the recent documents list.
void ClearRecentDocuments();
#if BUILDFLAG(IS_WIN)
// Set the application user model ID.
void SetAppUserModelID(const std::wstring& name);
#endif
// Remove the default protocol handler registry key
bool RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Set as default handler for a protocol.
bool SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Query the current state of default handler for a protocol.
bool IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
std::u16string GetApplicationNameForProtocol(const GURL& url);
#if !BUILDFLAG(IS_LINUX)
// get the name, icon and path for an application
v8::Local<v8::Promise> GetApplicationInfoForProtocol(v8::Isolate* isolate,
const GURL& url);
#endif
// Set/Get the badge count.
bool SetBadgeCount(absl::optional<int> count);
int GetBadgeCount();
#if BUILDFLAG(IS_WIN)
struct LaunchItem {
std::wstring name;
std::wstring path;
std::wstring scope;
std::vector<std::wstring> args;
bool enabled = true;
LaunchItem();
~LaunchItem();
LaunchItem(const LaunchItem&);
};
#endif
// Set/Get the login item settings of the app
struct LoginItemSettings {
bool open_at_login = false;
bool open_as_hidden = false;
bool restore_state = false;
bool opened_at_login = false;
bool opened_as_hidden = false;
std::u16string path;
std::vector<std::u16string> args;
#if BUILDFLAG(IS_WIN)
// used in browser::setLoginItemSettings
bool enabled = true;
std::wstring name;
// used in browser::getLoginItemSettings
bool executable_will_launch_at_login = false;
std::vector<LaunchItem> launch_items;
#endif
LoginItemSettings();
~LoginItemSettings();
LoginItemSettings(const LoginItemSettings&);
};
void SetLoginItemSettings(LoginItemSettings settings);
LoginItemSettings GetLoginItemSettings(const LoginItemSettings& options);
#if BUILDFLAG(IS_MAC)
// Set the handler which decides whether to shutdown.
void SetShutdownHandler(base::RepeatingCallback<bool()> handler);
// Hide the application.
void Hide();
bool IsHidden();
// Show the application.
void Show();
// Creates an activity and sets it as the one currently in use.
void SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args);
// Returns the type name of the current user activity.
std::string GetCurrentActivityType();
// Invalidates an activity and marks it as no longer eligible for
// continuation
void InvalidateCurrentActivity();
// Marks this activity object as inactive without invalidating it.
void ResignCurrentActivity();
// Updates the current user activity
void UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info);
// Indicates that an user activity is about to be resumed.
bool WillContinueUserActivity(const std::string& type);
// Indicates a failure to resume a Handoff activity.
void DidFailToContinueUserActivity(const std::string& type,
const std::string& error);
// Resumes an activity via hand-off.
bool ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details);
// Indicates that an activity was continued on another device.
void UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info);
// Gives an opportunity to update the Handoff payload.
bool UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info);
void ApplyForcedRTL();
// Bounce the dock icon.
enum class BounceType {
kCritical = 0, // NSCriticalRequest
kInformational = 10, // NSInformationalRequest
};
int DockBounce(BounceType type);
void DockCancelBounce(int request_id);
// Bounce the Downloads stack.
void DockDownloadFinished(const std::string& filePath);
// Set/Get dock's badge text.
void DockSetBadgeText(const std::string& label);
std::string DockGetBadgeText();
// Hide/Show dock.
void DockHide();
v8::Local<v8::Promise> DockShow(v8::Isolate* isolate);
bool DockIsVisible();
// Set docks' menu.
void DockSetMenu(ElectronMenuModel* model);
// Set docks' icon.
void DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
#endif // BUILDFLAG(IS_MAC)
void ShowAboutPanel();
void SetAboutPanelOptions(base::Value::Dict options);
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
void ShowEmojiPanel();
#endif
#if BUILDFLAG(IS_WIN)
struct UserTask {
base::FilePath program;
std::wstring arguments;
std::wstring title;
std::wstring description;
base::FilePath working_dir;
base::FilePath icon_path;
int icon_index;
UserTask();
UserTask(const UserTask&);
~UserTask();
};
// Add a custom task to jump list.
bool SetUserTasks(const std::vector<UserTask>& tasks);
// Returns the application user model ID, if there isn't one, then create
// one from app's name.
// The returned string managed by Browser, and should not be modified.
PCWSTR GetAppUserModelID();
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX)
// Whether Unity launcher is running.
bool IsUnityRunning();
#endif // BUILDFLAG(IS_LINUX)
// Tell the application to open a file.
bool OpenFile(const std::string& file_path);
// Tell the application to open a url.
void OpenURL(const std::string& url);
#if BUILDFLAG(IS_MAC)
// Tell the application to create a new window for a tab.
void NewWindowForTab();
// Indicate that the app is now active.
void DidBecomeActive();
// Indicate that the app is no longer active and doesn’t have focus.
void DidResignActive();
#endif // BUILDFLAG(IS_MAC)
// Tell the application that application is activated with visible/invisible
// windows.
void Activate(bool has_visible_windows);
bool IsEmojiPanelSupported();
// Tell the application the loading has been done.
void WillFinishLaunching();
void DidFinishLaunching(base::Value::Dict launch_info);
void OnAccessibilitySupportChanged();
void PreMainMessageLoopRun();
void PreCreateThreads();
// Stores the supplied |quit_closure|, to be run when the last Browser
// instance is destroyed.
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure);
void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(BrowserObserver* obs) { observers_.RemoveObserver(obs); }
#if BUILDFLAG(IS_MAC)
// Returns whether secure input is enabled
bool IsSecureKeyboardEntryEnabled();
void SetSecureKeyboardEntryEnabled(bool enabled);
#endif
bool is_shutting_down() const { return is_shutdown_; }
bool is_quitting() const { return is_quitting_; }
bool is_ready() const { return is_ready_; }
v8::Local<v8::Value> WhenReady(v8::Isolate* isolate);
protected:
// Returns the version of application bundle or executable file.
std::string GetExecutableFileVersion() const;
// Returns the name of application bundle or executable file.
std::string GetExecutableFileProductName() const;
// Send the will-quit message and then shutdown the application.
void NotifyAndShutdown();
// Send the before-quit message and start closing windows.
bool HandleBeforeQuit();
bool is_quitting_ = false;
private:
// WindowListObserver implementations:
void OnWindowCloseCancelled(NativeWindow* window) override;
void OnWindowAllClosed() override;
#if BUILDFLAG(IS_MAC)
void DockSetIconImage(gfx::Image const& icon);
#endif
// Observers of the browser.
base::ObserverList<BrowserObserver> observers_;
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
// Whether `app.exit()` has been called
bool is_exiting_ = false;
// Whether "ready" event has been emitted.
bool is_ready_ = false;
// The browser is being shutdown.
bool is_shutdown_ = false;
// Null until/unless the default main message loop is running.
base::OnceClosure quit_main_message_loop_;
int badge_count_ = 0;
std::unique_ptr<gin_helper::Promise<void>> ready_promise_;
#if BUILDFLAG(IS_MAC)
std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_;
base::Time last_dock_show_;
// DockSetIcon() can't set the icon if is_ready_ is false.
// This field caches it until the browser is ready. (#26604)
absl::optional<gfx::Image> dock_icon_;
#endif
base::Value::Dict about_panel_options_;
#if BUILDFLAG(IS_WIN)
void UpdateBadgeContents(HWND hwnd,
const absl::optional<std::string>& badge_content,
const std::string& badge_alt_string);
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
#endif
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_BROWSER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/browser/browser_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/apple/bundle_locations.h"
#include "base/i18n/rtl.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#include "base/mac/mac_util.mm"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "net/base/mac/url_conversions.h"
#include "shell/browser/badging/badge_manager.h"
#include "shell/browser/mac/dict_util.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/browser/mac/electron_application_delegate.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/application_info.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/platform_util.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
namespace electron {
namespace {
bool IsAppRTL() {
const std::string& locale = g_browser_process->GetApplicationLocale();
base::i18n::TextDirection text_direction =
base::i18n::GetTextDirectionForLocaleInStartUp(locale.c_str());
return text_direction == base::i18n::RIGHT_TO_LEFT;
}
NSString* GetAppPathForProtocol(const GURL& url) {
NSURL* ns_url = [NSURL
URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
base::ScopedCFTypeRef<CFErrorRef> out_err;
base::ScopedCFTypeRef<CFURLRef> openingApp(LSCopyDefaultApplicationURLForURL(
(CFURLRef)ns_url, kLSRolesAll, out_err.InitializeInto()));
if (out_err) {
// likely kLSApplicationNotFoundErr
return nullptr;
}
NSString* app_path = [base::mac::CFToNSCast(openingApp.get()) path];
return app_path;
}
gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
gfx::Image icon(image);
return icon;
}
std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
NSString* app_display_name =
[[NSFileManager defaultManager] displayNameAtPath:app_path];
return base::SysNSStringToUTF16(app_display_name);
}
#if !IS_MAS_BUILD()
bool CheckLoginItemStatus(bool* is_hidden) {
base::mac::LoginItemsFileList login_items;
if (!login_items.Initialize())
return false;
base::ScopedCFTypeRef<LSSharedFileListItemRef> item(
login_items.GetLoginItemForMainApp());
if (!item.get())
return false;
if (is_hidden)
*is_hidden = base::mac::IsHiddenLoginItem(item);
return true;
}
#endif
} // namespace
v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
v8::Isolate* isolate,
const GURL& url) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
NSString* ns_app_path = GetAppPathForProtocol(url);
if (!ns_app_path) {
promise.RejectWithErrorMessage(
"Unable to retrieve installation path to app");
return handle;
}
std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
dict.Set("name", app_display_name);
dict.Set("path", app_path);
dict.Set("icon", app_icon);
promise.Resolve(dict);
return handle;
}
void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
[[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
}
void Browser::Focus(gin::Arguments* args) {
gin_helper::Dictionary opts;
bool steal_focus = false;
if (args->GetNext(&opts)) {
gin_helper::ErrorThrower thrower(args->isolate());
if (!opts.Get("steal", &steal_focus)) {
thrower.ThrowError(
"Expected options object to contain a 'steal' boolean property");
return;
}
}
[[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
}
void Browser::Hide() {
[[AtomApplication sharedApplication] hide:nil];
}
bool Browser::IsHidden() {
return [[AtomApplication sharedApplication] isHidden];
}
void Browser::Show() {
[[AtomApplication sharedApplication] unhide:nil];
}
void Browser::AddRecentDocument(const base::FilePath& path) {
NSString* path_string = base::mac::FilePathToNSString(path);
if (!path_string)
return;
NSURL* u = [NSURL fileURLWithPath:path_string];
if (!u)
return;
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
}
void Browser::ClearRecentDocuments() {
[[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
}
bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
if (!Browser::IsDefaultProtocolClient(protocol, args))
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef protocol_cf = base::mac::NSToCFCast(protocol_ns);
CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
if (!bundleList) {
return false;
}
// On macOS, we can't query the default, but the handlers list seems to put
// Apple's defaults first, so we'll use the first option that isn't our bundle
CFStringRef other = nil;
for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
other =
base::mac::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
if (![identifier isEqualToString:(__bridge NSString*)other]) {
break;
}
}
// No other app was found set it to none instead of setting it back to itself.
if ([identifier isEqualToString:(__bridge NSString*)other]) {
other = base::mac::NSToCFCast(@"None");
}
OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
return return_code == noErr;
}
bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
OSStatus return_code = LSSetDefaultHandlerForURLScheme(
base::mac::NSToCFCast(protocol_ns), base::mac::NSToCFCast(identifier));
return return_code == noErr;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
base::ScopedCFTypeRef<CFStringRef> bundleId(
LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns)));
if (!bundleId)
return false;
// Ensure the comparison is case-insensitive
// as LS does not persist the case of the bundle id.
NSComparisonResult result =
[base::mac::CFToNSCast(bundleId) caseInsensitiveCompare:identifier];
return result == NSOrderedSame;
}
std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
NSString* app_path = GetAppPathForProtocol(url);
if (!app_path) {
return std::u16string();
}
std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
return app_display_name;
}
bool Browser::SetBadgeCount(absl::optional<int> count) {
DockSetBadgeText(!count.has_value() || count.value() != 0
? badging::BadgeManager::GetBadgeString(count)
: "");
if (count.has_value()) {
badge_count_ = count.value();
} else {
badge_count_ = 0;
}
return true;
}
void Browser::SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args) {
std::string url_string;
args->GetNext(&url_string);
[[AtomApplication sharedApplication]
setCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(std::move(user_info))
withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
}
std::string Browser::GetCurrentActivityType() {
NSUserActivity* userActivity =
[[AtomApplication sharedApplication] getCurrentActivity];
return base::SysNSStringToUTF8(userActivity.activityType);
}
void Browser::InvalidateCurrentActivity() {
[[AtomApplication sharedApplication] invalidateCurrentActivity];
}
void Browser::ResignCurrentActivity() {
[[AtomApplication sharedApplication] resignCurrentActivity];
}
void Browser::UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info) {
[[AtomApplication sharedApplication]
updateCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(
std::move(user_info))];
}
bool Browser::WillContinueUserActivity(const std::string& type) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillContinueUserActivity(&prevent_default, type);
return prevent_default;
}
void Browser::DidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
for (BrowserObserver& observer : observers_)
observer.OnDidFailToContinueUserActivity(type, error);
}
bool Browser::ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnContinueUserActivity(&prevent_default, type, user_info.Clone(),
details.Clone());
return prevent_default;
}
void Browser::UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
for (BrowserObserver& observer : observers_)
observer.OnUserActivityWasContinued(type, user_info.Clone());
}
bool Browser::UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnUpdateUserActivityState(&prevent_default, type,
user_info.Clone());
return prevent_default;
}
// Modified from chrome/browser/ui/cocoa/l10n_util.mm.
void Browser::ApplyForcedRTL() {
NSUserDefaults* defaults = NSUserDefaults.standardUserDefaults;
auto dir = base::i18n::GetForcedTextDirection();
// An Electron app should respect RTL behavior of application locale over
// system locale.
auto should_be_rtl = dir == base::i18n::RIGHT_TO_LEFT || IsAppRTL();
auto should_be_ltr = dir == base::i18n::LEFT_TO_RIGHT || !IsAppRTL();
// -registerDefaults: won't do the trick here because these defaults exist
// (in the global domain) to reflect the system locale. They need to be set
// in Chrome's domain to supersede the system value.
if (should_be_rtl) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:YES forKey:@"NSForceRightToLeftWritingDirection"];
} else if (should_be_ltr) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:NO forKey:@"NSForceRightToLeftWritingDirection"];
} else {
[defaults removeObjectForKey:@"AppleTextDirection"];
[defaults removeObjectForKey:@"NSForceRightToLeftWritingDirection"];
}
}
Browser::LoginItemSettings Browser::GetLoginItemSettings(
const LoginItemSettings& options) {
LoginItemSettings settings;
#if IS_MAS_BUILD()
settings.open_at_login = platform_util::GetLoginItemEnabled();
#else
settings.open_at_login = CheckLoginItemStatus(&settings.open_as_hidden);
settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
#endif
return settings;
}
void Browser::SetLoginItemSettings(LoginItemSettings settings) {
#if IS_MAS_BUILD()
if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
}
#else
if (settings.open_at_login) {
base::mac::AddToLoginItems(base::apple::MainBundlePath(),
settings.open_as_hidden);
} else {
base::mac::RemoveFromLoginItems(base::apple::MainBundlePath());
}
#endif
}
std::string Browser::GetExecutableFileVersion() const {
return GetApplicationVersion();
}
std::string Browser::GetExecutableFileProductName() const {
return GetApplicationName();
}
int Browser::DockBounce(BounceType type) {
return [[AtomApplication sharedApplication]
requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
}
void Browser::DockCancelBounce(int request_id) {
[[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
}
void Browser::DockSetBadgeText(const std::string& label) {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
[tile setBadgeLabel:base::SysUTF8ToNSString(label)];
}
void Browser::DockDownloadFinished(const std::string& filePath) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.DownloadFileFinished"
object:base::SysUTF8ToNSString(filePath)];
}
std::string Browser::DockGetBadgeText() {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
return base::SysNSStringToUTF8([tile badgeLabel]);
}
void Browser::DockHide() {
// Transforming application state from UIElement to Foreground is an
// asynchronous operation, and unfortunately there is currently no way to know
// when it is finished.
// So if we call DockHide => DockShow => DockHide => DockShow in a very short
// time, we would trigger a bug of macOS that, there would be multiple dock
// icons of the app left in system.
// To work around this, we make sure DockHide does nothing if it is called
// immediately after DockShow. After some experiments, 1 second seems to be
// a proper interval.
if (!last_dock_show_.is_null() &&
base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
return;
}
for (auto* const& window : WindowList::GetWindows())
[window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
ProcessSerialNumber psn = {0, kCurrentProcess};
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
}
bool Browser::DockIsVisible() {
// Because DockShow has a slight delay this may not be true immediately
// after that call.
return ([[NSRunningApplication currentApplication] activationPolicy] ==
NSApplicationActivationPolicyRegular);
}
v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
last_dock_show_ = base::Time::Now();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
BOOL active = [[NSRunningApplication currentApplication] isActive];
ProcessSerialNumber psn = {0, kCurrentProcess};
if (active) {
// Workaround buggy behavior of TransformProcessType.
// http://stackoverflow.com/questions/7596643/
NSArray* runningApps = [NSRunningApplication
runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
for (NSRunningApplication* app in runningApps) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
__block gin_helper::Promise<void> p = std::move(promise);
dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms, dispatch_get_main_queue(), ^{
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
dispatch_time_t one_ms_2 = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms_2, dispatch_get_main_queue(), ^{
[[NSRunningApplication currentApplication]
activateWithOptions:NSApplicationActivateIgnoringOtherApps];
p.Resolve();
});
});
} else {
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
promise.Resolve();
}
return handle;
}
void Browser::DockSetMenu(ElectronMenuModel* model) {
ElectronApplicationDelegate* delegate =
(ElectronApplicationDelegate*)[NSApp delegate];
[delegate setApplicationDockMenu:model];
}
void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
gfx::Image image;
if (!icon->IsNull()) {
api::NativeImage* native_image = nullptr;
if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
return;
image = native_image->image();
}
DockSetIconImage(image);
}
void Browser::DockSetIconImage(gfx::Image const& image) {
if (!is_ready_) {
dock_icon_ = image;
return;
}
[[AtomApplication sharedApplication]
setApplicationIconImage:image.AsNSImage()];
}
void Browser::ShowAboutPanel() {
NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
// Credits must be a NSAttributedString instead of NSString
NSString* credits = (NSString*)options[@"Credits"];
if (credits != nil) {
base::scoped_nsobject<NSMutableDictionary> mutable_options(
[options mutableCopy]);
base::scoped_nsobject<NSAttributedString> creditString(
[[NSAttributedString alloc]
initWithString:credits
attributes:@{
NSForegroundColorAttributeName : [NSColor textColor]
}]);
[mutable_options setValue:creditString forKey:@"Credits"];
options = [NSDictionary dictionaryWithDictionary:mutable_options];
}
[[AtomApplication sharedApplication]
orderFrontStandardAboutPanelWithOptions:options];
}
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
about_panel_options_.clear();
for (const auto pair : options) {
std::string key = pair.first;
if (!key.empty() && pair.second.is_string()) {
key[0] = base::ToUpperASCII(key[0]);
about_panel_options_.Set(key, pair.second.Clone());
}
}
}
void Browser::ShowEmojiPanel() {
[[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
}
bool Browser::IsEmojiPanelSupported() {
return true;
}
bool Browser::IsSecureKeyboardEntryEnabled() {
return password_input_enabler_.get() != nullptr;
}
void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
if (enabled) {
password_input_enabler_ =
std::make_unique<ui::ScopedPasswordInputEnabler>();
} else {
password_input_enabler_.reset();
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/common/api/electron_api_native_image.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/common/api/electron_api_native_image.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/pattern.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "gin/arguments.h"
#include "gin/object_template_builder.h"
#include "gin/per_isolate_data.h"
#include "gin/wrappable.h"
#include "net/base/data_url.h"
#include "shell/common/asar/asar_util.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gfx_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/function_template_extensions.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/skia_util.h"
#include "shell/common/thread_restrictions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "ui/base/layout.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/image/image_util.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "shell/common/asar/archive.h"
#include "ui/gfx/icon_util.h"
#endif
namespace electron::api {
namespace {
// Get the scale factor from options object at the first argument
float GetScaleFactorFromOptions(gin::Arguments* args) {
float scale_factor = 1.0f;
gin_helper::Dictionary options;
if (args->GetNext(&options))
options.Get("scaleFactor", &scale_factor);
return scale_factor;
}
base::FilePath NormalizePath(const base::FilePath& path) {
if (!path.ReferencesParent()) {
return path;
}
ScopedAllowBlockingForElectron allow_blocking;
base::FilePath absolute_path = MakeAbsoluteFilePath(path);
// MakeAbsoluteFilePath returns an empty path on failures so use original path
if (absolute_path.empty()) {
return path;
} else {
return absolute_path;
}
}
#if BUILDFLAG(IS_MAC)
bool IsTemplateFilename(const base::FilePath& path) {
return (base::MatchPattern(path.value(), "*Template.*") ||
base::MatchPattern(path.value(), "*Template@*x.*"));
}
#endif
#if BUILDFLAG(IS_WIN)
base::win::ScopedHICON ReadICOFromPath(int size, const base::FilePath& path) {
// If file is in asar archive, we extract it to a temp file so LoadImage can
// load it.
base::FilePath asar_path, relative_path;
base::FilePath image_path(path);
if (asar::GetAsarArchivePath(image_path, &asar_path, &relative_path)) {
std::shared_ptr<asar::Archive> archive =
asar::GetOrCreateAsarArchive(asar_path);
if (archive)
archive->CopyFileOut(relative_path, &image_path);
}
// Load the icon from file.
return base::win::ScopedHICON(
static_cast<HICON>(LoadImage(NULL, image_path.value().c_str(), IMAGE_ICON,
size, size, LR_LOADFROMFILE)));
}
#endif
} // namespace
NativeImage::NativeImage(v8::Isolate* isolate, const gfx::Image& image)
: image_(image), isolate_(isolate) {
UpdateExternalAllocatedMemoryUsage();
}
#if BUILDFLAG(IS_WIN)
NativeImage::NativeImage(v8::Isolate* isolate, const base::FilePath& hicon_path)
: hicon_path_(hicon_path), isolate_(isolate) {
// Use the 256x256 icon as fallback icon.
gfx::ImageSkia image_skia;
electron::util::ReadImageSkiaFromICO(&image_skia, GetHICON(256));
image_ = gfx::Image(image_skia);
UpdateExternalAllocatedMemoryUsage();
}
#endif
NativeImage::~NativeImage() {
isolate_->AdjustAmountOfExternalAllocatedMemory(-memory_usage_);
}
void NativeImage::UpdateExternalAllocatedMemoryUsage() {
int32_t new_memory_usage = 0;
if (image_.HasRepresentation(gfx::Image::kImageRepSkia)) {
auto* const image_skia = image_.ToImageSkia();
if (!image_skia->isNull()) {
new_memory_usage = image_skia->bitmap()->computeByteSize();
}
}
isolate_->AdjustAmountOfExternalAllocatedMemory(new_memory_usage -
memory_usage_);
memory_usage_ = new_memory_usage;
}
// static
bool NativeImage::TryConvertNativeImage(v8::Isolate* isolate,
v8::Local<v8::Value> image,
NativeImage** native_image,
OnConvertError on_error) {
std::string error_message;
base::FilePath icon_path;
if (gin::ConvertFromV8(isolate, image, &icon_path)) {
*native_image = NativeImage::CreateFromPath(isolate, icon_path).get();
if ((*native_image)->image().IsEmpty()) {
#if BUILDFLAG(IS_WIN)
const auto img_path = base::WideToUTF8(icon_path.value());
#else
const auto img_path = icon_path.value();
#endif
error_message = "Failed to load image from path '" + img_path + "'";
}
} else {
if (!gin::ConvertFromV8(isolate, image, native_image)) {
error_message = "Argument must be a file path or a NativeImage";
}
}
if (!error_message.empty()) {
switch (on_error) {
case OnConvertError::kThrow:
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, error_message)));
break;
case OnConvertError::kWarn:
LOG(WARNING) << error_message;
break;
}
return false;
}
return true;
}
#if BUILDFLAG(IS_WIN)
HICON NativeImage::GetHICON(int size) {
auto iter = hicons_.find(size);
if (iter != hicons_.end())
return iter->second.get();
// First try loading the icon with specified size.
if (!hicon_path_.empty()) {
hicons_[size] = ReadICOFromPath(size, hicon_path_);
return hicons_[size].get();
}
// Then convert the image to ICO.
if (image_.IsEmpty())
return NULL;
hicons_[size] = IconUtil::CreateHICONFromSkBitmap(image_.AsBitmap());
return hicons_[size].get();
}
#endif
v8::Local<v8::Value> NativeImage::ToPNG(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
if (scale_factor == 1.0f) {
// Use raw 1x PNG bytes when available
scoped_refptr<base::RefCountedMemory> png = image_.As1xPNGBytes();
if (png->size() > 0) {
const char* data = reinterpret_cast<const char*>(png->front());
size_t size = png->size();
return node::Buffer::Copy(args->isolate(), data, size).ToLocalChecked();
}
}
const SkBitmap bitmap =
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap();
std::vector<unsigned char> encoded;
gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &encoded);
const char* data = reinterpret_cast<char*>(encoded.data());
size_t size = encoded.size();
return node::Buffer::Copy(args->isolate(), data, size).ToLocalChecked();
}
v8::Local<v8::Value> NativeImage::ToBitmap(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
const SkBitmap bitmap =
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap();
SkImageInfo info =
SkImageInfo::MakeN32Premul(bitmap.width(), bitmap.height());
auto array_buffer =
v8::ArrayBuffer::New(args->isolate(), info.computeMinByteSize());
auto backing_store = array_buffer->GetBackingStore();
if (bitmap.readPixels(info, backing_store->Data(), info.minRowBytes(), 0,
0)) {
return node::Buffer::New(args->isolate(), array_buffer, 0,
info.computeMinByteSize())
.ToLocalChecked();
}
return node::Buffer::New(args->isolate(), 0).ToLocalChecked();
}
v8::Local<v8::Value> NativeImage::ToJPEG(v8::Isolate* isolate, int quality) {
std::vector<unsigned char> output;
gfx::JPEG1xEncodedDataFromImage(image_, quality, &output);
if (output.empty())
return node::Buffer::New(isolate, 0).ToLocalChecked();
return node::Buffer::Copy(isolate,
reinterpret_cast<const char*>(&output.front()),
output.size())
.ToLocalChecked();
}
std::string NativeImage::ToDataURL(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
if (scale_factor == 1.0f) {
// Use raw 1x PNG bytes when available
scoped_refptr<base::RefCountedMemory> png = image_.As1xPNGBytes();
if (png->size() > 0)
return webui::GetPngDataUrl(png->front(), png->size());
}
return webui::GetBitmapDataUrl(
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap());
}
v8::Local<v8::Value> NativeImage::GetBitmap(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
const SkBitmap bitmap =
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap();
SkPixelRef* ref = bitmap.pixelRef();
if (!ref)
return node::Buffer::New(args->isolate(), 0).ToLocalChecked();
return node::Buffer::Copy(args->isolate(),
reinterpret_cast<char*>(ref->pixels()),
bitmap.computeByteSize())
.ToLocalChecked();
}
v8::Local<v8::Value> NativeImage::GetNativeHandle(
gin_helper::ErrorThrower thrower) {
#if BUILDFLAG(IS_MAC)
if (IsEmpty())
return node::Buffer::New(thrower.isolate(), 0).ToLocalChecked();
NSImage* ptr = image_.AsNSImage();
return node::Buffer::Copy(thrower.isolate(), reinterpret_cast<char*>(ptr),
sizeof(void*))
.ToLocalChecked();
#else
thrower.ThrowError("Not implemented");
return v8::Undefined(thrower.isolate());
#endif
}
bool NativeImage::IsEmpty() {
return image_.IsEmpty();
}
gfx::Size NativeImage::GetSize(const absl::optional<float> scale_factor) {
float sf = scale_factor.value_or(1.0f);
gfx::ImageSkiaRep image_rep = image_.AsImageSkia().GetRepresentation(sf);
return gfx::Size(image_rep.GetWidth(), image_rep.GetHeight());
}
std::vector<float> NativeImage::GetScaleFactors() {
gfx::ImageSkia image_skia = image_.AsImageSkia();
std::vector<float> scale_factors;
for (const auto& rep : image_skia.image_reps()) {
scale_factors.push_back(rep.scale());
}
return scale_factors;
}
float NativeImage::GetAspectRatio(const absl::optional<float> scale_factor) {
float sf = scale_factor.value_or(1.0f);
gfx::Size size = GetSize(sf);
if (size.IsEmpty())
return 1.f;
else
return static_cast<float>(size.width()) / static_cast<float>(size.height());
}
gin::Handle<NativeImage> NativeImage::Resize(gin::Arguments* args,
base::Value::Dict options) {
float scale_factor = GetScaleFactorFromOptions(args);
gfx::Size size = GetSize(scale_factor);
absl::optional<int> new_width = options.FindInt("width");
absl::optional<int> new_height = options.FindInt("height");
int width = new_width.value_or(size.width());
int height = new_height.value_or(size.height());
size.SetSize(width, height);
if (width <= 0 && height <= 0) {
return CreateEmpty(args->isolate());
} else if (new_width && !new_height) {
// Scale height to preserve original aspect ratio
size.set_height(width);
size =
gfx::ScaleToRoundedSize(size, 1.f, 1.f / GetAspectRatio(scale_factor));
} else if (new_height && !new_width) {
// Scale width to preserve original aspect ratio
size.set_width(height);
size = gfx::ScaleToRoundedSize(size, GetAspectRatio(scale_factor), 1.f);
}
skia::ImageOperations::ResizeMethod method =
skia::ImageOperations::ResizeMethod::RESIZE_BEST;
std::string* quality = options.FindString("quality");
if (quality && *quality == "good")
method = skia::ImageOperations::ResizeMethod::RESIZE_GOOD;
else if (quality && *quality == "better")
method = skia::ImageOperations::ResizeMethod::RESIZE_BETTER;
gfx::ImageSkia resized = gfx::ImageSkiaOperations::CreateResizedImage(
image_.AsImageSkia(), method, size);
return gin::CreateHandle(
args->isolate(), new NativeImage(args->isolate(), gfx::Image(resized)));
}
gin::Handle<NativeImage> NativeImage::Crop(v8::Isolate* isolate,
const gfx::Rect& rect) {
gfx::ImageSkia cropped =
gfx::ImageSkiaOperations::ExtractSubset(image_.AsImageSkia(), rect);
return gin::CreateHandle(isolate,
new NativeImage(isolate, gfx::Image(cropped)));
}
void NativeImage::AddRepresentation(const gin_helper::Dictionary& options) {
int width = 0;
int height = 0;
float scale_factor = 1.0f;
options.Get("width", &width);
options.Get("height", &height);
options.Get("scaleFactor", &scale_factor);
bool skia_rep_added = false;
gfx::ImageSkia image_skia = image_.AsImageSkia();
v8::Local<v8::Value> buffer;
GURL url;
if (options.Get("buffer", &buffer) && node::Buffer::HasInstance(buffer)) {
auto* data = reinterpret_cast<unsigned char*>(node::Buffer::Data(buffer));
auto size = node::Buffer::Length(buffer);
skia_rep_added = electron::util::AddImageSkiaRepFromBuffer(
&image_skia, data, size, width, height, scale_factor);
} else if (options.Get("dataURL", &url)) {
std::string mime_type, charset, data;
if (net::DataURL::Parse(url, &mime_type, &charset, &data)) {
auto* data_ptr = reinterpret_cast<const unsigned char*>(data.c_str());
if (mime_type == "image/png") {
skia_rep_added = electron::util::AddImageSkiaRepFromPNG(
&image_skia, data_ptr, data.size(), scale_factor);
} else if (mime_type == "image/jpeg") {
skia_rep_added = electron::util::AddImageSkiaRepFromJPEG(
&image_skia, data_ptr, data.size(), scale_factor);
}
}
}
// Re-initialize image when first representation is added to an empty image
if (skia_rep_added && IsEmpty()) {
gfx::Image image(image_skia);
image_ = std::move(image);
}
}
#if !BUILDFLAG(IS_MAC)
void NativeImage::SetTemplateImage(bool setAsTemplate) {}
bool NativeImage::IsTemplateImage() {
return false;
}
#endif
// static
gin::Handle<NativeImage> NativeImage::CreateEmpty(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, new NativeImage(isolate, gfx::Image()));
}
// static
gin::Handle<NativeImage> NativeImage::Create(v8::Isolate* isolate,
const gfx::Image& image) {
return gin::CreateHandle(isolate, new NativeImage(isolate, image));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromPNG(v8::Isolate* isolate,
const char* buffer,
size_t length) {
gfx::ImageSkia image_skia;
electron::util::AddImageSkiaRepFromPNG(
&image_skia, reinterpret_cast<const unsigned char*>(buffer), length, 1.0);
return Create(isolate, gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromJPEG(v8::Isolate* isolate,
const char* buffer,
size_t length) {
gfx::ImageSkia image_skia;
electron::util::AddImageSkiaRepFromJPEG(
&image_skia, reinterpret_cast<const unsigned char*>(buffer), length, 1.0);
return Create(isolate, gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromPath(
v8::Isolate* isolate,
const base::FilePath& path) {
base::FilePath image_path = NormalizePath(path);
#if BUILDFLAG(IS_WIN)
if (image_path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) {
return gin::CreateHandle(isolate, new NativeImage(isolate, image_path));
}
#endif
gfx::ImageSkia image_skia;
electron::util::PopulateImageSkiaRepsFromPath(&image_skia, image_path);
gfx::Image image(image_skia);
gin::Handle<NativeImage> handle = Create(isolate, image);
#if BUILDFLAG(IS_MAC)
if (IsTemplateFilename(image_path))
handle->SetTemplateImage(true);
#endif
return handle;
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromBitmap(
gin_helper::ErrorThrower thrower,
v8::Local<v8::Value> buffer,
const gin_helper::Dictionary& options) {
if (!node::Buffer::HasInstance(buffer)) {
thrower.ThrowError("buffer must be a node Buffer");
return gin::Handle<NativeImage>();
}
unsigned int width = 0;
unsigned int height = 0;
double scale_factor = 1.;
if (!options.Get("width", &width)) {
thrower.ThrowError("width is required");
return gin::Handle<NativeImage>();
}
if (!options.Get("height", &height)) {
thrower.ThrowError("height is required");
return gin::Handle<NativeImage>();
}
auto info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType);
auto size_bytes = info.computeMinByteSize();
if (size_bytes != node::Buffer::Length(buffer)) {
thrower.ThrowError("invalid buffer size");
return gin::Handle<NativeImage>();
}
options.Get("scaleFactor", &scale_factor);
if (width == 0 || height == 0) {
return CreateEmpty(thrower.isolate());
}
SkBitmap bitmap;
bitmap.allocN32Pixels(width, height, false);
bitmap.writePixels({info, node::Buffer::Data(buffer), bitmap.rowBytes()});
gfx::ImageSkia image_skia =
gfx::ImageSkia::CreateFromBitmap(bitmap, scale_factor);
return Create(thrower.isolate(), gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromBuffer(
gin_helper::ErrorThrower thrower,
v8::Local<v8::Value> buffer,
gin::Arguments* args) {
if (!node::Buffer::HasInstance(buffer)) {
thrower.ThrowError("buffer must be a node Buffer");
return gin::Handle<NativeImage>();
}
int width = 0;
int height = 0;
double scale_factor = 1.;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("width", &width);
options.Get("height", &height);
options.Get("scaleFactor", &scale_factor);
}
gfx::ImageSkia image_skia;
electron::util::AddImageSkiaRepFromBuffer(
&image_skia, reinterpret_cast<unsigned char*>(node::Buffer::Data(buffer)),
node::Buffer::Length(buffer), width, height, scale_factor);
return Create(args->isolate(), gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromDataURL(v8::Isolate* isolate,
const GURL& url) {
std::string mime_type, charset, data;
if (net::DataURL::Parse(url, &mime_type, &charset, &data)) {
if (mime_type == "image/png")
return CreateFromPNG(isolate, data.c_str(), data.size());
else if (mime_type == "image/jpeg")
return CreateFromJPEG(isolate, data.c_str(), data.size());
}
return CreateEmpty(isolate);
}
#if !BUILDFLAG(IS_MAC)
gin::Handle<NativeImage> NativeImage::CreateFromNamedImage(gin::Arguments* args,
std::string name) {
return CreateEmpty(args->isolate());
}
#endif
// static
gin::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
auto* wrapper_info = &kWrapperInfo;
v8::Local<v8::FunctionTemplate> constructor =
data->GetFunctionTemplate(wrapper_info);
if (constructor.IsEmpty()) {
constructor = v8::FunctionTemplate::New(isolate);
constructor->SetClassName(gin::StringToV8(isolate, GetTypeName()));
data->SetFunctionTemplate(wrapper_info, constructor);
}
return gin::ObjectTemplateBuilder(isolate, GetTypeName(),
constructor->InstanceTemplate())
.SetMethod("toPNG", &NativeImage::ToPNG)
.SetMethod("toJPEG", &NativeImage::ToJPEG)
.SetMethod("toBitmap", &NativeImage::ToBitmap)
.SetMethod("getBitmap", &NativeImage::GetBitmap)
.SetMethod("getScaleFactors", &NativeImage::GetScaleFactors)
.SetMethod("getNativeHandle", &NativeImage::GetNativeHandle)
.SetMethod("toDataURL", &NativeImage::ToDataURL)
.SetMethod("isEmpty", &NativeImage::IsEmpty)
.SetMethod("getSize", &NativeImage::GetSize)
.SetMethod("setTemplateImage", &NativeImage::SetTemplateImage)
.SetMethod("isTemplateImage", &NativeImage::IsTemplateImage)
.SetProperty("isMacTemplateImage", &NativeImage::IsTemplateImage,
&NativeImage::SetTemplateImage)
.SetMethod("resize", &NativeImage::Resize)
.SetMethod("crop", &NativeImage::Crop)
.SetMethod("getAspectRatio", &NativeImage::GetAspectRatio)
.SetMethod("addRepresentation", &NativeImage::AddRepresentation);
}
const char* NativeImage::GetTypeName() {
return "NativeImage";
}
// static
gin::WrapperInfo NativeImage::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::NativeImage;
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);
gin_helper::Dictionary native_image = gin::Dictionary::CreateEmpty(isolate);
dict.Set("nativeImage", native_image);
native_image.SetMethod("createEmpty", &NativeImage::CreateEmpty);
native_image.SetMethod("createFromPath", &NativeImage::CreateFromPath);
native_image.SetMethod("createFromBitmap", &NativeImage::CreateFromBitmap);
native_image.SetMethod("createFromBuffer", &NativeImage::CreateFromBuffer);
native_image.SetMethod("createFromDataURL", &NativeImage::CreateFromDataURL);
native_image.SetMethod("createFromNamedImage",
&NativeImage::CreateFromNamedImage);
#if !BUILDFLAG(IS_LINUX)
native_image.SetMethod("createThumbnailFromPath",
&NativeImage::CreateThumbnailFromPath);
#endif
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_common_native_image, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/browser/browser.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/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/files/file_util.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/common/chrome_paths.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/login_handler.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/thread_restrictions.h"
namespace electron {
namespace {
// Call |quit| after Chromium is fully started.
//
// This is important for quitting immediately in the "ready" event, when
// certain initialization task may still be pending, and quitting at that time
// could end up with crash on exit.
void RunQuitClosure(base::OnceClosure quit) {
// On Linux/Windows the "ready" event is emitted in "PreMainMessageLoopRun",
// make sure we quit after message loop has run for once.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,
std::move(quit));
}
} // namespace
#if BUILDFLAG(IS_WIN)
Browser::LaunchItem::LaunchItem() = default;
Browser::LaunchItem::~LaunchItem() = default;
Browser::LaunchItem::LaunchItem(const LaunchItem& other) = default;
#endif
Browser::LoginItemSettings::LoginItemSettings() = default;
Browser::LoginItemSettings::~LoginItemSettings() = default;
Browser::LoginItemSettings::LoginItemSettings(const LoginItemSettings& other) =
default;
Browser::Browser() {
WindowList::AddObserver(this);
}
Browser::~Browser() {
WindowList::RemoveObserver(this);
}
// static
Browser* Browser::Get() {
return ElectronBrowserMainParts::Get()->browser();
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
void Browser::Focus(gin::Arguments* args) {
// Focus on the first visible window.
for (auto* const window : WindowList::GetWindows()) {
if (window->IsVisible()) {
window->Focus(true);
break;
}
}
}
#endif
void Browser::Quit() {
if (is_quitting_)
return;
is_quitting_ = HandleBeforeQuit();
if (!is_quitting_)
return;
if (electron::WindowList::IsEmpty())
NotifyAndShutdown();
else
electron::WindowList::CloseAllWindows();
}
void Browser::Exit(gin::Arguments* args) {
int code = 0;
args->GetNext(&code);
if (!ElectronBrowserMainParts::Get()->SetExitCode(code)) {
// Message loop is not ready, quit directly.
exit(code);
} else {
// Prepare to quit when all windows have been closed.
is_quitting_ = true;
// Remember this caller so that we don't emit unrelated events.
is_exiting_ = true;
// Must destroy windows before quitting, otherwise bad things can happen.
if (electron::WindowList::IsEmpty()) {
Shutdown();
} else {
// Unlike Quit(), we do not ask to close window, but destroy the window
// without asking.
electron::WindowList::DestroyAllWindows();
}
}
}
void Browser::Shutdown() {
if (is_shutdown_)
return;
is_shutdown_ = true;
is_quitting_ = true;
for (BrowserObserver& observer : observers_)
observer.OnQuit();
if (quit_main_message_loop_) {
RunQuitClosure(std::move(quit_main_message_loop_));
} else {
// There is no message loop available so we are in early stage, wait until
// the quit_main_message_loop_ is available.
// Exiting now would leave defunct processes behind.
}
}
std::string Browser::GetVersion() const {
std::string ret = OverriddenApplicationVersion();
if (ret.empty())
ret = GetExecutableFileVersion();
return ret;
}
void Browser::SetVersion(const std::string& version) {
OverriddenApplicationVersion() = version;
}
std::string Browser::GetName() const {
std::string ret = OverriddenApplicationName();
if (ret.empty())
ret = GetExecutableFileProductName();
return ret;
}
void Browser::SetName(const std::string& name) {
OverriddenApplicationName() = name;
}
int Browser::GetBadgeCount() {
return badge_count_;
}
bool Browser::OpenFile(const std::string& file_path) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnOpenFile(&prevent_default, file_path);
return prevent_default;
}
void Browser::OpenURL(const std::string& url) {
for (BrowserObserver& observer : observers_)
observer.OnOpenURL(url);
}
void Browser::Activate(bool has_visible_windows) {
for (BrowserObserver& observer : observers_)
observer.OnActivate(has_visible_windows);
}
void Browser::WillFinishLaunching() {
for (BrowserObserver& observer : observers_)
observer.OnWillFinishLaunching();
}
void Browser::DidFinishLaunching(base::Value::Dict launch_info) {
// Make sure the userData directory is created.
ScopedAllowBlockingForElectron allow_blocking;
base::FilePath user_data;
if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data)) {
base::CreateDirectoryAndGetError(user_data, nullptr);
#if BUILDFLAG(IS_WIN)
base::SetExtraNoExecuteAllowedPath(chrome::DIR_USER_DATA);
#endif
}
is_ready_ = true;
if (ready_promise_) {
ready_promise_->Resolve();
}
for (BrowserObserver& observer : observers_)
observer.OnFinishLaunching(launch_info.Clone());
#if BUILDFLAG(IS_MAC)
if (dock_icon_) {
DockSetIconImage(*dock_icon_);
dock_icon_.reset();
}
#endif
}
v8::Local<v8::Value> Browser::WhenReady(v8::Isolate* isolate) {
if (!ready_promise_) {
ready_promise_ = std::make_unique<gin_helper::Promise<void>>(isolate);
if (is_ready()) {
ready_promise_->Resolve();
}
}
return ready_promise_->GetHandle();
}
void Browser::OnAccessibilitySupportChanged() {
for (BrowserObserver& observer : observers_)
observer.OnAccessibilitySupportChanged();
}
void Browser::PreMainMessageLoopRun() {
for (BrowserObserver& observer : observers_) {
observer.OnPreMainMessageLoopRun();
}
}
void Browser::PreCreateThreads() {
for (BrowserObserver& observer : observers_) {
observer.OnPreCreateThreads();
}
}
void Browser::SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure) {
if (is_shutdown_)
RunQuitClosure(std::move(quit_closure));
else
quit_main_message_loop_ = std::move(quit_closure);
}
void Browser::NotifyAndShutdown() {
if (is_shutdown_)
return;
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillQuit(&prevent_default);
if (prevent_default) {
is_quitting_ = false;
return;
}
Shutdown();
}
bool Browser::HandleBeforeQuit() {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnBeforeQuit(&prevent_default);
return !prevent_default;
}
void Browser::OnWindowCloseCancelled(NativeWindow* window) {
if (is_quitting_)
// Once a beforeunload handler has prevented the closing, we think the quit
// is cancelled too.
is_quitting_ = false;
}
void Browser::OnWindowAllClosed() {
if (is_exiting_) {
Shutdown();
} else if (is_quitting_) {
NotifyAndShutdown();
} else {
for (BrowserObserver& observer : observers_)
observer.OnWindowAllClosed();
}
}
#if BUILDFLAG(IS_MAC)
void Browser::NewWindowForTab() {
for (BrowserObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void Browser::DidBecomeActive() {
for (BrowserObserver& observer : observers_)
observer.OnDidBecomeActive();
}
void Browser::DidResignActive() {
for (BrowserObserver& observer : observers_)
observer.OnDidResignActive();
}
#endif
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/browser/browser.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_BROWSER_H_
#define ELECTRON_SHELL_BROWSER_BROWSER_H_
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/observer_list.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
#include "gin/dictionary.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/window_list_observer.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "base/files/file_path.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/cocoa/secure_password_input.h"
#include "ui/gfx/image/image.h"
#endif
namespace base {
class FilePath;
}
namespace gin_helper {
class Arguments;
}
namespace electron {
class ElectronMenuModel;
// This class is used for control application-wide operations.
class Browser : public WindowListObserver {
public:
Browser();
~Browser() override;
// disable copy
Browser(const Browser&) = delete;
Browser& operator=(const Browser&) = delete;
static Browser* Get();
// Try to close all windows and quit the application.
void Quit();
// Exit the application immediately and set exit code.
void Exit(gin::Arguments* args);
// Cleanup everything and shutdown the application gracefully.
void Shutdown();
// Focus the application.
void Focus(gin::Arguments* args);
// Returns the version of the executable (or bundle).
std::string GetVersion() const;
// Overrides the application version.
void SetVersion(const std::string& version);
// Returns the application's name, default is just Electron.
std::string GetName() const;
// Overrides the application name.
void SetName(const std::string& name);
// Add the |path| to recent documents list.
void AddRecentDocument(const base::FilePath& path);
// Clear the recent documents list.
void ClearRecentDocuments();
#if BUILDFLAG(IS_WIN)
// Set the application user model ID.
void SetAppUserModelID(const std::wstring& name);
#endif
// Remove the default protocol handler registry key
bool RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Set as default handler for a protocol.
bool SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
// Query the current state of default handler for a protocol.
bool IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args);
std::u16string GetApplicationNameForProtocol(const GURL& url);
#if !BUILDFLAG(IS_LINUX)
// get the name, icon and path for an application
v8::Local<v8::Promise> GetApplicationInfoForProtocol(v8::Isolate* isolate,
const GURL& url);
#endif
// Set/Get the badge count.
bool SetBadgeCount(absl::optional<int> count);
int GetBadgeCount();
#if BUILDFLAG(IS_WIN)
struct LaunchItem {
std::wstring name;
std::wstring path;
std::wstring scope;
std::vector<std::wstring> args;
bool enabled = true;
LaunchItem();
~LaunchItem();
LaunchItem(const LaunchItem&);
};
#endif
// Set/Get the login item settings of the app
struct LoginItemSettings {
bool open_at_login = false;
bool open_as_hidden = false;
bool restore_state = false;
bool opened_at_login = false;
bool opened_as_hidden = false;
std::u16string path;
std::vector<std::u16string> args;
#if BUILDFLAG(IS_WIN)
// used in browser::setLoginItemSettings
bool enabled = true;
std::wstring name;
// used in browser::getLoginItemSettings
bool executable_will_launch_at_login = false;
std::vector<LaunchItem> launch_items;
#endif
LoginItemSettings();
~LoginItemSettings();
LoginItemSettings(const LoginItemSettings&);
};
void SetLoginItemSettings(LoginItemSettings settings);
LoginItemSettings GetLoginItemSettings(const LoginItemSettings& options);
#if BUILDFLAG(IS_MAC)
// Set the handler which decides whether to shutdown.
void SetShutdownHandler(base::RepeatingCallback<bool()> handler);
// Hide the application.
void Hide();
bool IsHidden();
// Show the application.
void Show();
// Creates an activity and sets it as the one currently in use.
void SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args);
// Returns the type name of the current user activity.
std::string GetCurrentActivityType();
// Invalidates an activity and marks it as no longer eligible for
// continuation
void InvalidateCurrentActivity();
// Marks this activity object as inactive without invalidating it.
void ResignCurrentActivity();
// Updates the current user activity
void UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info);
// Indicates that an user activity is about to be resumed.
bool WillContinueUserActivity(const std::string& type);
// Indicates a failure to resume a Handoff activity.
void DidFailToContinueUserActivity(const std::string& type,
const std::string& error);
// Resumes an activity via hand-off.
bool ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details);
// Indicates that an activity was continued on another device.
void UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info);
// Gives an opportunity to update the Handoff payload.
bool UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info);
void ApplyForcedRTL();
// Bounce the dock icon.
enum class BounceType {
kCritical = 0, // NSCriticalRequest
kInformational = 10, // NSInformationalRequest
};
int DockBounce(BounceType type);
void DockCancelBounce(int request_id);
// Bounce the Downloads stack.
void DockDownloadFinished(const std::string& filePath);
// Set/Get dock's badge text.
void DockSetBadgeText(const std::string& label);
std::string DockGetBadgeText();
// Hide/Show dock.
void DockHide();
v8::Local<v8::Promise> DockShow(v8::Isolate* isolate);
bool DockIsVisible();
// Set docks' menu.
void DockSetMenu(ElectronMenuModel* model);
// Set docks' icon.
void DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon);
#endif // BUILDFLAG(IS_MAC)
void ShowAboutPanel();
void SetAboutPanelOptions(base::Value::Dict options);
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
void ShowEmojiPanel();
#endif
#if BUILDFLAG(IS_WIN)
struct UserTask {
base::FilePath program;
std::wstring arguments;
std::wstring title;
std::wstring description;
base::FilePath working_dir;
base::FilePath icon_path;
int icon_index;
UserTask();
UserTask(const UserTask&);
~UserTask();
};
// Add a custom task to jump list.
bool SetUserTasks(const std::vector<UserTask>& tasks);
// Returns the application user model ID, if there isn't one, then create
// one from app's name.
// The returned string managed by Browser, and should not be modified.
PCWSTR GetAppUserModelID();
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_LINUX)
// Whether Unity launcher is running.
bool IsUnityRunning();
#endif // BUILDFLAG(IS_LINUX)
// Tell the application to open a file.
bool OpenFile(const std::string& file_path);
// Tell the application to open a url.
void OpenURL(const std::string& url);
#if BUILDFLAG(IS_MAC)
// Tell the application to create a new window for a tab.
void NewWindowForTab();
// Indicate that the app is now active.
void DidBecomeActive();
// Indicate that the app is no longer active and doesn’t have focus.
void DidResignActive();
#endif // BUILDFLAG(IS_MAC)
// Tell the application that application is activated with visible/invisible
// windows.
void Activate(bool has_visible_windows);
bool IsEmojiPanelSupported();
// Tell the application the loading has been done.
void WillFinishLaunching();
void DidFinishLaunching(base::Value::Dict launch_info);
void OnAccessibilitySupportChanged();
void PreMainMessageLoopRun();
void PreCreateThreads();
// Stores the supplied |quit_closure|, to be run when the last Browser
// instance is destroyed.
void SetMainMessageLoopQuitClosure(base::OnceClosure quit_closure);
void AddObserver(BrowserObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(BrowserObserver* obs) { observers_.RemoveObserver(obs); }
#if BUILDFLAG(IS_MAC)
// Returns whether secure input is enabled
bool IsSecureKeyboardEntryEnabled();
void SetSecureKeyboardEntryEnabled(bool enabled);
#endif
bool is_shutting_down() const { return is_shutdown_; }
bool is_quitting() const { return is_quitting_; }
bool is_ready() const { return is_ready_; }
v8::Local<v8::Value> WhenReady(v8::Isolate* isolate);
protected:
// Returns the version of application bundle or executable file.
std::string GetExecutableFileVersion() const;
// Returns the name of application bundle or executable file.
std::string GetExecutableFileProductName() const;
// Send the will-quit message and then shutdown the application.
void NotifyAndShutdown();
// Send the before-quit message and start closing windows.
bool HandleBeforeQuit();
bool is_quitting_ = false;
private:
// WindowListObserver implementations:
void OnWindowCloseCancelled(NativeWindow* window) override;
void OnWindowAllClosed() override;
#if BUILDFLAG(IS_MAC)
void DockSetIconImage(gfx::Image const& icon);
#endif
// Observers of the browser.
base::ObserverList<BrowserObserver> observers_;
// Tracks tasks requesting file icons.
base::CancelableTaskTracker cancelable_task_tracker_;
// Whether `app.exit()` has been called
bool is_exiting_ = false;
// Whether "ready" event has been emitted.
bool is_ready_ = false;
// The browser is being shutdown.
bool is_shutdown_ = false;
// Null until/unless the default main message loop is running.
base::OnceClosure quit_main_message_loop_;
int badge_count_ = 0;
std::unique_ptr<gin_helper::Promise<void>> ready_promise_;
#if BUILDFLAG(IS_MAC)
std::unique_ptr<ui::ScopedPasswordInputEnabler> password_input_enabler_;
base::Time last_dock_show_;
// DockSetIcon() can't set the icon if is_ready_ is false.
// This field caches it until the browser is ready. (#26604)
absl::optional<gfx::Image> dock_icon_;
#endif
base::Value::Dict about_panel_options_;
#if BUILDFLAG(IS_WIN)
void UpdateBadgeContents(HWND hwnd,
const absl::optional<std::string>& badge_content,
const std::string& badge_alt_string);
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
#endif
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_BROWSER_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/browser/browser_mac.mm
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/browser.h"
#include <memory>
#include <string>
#include <utility>
#include "base/apple/bundle_locations.h"
#include "base/i18n/rtl.h"
#include "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#include "base/mac/mac_util.mm"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/sys_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "net/base/mac/url_conversions.h"
#include "shell/browser/badging/badge_manager.h"
#include "shell/browser/mac/dict_util.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/browser/mac/electron_application_delegate.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/application_info.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/promise.h"
#include "shell/common/platform_util.h"
#include "ui/gfx/image/image.h"
#include "url/gurl.h"
namespace electron {
namespace {
bool IsAppRTL() {
const std::string& locale = g_browser_process->GetApplicationLocale();
base::i18n::TextDirection text_direction =
base::i18n::GetTextDirectionForLocaleInStartUp(locale.c_str());
return text_direction == base::i18n::RIGHT_TO_LEFT;
}
NSString* GetAppPathForProtocol(const GURL& url) {
NSURL* ns_url = [NSURL
URLWithString:base::SysUTF8ToNSString(url.possibly_invalid_spec())];
base::ScopedCFTypeRef<CFErrorRef> out_err;
base::ScopedCFTypeRef<CFURLRef> openingApp(LSCopyDefaultApplicationURLForURL(
(CFURLRef)ns_url, kLSRolesAll, out_err.InitializeInto()));
if (out_err) {
// likely kLSApplicationNotFoundErr
return nullptr;
}
NSString* app_path = [base::mac::CFToNSCast(openingApp.get()) path];
return app_path;
}
gfx::Image GetApplicationIconForProtocol(NSString* _Nonnull app_path) {
NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile:app_path];
gfx::Image icon(image);
return icon;
}
std::u16string GetAppDisplayNameForProtocol(NSString* app_path) {
NSString* app_display_name =
[[NSFileManager defaultManager] displayNameAtPath:app_path];
return base::SysNSStringToUTF16(app_display_name);
}
#if !IS_MAS_BUILD()
bool CheckLoginItemStatus(bool* is_hidden) {
base::mac::LoginItemsFileList login_items;
if (!login_items.Initialize())
return false;
base::ScopedCFTypeRef<LSSharedFileListItemRef> item(
login_items.GetLoginItemForMainApp());
if (!item.get())
return false;
if (is_hidden)
*is_hidden = base::mac::IsHiddenLoginItem(item);
return true;
}
#endif
} // namespace
v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol(
v8::Isolate* isolate,
const GURL& url) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
NSString* ns_app_path = GetAppPathForProtocol(url);
if (!ns_app_path) {
promise.RejectWithErrorMessage(
"Unable to retrieve installation path to app");
return handle;
}
std::u16string app_path = base::SysNSStringToUTF16(ns_app_path);
std::u16string app_display_name = GetAppDisplayNameForProtocol(ns_app_path);
gfx::Image app_icon = GetApplicationIconForProtocol(ns_app_path);
dict.Set("name", app_display_name);
dict.Set("path", app_path);
dict.Set("icon", app_icon);
promise.Resolve(dict);
return handle;
}
void Browser::SetShutdownHandler(base::RepeatingCallback<bool()> handler) {
[[AtomApplication sharedApplication] setShutdownHandler:std::move(handler)];
}
void Browser::Focus(gin::Arguments* args) {
gin_helper::Dictionary opts;
bool steal_focus = false;
if (args->GetNext(&opts)) {
gin_helper::ErrorThrower thrower(args->isolate());
if (!opts.Get("steal", &steal_focus)) {
thrower.ThrowError(
"Expected options object to contain a 'steal' boolean property");
return;
}
}
[[AtomApplication sharedApplication] activateIgnoringOtherApps:steal_focus];
}
void Browser::Hide() {
[[AtomApplication sharedApplication] hide:nil];
}
bool Browser::IsHidden() {
return [[AtomApplication sharedApplication] isHidden];
}
void Browser::Show() {
[[AtomApplication sharedApplication] unhide:nil];
}
void Browser::AddRecentDocument(const base::FilePath& path) {
NSString* path_string = base::mac::FilePathToNSString(path);
if (!path_string)
return;
NSURL* u = [NSURL fileURLWithPath:path_string];
if (!u)
return;
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:u];
}
void Browser::ClearRecentDocuments() {
[[NSDocumentController sharedDocumentController] clearRecentDocuments:nil];
}
bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
if (!Browser::IsDefaultProtocolClient(protocol, args))
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
CFStringRef protocol_cf = base::mac::NSToCFCast(protocol_ns);
CFArrayRef bundleList = LSCopyAllHandlersForURLScheme(protocol_cf);
if (!bundleList) {
return false;
}
// On macOS, we can't query the default, but the handlers list seems to put
// Apple's defaults first, so we'll use the first option that isn't our bundle
CFStringRef other = nil;
for (CFIndex i = 0; i < CFArrayGetCount(bundleList); ++i) {
other =
base::mac::CFCast<CFStringRef>(CFArrayGetValueAtIndex(bundleList, i));
if (![identifier isEqualToString:(__bridge NSString*)other]) {
break;
}
}
// No other app was found set it to none instead of setting it back to itself.
if ([identifier isEqualToString:(__bridge NSString*)other]) {
other = base::mac::NSToCFCast(@"None");
}
OSStatus return_code = LSSetDefaultHandlerForURLScheme(protocol_cf, other);
return return_code == noErr;
}
bool Browser::SetAsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
OSStatus return_code = LSSetDefaultHandlerForURLScheme(
base::mac::NSToCFCast(protocol_ns), base::mac::NSToCFCast(identifier));
return return_code == noErr;
}
bool Browser::IsDefaultProtocolClient(const std::string& protocol,
gin::Arguments* args) {
if (protocol.empty())
return false;
NSString* identifier = [base::apple::MainBundle() bundleIdentifier];
if (!identifier)
return false;
NSString* protocol_ns = [NSString stringWithUTF8String:protocol.c_str()];
base::ScopedCFTypeRef<CFStringRef> bundleId(
LSCopyDefaultHandlerForURLScheme(base::mac::NSToCFCast(protocol_ns)));
if (!bundleId)
return false;
// Ensure the comparison is case-insensitive
// as LS does not persist the case of the bundle id.
NSComparisonResult result =
[base::mac::CFToNSCast(bundleId) caseInsensitiveCompare:identifier];
return result == NSOrderedSame;
}
std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) {
NSString* app_path = GetAppPathForProtocol(url);
if (!app_path) {
return std::u16string();
}
std::u16string app_display_name = GetAppDisplayNameForProtocol(app_path);
return app_display_name;
}
bool Browser::SetBadgeCount(absl::optional<int> count) {
DockSetBadgeText(!count.has_value() || count.value() != 0
? badging::BadgeManager::GetBadgeString(count)
: "");
if (count.has_value()) {
badge_count_ = count.value();
} else {
badge_count_ = 0;
}
return true;
}
void Browser::SetUserActivity(const std::string& type,
base::Value::Dict user_info,
gin::Arguments* args) {
std::string url_string;
args->GetNext(&url_string);
[[AtomApplication sharedApplication]
setCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(std::move(user_info))
withWebpageURL:net::NSURLWithGURL(GURL(url_string))];
}
std::string Browser::GetCurrentActivityType() {
NSUserActivity* userActivity =
[[AtomApplication sharedApplication] getCurrentActivity];
return base::SysNSStringToUTF8(userActivity.activityType);
}
void Browser::InvalidateCurrentActivity() {
[[AtomApplication sharedApplication] invalidateCurrentActivity];
}
void Browser::ResignCurrentActivity() {
[[AtomApplication sharedApplication] resignCurrentActivity];
}
void Browser::UpdateCurrentActivity(const std::string& type,
base::Value::Dict user_info) {
[[AtomApplication sharedApplication]
updateCurrentActivity:base::SysUTF8ToNSString(type)
withUserInfo:DictionaryValueToNSDictionary(
std::move(user_info))];
}
bool Browser::WillContinueUserActivity(const std::string& type) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnWillContinueUserActivity(&prevent_default, type);
return prevent_default;
}
void Browser::DidFailToContinueUserActivity(const std::string& type,
const std::string& error) {
for (BrowserObserver& observer : observers_)
observer.OnDidFailToContinueUserActivity(type, error);
}
bool Browser::ContinueUserActivity(const std::string& type,
base::Value::Dict user_info,
base::Value::Dict details) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnContinueUserActivity(&prevent_default, type, user_info.Clone(),
details.Clone());
return prevent_default;
}
void Browser::UserActivityWasContinued(const std::string& type,
base::Value::Dict user_info) {
for (BrowserObserver& observer : observers_)
observer.OnUserActivityWasContinued(type, user_info.Clone());
}
bool Browser::UpdateUserActivityState(const std::string& type,
base::Value::Dict user_info) {
bool prevent_default = false;
for (BrowserObserver& observer : observers_)
observer.OnUpdateUserActivityState(&prevent_default, type,
user_info.Clone());
return prevent_default;
}
// Modified from chrome/browser/ui/cocoa/l10n_util.mm.
void Browser::ApplyForcedRTL() {
NSUserDefaults* defaults = NSUserDefaults.standardUserDefaults;
auto dir = base::i18n::GetForcedTextDirection();
// An Electron app should respect RTL behavior of application locale over
// system locale.
auto should_be_rtl = dir == base::i18n::RIGHT_TO_LEFT || IsAppRTL();
auto should_be_ltr = dir == base::i18n::LEFT_TO_RIGHT || !IsAppRTL();
// -registerDefaults: won't do the trick here because these defaults exist
// (in the global domain) to reflect the system locale. They need to be set
// in Chrome's domain to supersede the system value.
if (should_be_rtl) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:YES forKey:@"NSForceRightToLeftWritingDirection"];
} else if (should_be_ltr) {
[defaults setBool:YES forKey:@"AppleTextDirection"];
[defaults setBool:NO forKey:@"NSForceRightToLeftWritingDirection"];
} else {
[defaults removeObjectForKey:@"AppleTextDirection"];
[defaults removeObjectForKey:@"NSForceRightToLeftWritingDirection"];
}
}
Browser::LoginItemSettings Browser::GetLoginItemSettings(
const LoginItemSettings& options) {
LoginItemSettings settings;
#if IS_MAS_BUILD()
settings.open_at_login = platform_util::GetLoginItemEnabled();
#else
settings.open_at_login = CheckLoginItemStatus(&settings.open_as_hidden);
settings.restore_state = base::mac::WasLaunchedAsLoginItemRestoreState();
settings.opened_at_login = base::mac::WasLaunchedAsLoginOrResumeItem();
settings.opened_as_hidden = base::mac::WasLaunchedAsHiddenLoginItem();
#endif
return settings;
}
void Browser::SetLoginItemSettings(LoginItemSettings settings) {
#if IS_MAS_BUILD()
if (!platform_util::SetLoginItemEnabled(settings.open_at_login)) {
LOG(ERROR) << "Unable to set login item enabled on sandboxed app.";
}
#else
if (settings.open_at_login) {
base::mac::AddToLoginItems(base::apple::MainBundlePath(),
settings.open_as_hidden);
} else {
base::mac::RemoveFromLoginItems(base::apple::MainBundlePath());
}
#endif
}
std::string Browser::GetExecutableFileVersion() const {
return GetApplicationVersion();
}
std::string Browser::GetExecutableFileProductName() const {
return GetApplicationName();
}
int Browser::DockBounce(BounceType type) {
return [[AtomApplication sharedApplication]
requestUserAttention:static_cast<NSRequestUserAttentionType>(type)];
}
void Browser::DockCancelBounce(int request_id) {
[[AtomApplication sharedApplication] cancelUserAttentionRequest:request_id];
}
void Browser::DockSetBadgeText(const std::string& label) {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
[tile setBadgeLabel:base::SysUTF8ToNSString(label)];
}
void Browser::DockDownloadFinished(const std::string& filePath) {
[[NSDistributedNotificationCenter defaultCenter]
postNotificationName:@"com.apple.DownloadFileFinished"
object:base::SysUTF8ToNSString(filePath)];
}
std::string Browser::DockGetBadgeText() {
NSDockTile* tile = [[AtomApplication sharedApplication] dockTile];
return base::SysNSStringToUTF8([tile badgeLabel]);
}
void Browser::DockHide() {
// Transforming application state from UIElement to Foreground is an
// asynchronous operation, and unfortunately there is currently no way to know
// when it is finished.
// So if we call DockHide => DockShow => DockHide => DockShow in a very short
// time, we would trigger a bug of macOS that, there would be multiple dock
// icons of the app left in system.
// To work around this, we make sure DockHide does nothing if it is called
// immediately after DockShow. After some experiments, 1 second seems to be
// a proper interval.
if (!last_dock_show_.is_null() &&
base::Time::Now() - last_dock_show_ < base::Seconds(1)) {
return;
}
for (auto* const& window : WindowList::GetWindows())
[window->GetNativeWindow().GetNativeNSWindow() setCanHide:NO];
ProcessSerialNumber psn = {0, kCurrentProcess};
TransformProcessType(&psn, kProcessTransformToUIElementApplication);
}
bool Browser::DockIsVisible() {
// Because DockShow has a slight delay this may not be true immediately
// after that call.
return ([[NSRunningApplication currentApplication] activationPolicy] ==
NSApplicationActivationPolicyRegular);
}
v8::Local<v8::Promise> Browser::DockShow(v8::Isolate* isolate) {
last_dock_show_ = base::Time::Now();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
BOOL active = [[NSRunningApplication currentApplication] isActive];
ProcessSerialNumber psn = {0, kCurrentProcess};
if (active) {
// Workaround buggy behavior of TransformProcessType.
// http://stackoverflow.com/questions/7596643/
NSArray* runningApps = [NSRunningApplication
runningApplicationsWithBundleIdentifier:@"com.apple.dock"];
for (NSRunningApplication* app in runningApps) {
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
break;
}
__block gin_helper::Promise<void> p = std::move(promise);
dispatch_time_t one_ms = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms, dispatch_get_main_queue(), ^{
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
dispatch_time_t one_ms_2 = dispatch_time(DISPATCH_TIME_NOW, USEC_PER_SEC);
dispatch_after(one_ms_2, dispatch_get_main_queue(), ^{
[[NSRunningApplication currentApplication]
activateWithOptions:NSApplicationActivateIgnoringOtherApps];
p.Resolve();
});
});
} else {
TransformProcessType(&psn, kProcessTransformToForegroundApplication);
promise.Resolve();
}
return handle;
}
void Browser::DockSetMenu(ElectronMenuModel* model) {
ElectronApplicationDelegate* delegate =
(ElectronApplicationDelegate*)[NSApp delegate];
[delegate setApplicationDockMenu:model];
}
void Browser::DockSetIcon(v8::Isolate* isolate, v8::Local<v8::Value> icon) {
gfx::Image image;
if (!icon->IsNull()) {
api::NativeImage* native_image = nullptr;
if (!api::NativeImage::TryConvertNativeImage(isolate, icon, &native_image))
return;
image = native_image->image();
}
DockSetIconImage(image);
}
void Browser::DockSetIconImage(gfx::Image const& image) {
if (!is_ready_) {
dock_icon_ = image;
return;
}
[[AtomApplication sharedApplication]
setApplicationIconImage:image.AsNSImage()];
}
void Browser::ShowAboutPanel() {
NSDictionary* options = DictionaryValueToNSDictionary(about_panel_options_);
// Credits must be a NSAttributedString instead of NSString
NSString* credits = (NSString*)options[@"Credits"];
if (credits != nil) {
base::scoped_nsobject<NSMutableDictionary> mutable_options(
[options mutableCopy]);
base::scoped_nsobject<NSAttributedString> creditString(
[[NSAttributedString alloc]
initWithString:credits
attributes:@{
NSForegroundColorAttributeName : [NSColor textColor]
}]);
[mutable_options setValue:creditString forKey:@"Credits"];
options = [NSDictionary dictionaryWithDictionary:mutable_options];
}
[[AtomApplication sharedApplication]
orderFrontStandardAboutPanelWithOptions:options];
}
void Browser::SetAboutPanelOptions(base::Value::Dict options) {
about_panel_options_.clear();
for (const auto pair : options) {
std::string key = pair.first;
if (!key.empty() && pair.second.is_string()) {
key[0] = base::ToUpperASCII(key[0]);
about_panel_options_.Set(key, pair.second.Clone());
}
}
}
void Browser::ShowEmojiPanel() {
[[AtomApplication sharedApplication] orderFrontCharacterPalette:nil];
}
bool Browser::IsEmojiPanelSupported() {
return true;
}
bool Browser::IsSecureKeyboardEntryEnabled() {
return password_input_enabler_.get() != nullptr;
}
void Browser::SetSecureKeyboardEntryEnabled(bool enabled) {
if (enabled) {
password_input_enabler_ =
std::make_unique<ui::ScopedPasswordInputEnabler>();
} else {
password_input_enabler_.reset();
}
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,592 |
[Bug]: crash when resizing `nativeImage` before app is ready
|
### Preflight Checklist
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
25.0.0
### What operating system are you using?
Ubuntu
### Operating System Version
22.04.2
### What arch are you using?
x64
### Last Known Working Electron version
24.4.0
### Expected Behavior
Electron should start.
### Actual Behavior
Electron doesn't start.
### Testcase Gist URL
_No response_
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/38592
|
https://github.com/electron/electron/pull/38836
|
2b3902e526d57a37c68f8f7c5dd370358c5c06f7
|
f6bbc3465888a113db91e16647e54a2aa4650606
| 2023-06-05T13:27:11Z |
c++
| 2023-06-20T16:24:03Z |
shell/common/api/electron_api_native_image.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/common/api/electron_api_native_image.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/pattern.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "gin/arguments.h"
#include "gin/object_template_builder.h"
#include "gin/per_isolate_data.h"
#include "gin/wrappable.h"
#include "net/base/data_url.h"
#include "shell/common/asar/asar_util.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gfx_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/function_template_extensions.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/skia_util.h"
#include "shell/common/thread_restrictions.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "ui/base/layout.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/gfx/codec/jpeg_codec.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/gfx/image/image_util.h"
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "shell/common/asar/archive.h"
#include "ui/gfx/icon_util.h"
#endif
namespace electron::api {
namespace {
// Get the scale factor from options object at the first argument
float GetScaleFactorFromOptions(gin::Arguments* args) {
float scale_factor = 1.0f;
gin_helper::Dictionary options;
if (args->GetNext(&options))
options.Get("scaleFactor", &scale_factor);
return scale_factor;
}
base::FilePath NormalizePath(const base::FilePath& path) {
if (!path.ReferencesParent()) {
return path;
}
ScopedAllowBlockingForElectron allow_blocking;
base::FilePath absolute_path = MakeAbsoluteFilePath(path);
// MakeAbsoluteFilePath returns an empty path on failures so use original path
if (absolute_path.empty()) {
return path;
} else {
return absolute_path;
}
}
#if BUILDFLAG(IS_MAC)
bool IsTemplateFilename(const base::FilePath& path) {
return (base::MatchPattern(path.value(), "*Template.*") ||
base::MatchPattern(path.value(), "*Template@*x.*"));
}
#endif
#if BUILDFLAG(IS_WIN)
base::win::ScopedHICON ReadICOFromPath(int size, const base::FilePath& path) {
// If file is in asar archive, we extract it to a temp file so LoadImage can
// load it.
base::FilePath asar_path, relative_path;
base::FilePath image_path(path);
if (asar::GetAsarArchivePath(image_path, &asar_path, &relative_path)) {
std::shared_ptr<asar::Archive> archive =
asar::GetOrCreateAsarArchive(asar_path);
if (archive)
archive->CopyFileOut(relative_path, &image_path);
}
// Load the icon from file.
return base::win::ScopedHICON(
static_cast<HICON>(LoadImage(NULL, image_path.value().c_str(), IMAGE_ICON,
size, size, LR_LOADFROMFILE)));
}
#endif
} // namespace
NativeImage::NativeImage(v8::Isolate* isolate, const gfx::Image& image)
: image_(image), isolate_(isolate) {
UpdateExternalAllocatedMemoryUsage();
}
#if BUILDFLAG(IS_WIN)
NativeImage::NativeImage(v8::Isolate* isolate, const base::FilePath& hicon_path)
: hicon_path_(hicon_path), isolate_(isolate) {
// Use the 256x256 icon as fallback icon.
gfx::ImageSkia image_skia;
electron::util::ReadImageSkiaFromICO(&image_skia, GetHICON(256));
image_ = gfx::Image(image_skia);
UpdateExternalAllocatedMemoryUsage();
}
#endif
NativeImage::~NativeImage() {
isolate_->AdjustAmountOfExternalAllocatedMemory(-memory_usage_);
}
void NativeImage::UpdateExternalAllocatedMemoryUsage() {
int32_t new_memory_usage = 0;
if (image_.HasRepresentation(gfx::Image::kImageRepSkia)) {
auto* const image_skia = image_.ToImageSkia();
if (!image_skia->isNull()) {
new_memory_usage = image_skia->bitmap()->computeByteSize();
}
}
isolate_->AdjustAmountOfExternalAllocatedMemory(new_memory_usage -
memory_usage_);
memory_usage_ = new_memory_usage;
}
// static
bool NativeImage::TryConvertNativeImage(v8::Isolate* isolate,
v8::Local<v8::Value> image,
NativeImage** native_image,
OnConvertError on_error) {
std::string error_message;
base::FilePath icon_path;
if (gin::ConvertFromV8(isolate, image, &icon_path)) {
*native_image = NativeImage::CreateFromPath(isolate, icon_path).get();
if ((*native_image)->image().IsEmpty()) {
#if BUILDFLAG(IS_WIN)
const auto img_path = base::WideToUTF8(icon_path.value());
#else
const auto img_path = icon_path.value();
#endif
error_message = "Failed to load image from path '" + img_path + "'";
}
} else {
if (!gin::ConvertFromV8(isolate, image, native_image)) {
error_message = "Argument must be a file path or a NativeImage";
}
}
if (!error_message.empty()) {
switch (on_error) {
case OnConvertError::kThrow:
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, error_message)));
break;
case OnConvertError::kWarn:
LOG(WARNING) << error_message;
break;
}
return false;
}
return true;
}
#if BUILDFLAG(IS_WIN)
HICON NativeImage::GetHICON(int size) {
auto iter = hicons_.find(size);
if (iter != hicons_.end())
return iter->second.get();
// First try loading the icon with specified size.
if (!hicon_path_.empty()) {
hicons_[size] = ReadICOFromPath(size, hicon_path_);
return hicons_[size].get();
}
// Then convert the image to ICO.
if (image_.IsEmpty())
return NULL;
hicons_[size] = IconUtil::CreateHICONFromSkBitmap(image_.AsBitmap());
return hicons_[size].get();
}
#endif
v8::Local<v8::Value> NativeImage::ToPNG(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
if (scale_factor == 1.0f) {
// Use raw 1x PNG bytes when available
scoped_refptr<base::RefCountedMemory> png = image_.As1xPNGBytes();
if (png->size() > 0) {
const char* data = reinterpret_cast<const char*>(png->front());
size_t size = png->size();
return node::Buffer::Copy(args->isolate(), data, size).ToLocalChecked();
}
}
const SkBitmap bitmap =
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap();
std::vector<unsigned char> encoded;
gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &encoded);
const char* data = reinterpret_cast<char*>(encoded.data());
size_t size = encoded.size();
return node::Buffer::Copy(args->isolate(), data, size).ToLocalChecked();
}
v8::Local<v8::Value> NativeImage::ToBitmap(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
const SkBitmap bitmap =
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap();
SkImageInfo info =
SkImageInfo::MakeN32Premul(bitmap.width(), bitmap.height());
auto array_buffer =
v8::ArrayBuffer::New(args->isolate(), info.computeMinByteSize());
auto backing_store = array_buffer->GetBackingStore();
if (bitmap.readPixels(info, backing_store->Data(), info.minRowBytes(), 0,
0)) {
return node::Buffer::New(args->isolate(), array_buffer, 0,
info.computeMinByteSize())
.ToLocalChecked();
}
return node::Buffer::New(args->isolate(), 0).ToLocalChecked();
}
v8::Local<v8::Value> NativeImage::ToJPEG(v8::Isolate* isolate, int quality) {
std::vector<unsigned char> output;
gfx::JPEG1xEncodedDataFromImage(image_, quality, &output);
if (output.empty())
return node::Buffer::New(isolate, 0).ToLocalChecked();
return node::Buffer::Copy(isolate,
reinterpret_cast<const char*>(&output.front()),
output.size())
.ToLocalChecked();
}
std::string NativeImage::ToDataURL(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
if (scale_factor == 1.0f) {
// Use raw 1x PNG bytes when available
scoped_refptr<base::RefCountedMemory> png = image_.As1xPNGBytes();
if (png->size() > 0)
return webui::GetPngDataUrl(png->front(), png->size());
}
return webui::GetBitmapDataUrl(
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap());
}
v8::Local<v8::Value> NativeImage::GetBitmap(gin::Arguments* args) {
float scale_factor = GetScaleFactorFromOptions(args);
const SkBitmap bitmap =
image_.AsImageSkia().GetRepresentation(scale_factor).GetBitmap();
SkPixelRef* ref = bitmap.pixelRef();
if (!ref)
return node::Buffer::New(args->isolate(), 0).ToLocalChecked();
return node::Buffer::Copy(args->isolate(),
reinterpret_cast<char*>(ref->pixels()),
bitmap.computeByteSize())
.ToLocalChecked();
}
v8::Local<v8::Value> NativeImage::GetNativeHandle(
gin_helper::ErrorThrower thrower) {
#if BUILDFLAG(IS_MAC)
if (IsEmpty())
return node::Buffer::New(thrower.isolate(), 0).ToLocalChecked();
NSImage* ptr = image_.AsNSImage();
return node::Buffer::Copy(thrower.isolate(), reinterpret_cast<char*>(ptr),
sizeof(void*))
.ToLocalChecked();
#else
thrower.ThrowError("Not implemented");
return v8::Undefined(thrower.isolate());
#endif
}
bool NativeImage::IsEmpty() {
return image_.IsEmpty();
}
gfx::Size NativeImage::GetSize(const absl::optional<float> scale_factor) {
float sf = scale_factor.value_or(1.0f);
gfx::ImageSkiaRep image_rep = image_.AsImageSkia().GetRepresentation(sf);
return gfx::Size(image_rep.GetWidth(), image_rep.GetHeight());
}
std::vector<float> NativeImage::GetScaleFactors() {
gfx::ImageSkia image_skia = image_.AsImageSkia();
std::vector<float> scale_factors;
for (const auto& rep : image_skia.image_reps()) {
scale_factors.push_back(rep.scale());
}
return scale_factors;
}
float NativeImage::GetAspectRatio(const absl::optional<float> scale_factor) {
float sf = scale_factor.value_or(1.0f);
gfx::Size size = GetSize(sf);
if (size.IsEmpty())
return 1.f;
else
return static_cast<float>(size.width()) / static_cast<float>(size.height());
}
gin::Handle<NativeImage> NativeImage::Resize(gin::Arguments* args,
base::Value::Dict options) {
float scale_factor = GetScaleFactorFromOptions(args);
gfx::Size size = GetSize(scale_factor);
absl::optional<int> new_width = options.FindInt("width");
absl::optional<int> new_height = options.FindInt("height");
int width = new_width.value_or(size.width());
int height = new_height.value_or(size.height());
size.SetSize(width, height);
if (width <= 0 && height <= 0) {
return CreateEmpty(args->isolate());
} else if (new_width && !new_height) {
// Scale height to preserve original aspect ratio
size.set_height(width);
size =
gfx::ScaleToRoundedSize(size, 1.f, 1.f / GetAspectRatio(scale_factor));
} else if (new_height && !new_width) {
// Scale width to preserve original aspect ratio
size.set_width(height);
size = gfx::ScaleToRoundedSize(size, GetAspectRatio(scale_factor), 1.f);
}
skia::ImageOperations::ResizeMethod method =
skia::ImageOperations::ResizeMethod::RESIZE_BEST;
std::string* quality = options.FindString("quality");
if (quality && *quality == "good")
method = skia::ImageOperations::ResizeMethod::RESIZE_GOOD;
else if (quality && *quality == "better")
method = skia::ImageOperations::ResizeMethod::RESIZE_BETTER;
gfx::ImageSkia resized = gfx::ImageSkiaOperations::CreateResizedImage(
image_.AsImageSkia(), method, size);
return gin::CreateHandle(
args->isolate(), new NativeImage(args->isolate(), gfx::Image(resized)));
}
gin::Handle<NativeImage> NativeImage::Crop(v8::Isolate* isolate,
const gfx::Rect& rect) {
gfx::ImageSkia cropped =
gfx::ImageSkiaOperations::ExtractSubset(image_.AsImageSkia(), rect);
return gin::CreateHandle(isolate,
new NativeImage(isolate, gfx::Image(cropped)));
}
void NativeImage::AddRepresentation(const gin_helper::Dictionary& options) {
int width = 0;
int height = 0;
float scale_factor = 1.0f;
options.Get("width", &width);
options.Get("height", &height);
options.Get("scaleFactor", &scale_factor);
bool skia_rep_added = false;
gfx::ImageSkia image_skia = image_.AsImageSkia();
v8::Local<v8::Value> buffer;
GURL url;
if (options.Get("buffer", &buffer) && node::Buffer::HasInstance(buffer)) {
auto* data = reinterpret_cast<unsigned char*>(node::Buffer::Data(buffer));
auto size = node::Buffer::Length(buffer);
skia_rep_added = electron::util::AddImageSkiaRepFromBuffer(
&image_skia, data, size, width, height, scale_factor);
} else if (options.Get("dataURL", &url)) {
std::string mime_type, charset, data;
if (net::DataURL::Parse(url, &mime_type, &charset, &data)) {
auto* data_ptr = reinterpret_cast<const unsigned char*>(data.c_str());
if (mime_type == "image/png") {
skia_rep_added = electron::util::AddImageSkiaRepFromPNG(
&image_skia, data_ptr, data.size(), scale_factor);
} else if (mime_type == "image/jpeg") {
skia_rep_added = electron::util::AddImageSkiaRepFromJPEG(
&image_skia, data_ptr, data.size(), scale_factor);
}
}
}
// Re-initialize image when first representation is added to an empty image
if (skia_rep_added && IsEmpty()) {
gfx::Image image(image_skia);
image_ = std::move(image);
}
}
#if !BUILDFLAG(IS_MAC)
void NativeImage::SetTemplateImage(bool setAsTemplate) {}
bool NativeImage::IsTemplateImage() {
return false;
}
#endif
// static
gin::Handle<NativeImage> NativeImage::CreateEmpty(v8::Isolate* isolate) {
return gin::CreateHandle(isolate, new NativeImage(isolate, gfx::Image()));
}
// static
gin::Handle<NativeImage> NativeImage::Create(v8::Isolate* isolate,
const gfx::Image& image) {
return gin::CreateHandle(isolate, new NativeImage(isolate, image));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromPNG(v8::Isolate* isolate,
const char* buffer,
size_t length) {
gfx::ImageSkia image_skia;
electron::util::AddImageSkiaRepFromPNG(
&image_skia, reinterpret_cast<const unsigned char*>(buffer), length, 1.0);
return Create(isolate, gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromJPEG(v8::Isolate* isolate,
const char* buffer,
size_t length) {
gfx::ImageSkia image_skia;
electron::util::AddImageSkiaRepFromJPEG(
&image_skia, reinterpret_cast<const unsigned char*>(buffer), length, 1.0);
return Create(isolate, gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromPath(
v8::Isolate* isolate,
const base::FilePath& path) {
base::FilePath image_path = NormalizePath(path);
#if BUILDFLAG(IS_WIN)
if (image_path.MatchesExtension(FILE_PATH_LITERAL(".ico"))) {
return gin::CreateHandle(isolate, new NativeImage(isolate, image_path));
}
#endif
gfx::ImageSkia image_skia;
electron::util::PopulateImageSkiaRepsFromPath(&image_skia, image_path);
gfx::Image image(image_skia);
gin::Handle<NativeImage> handle = Create(isolate, image);
#if BUILDFLAG(IS_MAC)
if (IsTemplateFilename(image_path))
handle->SetTemplateImage(true);
#endif
return handle;
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromBitmap(
gin_helper::ErrorThrower thrower,
v8::Local<v8::Value> buffer,
const gin_helper::Dictionary& options) {
if (!node::Buffer::HasInstance(buffer)) {
thrower.ThrowError("buffer must be a node Buffer");
return gin::Handle<NativeImage>();
}
unsigned int width = 0;
unsigned int height = 0;
double scale_factor = 1.;
if (!options.Get("width", &width)) {
thrower.ThrowError("width is required");
return gin::Handle<NativeImage>();
}
if (!options.Get("height", &height)) {
thrower.ThrowError("height is required");
return gin::Handle<NativeImage>();
}
auto info = SkImageInfo::MakeN32(width, height, kPremul_SkAlphaType);
auto size_bytes = info.computeMinByteSize();
if (size_bytes != node::Buffer::Length(buffer)) {
thrower.ThrowError("invalid buffer size");
return gin::Handle<NativeImage>();
}
options.Get("scaleFactor", &scale_factor);
if (width == 0 || height == 0) {
return CreateEmpty(thrower.isolate());
}
SkBitmap bitmap;
bitmap.allocN32Pixels(width, height, false);
bitmap.writePixels({info, node::Buffer::Data(buffer), bitmap.rowBytes()});
gfx::ImageSkia image_skia =
gfx::ImageSkia::CreateFromBitmap(bitmap, scale_factor);
return Create(thrower.isolate(), gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromBuffer(
gin_helper::ErrorThrower thrower,
v8::Local<v8::Value> buffer,
gin::Arguments* args) {
if (!node::Buffer::HasInstance(buffer)) {
thrower.ThrowError("buffer must be a node Buffer");
return gin::Handle<NativeImage>();
}
int width = 0;
int height = 0;
double scale_factor = 1.;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("width", &width);
options.Get("height", &height);
options.Get("scaleFactor", &scale_factor);
}
gfx::ImageSkia image_skia;
electron::util::AddImageSkiaRepFromBuffer(
&image_skia, reinterpret_cast<unsigned char*>(node::Buffer::Data(buffer)),
node::Buffer::Length(buffer), width, height, scale_factor);
return Create(args->isolate(), gfx::Image(image_skia));
}
// static
gin::Handle<NativeImage> NativeImage::CreateFromDataURL(v8::Isolate* isolate,
const GURL& url) {
std::string mime_type, charset, data;
if (net::DataURL::Parse(url, &mime_type, &charset, &data)) {
if (mime_type == "image/png")
return CreateFromPNG(isolate, data.c_str(), data.size());
else if (mime_type == "image/jpeg")
return CreateFromJPEG(isolate, data.c_str(), data.size());
}
return CreateEmpty(isolate);
}
#if !BUILDFLAG(IS_MAC)
gin::Handle<NativeImage> NativeImage::CreateFromNamedImage(gin::Arguments* args,
std::string name) {
return CreateEmpty(args->isolate());
}
#endif
// static
gin::ObjectTemplateBuilder NativeImage::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
gin::PerIsolateData* data = gin::PerIsolateData::From(isolate);
auto* wrapper_info = &kWrapperInfo;
v8::Local<v8::FunctionTemplate> constructor =
data->GetFunctionTemplate(wrapper_info);
if (constructor.IsEmpty()) {
constructor = v8::FunctionTemplate::New(isolate);
constructor->SetClassName(gin::StringToV8(isolate, GetTypeName()));
data->SetFunctionTemplate(wrapper_info, constructor);
}
return gin::ObjectTemplateBuilder(isolate, GetTypeName(),
constructor->InstanceTemplate())
.SetMethod("toPNG", &NativeImage::ToPNG)
.SetMethod("toJPEG", &NativeImage::ToJPEG)
.SetMethod("toBitmap", &NativeImage::ToBitmap)
.SetMethod("getBitmap", &NativeImage::GetBitmap)
.SetMethod("getScaleFactors", &NativeImage::GetScaleFactors)
.SetMethod("getNativeHandle", &NativeImage::GetNativeHandle)
.SetMethod("toDataURL", &NativeImage::ToDataURL)
.SetMethod("isEmpty", &NativeImage::IsEmpty)
.SetMethod("getSize", &NativeImage::GetSize)
.SetMethod("setTemplateImage", &NativeImage::SetTemplateImage)
.SetMethod("isTemplateImage", &NativeImage::IsTemplateImage)
.SetProperty("isMacTemplateImage", &NativeImage::IsTemplateImage,
&NativeImage::SetTemplateImage)
.SetMethod("resize", &NativeImage::Resize)
.SetMethod("crop", &NativeImage::Crop)
.SetMethod("getAspectRatio", &NativeImage::GetAspectRatio)
.SetMethod("addRepresentation", &NativeImage::AddRepresentation);
}
const char* NativeImage::GetTypeName() {
return "NativeImage";
}
// static
gin::WrapperInfo NativeImage::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::NativeImage;
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);
gin_helper::Dictionary native_image = gin::Dictionary::CreateEmpty(isolate);
dict.Set("nativeImage", native_image);
native_image.SetMethod("createEmpty", &NativeImage::CreateEmpty);
native_image.SetMethod("createFromPath", &NativeImage::CreateFromPath);
native_image.SetMethod("createFromBitmap", &NativeImage::CreateFromBitmap);
native_image.SetMethod("createFromBuffer", &NativeImage::CreateFromBuffer);
native_image.SetMethod("createFromDataURL", &NativeImage::CreateFromDataURL);
native_image.SetMethod("createFromNamedImage",
&NativeImage::CreateFromNamedImage);
#if !BUILDFLAG(IS_LINUX)
native_image.SetMethod("createThumbnailFromPath",
&NativeImage::CreateThumbnailFromPath);
#endif
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_common_native_image, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
docs/api/session.md
|
# session
> Manage browser sessions, cookies, cache, proxy settings, etc.
Process: [Main](../glossary.md#main-process)
The `session` module can be used to create new `Session` objects.
You can also access the `session` of existing pages by using the `session`
property of [`WebContents`](web-contents.md), or from the `session` module.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com')
const ses = win.webContents.session
console.log(ses.getUserAgent())
```
## Methods
The `session` module has the following methods:
### `session.fromPartition(partition[, options])`
* `partition` string
* `options` Object (optional)
* `cache` boolean - Whether to enable cache.
Returns `Session` - A session instance from `partition` string. When there is an existing
`Session` with the same `partition`, it will be returned; otherwise a new
`Session` instance will be created with `options`.
If `partition` starts with `persist:`, the page will use a persistent session
available to all pages in the app with the same `partition`. if there is no
`persist:` prefix, the page will use an in-memory session. If the `partition` is
empty then default session of the app will be returned.
To create a `Session` with `options`, you have to ensure the `Session` with the
`partition` has never been used before. There is no way to change the `options`
of an existing `Session` object.
### `session.fromPath(path[, options])`
* `path` string
* `options` Object (optional)
* `cache` boolean - Whether to enable cache.
Returns `Session` - A session instance from the absolute path as specified by the `path`
string. When there is an existing `Session` with the same absolute path, it
will be returned; otherwise a new `Session` instance will be created with `options`. The
call will throw an error if the path is not an absolute path. Additionally, an error will
be thrown if an empty string is provided.
To create a `Session` with `options`, you have to ensure the `Session` with the
`path` has never been used before. There is no way to change the `options`
of an existing `Session` object.
## Properties
The `session` module has the following properties:
### `session.defaultSession`
A `Session` object, the default session object of the app.
## Class: Session
> Get and set properties of a session.
Process: [Main](../glossary.md#main-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
You can create a `Session` object in the `session` module:
```javascript
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
```
### Instance Events
The following events are available on instances of `Session`:
#### Event: 'will-download'
Returns:
* `event` Event
* `item` [DownloadItem](download-item.md)
* `webContents` [WebContents](web-contents.md)
Emitted when Electron is about to download `item` in `webContents`.
Calling `event.preventDefault()` will cancel the download and `item` will not be
available from next tick of the process.
```javascript @ts-expect-error=[4]
const { session } = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault()
require('got')(item.getURL()).then((response) => {
require('fs').writeFileSync('/somewhere', response.body)
})
})
```
#### Event: 'extension-loaded'
Returns:
* `event` Event
* `extension` [Extension](structures/extension.md)
Emitted after an extension is loaded. This occurs whenever an extension is
added to the "enabled" set of extensions. This includes:
* Extensions being loaded from `Session.loadExtension`.
* Extensions being reloaded:
* from a crash.
* if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)).
#### Event: 'extension-unloaded'
Returns:
* `event` Event
* `extension` [Extension](structures/extension.md)
Emitted after an extension is unloaded. This occurs when
`Session.removeExtension` is called.
#### Event: 'extension-ready'
Returns:
* `event` Event
* `extension` [Extension](structures/extension.md)
Emitted after an extension is loaded and all necessary browser state is
initialized to support the start of the extension's background page.
#### Event: 'preconnect'
Returns:
* `event` Event
* `preconnectUrl` string - The URL being requested for preconnection by the
renderer.
* `allowCredentials` boolean - True if the renderer is requesting that the
connection include credentials (see the
[spec](https://w3c.github.io/resource-hints/#preconnect) for more details.)
Emitted when a render process requests preconnection to a URL, generally due to
a [resource hint](https://w3c.github.io/resource-hints/).
#### Event: 'spellcheck-dictionary-initialized'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file has been successfully initialized. This
occurs after the file has been downloaded.
#### Event: 'spellcheck-dictionary-download-begin'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file starts downloading
#### Event: 'spellcheck-dictionary-download-success'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file has been successfully downloaded
#### Event: 'spellcheck-dictionary-download-failure'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file download fails. For details
on the failure you should collect a netlog and inspect the download
request.
#### Event: 'select-hid-device'
Returns:
* `event` Event
* `details` Object
* `deviceList` [HIDDevice[]](structures/hid-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
* `callback` Function
* `deviceId` string | null (optional)
Emitted when a HID device needs to be selected when a call to
`navigator.hid.requestDevice` is made. `callback` should be called with
`deviceId` to be selected; passing no arguments to `callback` will
cancel the request. Additionally, permissioning on `navigator.hid` can
be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler)
and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'hid') {
// Add logic here to determine if permission should be given to allow HID selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})
```
#### Event: 'hid-device-added'
Returns:
* `event` Event
* `details` Object
* `device` [HIDDevice[]](structures/hid-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
Emitted after `navigator.hid.requestDevice` has been called and
`select-hid-device` has fired if a new device becomes available before
the callback from `select-hid-device` is called. This event is intended for
use when using a UI to ask users to pick a device so that the UI can be updated
with the newly added device.
#### Event: 'hid-device-removed'
Returns:
* `event` Event
* `details` Object
* `device` [HIDDevice[]](structures/hid-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
Emitted after `navigator.hid.requestDevice` has been called and
`select-hid-device` has fired if a device has been removed before the callback
from `select-hid-device` is called. This event is intended for use when using
a UI to ask users to pick a device so that the UI can be updated to remove the
specified device.
#### Event: 'hid-device-revoked'
Returns:
* `event` Event
* `details` Object
* `device` [HIDDevice[]](structures/hid-device.md)
* `origin` string (optional) - The origin that the device has been revoked from.
Emitted after `HIDDevice.forget()` has been called. This event can be used
to help maintain persistent storage of permissions when
`setDevicePermissionHandler` is used.
#### Event: 'select-serial-port'
Returns:
* `event` Event
* `portList` [SerialPort[]](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)
* `callback` Function
* `portId` string
Emitted when a serial port needs to be selected when a call to
`navigator.serial.requestPort` is made. `callback` should be called with
`portId` to be selected, passing an empty string to `callback` will
cancel the request. Additionally, permissioning on `navigator.serial` can
be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler)
with the `serial` permission.
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({
width: 800,
height: 600
})
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
event.preventDefault()
const selectedPort = portList.find((device) => {
return device.vendorId === '9025' && device.productId === '67'
})
if (!selectedPort) {
callback('')
} else {
callback(selectedPort.portId)
}
})
})
```
#### Event: 'serial-port-added'
Returns:
* `event` Event
* `port` [SerialPort](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.serial.requestPort` has been called and
`select-serial-port` has fired if a new serial port becomes available before
the callback from `select-serial-port` is called. This event is intended for
use when using a UI to ask users to pick a port so that the UI can be updated
with the newly added port.
#### Event: 'serial-port-removed'
Returns:
* `event` Event
* `port` [SerialPort](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.serial.requestPort` has been called and
`select-serial-port` has fired if a serial port has been removed before the
callback from `select-serial-port` is called. This event is intended for use
when using a UI to ask users to pick a port so that the UI can be updated
to remove the specified port.
#### Event: 'serial-port-revoked'
Returns:
* `event` Event
* `details` Object
* `port` [SerialPort](structures/serial-port.md)
* `frame` [WebFrameMain](web-frame-main.md)
* `origin` string - The origin that the device has been revoked from.
Emitted after `SerialPort.forget()` has been called. This event can be used
to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used.
```js
// Browser Process
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.webContents.session.on('serial-port-revoked', (event, details) => {
console.log(`Access revoked for serial device from origin ${details.origin}`)
})
})
```
```js
// Renderer Process
const portConnect = async () => {
// Request a port.
const port = await navigator.serial.requestPort()
// Wait for the serial port to open.
await port.open({ baudRate: 9600 })
// ...later, revoke access to the serial port.
await port.forget()
}
```
#### Event: 'select-usb-device'
Returns:
* `event` Event
* `details` Object
* `deviceList` [USBDevice[]](structures/usb-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
* `callback` Function
* `deviceId` string (optional)
Emitted when a USB device needs to be selected when a call to
`navigator.usb.requestDevice` is made. `callback` should be called with
`deviceId` to be selected; passing no arguments to `callback` will
cancel the request. Additionally, permissioning on `navigator.usb` can
be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler)
and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'usb') {
// Add logic here to determine if permission should be given to allow USB selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions)
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-usb-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
if (selectedDevice) {
// Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions)
grantedDevices.push(selectedDevice)
updateGrantedDevices(grantedDevices)
}
callback(selectedDevice?.deviceId)
})
})
```
#### Event: 'usb-device-added'
Returns:
* `event` Event
* `device` [USBDevice](structures/usb-device.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.usb.requestDevice` has been called and
`select-usb-device` has fired if a new device becomes available before
the callback from `select-usb-device` is called. This event is intended for
use when using a UI to ask users to pick a device so that the UI can be updated
with the newly added device.
#### Event: 'usb-device-removed'
Returns:
* `event` Event
* `device` [USBDevice](structures/usb-device.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.usb.requestDevice` has been called and
`select-usb-device` has fired if a device has been removed before the callback
from `select-usb-device` is called. This event is intended for use when using
a UI to ask users to pick a device so that the UI can be updated to remove the
specified device.
#### Event: 'usb-device-revoked'
Returns:
* `event` Event
* `details` Object
* `device` [USBDevice](structures/usb-device.md)
* `origin` string (optional) - The origin that the device has been revoked from.
Emitted after `USBDevice.forget()` has been called. This event can be used
to help maintain persistent storage of permissions when
`setDevicePermissionHandler` is used.
### Instance Methods
The following methods are available on instances of `Session`:
#### `ses.getCacheSize()`
Returns `Promise<Integer>` - the session's current cache size, in bytes.
#### `ses.clearCache()`
Returns `Promise<void>` - resolves when the cache clear operation is complete.
Clears the session’s HTTP cache.
#### `ses.clearStorageData([options])`
* `options` Object (optional)
* `origin` string (optional) - Should follow `window.location.origin`’s representation
`scheme://host:port`.
* `storages` string[] (optional) - The types of storages to clear, can contain:
`cookies`, `filesystem`, `indexdb`, `localstorage`,
`shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not
specified, clear all storage types.
* `quotas` string[] (optional) - The types of quotas to clear, can contain:
`temporary`, `syncable`. If not specified, clear all quotas.
Returns `Promise<void>` - resolves when the storage data has been cleared.
#### `ses.flushStorageData()`
Writes any unwritten DOMStorage data to disk.
#### `ses.setProxy(config)`
* `config` Object
* `mode` string (optional) - The proxy mode. Should be one of `direct`,
`auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's
unspecified, it will be automatically determined based on other specified
options.
* `direct`
In direct mode all connections are created directly, without any proxy involved.
* `auto_detect`
In auto_detect mode the proxy configuration is determined by a PAC script that can
be downloaded at http://wpad/wpad.dat.
* `pac_script`
In pac_script mode the proxy configuration is determined by a PAC script that is
retrieved from the URL specified in the `pacScript`. This is the default mode
if `pacScript` is specified.
* `fixed_servers`
In fixed_servers mode the proxy configuration is specified in `proxyRules`.
This is the default mode if `proxyRules` is specified.
* `system`
In system mode the proxy configuration is taken from the operating system.
Note that the system mode is different from setting no proxy configuration.
In the latter case, Electron falls back to the system settings
only if no command-line options influence the proxy configuration.
* `pacScript` string (optional) - The URL associated with the PAC file.
* `proxyRules` string (optional) - Rules indicating which proxies to use.
* `proxyBypassRules` string (optional) - Rules indicating which URLs should
bypass the proxy settings.
Returns `Promise<void>` - Resolves when the proxy setting process is complete.
Sets the proxy settings.
When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules`
option is ignored and `pacScript` configuration is applied.
You may need `ses.closeAllConnections` to close currently in flight connections to prevent
pooled sockets using previous proxy from being reused by future requests.
The `proxyRules` has to follow the rules below:
```sh
proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]
```
For example:
* `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and
HTTP proxy `foopy2:80` for `ftp://` URLs.
* `foopy:80` - Use HTTP proxy `foopy:80` for all URLs.
* `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing
over to `bar` if `foopy:80` is unavailable, and after that using no proxy.
* `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs.
* `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail
over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable.
* `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no
proxy if `foopy` is unavailable.
* `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use
`socks4://foopy2` for all other URLs.
The `proxyBypassRules` is a comma separated list of rules described below:
* `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]`
Match all hostnames that match the pattern HOSTNAME_PATTERN.
Examples:
"foobar.com", "\*foobar.com", "\*.foobar.com", "\*foobar.com:99",
"https://x.\*.y.com:99"
* `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]`
Match a particular domain suffix.
Examples:
".google.com", ".com", "http://.google.com"
* `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]`
Match URLs which are IP address literals.
Examples:
"127.0.1", "\[0:0::1]", "\[::1]", "http://\[::1]:99"
* `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS`
Match any URL that is to an IP literal that falls between the
given range. IP range is specified using CIDR notation.
Examples:
"192.168.1.1/16", "fefe:13::abc/33".
* `<local>`
Match local addresses. The meaning of `<local>` is whether the
host matches one of: "127.0.0.1", "::1", "localhost".
#### `ses.resolveHost(host, [options])`
* `host` string - Hostname to resolve.
* `options` Object (optional)
* `queryType` string (optional) - Requested DNS query type. If unspecified,
resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings:
* `A` - Fetch only A records
* `AAAA` - Fetch only AAAA records.
* `source` string (optional) - The source to use for resolved addresses.
Default allows the resolver to pick an appropriate source. Only affects use
of big external sources (e.g. calling the system for resolution or using
DNS). Even if a source is specified, results can still come from cache,
resolving "localhost" or IP literals, etc. One of the following values:
* `any` (default) - Resolver will pick an appropriate source. Results could
come from DNS, MulticastDNS, HOSTS file, etc
* `system` - Results will only be retrieved from the system or OS, e.g. via
the `getaddrinfo()` system call
* `dns` - Results will only come from DNS queries
* `mdns` - Results will only come from Multicast DNS queries
* `localOnly` - No external sources will be used. Results will only come
from fast local sources that are available no matter the source setting,
e.g. cache, hosts file, IP literal resolution, etc.
* `cacheUsage` string (optional) - Indicates what DNS cache entries, if any,
can be used to provide a response. One of the following values:
* `allowed` (default) - Results may come from the host cache if non-stale
* `staleAllowed` - Results may come from the host cache even if stale (by
expiration or network changes)
* `disallowed` - Results will not come from the host cache.
* `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS
behavior for this request. One of the following values:
* `allow` (default)
* `disable`
Returns [`Promise<ResolvedHost>`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`.
#### `ses.resolveProxy(url)`
* `url` URL
Returns `Promise<string>` - Resolves with the proxy information for `url`.
#### `ses.forceReloadProxyConfig()`
Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`.
#### `ses.setDownloadPath(path)`
* `path` string - The download location.
Sets download saving directory. By default, the download directory will be the
`Downloads` under the respective app folder.
#### `ses.enableNetworkEmulation(options)`
* `options` Object
* `offline` boolean (optional) - Whether to emulate network outage. Defaults
to false.
* `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable
latency throttling.
* `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0
which will disable download throttling.
* `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0
which will disable upload throttling.
Emulates network with the given configuration for the `session`.
```javascript
const win = new BrowserWindow()
// To emulate a GPRS connection with 50kbps throughput and 500 ms latency.
win.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
// To emulate a network outage.
win.webContents.session.enableNetworkEmulation({ offline: true })
```
#### `ses.preconnect(options)`
* `options` Object
* `url` string - URL for preconnect. Only the origin is relevant for opening the socket.
* `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1.
Preconnects the given number of sockets to an origin.
#### `ses.closeAllConnections()`
Returns `Promise<void>` - Resolves when all connections are closed.
**Note:** It will terminate / fail all requests currently in flight.
#### `ses.fetch(input[, init])`
* `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request)
* `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) (optional)
Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response).
Sends a request, similarly to how `fetch()` works in the renderer, using
Chrome's network stack. This differs from Node's `fetch()`, which uses
Node.js's HTTP stack.
Example:
```js
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
```
See also [`net.fetch()`](net.md#netfetchinput-init), a convenience method which
issues requests from the [default session](#sessiondefaultsession).
See the MDN documentation for
[`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more
details.
Limitations:
* `net.fetch()` does not support the `data:` or `blob:` schemes.
* The value of the `integrity` option is ignored.
* The `.type` and `.url` values of the returned `Response` object are
incorrect.
By default, requests made with `net.fetch` can be made to [custom
protocols](protocol.md) as well as `file:`, and will trigger
[webRequest](web-request.md) handlers if present. When the non-standard
`bypassCustomProtocolHandlers` option is set in RequestInit, custom protocol
handlers will not be called for this request. This allows forwarding an
intercepted request to the built-in handler. [webRequest](web-request.md)
handlers will still be triggered when bypassing custom protocols.
```js
protocol.handle('https', (req) => {
if (req.url === 'https://my-app.com') {
return new Response('<body>my app</body>')
} else {
return net.fetch(req, { bypassCustomProtocolHandlers: true })
}
})
```
#### `ses.disableNetworkEmulation()`
Disables any network emulation already active for the `session`. Resets to
the original network configuration.
#### `ses.setCertificateVerifyProc(proc)`
* `proc` Function | null
* `request` Object
* `hostname` string
* `certificate` [Certificate](structures/certificate.md)
* `validatedCertificate` [Certificate](structures/certificate.md)
* `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`.
* `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`.
* `errorCode` Integer - Error code.
* `callback` Function
* `verificationResult` Integer - Value can be one of certificate error codes
from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h).
Apart from the certificate error codes, the following special codes can be used.
* `0` - Indicates success and disables Certificate Transparency verification.
* `-2` - Indicates failure.
* `-3` - Uses the verification result from chromium.
Sets the certificate verify proc for `session`, the `proc` will be called with
`proc(request, callback)` whenever a server certificate
verification is requested. Calling `callback(0)` accepts the certificate,
calling `callback(-2)` rejects it.
Calling `setCertificateVerifyProc(null)` will revert back to default certificate
verify proc.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.session.setCertificateVerifyProc((request, callback) => {
const { hostname } = request
if (hostname === 'github.com') {
callback(0)
} else {
callback(-2)
}
})
```
> **NOTE:** The result of this procedure is cached by the network service.
#### `ses.setPermissionRequestHandler(handler)`
* `handler` Function | null
* `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin.
* `permission` string - The type of requested permission.
* `clipboard-read` - Request access to read from the clipboard.
* `clipboard-sanitized-write` - Request access to write to the clipboard.
* `media` - Request access to media devices such as camera, microphone and speakers.
* `display-capture` - Request access to capture the screen.
* `mediaKeySystem` - Request access to DRM protected content.
* `geolocation` - Request access to user's current location.
* `notifications` - Request notification creation and the ability to display them in the user's system tray.
* `midi` - Request MIDI access in the `webmidi` API.
* `midiSysex` - Request the use of system exclusive messages in the `webmidi` API.
* `pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more. These requests always appear to originate from the main frame.
* `fullscreen` - Request for the app to enter fullscreen mode.
* `openExternal` - Request to open links in external applications.
* `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API.
* `unknown` - An unrecognized permission request
* `callback` Function
* `permissionGranted` boolean - Allow or deny the permission.
* `details` Object - Some properties are only available on certain permission types.
* `externalURL` string (optional) - The url of the `openExternal` request.
* `securityOrigin` string (optional) - The security origin of the `media` request.
* `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video`
or `audio`
* `requestingUrl` string - The last URL the requesting frame loaded
* `isMainFrame` boolean - Whether the frame making the request is the main frame
Sets the handler which can be used to respond to permission requests for the `session`.
Calling `callback(true)` will allow the permission and `callback(false)` will reject it.
To clear the handler, call `setPermissionRequestHandler(null)`. Please note that
you must also implement `setPermissionCheckHandler` to get complete permission handling.
Most web APIs do a permission check and then make a permission request if the check is denied.
```javascript
const { session } = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') {
return callback(false) // denied.
}
callback(true)
})
```
#### `ses.setPermissionCheckHandler(handler)`
* `handler` Function\<boolean> | null
* `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively.
* `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, `serial`, or `usb`.
* `requestingOrigin` string - The origin URL of the permission check
* `details` Object - Some properties are only available on certain permission types.
* `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks.
* `securityOrigin` string (optional) - The security origin of the `media` check.
* `mediaType` string (optional) - The type of media access being requested, can be `video`,
`audio` or `unknown`
* `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks.
* `isMainFrame` boolean - Whether the frame making the request is the main frame
Sets the handler which can be used to respond to permission checks for the `session`.
Returning `true` will allow the permission and `false` will reject it. Please note that
you must also implement `setPermissionRequestHandler` to get complete permission handling.
Most web APIs do a permission check and then make a permission request if the check is denied.
To clear the handler, call `setPermissionCheckHandler(null)`.
```javascript
const { session } = require('electron')
const url = require('url')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') {
return true // granted
}
return false // denied
})
```
#### `ses.setDisplayMediaRequestHandler(handler)`
* `handler` Function | null
* `request` Object
* `frame` [WebFrameMain](web-frame-main.md) - Frame that is requesting access to media.
* `securityOrigin` String - Origin of the page making the request.
* `videoRequested` Boolean - true if the web content requested a video stream.
* `audioRequested` Boolean - true if the web content requested an audio stream.
* `userGesture` Boolean - Whether a user gesture was active when this request was triggered.
* `callback` Function
* `streams` Object
* `video` Object | [WebFrameMain](web-frame-main.md) (optional)
* `id` String - The id of the stream being granted. This will usually
come from a [DesktopCapturerSource](structures/desktop-capturer-source.md)
object.
* `name` String - The name of the stream being granted. This will
usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md)
object.
* `audio` String | [WebFrameMain](web-frame-main.md) (optional) - If
a string is specified, can be `loopback` or `loopbackWithMute`.
Specifying a loopback device will capture system audio, and is
currently only supported on Windows. If a WebFrameMain is specified,
will capture audio from that frame.
* `enableLocalEcho` Boolean (optional) - If `audio` is a [WebFrameMain](web-frame-main.md)
and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder`
to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers
while recording). Default is `false`.
This handler will be called when web content requests access to display media
via the `navigator.mediaDevices.getDisplayMedia` API. Use the
[desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant
access to.
```javascript
const { session, desktopCapturer } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
// Grant access to the first screen found.
callback({ video: sources[0] })
})
})
```
Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream
will capture the video or audio stream from that frame.
```javascript
const { session } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
// Allow the tab to capture itself.
callback({ video: request.frame })
})
```
Passing `null` instead of a function resets the handler to its default state.
#### `ses.setDevicePermissionHandler(handler)`
* `handler` Function\<boolean> | null
* `details` Object
* `deviceType` string - The type of device that permission is being requested on, can be `hid`, `serial`, or `usb`.
* `origin` string - The origin URL of the device permission check.
* `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md) | [USBDevice](structures/usb-device.md) - the device that permission is being requested for.
Sets the handler which can be used to respond to device permission checks for the `session`.
Returning `true` will allow the device to be permitted and `false` will reject it.
To clear the handler, call `setDevicePermissionHandler(null)`.
This handler can be used to provide default permissioning to devices without first calling for permission
to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device
permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used.
Additionally, the default behavior of Electron is to store granted device permision in memory.
If longer term storage is needed, a developer can store granted device
permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`.
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'hid') {
// Add logic here to determine if permission should be given to allow HID selection
return true
} else if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial port selection
} else if (permission === 'usb') {
// Add logic here to determine if permission should be given to allow USB device selection
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
} else if (details.deviceType === 'serial') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
}
return false
})
win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})
```
#### `ses.setUSBProtectedClassesHandler(handler)`
* `handler` Function\<string[]> | null
* `details` Object
* `protectedClasses` string[] - The current list of protected USB classes. Possible class values are:
* `audio`
* `audio-video`
* `hid`
* `mass-storage`
* `smart-card`
* `video`
* `wireless`
Sets the handler which can be used to override which [USB classes are protected](https://wicg.github.io/webusb/#usbinterface-interface).
The return value for the handler is a string array of USB classes which should be considered protected (eg not available in the renderer). Valid values for the array are:
* `audio`
* `audio-video`
* `hid`
* `mass-storage`
* `smart-card`
* `video`
* `wireless`
Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined).
To clear the handler, call `setUSBProtectedClassesHandler(null)`.
```javascript
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setUSBProtectedClassesHandler((details) => {
// Allow all classes:
// return []
// Keep the current set of protected classes:
// return details.protectedClasses
// Selectively remove classes:
return details.protectedClasses.filter((usbClass) => {
// Exclude classes except for audio classes
return usbClass.indexOf('audio') === -1
})
})
})
```
#### `ses.setBluetoothPairingHandler(handler)` _Windows_ _Linux_
* `handler` Function | null
* `details` Object
* `deviceId` string
* `pairingKind` string - The type of pairing prompt being requested.
One of the following values:
* `confirm`
This prompt is requesting confirmation that the Bluetooth device should
be paired.
* `confirmPin`
This prompt is requesting confirmation that the provided PIN matches the
pin displayed on the device.
* `providePin`
This prompt is requesting that a pin be provided for the device.
* `frame` [WebFrameMain](web-frame-main.md)
* `pin` string (optional) - The pin value to verify if `pairingKind` is `confirmPin`.
* `callback` Function
* `response` Object
* `confirmed` boolean - `false` should be passed in if the dialog is canceled.
If the `pairingKind` is `confirm` or `confirmPin`, this value should indicate
if the pairing is confirmed. If the `pairingKind` is `providePin` the value
should be `true` when a value is provided.
* `pin` string | null (optional) - When the `pairingKind` is `providePin`
this value should be the required pin for the Bluetooth device.
Sets a handler to respond to Bluetooth pairing requests. This handler
allows developers to handle devices that require additional validation
before pairing. When a handler is not defined, any pairing on Linux or Windows
that requires additional validation will be automatically cancelled.
macOS does not require a handler because macOS handles the pairing
automatically. To clear the handler, call `setBluetoothPairingHandler(null)`.
```javascript
const { app, BrowserWindow, session } = require('electron')
const path = require('path')
function createWindow () {
let bluetoothPinCallback = null
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => {
bluetoothPinCallback = callback
// Send a IPC message to the renderer to prompt the user to confirm the pairing.
// Note that this will require logic in the renderer to handle this message and
// display a prompt to the user.
mainWindow.webContents.send('bluetooth-pairing-request', details)
})
// Listen for an IPC message from the renderer to get the response for the Bluetooth pairing.
mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => {
bluetoothPinCallback(response)
})
}
app.whenReady().then(() => {
createWindow()
})
```
#### `ses.clearHostResolverCache()`
Returns `Promise<void>` - Resolves when the operation is complete.
Clears the host resolver cache.
#### `ses.allowNTLMCredentialsForDomains(domains)`
* `domains` string - A comma-separated list of servers for which
integrated authentication is enabled.
Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
authentication.
```javascript
const { session } = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')
// consider all urls for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*')
```
#### `ses.setUserAgent(userAgent[, acceptLanguages])`
* `userAgent` string
* `acceptLanguages` string (optional)
Overrides the `userAgent` and `acceptLanguages` for this session.
The `acceptLanguages` must a comma separated ordered list of language codes, for
example `"en-US,fr,de,ko,zh-CN,ja"`.
This doesn't affect existing `WebContents`, and each `WebContents` can use
`webContents.setUserAgent` to override the session-wide user agent.
#### `ses.isPersistent()`
Returns `boolean` - Whether or not this session is a persistent one. The default
`webContents` session of a `BrowserWindow` is persistent. When creating a session
from a partition, session prefixed with `persist:` will be persistent, while others
will be temporary.
#### `ses.getUserAgent()`
Returns `string` - The user agent for this session.
#### `ses.setSSLConfig(config)`
* `config` Object
* `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The
minimum SSL version to allow when connecting to remote servers. Defaults to
`tls1`.
* `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version
to allow when connecting to remote servers. Defaults to `tls1.3`.
* `disabledCipherSuites` Integer[] (optional) - List of cipher suites which
should be explicitly prevented from being used in addition to those
disabled by the net built-in policy.
Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is
`cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but
parsable cipher suites in this form will not return an error.
Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to
disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002.
Note that TLSv1.3 ciphers cannot be disabled using this mechanism.
Sets the SSL configuration for the session. All subsequent network requests
will use the new configuration. Existing network connections (such as WebSocket
connections) will not be terminated, but old sockets in the pool will not be
reused for new connections.
#### `ses.getBlobData(identifier)`
* `identifier` string - Valid UUID.
Returns `Promise<Buffer>` - resolves with blob data.
#### `ses.downloadURL(url)`
* `url` string
Initiates a download of the resource at `url`.
The API will generate a [DownloadItem](download-item.md) that can be accessed
with the [will-download](#event-will-download) event.
**Note:** This does not perform any security checks that relate to a page's origin,
unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl).
#### `ses.createInterruptedDownload(options)`
* `options` Object
* `path` string - Absolute path of the download.
* `urlChain` string[] - Complete URL chain for the download.
* `mimeType` string (optional)
* `offset` Integer - Start range for the download.
* `length` Integer - Total length of the download.
* `lastModified` string (optional) - Last-Modified header value.
* `eTag` string (optional) - ETag header value.
* `startTime` Double (optional) - Time when download was started in
number of seconds since UNIX epoch.
Allows resuming `cancelled` or `interrupted` downloads from previous `Session`.
The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download)
event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and
the initial state will be `interrupted`. The download will start only when the
`resume` API is called on the [DownloadItem](download-item.md).
#### `ses.clearAuthCache()`
Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared.
#### `ses.setPreloads(preloads)`
* `preloads` string[] - An array of absolute path to preload scripts
Adds scripts that will be executed on ALL web contents that are associated with
this session just before normal `preload` scripts run.
#### `ses.getPreloads()`
Returns `string[]` an array of paths to preload scripts that have been
registered.
#### `ses.setCodeCachePath(path)`
* `path` String - Absolute path to store the v8 generated JS code cache from the renderer.
Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the
respective user data folder.
#### `ses.clearCodeCaches(options)`
* `options` Object
* `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed.
Returns `Promise<void>` - resolves when the code cache clear operation is complete.
#### `ses.setSpellCheckerEnabled(enable)`
* `enable` boolean
Sets whether to enable the builtin spell checker.
#### `ses.isSpellCheckerEnabled()`
Returns `boolean` - Whether the builtin spell checker is enabled.
#### `ses.setSpellCheckerLanguages(languages)`
* `languages` string[] - An array of language codes to enable the spellchecker for.
The built in spellchecker does not automatically detect what language a user is typing in. In order for the
spell checker to correctly check their words you must call this API with an array of language codes. You can
get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property.
**Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS.
#### `ses.getSpellCheckerLanguages()`
Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker
will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this
setting with the current OS locale. This setting is persisted across restarts.
**Note:** On macOS the OS spellchecker is used and has its own list of languages. On macOS, this API will return whichever languages have been configured by the OS.
#### `ses.setSpellCheckerDictionaryDownloadURL(url)`
* `url` string - A base URL for Electron to download hunspell dictionaries from.
By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this
behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell
dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need
to host here.
The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with
the case it has in the ZIP file and once with the filename as all lowercase.
If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic`
then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please
note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`.
**Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS.
#### `ses.listWordsInSpellCheckerDictionary()`
Returns `Promise<string[]>` - An array of all words in app's custom dictionary.
Resolves when the full dictionary is loaded from disk.
#### `ses.addWordToSpellCheckerDictionary(word)`
* `word` string - The word you want to add to the dictionary
Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API
will not work on non-persistent (in-memory) sessions.
**Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well
#### `ses.removeWordFromSpellCheckerDictionary(word)`
* `word` string - The word you want to remove from the dictionary
Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API
will not work on non-persistent (in-memory) sessions.
**Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well
#### `ses.loadExtension(path[, options])`
* `path` string - Path to a directory containing an unpacked Chrome extension
* `options` Object (optional)
* `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://`
protocol and inject content scripts into `file://` pages. This is required e.g. for loading
devtools extensions on `file://` URLs. Defaults to false.
Returns `Promise<Extension>` - resolves when the extension is loaded.
This method will raise an exception if the extension could not be loaded. If
there are warnings when installing the extension (e.g. if the extension
requests an API that Electron does not support) then they will be logged to the
console.
Note that Electron does not support the full range of Chrome extensions APIs.
See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for
more details on what is supported.
Note that in previous versions of Electron, extensions that were loaded would
be remembered for future runs of the application. This is no longer the case:
`loadExtension` must be called on every boot of your app if you want the
extension to be loaded.
```js
const { app, session } = require('electron')
const path = require('path')
app.whenReady().then(async () => {
await session.defaultSession.loadExtension(
path.join(__dirname, 'react-devtools'),
// allowFileAccess is required to load the devtools extension on file:// URLs.
{ allowFileAccess: true }
)
// Note that in order to use the React DevTools extension, you'll need to
// download and unzip a copy of the extension.
})
```
This API does not support loading packed (.crx) extensions.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
**Note:** Loading extensions into in-memory (non-persistent) sessions is not
supported and will throw an error.
#### `ses.removeExtension(extensionId)`
* `extensionId` string - ID of extension to remove
Unloads an extension.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
#### `ses.getExtension(extensionId)`
* `extensionId` string - ID of extension to query
Returns `Extension` | `null` - The loaded extension with the given ID.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
#### `ses.getAllExtensions()`
Returns `Extension[]` - A list of all loaded extensions.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
#### `ses.getStoragePath()`
Returns `string | null` - The absolute file system path where data for this
session is persisted on disk. For in memory sessions this returns `null`.
### Instance Properties
The following properties are available on instances of `Session`:
#### `ses.availableSpellCheckerLanguages` _Readonly_
A `string[]` array which consists of all the known available spell checker languages. Providing a language
code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error.
#### `ses.spellCheckerEnabled`
A `boolean` indicating whether builtin spell checker is enabled.
#### `ses.storagePath` _Readonly_
A `string | null` indicating the absolute file system path where data for this
session is persisted on disk. For in memory sessions this returns `null`.
#### `ses.cookies` _Readonly_
A [`Cookies`](cookies.md) object for this session.
#### `ses.serviceWorkers` _Readonly_
A [`ServiceWorkers`](service-workers.md) object for this session.
#### `ses.webRequest` _Readonly_
A [`WebRequest`](web-request.md) object for this session.
#### `ses.protocol` _Readonly_
A [`Protocol`](protocol.md) object for this session.
```javascript
const { app, session } = require('electron')
const path = require('path')
app.whenReady().then(() => {
const protocol = session.fromPartition('some-partition').protocol
if (!protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7)
callback({ path: path.normalize(path.join(__dirname, url)) })
})) {
console.error('Failed to register protocol')
}
})
```
#### `ses.netLog` _Readonly_
A [`NetLog`](net-log.md) object for this session.
```javascript
const { app, session } = require('electron')
app.whenReady().then(async () => {
const netLog = session.fromPartition('some-partition').netLog
netLog.startLogging('/path/to/net-log')
// After some network events
const path = await netLog.stopLogging()
console.log('Net-logs written to', path)
})
```
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
shell/browser/api/electron_api_session.cc
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_session.h"
#include <algorithm>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/uuid.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_url_parameters.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/value_map_pref_store.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "components/proxy_config/proxy_prefs.h"
#include "content/browser/code_cache/generated_code_cache_context.h" // nogncheck
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager_delegate.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
#include "gin/arguments.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/completion_repeating_callback.h"
#include "net/base/load_flags.h"
#include "net/base/network_anonymization_key.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_cache.h"
#include "net/http/http_util.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/clear_data_filter.mojom.h"
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_cookies.h"
#include "shell/browser/api/electron_api_data_pipe_holder.h"
#include "shell/browser/api/electron_api_download_item.h"
#include "shell/browser/api/electron_api_net_log.h"
#include "shell/browser/api/electron_api_protocol.h"
#include "shell/browser/api/electron_api_service_worker_context.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/electron_api_web_request.h"
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/media/media_device_id_salt.h"
#include "shell/browser/net/cert_verifier_client.h"
#include "shell/browser/net/resolve_host_function.h"
#include "shell/browser/session_preferences.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/media_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/usb_protected_classes_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/extension_registry.h"
#include "shell/browser/extensions/electron_extension_system.h"
#include "shell/common/gin_converters/extension_converter.h"
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
#include "chrome/browser/spellchecker/spellcheck_service.h" // nogncheck
#include "components/spellcheck/browser/pref_names.h"
#include "components/spellcheck/common/spellcheck_common.h"
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
#include "components/spellcheck/browser/spellcheck_platform.h"
#include "components/spellcheck/common/spellcheck_features.h"
#endif
#endif
using content::BrowserThread;
using content::StoragePartition;
namespace {
struct ClearStorageDataOptions {
blink::StorageKey storage_key;
uint32_t storage_types = StoragePartition::REMOVE_DATA_MASK_ALL;
uint32_t quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL;
};
uint32_t GetStorageMask(const std::vector<std::string>& storage_types) {
uint32_t storage_mask = 0;
for (const auto& it : storage_types) {
auto type = base::ToLowerASCII(it);
if (type == "cookies")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES;
else if (type == "filesystem")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS;
else if (type == "indexdb")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB;
else if (type == "localstorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE;
else if (type == "shadercache")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE;
else if (type == "websql")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL;
else if (type == "serviceworkers")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS;
else if (type == "cachestorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE;
}
return storage_mask;
}
uint32_t GetQuotaMask(const std::vector<std::string>& quota_types) {
uint32_t quota_mask = 0;
for (const auto& it : quota_types) {
auto type = base::ToLowerASCII(it);
if (type == "temporary")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY;
else if (type == "syncable")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_SYNCABLE;
}
return quota_mask;
}
base::Value::Dict createProxyConfig(ProxyPrefs::ProxyMode proxy_mode,
std::string const& pac_url,
std::string const& proxy_server,
std::string const& bypass_list) {
if (proxy_mode == ProxyPrefs::MODE_DIRECT) {
return ProxyConfigDictionary::CreateDirect();
}
if (proxy_mode == ProxyPrefs::MODE_SYSTEM) {
return ProxyConfigDictionary::CreateSystem();
}
if (proxy_mode == ProxyPrefs::MODE_AUTO_DETECT) {
return ProxyConfigDictionary::CreateAutoDetect();
}
if (proxy_mode == ProxyPrefs::MODE_PAC_SCRIPT) {
const bool pac_mandatory = true;
return ProxyConfigDictionary::CreatePacScript(pac_url, pac_mandatory);
}
return ProxyConfigDictionary::CreateFixedServers(proxy_server, bypass_list);
}
} // namespace
namespace gin {
template <>
struct Converter<ClearStorageDataOptions> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
ClearStorageDataOptions* out) {
gin_helper::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
if (GURL storage_origin; options.Get("origin", &storage_origin))
out->storage_key = blink::StorageKey::CreateFirstParty(
url::Origin::Create(storage_origin));
std::vector<std::string> types;
if (options.Get("storages", &types))
out->storage_types = GetStorageMask(types);
if (options.Get("quotas", &types))
out->quota_types = GetQuotaMask(types);
return true;
}
};
bool SSLProtocolVersionFromString(const std::string& version_str,
network::mojom::SSLVersion* version) {
if (version_str == switches::kSSLVersionTLSv12) {
*version = network::mojom::SSLVersion::kTLS12;
return true;
}
if (version_str == switches::kSSLVersionTLSv13) {
*version = network::mojom::SSLVersion::kTLS13;
return true;
}
return false;
}
template <>
struct Converter<uint16_t> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
uint16_t* out) {
auto maybe = val->IntegerValue(isolate->GetCurrentContext());
if (maybe.IsNothing())
return false;
*out = maybe.FromJust();
return true;
}
};
template <>
struct Converter<network::mojom::SSLConfigPtr> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::SSLConfigPtr* out) {
gin_helper::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
*out = network::mojom::SSLConfig::New();
std::string version_min_str;
if (options.Get("minVersion", &version_min_str)) {
if (!SSLProtocolVersionFromString(version_min_str, &(*out)->version_min))
return false;
}
std::string version_max_str;
if (options.Get("maxVersion", &version_max_str)) {
if (!SSLProtocolVersionFromString(version_max_str,
&(*out)->version_max) ||
(*out)->version_max < network::mojom::SSLVersion::kTLS12)
return false;
}
if (options.Has("disabledCipherSuites") &&
!options.Get("disabledCipherSuites", &(*out)->disabled_cipher_suites)) {
return false;
}
std::sort((*out)->disabled_cipher_suites.begin(),
(*out)->disabled_cipher_suites.end());
// TODO(nornagon): also support other SSLConfig properties?
return true;
}
};
} // namespace gin
namespace electron::api {
namespace {
const char kPersistPrefix[] = "persist:";
void DownloadIdCallback(content::DownloadManager* download_manager,
const base::FilePath& path,
const std::vector<GURL>& url_chain,
const std::string& mime_type,
int64_t offset,
int64_t length,
const std::string& last_modified,
const std::string& etag,
const base::Time& start_time,
uint32_t id) {
download_manager->CreateDownloadItem(
base::Uuid::GenerateRandomV4().AsLowercaseString(), id, path, path,
url_chain, GURL(),
content::StoragePartitionConfig::CreateDefault(
download_manager->GetBrowserContext()),
GURL(), GURL(), absl::nullopt, mime_type, mime_type, start_time,
base::Time(), etag, last_modified, offset, length, std::string(),
download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(),
false, std::vector<download::DownloadItem::ReceivedSlice>());
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
class DictionaryObserver final : public SpellcheckCustomDictionary::Observer {
private:
std::unique_ptr<gin_helper::Promise<std::set<std::string>>> promise_;
base::WeakPtr<SpellcheckService> spellcheck_;
public:
DictionaryObserver(gin_helper::Promise<std::set<std::string>> promise,
base::WeakPtr<SpellcheckService> spellcheck)
: spellcheck_(spellcheck) {
promise_ = std::make_unique<gin_helper::Promise<std::set<std::string>>>(
std::move(promise));
if (spellcheck_)
spellcheck_->GetCustomDictionary()->AddObserver(this);
}
~DictionaryObserver() {
if (spellcheck_)
spellcheck_->GetCustomDictionary()->RemoveObserver(this);
}
void OnCustomDictionaryLoaded() override {
if (spellcheck_) {
promise_->Resolve(spellcheck_->GetCustomDictionary()->GetWords());
} else {
promise_->RejectWithErrorMessage(
"Spellcheck in unexpected state: failed to load custom dictionary.");
}
delete this;
}
void OnCustomDictionaryChanged(
const SpellcheckCustomDictionary::Change& dictionary_change) override {
// noop
}
};
#endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
struct UserDataLink : base::SupportsUserData::Data {
explicit UserDataLink(Session* ses) : session(ses) {}
raw_ptr<Session> session;
};
const void* kElectronApiSessionKey = &kElectronApiSessionKey;
} // namespace
gin::WrapperInfo Session::kWrapperInfo = {gin::kEmbedderNativeGin};
Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context)
: isolate_(isolate),
network_emulation_token_(base::UnguessableToken::Create()),
browser_context_(browser_context) {
// Observe DownloadManager to get download notifications.
browser_context->GetDownloadManager()->AddObserver(this);
SessionPreferences::CreateForBrowserContext(browser_context);
protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8());
browser_context->SetUserData(kElectronApiSessionKey,
std::make_unique<UserDataLink>(this));
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (service) {
service->SetHunspellObserver(this);
}
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionRegistry::Get(browser_context)->AddObserver(this);
#endif
}
Session::~Session() {
browser_context()->GetDownloadManager()->RemoveObserver(this);
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (service) {
service->SetHunspellObserver(nullptr);
}
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionRegistry::Get(browser_context())->RemoveObserver(this);
#endif
}
void Session::OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) {
if (item->IsSavePackageDownload())
return;
v8::HandleScope handle_scope(isolate_);
auto handle = DownloadItem::FromOrCreate(isolate_, item);
if (item->GetState() == download::DownloadItem::INTERRUPTED)
handle->SetSavePath(item->GetTargetFilePath());
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
bool prevent_default = Emit("will-download", handle, web_contents);
if (prevent_default) {
item->Cancel(true);
item->Remove();
}
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
void Session::OnHunspellDictionaryInitialized(const std::string& language) {
Emit("spellcheck-dictionary-initialized", language);
}
void Session::OnHunspellDictionaryDownloadBegin(const std::string& language) {
Emit("spellcheck-dictionary-download-begin", language);
}
void Session::OnHunspellDictionaryDownloadSuccess(const std::string& language) {
Emit("spellcheck-dictionary-download-success", language);
}
void Session::OnHunspellDictionaryDownloadFailure(const std::string& language) {
Emit("spellcheck-dictionary-download-failure", language);
}
#endif
v8::Local<v8::Promise> Session::ResolveProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<std::string> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
GURL url;
args->GetNext(&url);
browser_context_->GetResolveProxyHelper()->ResolveProxy(
url, base::BindOnce(gin_helper::Promise<std::string>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ResolveHost(
std::string host,
absl::optional<network::mojom::ResolveHostParametersPtr> params) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto fn = base::MakeRefCounted<ResolveHostFunction>(
browser_context_, std::move(host),
params ? std::move(params.value()) : nullptr,
base::BindOnce(
[](gin_helper::Promise<gin_helper::Dictionary> promise,
int64_t net_error, const absl::optional<net::AddressList>& addrs) {
if (net_error < 0) {
promise.RejectWithErrorMessage(net::ErrorToString(net_error));
} else {
DCHECK(addrs.has_value() && !addrs->empty());
v8::HandleScope handle_scope(promise.isolate());
gin_helper::Dictionary dict =
gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("endpoints", addrs->endpoints());
promise.Resolve(dict);
}
},
std::move(promise)));
fn->Run();
return handle;
}
v8::Local<v8::Promise> Session::GetCacheSize() {
gin_helper::Promise<int64_t> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ComputeHttpCacheSize(
base::Time(), base::Time::Max(),
base::BindOnce(
[](gin_helper::Promise<int64_t> promise, bool is_upper_bound,
int64_t size_or_error) {
if (size_or_error < 0) {
promise.RejectWithErrorMessage(
net::ErrorToString(size_or_error));
} else {
promise.Resolve(size_or_error);
}
},
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearCache() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ClearHttpCache(base::Time(), base::Time::Max(), nullptr,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearStorageData(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ClearStorageDataOptions options;
args->GetNext(&options);
auto* storage_partition = browser_context()->GetStoragePartition(nullptr);
if (options.storage_types & StoragePartition::REMOVE_DATA_MASK_COOKIES) {
// Reset media device id salt when cookies are cleared.
// https://w3c.github.io/mediacapture-main/#dom-mediadeviceinfo-deviceid
MediaDeviceIDSalt::Reset(browser_context()->prefs());
}
storage_partition->ClearData(
options.storage_types, options.quota_types, options.storage_key,
base::Time(), base::Time::Max(),
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
void Session::FlushStorageData() {
auto* storage_partition = browser_context()->GetStoragePartition(nullptr);
storage_partition->Flush();
}
v8::Local<v8::Promise> Session::SetProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary options;
args->GetNext(&options);
if (!browser_context_->in_memory_pref_store()) {
promise.Resolve();
return handle;
}
std::string mode, proxy_rules, bypass_list, pac_url;
options.Get("pacScript", &pac_url);
options.Get("proxyRules", &proxy_rules);
options.Get("proxyBypassRules", &bypass_list);
ProxyPrefs::ProxyMode proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS;
if (!options.Get("mode", &mode)) {
// pacScript takes precedence over proxyRules.
if (!pac_url.empty()) {
proxy_mode = ProxyPrefs::MODE_PAC_SCRIPT;
} else {
proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS;
}
} else {
if (!ProxyPrefs::StringToProxyMode(mode, &proxy_mode)) {
promise.RejectWithErrorMessage(
"Invalid mode, must be one of direct, auto_detect, pac_script, "
"fixed_servers or system");
return handle;
}
}
browser_context_->in_memory_pref_store()->SetValue(
proxy_config::prefs::kProxy,
base::Value{
createProxyConfig(proxy_mode, pac_url, proxy_rules, bypass_list)},
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ForceReloadProxyConfig() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ForceReloadProxyConfig(base::BindOnce(
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}
void Session::SetDownloadPath(const base::FilePath& path) {
browser_context_->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
path);
}
void Session::EnableNetworkEmulation(const gin_helper::Dictionary& options) {
auto conditions = network::mojom::NetworkConditions::New();
options.Get("offline", &conditions->offline);
options.Get("downloadThroughput", &conditions->download_throughput);
options.Get("uploadThroughput", &conditions->upload_throughput);
double latency = 0.0;
if (options.Get("latency", &latency) && latency) {
conditions->latency = base::Milliseconds(latency);
}
auto* network_context =
browser_context_->GetDefaultStoragePartition()->GetNetworkContext();
network_context->SetNetworkConditions(network_emulation_token_,
std::move(conditions));
}
void Session::DisableNetworkEmulation() {
auto* network_context =
browser_context_->GetDefaultStoragePartition()->GetNetworkContext();
network_context->SetNetworkConditions(
network_emulation_token_, network::mojom::NetworkConditions::New());
}
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,
gin::Arguments* args) {
CertVerifierClient::CertVerifyProc proc;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &proc))) {
args->ThrowTypeError("Must pass null or function");
return;
}
mojo::PendingRemote<network::mojom::CertVerifierClient>
cert_verifier_client_remote;
if (proc) {
mojo::MakeSelfOwnedReceiver(
std::make_unique<CertVerifierClient>(proc),
cert_verifier_client_remote.InitWithNewPipeAndPassReceiver());
}
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->SetCertVerifierClient(std::move(cert_verifier_client_remote));
}
void Session::SetPermissionRequestHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
if (val->IsNull()) {
permission_manager->SetPermissionRequestHandler(
ElectronPermissionManager::RequestHandler());
return;
}
auto handler = std::make_unique<ElectronPermissionManager::RequestHandler>();
if (!gin::ConvertFromV8(args->isolate(), val, handler.get())) {
args->ThrowTypeError("Must pass null or function");
return;
}
permission_manager->SetPermissionRequestHandler(base::BindRepeating(
[](ElectronPermissionManager::RequestHandler* handler,
content::WebContents* web_contents,
blink::PermissionType permission_type,
ElectronPermissionManager::StatusCallback callback,
const base::Value& details) {
handler->Run(web_contents, permission_type, std::move(callback),
details);
},
base::Owned(std::move(handler))));
}
void Session::SetPermissionCheckHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::CheckHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetPermissionCheckHandler(handler);
}
void Session::SetDisplayMediaRequestHandler(v8::Isolate* isolate,
v8::Local<v8::Value> val) {
if (val->IsNull()) {
browser_context_->SetDisplayMediaRequestHandler(
DisplayMediaRequestHandler());
return;
}
DisplayMediaRequestHandler handler;
if (!gin::ConvertFromV8(isolate, val, &handler)) {
gin_helper::ErrorThrower(isolate).ThrowTypeError(
"Display media request handler must be null or a function");
return;
}
browser_context_->SetDisplayMediaRequestHandler(handler);
}
void Session::SetDevicePermissionHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::DeviceCheckHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetDevicePermissionHandler(handler);
}
void Session::SetUSBProtectedClassesHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::ProtectedUSBHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetProtectedUSBHandler(handler);
}
void Session::SetBluetoothPairingHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::BluetoothPairingHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetBluetoothPairingHandler(handler);
}
v8::Local<v8::Promise> Session::ClearHostResolverCache(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ClearHostCache(nullptr,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearAuthCache() {
gin_helper::Promise<void> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ClearHttpAuthCache(
base::Time(), base::Time::Max(),
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
void Session::AllowNTLMCredentialsForDomains(const std::string& domains) {
auto* command_line = base::CommandLine::ForCurrentProcess();
network::mojom::HttpAuthDynamicParamsPtr auth_dynamic_params =
network::mojom::HttpAuthDynamicParams::New();
auth_dynamic_params->server_allowlist = domains;
auth_dynamic_params->enable_negotiate_port =
command_line->HasSwitch(electron::switches::kEnableAuthNegotiatePort);
auth_dynamic_params->ntlm_v2_enabled =
!command_line->HasSwitch(electron::switches::kDisableNTLMv2);
content::GetNetworkService()->ConfigureHttpAuthPrefs(
std::move(auth_dynamic_params));
}
void Session::SetUserAgent(const std::string& user_agent,
gin::Arguments* args) {
browser_context_->SetUserAgent(user_agent);
auto* network_context =
browser_context_->GetDefaultStoragePartition()->GetNetworkContext();
network_context->SetUserAgent(user_agent);
std::string accept_lang;
if (args->GetNext(&accept_lang)) {
network_context->SetAcceptLanguage(
net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang));
}
}
std::string Session::GetUserAgent() {
return browser_context_->GetUserAgent();
}
void Session::SetSSLConfig(network::mojom::SSLConfigPtr config) {
browser_context_->SetSSLConfig(std::move(config));
}
bool Session::IsPersistent() {
return !browser_context_->IsOffTheRecord();
}
v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate,
const std::string& uuid) {
gin::Handle<DataPipeHolder> holder = DataPipeHolder::From(isolate, uuid);
if (holder.IsEmpty()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("Could not get blob data handle");
return promise.GetHandle();
}
return holder->ReadAll(isolate);
}
void Session::DownloadURL(const GURL& url) {
auto* download_manager = browser_context()->GetDownloadManager();
auto download_params = std::make_unique<download::DownloadUrlParameters>(
url, MISSING_TRAFFIC_ANNOTATION);
download_manager->DownloadUrl(std::move(download_params));
}
void Session::CreateInterruptedDownload(const gin_helper::Dictionary& options) {
int64_t offset = 0, length = 0;
double start_time = base::Time::Now().ToDoubleT();
std::string mime_type, last_modified, etag;
base::FilePath path;
std::vector<GURL> url_chain;
options.Get("path", &path);
options.Get("urlChain", &url_chain);
options.Get("mimeType", &mime_type);
options.Get("offset", &offset);
options.Get("length", &length);
options.Get("lastModified", &last_modified);
options.Get("eTag", &etag);
options.Get("startTime", &start_time);
if (path.empty() || url_chain.empty() || length == 0) {
isolate_->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate_, "Must pass non-empty path, urlChain and length.")));
return;
}
if (offset >= length) {
isolate_->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate_, "Must pass an offset value less than length.")));
return;
}
auto* download_manager = browser_context()->GetDownloadManager();
download_manager->GetNextId(base::BindRepeating(
&DownloadIdCallback, download_manager, path, url_chain, mime_type, offset,
length, last_modified, etag, base::Time::FromDoubleT(start_time)));
}
void Session::SetPreloads(const std::vector<base::FilePath>& preloads) {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
prefs->set_preloads(preloads);
}
std::vector<base::FilePath> Session::GetPreloads() const {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
return prefs->preloads();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
v8::Local<v8::Promise> Session::LoadExtension(
const base::FilePath& extension_path,
gin::Arguments* args) {
gin_helper::Promise<const extensions::Extension*> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!extension_path.IsAbsolute()) {
promise.RejectWithErrorMessage(
"The path to the extension in 'loadExtension' must be absolute");
return handle;
}
if (browser_context()->IsOffTheRecord()) {
promise.RejectWithErrorMessage(
"Extensions cannot be loaded in a temporary session");
return handle;
}
int load_flags = extensions::Extension::FOLLOW_SYMLINKS_ANYWHERE;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
bool allowFileAccess = false;
options.Get("allowFileAccess", &allowFileAccess);
if (allowFileAccess)
load_flags |= extensions::Extension::ALLOW_FILE_ACCESS;
}
auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>(
extensions::ExtensionSystem::Get(browser_context()));
extension_system->LoadExtension(
extension_path, load_flags,
base::BindOnce(
[](gin_helper::Promise<const extensions::Extension*> promise,
const extensions::Extension* extension,
const std::string& error_msg) {
if (extension) {
if (!error_msg.empty()) {
node::Environment* env =
node::Environment::GetCurrent(promise.isolate());
EmitWarning(env, error_msg, "ExtensionLoadWarning");
}
promise.Resolve(extension);
} else {
promise.RejectWithErrorMessage(error_msg);
}
},
std::move(promise)));
return handle;
}
void Session::RemoveExtension(const std::string& extension_id) {
auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>(
extensions::ExtensionSystem::Get(browser_context()));
extension_system->RemoveExtension(extension_id);
}
v8::Local<v8::Value> Session::GetExtension(const std::string& extension_id) {
auto* registry = extensions::ExtensionRegistry::Get(browser_context());
const extensions::Extension* extension =
registry->GetInstalledExtension(extension_id);
if (extension) {
return gin::ConvertToV8(isolate_, extension);
} else {
return v8::Null(isolate_);
}
}
v8::Local<v8::Value> Session::GetAllExtensions() {
auto* registry = extensions::ExtensionRegistry::Get(browser_context());
const extensions::ExtensionSet extensions =
registry->GenerateInstalledExtensionsSet();
std::vector<const extensions::Extension*> extensions_vector;
for (const auto& extension : extensions) {
if (extension->location() !=
extensions::mojom::ManifestLocation::kComponent)
extensions_vector.emplace_back(extension.get());
}
return gin::ConvertToV8(isolate_, extensions_vector);
}
void Session::OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) {
Emit("extension-loaded", extension);
}
void Session::OnExtensionUnloaded(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) {
Emit("extension-unloaded", extension);
}
void Session::OnExtensionReady(content::BrowserContext* browser_context,
const extensions::Extension* extension) {
Emit("extension-ready", extension);
}
#endif
v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) {
if (cookies_.IsEmpty()) {
auto handle = Cookies::Create(isolate, browser_context());
cookies_.Reset(isolate, handle.ToV8());
}
return cookies_.Get(isolate);
}
v8::Local<v8::Value> Session::Protocol(v8::Isolate* isolate) {
return protocol_.Get(isolate);
}
v8::Local<v8::Value> Session::ServiceWorkerContext(v8::Isolate* isolate) {
if (service_worker_context_.IsEmpty()) {
v8::Local<v8::Value> handle;
handle = ServiceWorkerContext::Create(isolate, browser_context()).ToV8();
service_worker_context_.Reset(isolate, handle);
}
return service_worker_context_.Get(isolate);
}
v8::Local<v8::Value> Session::WebRequest(v8::Isolate* isolate) {
if (web_request_.IsEmpty()) {
auto handle = WebRequest::Create(isolate, browser_context());
web_request_.Reset(isolate, handle.ToV8());
}
return web_request_.Get(isolate);
}
v8::Local<v8::Value> Session::NetLog(v8::Isolate* isolate) {
if (net_log_.IsEmpty()) {
auto handle = NetLog::Create(isolate, browser_context());
net_log_.Reset(isolate, handle.ToV8());
}
return net_log_.Get(isolate);
}
static void StartPreconnectOnUI(ElectronBrowserContext* browser_context,
const GURL& url,
int num_sockets_to_preconnect) {
url::Origin origin = url::Origin::Create(url);
std::vector<predictors::PreconnectRequest> requests = {
{url::Origin::Create(url), num_sockets_to_preconnect,
net::NetworkAnonymizationKey::CreateSameSite(
net::SchemefulSite(origin))}};
browser_context->GetPreconnectManager()->Start(url, requests);
}
void Session::Preconnect(const gin_helper::Dictionary& options,
gin::Arguments* args) {
GURL url;
if (!options.Get("url", &url) || !url.is_valid()) {
args->ThrowTypeError(
"Must pass non-empty valid url to session.preconnect.");
return;
}
int num_sockets_to_preconnect = 1;
if (options.Get("numSockets", &num_sockets_to_preconnect)) {
const int kMinSocketsToPreconnect = 1;
const int kMaxSocketsToPreconnect = 6;
if (num_sockets_to_preconnect < kMinSocketsToPreconnect ||
num_sockets_to_preconnect > kMaxSocketsToPreconnect) {
args->ThrowTypeError(
base::StringPrintf("numSocketsToPreconnect is outside range [%d,%d]",
kMinSocketsToPreconnect, kMaxSocketsToPreconnect));
return;
}
}
DCHECK_GT(num_sockets_to_preconnect, 0);
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&StartPreconnectOnUI, base::Unretained(browser_context_),
url, num_sockets_to_preconnect));
}
v8::Local<v8::Promise> Session::CloseAllConnections() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->CloseAllConnections(base::BindOnce(
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}
v8::Local<v8::Value> Session::GetPath(v8::Isolate* isolate) {
if (browser_context_->IsOffTheRecord()) {
return v8::Null(isolate);
}
return gin::ConvertToV8(isolate, browser_context_->GetPath());
}
void Session::SetCodeCachePath(gin::Arguments* args) {
base::FilePath code_cache_path;
auto* storage_partition = browser_context_->GetDefaultStoragePartition();
auto* code_cache_context = storage_partition->GetGeneratedCodeCacheContext();
if (code_cache_context) {
if (!args->GetNext(&code_cache_path) || !code_cache_path.IsAbsolute()) {
args->ThrowTypeError(
"Absolute path must be provided to store code cache.");
return;
}
code_cache_context->Initialize(
code_cache_path, 0 /* allows disk_cache to choose the size */);
}
}
v8::Local<v8::Promise> Session::ClearCodeCaches(
const gin_helper::Dictionary& options) {
auto* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
std::set<GURL> url_list;
base::RepeatingCallback<bool(const GURL&)> url_matcher = base::NullCallback();
if (options.Get("urls", &url_list) && !url_list.empty()) {
url_matcher = base::BindRepeating(
[](const std::set<GURL>& url_list, const GURL& url) {
return base::Contains(url_list, url);
},
url_list);
}
browser_context_->GetDefaultStoragePartition()->ClearCodeCaches(
base::Time(), base::Time::Max(), url_matcher,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
base::Value Session::GetSpellCheckerLanguages() {
return browser_context_->prefs()
->GetValue(spellcheck::prefs::kSpellCheckDictionaries)
.Clone();
}
void Session::SetSpellCheckerLanguages(
gin_helper::ErrorThrower thrower,
const std::vector<std::string>& languages) {
#if !BUILDFLAG(IS_MAC)
base::Value::List language_codes;
for (const std::string& lang : languages) {
std::string code = spellcheck::GetCorrespondingSpellCheckLanguage(lang);
if (code.empty()) {
thrower.ThrowError("Invalid language code provided: \"" + lang +
"\" is not a valid language code");
return;
}
language_codes.Append(code);
}
browser_context_->prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries,
base::Value(std::move(language_codes)));
// Enable spellcheck if > 0 languages, disable if no languages set
browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable,
!languages.empty());
#endif
}
void SetSpellCheckerDictionaryDownloadURL(gin_helper::ErrorThrower thrower,
const GURL& url) {
#if !BUILDFLAG(IS_MAC)
if (!url.is_valid()) {
thrower.ThrowError(
"The URL you provided to setSpellCheckerDictionaryDownloadURL is not a "
"valid URL");
return;
}
SpellcheckHunspellDictionary::SetBaseDownloadURL(url);
#endif
}
v8::Local<v8::Promise> Session::ListWordsInSpellCheckerDictionary() {
gin_helper::Promise<std::set<std::string>> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!spellcheck) {
promise.RejectWithErrorMessage(
"Spellcheck in unexpected state: failed to load custom dictionary.");
return handle;
}
if (spellcheck->GetCustomDictionary()->IsLoaded()) {
promise.Resolve(spellcheck->GetCustomDictionary()->GetWords());
} else {
new DictionaryObserver(std::move(promise), spellcheck->GetWeakPtr());
// Dictionary loads by default asynchronously,
// call the load function anyways just to be sure.
spellcheck->GetCustomDictionary()->Load();
}
return handle;
}
bool Session::AddWordToSpellCheckerDictionary(const std::string& word) {
// don't let in-memory sessions add spellchecker words
// because files will persist unintentionally
bool is_in_memory = browser_context_->IsOffTheRecord();
if (is_in_memory)
return false;
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!service)
return false;
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
if (spellcheck::UseBrowserSpellChecker()) {
spellcheck_platform::AddWord(service->platform_spell_checker(),
base::UTF8ToUTF16(word));
}
#endif
return service->GetCustomDictionary()->AddWord(word);
}
bool Session::RemoveWordFromSpellCheckerDictionary(const std::string& word) {
// don't let in-memory sessions remove spellchecker words
// because files will persist unintentionally
bool is_in_memory = browser_context_->IsOffTheRecord();
if (is_in_memory)
return false;
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!service)
return false;
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
if (spellcheck::UseBrowserSpellChecker()) {
spellcheck_platform::RemoveWord(service->platform_spell_checker(),
base::UTF8ToUTF16(word));
}
#endif
return service->GetCustomDictionary()->RemoveWord(word);
}
void Session::SetSpellCheckerEnabled(bool b) {
browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable,
b);
}
bool Session::IsSpellCheckerEnabled() const {
return browser_context_->prefs()->GetBoolean(
spellcheck::prefs::kSpellCheckEnable);
}
#endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
// static
Session* Session::FromBrowserContext(content::BrowserContext* context) {
auto* data =
static_cast<UserDataLink*>(context->GetUserData(kElectronApiSessionKey));
return data ? data->session : nullptr;
}
// static
gin::Handle<Session> Session::CreateFrom(
v8::Isolate* isolate,
ElectronBrowserContext* browser_context) {
Session* existing = FromBrowserContext(browser_context);
if (existing)
return gin::CreateHandle(isolate, existing);
auto handle =
gin::CreateHandle(isolate, new Session(isolate, browser_context));
// The Sessions should never be garbage collected, since the common pattern is
// to use partition strings, instead of using the Session object directly.
handle->Pin(isolate);
App::Get()->EmitWithoutEvent("session-created", handle);
return handle;
}
// static
gin::Handle<Session> Session::FromPartition(v8::Isolate* isolate,
const std::string& partition,
base::Value::Dict options) {
ElectronBrowserContext* browser_context;
if (partition.empty()) {
browser_context =
ElectronBrowserContext::From("", false, std::move(options));
} else if (base::StartsWith(partition, kPersistPrefix,
base::CompareCase::SENSITIVE)) {
std::string name = partition.substr(8);
browser_context =
ElectronBrowserContext::From(name, false, std::move(options));
} else {
browser_context =
ElectronBrowserContext::From(partition, true, std::move(options));
}
return CreateFrom(isolate, browser_context);
}
// static
absl::optional<gin::Handle<Session>> Session::FromPath(
v8::Isolate* isolate,
const base::FilePath& path,
base::Value::Dict options) {
ElectronBrowserContext* browser_context;
if (path.empty()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("An empty path was specified");
return absl::nullopt;
}
if (!path.IsAbsolute()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("An absolute path was not provided");
return absl::nullopt;
}
browser_context =
ElectronBrowserContext::FromPath(std::move(path), std::move(options));
return CreateFrom(isolate, browser_context);
}
// static
gin::Handle<Session> Session::New() {
gin_helper::ErrorThrower(JavascriptEnvironment::GetIsolate())
.ThrowError("Session objects cannot be created with 'new'");
return gin::Handle<Session>();
}
void Session::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::ObjectTemplateBuilder(isolate, "Session", templ)
.SetMethod("resolveHost", &Session::ResolveHost)
.SetMethod("resolveProxy", &Session::ResolveProxy)
.SetMethod("getCacheSize", &Session::GetCacheSize)
.SetMethod("clearCache", &Session::ClearCache)
.SetMethod("clearStorageData", &Session::ClearStorageData)
.SetMethod("flushStorageData", &Session::FlushStorageData)
.SetMethod("setProxy", &Session::SetProxy)
.SetMethod("forceReloadProxyConfig", &Session::ForceReloadProxyConfig)
.SetMethod("setDownloadPath", &Session::SetDownloadPath)
.SetMethod("enableNetworkEmulation", &Session::EnableNetworkEmulation)
.SetMethod("disableNetworkEmulation", &Session::DisableNetworkEmulation)
.SetMethod("setCertificateVerifyProc", &Session::SetCertVerifyProc)
.SetMethod("setPermissionRequestHandler",
&Session::SetPermissionRequestHandler)
.SetMethod("setPermissionCheckHandler",
&Session::SetPermissionCheckHandler)
.SetMethod("setDisplayMediaRequestHandler",
&Session::SetDisplayMediaRequestHandler)
.SetMethod("setDevicePermissionHandler",
&Session::SetDevicePermissionHandler)
.SetMethod("setUSBProtectedClassesHandler",
&Session::SetUSBProtectedClassesHandler)
.SetMethod("setBluetoothPairingHandler",
&Session::SetBluetoothPairingHandler)
.SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache)
.SetMethod("clearAuthCache", &Session::ClearAuthCache)
.SetMethod("allowNTLMCredentialsForDomains",
&Session::AllowNTLMCredentialsForDomains)
.SetMethod("isPersistent", &Session::IsPersistent)
.SetMethod("setUserAgent", &Session::SetUserAgent)
.SetMethod("getUserAgent", &Session::GetUserAgent)
.SetMethod("setSSLConfig", &Session::SetSSLConfig)
.SetMethod("getBlobData", &Session::GetBlobData)
.SetMethod("downloadURL", &Session::DownloadURL)
.SetMethod("createInterruptedDownload",
&Session::CreateInterruptedDownload)
.SetMethod("setPreloads", &Session::SetPreloads)
.SetMethod("getPreloads", &Session::GetPreloads)
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
.SetMethod("loadExtension", &Session::LoadExtension)
.SetMethod("removeExtension", &Session::RemoveExtension)
.SetMethod("getExtension", &Session::GetExtension)
.SetMethod("getAllExtensions", &Session::GetAllExtensions)
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
.SetMethod("getSpellCheckerLanguages", &Session::GetSpellCheckerLanguages)
.SetMethod("setSpellCheckerLanguages", &Session::SetSpellCheckerLanguages)
.SetProperty("availableSpellCheckerLanguages",
&spellcheck::SpellCheckLanguages)
.SetMethod("setSpellCheckerDictionaryDownloadURL",
&SetSpellCheckerDictionaryDownloadURL)
.SetMethod("listWordsInSpellCheckerDictionary",
&Session::ListWordsInSpellCheckerDictionary)
.SetMethod("addWordToSpellCheckerDictionary",
&Session::AddWordToSpellCheckerDictionary)
.SetMethod("removeWordFromSpellCheckerDictionary",
&Session::RemoveWordFromSpellCheckerDictionary)
.SetMethod("setSpellCheckerEnabled", &Session::SetSpellCheckerEnabled)
.SetMethod("isSpellCheckerEnabled", &Session::IsSpellCheckerEnabled)
.SetProperty("spellCheckerEnabled", &Session::IsSpellCheckerEnabled,
&Session::SetSpellCheckerEnabled)
#endif
.SetMethod("preconnect", &Session::Preconnect)
.SetMethod("closeAllConnections", &Session::CloseAllConnections)
.SetMethod("getStoragePath", &Session::GetPath)
.SetMethod("setCodeCachePath", &Session::SetCodeCachePath)
.SetMethod("clearCodeCaches", &Session::ClearCodeCaches)
.SetProperty("cookies", &Session::Cookies)
.SetProperty("netLog", &Session::NetLog)
.SetProperty("protocol", &Session::Protocol)
.SetProperty("serviceWorkers", &Session::ServiceWorkerContext)
.SetProperty("webRequest", &Session::WebRequest)
.SetProperty("storagePath", &Session::GetPath)
.Build();
}
const char* Session::GetTypeName() {
return "Session";
}
} // namespace electron::api
namespace {
using electron::api::Session;
v8::Local<v8::Value> FromPartition(const std::string& partition,
gin::Arguments* args) {
if (!electron::Browser::Get()->is_ready()) {
args->ThrowTypeError("Session can only be received when app is ready");
return v8::Null(args->isolate());
}
base::Value::Dict options;
args->GetNext(&options);
return Session::FromPartition(args->isolate(), partition, std::move(options))
.ToV8();
}
v8::Local<v8::Value> FromPath(const base::FilePath& path,
gin::Arguments* args) {
if (!electron::Browser::Get()->is_ready()) {
args->ThrowTypeError("Session can only be received when app is ready");
return v8::Null(args->isolate());
}
base::Value::Dict options;
args->GetNext(&options);
absl::optional<gin::Handle<Session>> session_handle =
Session::FromPath(args->isolate(), path, std::move(options));
if (session_handle)
return session_handle.value().ToV8();
else
return v8::Null(args->isolate());
}
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("Session", Session::GetConstructor(context));
dict.SetMethod("fromPartition", &FromPartition);
dict.SetMethod("fromPath", &FromPath);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_session, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
shell/browser/api/electron_api_session.h
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SESSION_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SESSION_H_
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/values.h"
#include "content/public/browser/download_manager.h"
#include "electron/buildflags/buildflags.h"
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "services/network/public/mojom/host_resolver.mojom.h"
#include "services/network/public/mojom/ssl_config.mojom.h"
#include "shell/browser/event_emitter_mixin.h"
#include "shell/browser/net/resolve_proxy_helper.h"
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/function_template_extensions.h"
#include "shell/common/gin_helper/pinnable.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
#endif
class GURL;
namespace base {
class FilePath;
}
namespace gin_helper {
class Dictionary;
}
namespace gin {
class Arguments;
}
namespace net {
class ProxyConfig;
}
namespace electron {
class ElectronBrowserContext;
namespace api {
class Session : public gin::Wrappable<Session>,
public gin_helper::Pinnable<Session>,
public gin_helper::Constructible<Session>,
public gin_helper::EventEmitterMixin<Session>,
public gin_helper::CleanedUpAtExit,
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
public SpellcheckHunspellDictionary::Observer,
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
public extensions::ExtensionRegistryObserver,
#endif
public content::DownloadManager::Observer {
public:
// Gets or creates Session from the |browser_context|.
static gin::Handle<Session> CreateFrom(
v8::Isolate* isolate,
ElectronBrowserContext* browser_context);
static gin::Handle<Session> New(); // Dummy, do not use!
static Session* FromBrowserContext(content::BrowserContext* context);
// Gets the Session of |partition|.
static gin::Handle<Session> FromPartition(v8::Isolate* isolate,
const std::string& partition,
base::Value::Dict options = {});
// Gets the Session based on |path|.
static absl::optional<gin::Handle<Session>> FromPath(
v8::Isolate* isolate,
const base::FilePath& path,
base::Value::Dict options = {});
ElectronBrowserContext* browser_context() const { return browser_context_; }
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
const char* GetTypeName() override;
// Methods.
v8::Local<v8::Promise> ResolveHost(
std::string host,
absl::optional<network::mojom::ResolveHostParametersPtr> params);
v8::Local<v8::Promise> ResolveProxy(gin::Arguments* args);
v8::Local<v8::Promise> GetCacheSize();
v8::Local<v8::Promise> ClearCache();
v8::Local<v8::Promise> ClearStorageData(gin::Arguments* args);
void FlushStorageData();
v8::Local<v8::Promise> SetProxy(gin::Arguments* args);
v8::Local<v8::Promise> ForceReloadProxyConfig();
void SetDownloadPath(const base::FilePath& path);
void EnableNetworkEmulation(const gin_helper::Dictionary& options);
void DisableNetworkEmulation();
void SetCertVerifyProc(v8::Local<v8::Value> proc, gin::Arguments* args);
void SetPermissionRequestHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetPermissionCheckHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetDevicePermissionHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetUSBProtectedClassesHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetBluetoothPairingHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
v8::Local<v8::Promise> ClearHostResolverCache(gin::Arguments* args);
v8::Local<v8::Promise> ClearAuthCache();
void AllowNTLMCredentialsForDomains(const std::string& domains);
void SetUserAgent(const std::string& user_agent, gin::Arguments* args);
std::string GetUserAgent();
void SetSSLConfig(network::mojom::SSLConfigPtr config);
bool IsPersistent();
v8::Local<v8::Promise> GetBlobData(v8::Isolate* isolate,
const std::string& uuid);
void DownloadURL(const GURL& url);
void CreateInterruptedDownload(const gin_helper::Dictionary& options);
void SetPreloads(const std::vector<base::FilePath>& preloads);
std::vector<base::FilePath> GetPreloads() const;
v8::Local<v8::Value> Cookies(v8::Isolate* isolate);
v8::Local<v8::Value> Protocol(v8::Isolate* isolate);
v8::Local<v8::Value> ServiceWorkerContext(v8::Isolate* isolate);
v8::Local<v8::Value> WebRequest(v8::Isolate* isolate);
v8::Local<v8::Value> NetLog(v8::Isolate* isolate);
void Preconnect(const gin_helper::Dictionary& options, gin::Arguments* args);
v8::Local<v8::Promise> CloseAllConnections();
v8::Local<v8::Value> GetPath(v8::Isolate* isolate);
void SetCodeCachePath(gin::Arguments* args);
v8::Local<v8::Promise> ClearCodeCaches(const gin_helper::Dictionary& options);
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
base::Value GetSpellCheckerLanguages();
void SetSpellCheckerLanguages(gin_helper::ErrorThrower thrower,
const std::vector<std::string>& languages);
v8::Local<v8::Promise> ListWordsInSpellCheckerDictionary();
bool AddWordToSpellCheckerDictionary(const std::string& word);
bool RemoveWordFromSpellCheckerDictionary(const std::string& word);
void SetSpellCheckerEnabled(bool b);
bool IsSpellCheckerEnabled() const;
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
v8::Local<v8::Promise> LoadExtension(const base::FilePath& extension_path,
gin::Arguments* args);
void RemoveExtension(const std::string& extension_id);
v8::Local<v8::Value> GetExtension(const std::string& extension_id);
v8::Local<v8::Value> GetAllExtensions();
// extensions::ExtensionRegistryObserver:
void OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) override;
void OnExtensionReady(content::BrowserContext* browser_context,
const extensions::Extension* extension) override;
void OnExtensionUnloaded(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) override;
#endif
// disable copy
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
protected:
Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context);
~Session() override;
// content::DownloadManager::Observer:
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) override;
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
// SpellcheckHunspellDictionary::Observer
void OnHunspellDictionaryInitialized(const std::string& language) override;
void OnHunspellDictionaryDownloadBegin(const std::string& language) override;
void OnHunspellDictionaryDownloadSuccess(
const std::string& language) override;
void OnHunspellDictionaryDownloadFailure(
const std::string& language) override;
#endif
private:
void SetDisplayMediaRequestHandler(v8::Isolate* isolate,
v8::Local<v8::Value> val);
// Cached gin_helper::Wrappable objects.
v8::Global<v8::Value> cookies_;
v8::Global<v8::Value> protocol_;
v8::Global<v8::Value> net_log_;
v8::Global<v8::Value> service_worker_context_;
v8::Global<v8::Value> web_request_;
raw_ptr<v8::Isolate> isolate_;
// The client id to enable the network throttler.
base::UnguessableToken network_emulation_token_;
raw_ptr<ElectronBrowserContext> browser_context_;
};
} // namespace api
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SESSION_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
spec/api-session-spec.ts
|
import { expect } from 'chai';
import * as http from 'node:http';
import * as https from 'node:https';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as ChildProcess from 'node:child_process';
import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main';
import * as send from 'send';
import * as auth from 'basic-auth';
import { closeAllWindows } from './lib/window-helpers';
import { defer, listen } from './lib/spec-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
describe('session module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
const url = 'http://127.0.0.1';
describe('session.defaultSession', () => {
it('returns the default session', () => {
expect(session.defaultSession).to.equal(session.fromPartition(''));
});
});
describe('session.fromPartition(partition, options)', () => {
it('returns existing session with same partition', () => {
expect(session.fromPartition('test')).to.equal(session.fromPartition('test'));
});
});
describe('session.fromPath(path)', () => {
it('returns storage path of a session which was created with an absolute path', () => {
const tmppath = require('electron').app.getPath('temp');
const ses = session.fromPath(tmppath);
expect(ses.storagePath).to.equal(tmppath);
});
});
describe('ses.cookies', () => {
const name = '0';
const value = '0';
afterEach(closeAllWindows);
// Clear cookie of defaultSession after each test.
afterEach(async () => {
const { cookies } = session.defaultSession;
const cs = await cookies.get({ url });
for (const c of cs) {
await cookies.remove(url, c.name);
}
});
it('should get cookies', async () => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`]);
res.end('finished');
server.close();
});
const { port } = await listen(server);
const w = new BrowserWindow({ show: false });
await w.loadURL(`${url}:${port}`);
const list = await w.webContents.session.cookies.get({ url });
const cookie = list.find(cookie => cookie.name === name);
expect(cookie).to.exist.and.to.have.property('value', value);
});
it('sets cookies', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(false);
});
it('sets session cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '1';
await cookies.set({ url, name, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(true);
});
it('sets cookies without name', async () => {
const { cookies } = session.defaultSession;
const value = '3';
await cookies.set({ url, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
});
for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) {
it(`sets cookies with samesite=${sameSite}`, async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await cookies.set({ url, value, sameSite });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
expect(c.sameSite).to.equal(sameSite);
});
}
it('fails to set cookies with samesite=garbage', async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await expect(cookies.set({ url, value, sameSite: 'garbage' as any })).to.eventually.be.rejectedWith('Failed to convert \'garbage\' to an appropriate cookie same site value');
});
it('gets cookies without url', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const cs = await cookies.get({ domain: '127.0.0.1' });
expect(cs.some(c => c.name === name && c.value === value)).to.equal(true);
});
it('yields an error when setting a cookie with missing required fields', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: '', name, value })
).to.eventually.be.rejectedWith('Failed to set cookie with an invalid domain attribute');
});
it('yields an error when setting a cookie with an invalid URL', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: 'asdf', name, value })
).to.eventually.be.rejectedWith('Failed to set cookie with an invalid domain attribute');
});
it('should overwrite previous cookies', async () => {
const { cookies } = session.defaultSession;
const name = 'DidOverwrite';
for (const value of ['No', 'Yes']) {
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true);
}
});
it('should remove cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '2';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
await cookies.remove(url, name);
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false);
});
// DISABLED-FIXME
it('should set cookie for standard scheme', async () => {
const { cookies } = session.defaultSession;
const domain = 'fake-host';
const url = `${standardScheme}://${domain}`;
const name = 'custom';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list).to.have.lengthOf(1);
expect(list[0]).to.have.property('name', name);
expect(list[0]).to.have.property('value', value);
expect(list[0]).to.have.property('domain', domain);
});
it('emits a changed event when a cookie is added or removed', async () => {
const { cookies } = session.fromPartition('cookies-changed');
const name = 'foo';
const value = 'bar';
const a = once(cookies, 'changed');
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const [, setEventCookie, setEventCause, setEventRemoved] = await a;
const b = once(cookies, 'changed');
await cookies.remove(url, name);
const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b;
expect(setEventCookie.name).to.equal(name);
expect(setEventCookie.value).to.equal(value);
expect(setEventCause).to.equal('explicit');
expect(setEventRemoved).to.equal(false);
expect(removeEventCookie.name).to.equal(name);
expect(removeEventCookie.value).to.equal(value);
expect(removeEventCause).to.equal('explicit');
expect(removeEventRemoved).to.equal(true);
});
describe('ses.cookies.flushStore()', async () => {
it('flushes the cookies to disk', async () => {
const name = 'foo';
const value = 'bar';
const { cookies } = session.defaultSession;
await cookies.set({ url, name, value });
await cookies.flushStore();
});
});
it('should survive an app restart for persistent partition', async function () {
this.timeout(60000);
const appPath = path.join(fixtures, 'api', 'cookie-app');
const runAppWithPhase = (phase: string) => {
return new Promise((resolve) => {
let output = '';
const appProcess = ChildProcess.spawn(
process.execPath,
[appPath],
{ env: { PHASE: phase, ...process.env } }
);
appProcess.stdout.on('data', data => { output += data; });
appProcess.on('exit', () => {
resolve(output.replace(/(\r\n|\n|\r)/gm, ''));
});
});
};
expect(await runAppWithPhase('one')).to.equal('011');
expect(await runAppWithPhase('two')).to.equal('110');
});
});
describe('ses.clearStorageData(options)', () => {
afterEach(closeAllWindows);
it('clears localstorage data', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'));
const options = {
origin: 'file://',
storages: ['localstorage'],
quotas: ['persistent']
};
await w.webContents.session.clearStorageData(options);
while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
// The storage clear isn't instantly visible to the renderer, so keep
// trying until it is.
}
});
});
describe('will-download event', () => {
afterEach(closeAllWindows);
it('can cancel default download behavior', async () => {
const w = new BrowserWindow({ show: false });
const mockFile = Buffer.alloc(1024);
const contentDisposition = 'inline; filename="mockFile.txt"';
const downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockFile.length,
'Content-Type': 'application/plain',
'Content-Disposition': contentDisposition
});
res.end(mockFile);
downloadServer.close();
});
const url = (await listen(downloadServer)).url;
const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
e.preventDefault();
resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item });
});
});
w.loadURL(url);
const { item, itemUrl, itemFilename } = await downloadPrevented;
expect(itemUrl).to.equal(url + '/');
expect(itemFilename).to.equal('mockFile.txt');
// Delay till the next tick.
await new Promise(setImmediate);
expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
});
});
describe('ses.protocol', () => {
const partitionName = 'temp';
const protocolName = 'sp';
let customSession: Session;
const protocol = session.defaultSession.protocol;
const handler = (ignoredError: any, callback: Function) => {
callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' });
};
beforeEach(async () => {
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
});
afterEach(async () => {
await customSession.protocol.unregisterProtocol(protocolName);
customSession = null as any;
});
afterEach(closeAllWindows);
it('does not affect defaultSession', () => {
const result1 = protocol.isProtocolRegistered(protocolName);
expect(result1).to.equal(false);
const result2 = customSession.protocol.isProtocolRegistered(protocolName);
expect(result2).to.equal(true);
});
it('handles requests from partition', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: partitionName,
nodeIntegration: true,
contextIsolation: false
}
});
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
w.loadURL(`${protocolName}://fake-host`);
await once(ipcMain, 'hello');
});
});
describe('ses.setProxy(options)', () => {
let server: http.Server;
let customSession: Electron.Session;
let created = false;
beforeEach(async () => {
customSession = session.fromPartition('proxyconfig');
if (!created) {
// Work around for https://github.com/electron/electron/issues/26166 to
// reduce flake
await setTimeout(100);
created = true;
}
});
afterEach(() => {
if (server) {
server.close();
}
customSession = null as any;
});
it('allows configuring proxy settings', async () => {
const config = { proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows removing the implicit bypass rules for localhost', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<-loopback>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://localhost');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with pacScript', async () => {
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:8132";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
const { url } = await listen(server);
{
const config = { pacScript: url };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
{
const config = { mode: 'pac_script' as any, pacScript: url };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
});
it('allows bypassing proxy settings', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<local>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `direct`', async () => {
const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `auto_detect`', async () => {
const config = { mode: 'auto_detect' as any };
await customSession.setProxy(config);
});
it('allows configuring proxy settings with mode `pac_script`', async () => {
const config = { mode: 'pac_script' as any };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `fixed_servers`', async () => {
const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with mode `system`', async () => {
const config = { mode: 'system' as any };
await customSession.setProxy(config);
});
it('disallows configuring proxy settings with mode `invalid`', async () => {
const config = { mode: 'invalid' as any };
await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
});
it('reload proxy configuration', async () => {
let proxyPort = 8132;
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:${proxyPort}";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
const { url } = await listen(server);
const config = { mode: 'pac_script' as any, pacScript: url };
await customSession.setProxy(config);
{
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
{
proxyPort = 8133;
await customSession.forceReloadProxyConfig();
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
});
});
describe('ses.resolveHost(host)', () => {
let customSession: Electron.Session;
beforeEach(async () => {
customSession = session.fromPartition('resolvehost');
});
afterEach(() => {
customSession = null as any;
});
it('resolves ipv4.localhost2', async () => {
const { endpoints } = await customSession.resolveHost('ipv4.localhost2');
expect(endpoints).to.be.a('array');
expect(endpoints).to.have.lengthOf(1);
expect(endpoints[0].family).to.equal('ipv4');
expect(endpoints[0].address).to.equal('10.0.0.1');
});
it('fails to resolve AAAA record for ipv4.localhost2', async () => {
await expect(customSession.resolveHost('ipv4.localhost2', {
queryType: 'AAAA'
}))
.to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
it('resolves ipv6.localhost2', async () => {
const { endpoints } = await customSession.resolveHost('ipv6.localhost2');
expect(endpoints).to.be.a('array');
expect(endpoints).to.have.lengthOf(1);
expect(endpoints[0].family).to.equal('ipv6');
expect(endpoints[0].address).to.equal('::1');
});
it('fails to resolve A record for ipv6.localhost2', async () => {
await expect(customSession.resolveHost('notfound.localhost2', {
queryType: 'A'
}))
.to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
it('fails to resolve notfound.localhost2', async () => {
await expect(customSession.resolveHost('notfound.localhost2'))
.to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
});
describe('ses.getBlobData()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const postData = JSON.stringify({
type: 'blob',
value: 'hello'
});
const content = `<html>
<script>
let fd = new FormData();
fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
expect(result.toString()).to.equal(postData);
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.getBlobData2()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const content = `<html>
<script>
let fd = new FormData();
fd.append("data", new Blob(new Array(65_537).fill('a')));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
const data = new Array(65_537).fill('a');
expect(result.toString()).to.equal(data.join(''));
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.setCertificateVerifyProc(callback)', () => {
let server: http.Server;
let serverUrl: string;
beforeEach(async () => {
const certPath = path.join(fixtures, 'certificates');
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
rejectUnauthorized: false
};
server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('<title>hello</title>');
});
serverUrl = (await listen(server)).url;
});
afterEach((done) => {
server.close(done);
});
afterEach(closeAllWindows);
it('accepts the request when the callback is called with 0', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(errorCode).to.be.oneOf([-202, -200]);
};
callback(0);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
expect(w.webContents.getTitle()).to.equal('hello');
expect(validate!).not.to.be.undefined();
validate!();
});
it('rejects the request when the callback is called with -2', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(certificate.issuerName).to.equal('Intermediate CA');
expect(certificate.subjectName).to.equal('localhost');
expect(certificate.issuer.commonName).to.equal('Intermediate CA');
expect(certificate.subject.commonName).to.equal('localhost');
expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(isIssuedByKnownRoot).to.be.false();
};
callback(-2);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(serverUrl)).to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(validate!).not.to.be.undefined();
validate!();
});
it('saves cached results', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let numVerificationRequests = 0;
ses.setCertificateVerifyProc((e, callback) => {
if (e.hostname !== '127.0.0.1') return callback(-3);
numVerificationRequests++;
callback(-2);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(serverUrl), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
await once(w.webContents, 'did-stop-loading');
await expect(w.loadURL(serverUrl + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(numVerificationRequests).to.equal(1);
});
it('does not cancel requests in other sessions', async () => {
const ses1 = session.fromPartition(`${Math.random()}`);
ses1.setCertificateVerifyProc((opts, cb) => cb(0));
const ses2 = session.fromPartition(`${Math.random()}`);
const req = net.request({ url: serverUrl, session: ses1, credentials: 'include' });
req.end();
setTimeout().then(() => {
ses2.setCertificateVerifyProc((opts, callback) => callback(0));
});
await expect(new Promise<void>((resolve, reject) => {
req.on('error', (err) => {
reject(err);
});
req.on('response', () => {
resolve();
});
})).to.eventually.be.fulfilled();
});
});
describe('ses.clearAuthCache()', () => {
it('can clear http auth info from cache', async () => {
const ses = session.fromPartition('auth-cache');
const server = http.createServer((req, res) => {
const credentials = auth(req);
if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
res.end();
} else {
res.end('authenticated');
}
});
const { port } = await listen(server);
const fetch = (url: string) => new Promise((resolve, reject) => {
const request = net.request({ url, session: ses });
request.on('response', (response) => {
let data: string | null = null;
response.on('data', (chunk) => {
if (!data) {
data = '';
}
data += chunk;
});
response.on('end', () => {
if (!data) {
reject(new Error('Empty response'));
} else {
resolve(data);
}
});
response.on('error', (error: any) => { reject(new Error(error)); });
});
request.on('error', (error: any) => { reject(new Error(error)); });
request.end();
});
// the first time should throw due to unauthenticated
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
// passing the password should let us in
expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
// subsequently, the credentials are cached
expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
await ses.clearAuthCache();
// once the cache is cleared, we should get an error again
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
});
});
describe('DownloadItem', () => {
const mockPDF = Buffer.alloc(1024 * 1024 * 5);
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const protocolName = 'custom-dl';
const contentDisposition = 'inline; filename="mock.pdf"';
let port: number;
let downloadServer: http.Server;
before(async () => {
downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockPDF.length,
'Content-Type': 'application/pdf',
'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
});
res.end(mockPDF);
});
port = (await listen(downloadServer)).port;
});
after(async () => {
await new Promise(resolve => downloadServer.close(resolve));
});
afterEach(closeAllWindows);
const isPathEqual = (path1: string, path2: string) => {
return path.relative(path1, path2) === '';
};
const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
expect(state).to.equal('completed');
expect(item.getFilename()).to.equal('mock.pdf');
expect(path.isAbsolute(item.savePath)).to.equal(true);
expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
if (isCustom) {
expect(item.getURL()).to.equal(`${protocolName}://item`);
} else {
expect(item.getURL()).to.be.equal(`${url}:${port}/`);
}
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(mockPDF.length);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
fs.unlinkSync(downloadFilePath);
};
it('can download using session.downloadURL', (done) => {
session.defaultSession.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
session.defaultSession.downloadURL(`${url}:${port}`);
});
it('can download using WebContents.downloadURL', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${url}:${port}`);
});
it('can download from custom protocols using WebContents.downloadURL', (done) => {
const protocol = session.defaultSession.protocol;
const handler = (ignoredError: any, callback: Function) => {
callback({ url: `${url}:${port}` });
};
protocol.registerHttpProtocol(protocolName, handler);
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item, true);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${protocolName}://item`);
});
it('can download using WebView.downloadURL', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
await w.loadURL('about:blank');
function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) {
const webview = new (window as any).WebView();
webview.addEventListener('did-finish-load', () => {
webview.downloadURL(`${url}:${port}/`);
});
webview.src = `file://${fixtures}/api/blank.html`;
document.body.appendChild(webview);
}
const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
resolve([state, item]);
});
});
});
await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
const [state, item] = await done;
assertDownload(state, item);
});
it('can cancel download', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
expect(state).to.equal('cancelled');
expect(item.getFilename()).to.equal('mock.pdf');
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(0);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/`);
});
it('can generate a default filename', function (done) {
if (process.env.APPVEYOR === 'True') {
// FIXME(alexeykuzmin): Skip the test.
// this.skip()
return done();
}
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function () {
try {
expect(item.getFilename()).to.equal('download.pdf');
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/?testFilename`);
});
it('can set options for the save dialog', (done) => {
const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
const options = {
window: null,
title: 'title',
message: 'message',
buttonLabel: 'buttonLabel',
nameFieldLabel: 'nameFieldLabel',
defaultPath: '/',
filters: [{
name: '1', extensions: ['.1', '.2']
}, {
name: '2', extensions: ['.3', '.4', '.5']
}],
showsTagField: true,
securityScopedBookmarks: true
};
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(filePath);
item.setSaveDialogOptions(options);
item.on('done', function () {
try {
expect(item.getSaveDialogOptions()).to.deep.equal(options);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}`);
});
describe('when a save path is specified and the URL is unavailable', () => {
it('does not display a save dialog and reports the done state as interrupted', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
if (item.getState() === 'interrupted') {
item.resume();
}
item.on('done', function (e, state) {
try {
expect(state).to.equal('interrupted');
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
});
});
});
describe('ses.createInterruptedDownload(options)', () => {
afterEach(closeAllWindows);
it('can create an interrupted download item', async () => {
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const options = {
path: downloadFilePath,
urlChain: ['http://127.0.0.1/'],
mimeType: 'application/pdf',
offset: 0,
length: 5242880
};
const w = new BrowserWindow({ show: false });
const p = once(w.webContents.session, 'will-download');
w.webContents.session.createInterruptedDownload(options);
const [, item] = await p;
expect(item.getState()).to.equal('interrupted');
item.cancel();
expect(item.getURLChain()).to.deep.equal(options.urlChain);
expect(item.getMimeType()).to.equal(options.mimeType);
expect(item.getReceivedBytes()).to.equal(options.offset);
expect(item.getTotalBytes()).to.equal(options.length);
expect(item.savePath).to.equal(downloadFilePath);
});
it('can be resumed', async () => {
const downloadFilePath = path.join(fixtures, 'logo.png');
const rangeServer = http.createServer((req, res) => {
const options = { root: fixtures };
send(req, req.url!, options)
.on('error', (error: any) => { throw error; }).pipe(res);
});
try {
const { url } = await listen(rangeServer);
const w = new BrowserWindow({ show: false });
const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(downloadFilePath);
item.on('done', function () {
resolve(item);
});
item.cancel();
});
});
const downloadUrl = `${url}/assets/logo.png`;
w.webContents.downloadURL(downloadUrl);
const item = await downloadCancelled;
expect(item.getState()).to.equal('cancelled');
const options = {
path: item.savePath,
urlChain: item.getURLChain(),
mimeType: item.getMimeType(),
offset: item.getReceivedBytes(),
length: item.getTotalBytes(),
lastModified: item.getLastModifiedTime(),
eTag: item.getETag()
};
const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
expect(item.getState()).to.equal('interrupted');
item.setSavePath(downloadFilePath);
item.resume();
item.on('done', function () {
resolve(item);
});
});
});
w.webContents.session.createInterruptedDownload(options);
const completedItem = await downloadResumed;
expect(completedItem.getState()).to.equal('completed');
expect(completedItem.getFilename()).to.equal('logo.png');
expect(completedItem.savePath).to.equal(downloadFilePath);
expect(completedItem.getURL()).to.equal(downloadUrl);
expect(completedItem.getMimeType()).to.equal('image/png');
expect(completedItem.getReceivedBytes()).to.equal(14022);
expect(completedItem.getTotalBytes()).to.equal(14022);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
} finally {
rangeServer.close();
}
});
});
describe('ses.setPermissionRequestHandler(handler)', () => {
afterEach(closeAllWindows);
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('cancels any pending requests when cleared', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler',
nodeIntegration: true,
contextIsolation: false
}
});
const ses = w.webContents.session;
ses.setPermissionRequestHandler(() => {
ses.setPermissionRequestHandler(null);
});
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb(`<html><script>(${remote})()</script></html>`);
});
const result = once(require('electron').ipcMain, 'message');
function remote () {
(navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
require('electron').ipcRenderer.send('message', err.name);
});
}
await w.loadURL('https://myfakesite');
const [, name] = await result;
expect(name).to.deep.equal('SecurityError');
});
it('successfully resolves when calling legacy getUserMedia', async () => {
const ses = session.fromPartition('' + Math.random());
ses.setPermissionRequestHandler(
(_webContents, _permission, callback) => {
callback(true);
}
);
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const { ok, message } = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => navigator.getUserMedia({
video: true,
audio: true,
}, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message})))
`);
expect(ok).to.be.true(message);
});
it('successfully rejects when calling legacy getUserMedia', async () => {
const ses = session.fromPartition('' + Math.random());
ses.setPermissionRequestHandler(
(_webContents, _permission, callback) => {
callback(false);
}
);
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
await expect(w.webContents.executeJavaScript(`
new Promise((resolve, reject) => navigator.getUserMedia({
video: true,
audio: true,
}, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message})))
`)).to.eventually.be.rejectedWith('Permission denied');
});
});
describe('ses.setPermissionCheckHandler(handler)', () => {
afterEach(closeAllWindows);
it('details provides requestingURL for mainFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = () => {
return w.webContents.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadURL(loadUrl);
const state = await readClipboardPermission();
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
});
it('details provides requestingURL for cross origin subFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = (frame: WebFrameMain) => {
return frame.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe');
iframe.src = '${loadUrl}';
document.body.appendChild(iframe);
null;
`);
const [,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-finish-load');
const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId));
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
expect(handlerDetails!.isMainFrame).to.be.false();
expect(handlerDetails!.embeddingOrigin).to.equal('file:///');
});
});
describe('ses.isPersistent()', () => {
afterEach(closeAllWindows);
it('returns default session as persistent', () => {
const w = new BrowserWindow({
show: false
});
const ses = w.webContents.session;
expect(ses.isPersistent()).to.be.true();
});
it('returns persist: session as persistent', () => {
const ses = session.fromPartition(`persist:${Math.random()}`);
expect(ses.isPersistent()).to.be.true();
});
it('returns temporary session as not persistent', () => {
const ses = session.fromPartition(`${Math.random()}`);
expect(ses.isPersistent()).to.be.false();
});
});
describe('ses.setUserAgent()', () => {
afterEach(closeAllWindows);
it('can be retrieved with getUserAgent()', () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent);
expect(ses.getUserAgent()).to.equal(userAgent);
});
it('sets the User-Agent header for web requests made from renderers', async () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent, 'en-US,fr,de');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
let headers: http.IncomingHttpHeaders | null = null;
const server = http.createServer((req, res) => {
headers = req.headers;
res.end();
server.close();
});
const { url } = await listen(server);
await w.loadURL(url);
expect(headers!['user-agent']).to.equal(userAgent);
expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
});
});
describe('session-created event', () => {
it('is emitted when a session is created', async () => {
const sessionCreated = once(app, 'session-created');
const session1 = session.fromPartition('' + Math.random());
const [session2] = await sessionCreated;
expect(session1).to.equal(session2);
});
});
describe('session.storagePage', () => {
it('returns a string', () => {
expect(session.defaultSession.storagePath).to.be.a('string');
});
it('returns null for in memory sessions', () => {
expect(session.fromPartition('in-memory').storagePath).to.equal(null);
});
it('returns different paths for partitions and the default session', () => {
expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
it('returns different paths for different partitions', () => {
expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
});
describe('session.setCodeCachePath()', () => {
it('throws when relative or empty path is provided', () => {
expect(() => {
session.defaultSession.setCodeCachePath('../fixtures');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath('');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache'));
}).to.not.throw();
});
});
describe('ses.setSSLConfig()', () => {
it('can disable cipher suites', async () => {
const ses = session.fromPartition('' + Math.random());
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
const server = https.createServer({
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.2',
ciphers: 'AES128-GCM-SHA256'
}, (req, res) => {
res.end('hi');
});
const { port } = await listen(server);
defer(() => server.close());
function request () {
return new Promise((resolve, reject) => {
const r = net.request({
url: `https://127.0.0.1:${port}`,
session: ses
});
r.on('response', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk.toString('utf8');
});
res.on('end', () => {
resolve(data);
});
});
r.on('error', (err) => {
reject(err);
});
r.end();
});
}
await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
ses.setSSLConfig({
disabledCipherSuites: [0x009C]
});
await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
docs/api/session.md
|
# session
> Manage browser sessions, cookies, cache, proxy settings, etc.
Process: [Main](../glossary.md#main-process)
The `session` module can be used to create new `Session` objects.
You can also access the `session` of existing pages by using the `session`
property of [`WebContents`](web-contents.md), or from the `session` module.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadURL('http://github.com')
const ses = win.webContents.session
console.log(ses.getUserAgent())
```
## Methods
The `session` module has the following methods:
### `session.fromPartition(partition[, options])`
* `partition` string
* `options` Object (optional)
* `cache` boolean - Whether to enable cache.
Returns `Session` - A session instance from `partition` string. When there is an existing
`Session` with the same `partition`, it will be returned; otherwise a new
`Session` instance will be created with `options`.
If `partition` starts with `persist:`, the page will use a persistent session
available to all pages in the app with the same `partition`. if there is no
`persist:` prefix, the page will use an in-memory session. If the `partition` is
empty then default session of the app will be returned.
To create a `Session` with `options`, you have to ensure the `Session` with the
`partition` has never been used before. There is no way to change the `options`
of an existing `Session` object.
### `session.fromPath(path[, options])`
* `path` string
* `options` Object (optional)
* `cache` boolean - Whether to enable cache.
Returns `Session` - A session instance from the absolute path as specified by the `path`
string. When there is an existing `Session` with the same absolute path, it
will be returned; otherwise a new `Session` instance will be created with `options`. The
call will throw an error if the path is not an absolute path. Additionally, an error will
be thrown if an empty string is provided.
To create a `Session` with `options`, you have to ensure the `Session` with the
`path` has never been used before. There is no way to change the `options`
of an existing `Session` object.
## Properties
The `session` module has the following properties:
### `session.defaultSession`
A `Session` object, the default session object of the app.
## Class: Session
> Get and set properties of a session.
Process: [Main](../glossary.md#main-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
You can create a `Session` object in the `session` module:
```javascript
const { session } = require('electron')
const ses = session.fromPartition('persist:name')
console.log(ses.getUserAgent())
```
### Instance Events
The following events are available on instances of `Session`:
#### Event: 'will-download'
Returns:
* `event` Event
* `item` [DownloadItem](download-item.md)
* `webContents` [WebContents](web-contents.md)
Emitted when Electron is about to download `item` in `webContents`.
Calling `event.preventDefault()` will cancel the download and `item` will not be
available from next tick of the process.
```javascript @ts-expect-error=[4]
const { session } = require('electron')
session.defaultSession.on('will-download', (event, item, webContents) => {
event.preventDefault()
require('got')(item.getURL()).then((response) => {
require('fs').writeFileSync('/somewhere', response.body)
})
})
```
#### Event: 'extension-loaded'
Returns:
* `event` Event
* `extension` [Extension](structures/extension.md)
Emitted after an extension is loaded. This occurs whenever an extension is
added to the "enabled" set of extensions. This includes:
* Extensions being loaded from `Session.loadExtension`.
* Extensions being reloaded:
* from a crash.
* if the extension requested it ([`chrome.runtime.reload()`](https://developer.chrome.com/extensions/runtime#method-reload)).
#### Event: 'extension-unloaded'
Returns:
* `event` Event
* `extension` [Extension](structures/extension.md)
Emitted after an extension is unloaded. This occurs when
`Session.removeExtension` is called.
#### Event: 'extension-ready'
Returns:
* `event` Event
* `extension` [Extension](structures/extension.md)
Emitted after an extension is loaded and all necessary browser state is
initialized to support the start of the extension's background page.
#### Event: 'preconnect'
Returns:
* `event` Event
* `preconnectUrl` string - The URL being requested for preconnection by the
renderer.
* `allowCredentials` boolean - True if the renderer is requesting that the
connection include credentials (see the
[spec](https://w3c.github.io/resource-hints/#preconnect) for more details.)
Emitted when a render process requests preconnection to a URL, generally due to
a [resource hint](https://w3c.github.io/resource-hints/).
#### Event: 'spellcheck-dictionary-initialized'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file has been successfully initialized. This
occurs after the file has been downloaded.
#### Event: 'spellcheck-dictionary-download-begin'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file starts downloading
#### Event: 'spellcheck-dictionary-download-success'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file has been successfully downloaded
#### Event: 'spellcheck-dictionary-download-failure'
Returns:
* `event` Event
* `languageCode` string - The language code of the dictionary file
Emitted when a hunspell dictionary file download fails. For details
on the failure you should collect a netlog and inspect the download
request.
#### Event: 'select-hid-device'
Returns:
* `event` Event
* `details` Object
* `deviceList` [HIDDevice[]](structures/hid-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
* `callback` Function
* `deviceId` string | null (optional)
Emitted when a HID device needs to be selected when a call to
`navigator.hid.requestDevice` is made. `callback` should be called with
`deviceId` to be selected; passing no arguments to `callback` will
cancel the request. Additionally, permissioning on `navigator.hid` can
be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler)
and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'hid') {
// Add logic here to determine if permission should be given to allow HID selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})
```
#### Event: 'hid-device-added'
Returns:
* `event` Event
* `details` Object
* `device` [HIDDevice[]](structures/hid-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
Emitted after `navigator.hid.requestDevice` has been called and
`select-hid-device` has fired if a new device becomes available before
the callback from `select-hid-device` is called. This event is intended for
use when using a UI to ask users to pick a device so that the UI can be updated
with the newly added device.
#### Event: 'hid-device-removed'
Returns:
* `event` Event
* `details` Object
* `device` [HIDDevice[]](structures/hid-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
Emitted after `navigator.hid.requestDevice` has been called and
`select-hid-device` has fired if a device has been removed before the callback
from `select-hid-device` is called. This event is intended for use when using
a UI to ask users to pick a device so that the UI can be updated to remove the
specified device.
#### Event: 'hid-device-revoked'
Returns:
* `event` Event
* `details` Object
* `device` [HIDDevice[]](structures/hid-device.md)
* `origin` string (optional) - The origin that the device has been revoked from.
Emitted after `HIDDevice.forget()` has been called. This event can be used
to help maintain persistent storage of permissions when
`setDevicePermissionHandler` is used.
#### Event: 'select-serial-port'
Returns:
* `event` Event
* `portList` [SerialPort[]](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)
* `callback` Function
* `portId` string
Emitted when a serial port needs to be selected when a call to
`navigator.serial.requestPort` is made. `callback` should be called with
`portId` to be selected, passing an empty string to `callback` will
cancel the request. Additionally, permissioning on `navigator.serial` can
be managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler)
with the `serial` permission.
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow({
width: 800,
height: 600
})
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'serial') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.serial.requestPort` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
event.preventDefault()
const selectedPort = portList.find((device) => {
return device.vendorId === '9025' && device.productId === '67'
})
if (!selectedPort) {
callback('')
} else {
callback(selectedPort.portId)
}
})
})
```
#### Event: 'serial-port-added'
Returns:
* `event` Event
* `port` [SerialPort](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.serial.requestPort` has been called and
`select-serial-port` has fired if a new serial port becomes available before
the callback from `select-serial-port` is called. This event is intended for
use when using a UI to ask users to pick a port so that the UI can be updated
with the newly added port.
#### Event: 'serial-port-removed'
Returns:
* `event` Event
* `port` [SerialPort](structures/serial-port.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.serial.requestPort` has been called and
`select-serial-port` has fired if a serial port has been removed before the
callback from `select-serial-port` is called. This event is intended for use
when using a UI to ask users to pick a port so that the UI can be updated
to remove the specified port.
#### Event: 'serial-port-revoked'
Returns:
* `event` Event
* `details` Object
* `port` [SerialPort](structures/serial-port.md)
* `frame` [WebFrameMain](web-frame-main.md)
* `origin` string - The origin that the device has been revoked from.
Emitted after `SerialPort.forget()` has been called. This event can be used
to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used.
```js
// Browser Process
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.webContents.session.on('serial-port-revoked', (event, details) => {
console.log(`Access revoked for serial device from origin ${details.origin}`)
})
})
```
```js
// Renderer Process
const portConnect = async () => {
// Request a port.
const port = await navigator.serial.requestPort()
// Wait for the serial port to open.
await port.open({ baudRate: 9600 })
// ...later, revoke access to the serial port.
await port.forget()
}
```
#### Event: 'select-usb-device'
Returns:
* `event` Event
* `details` Object
* `deviceList` [USBDevice[]](structures/usb-device.md)
* `frame` [WebFrameMain](web-frame-main.md)
* `callback` Function
* `deviceId` string (optional)
Emitted when a USB device needs to be selected when a call to
`navigator.usb.requestDevice` is made. `callback` should be called with
`deviceId` to be selected; passing no arguments to `callback` will
cancel the request. Additionally, permissioning on `navigator.usb` can
be further managed by using [`ses.setPermissionCheckHandler(handler)`](#sessetpermissioncheckhandlerhandler)
and [`ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)} @ts-type={updateGrantedDevices:(devices:Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)=>void}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'usb') {
// Add logic here to determine if permission should be given to allow USB selection
return true
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions)
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
}
return false
})
win.webContents.session.on('select-usb-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
if (selectedDevice) {
// Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions)
grantedDevices.push(selectedDevice)
updateGrantedDevices(grantedDevices)
}
callback(selectedDevice?.deviceId)
})
})
```
#### Event: 'usb-device-added'
Returns:
* `event` Event
* `device` [USBDevice](structures/usb-device.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.usb.requestDevice` has been called and
`select-usb-device` has fired if a new device becomes available before
the callback from `select-usb-device` is called. This event is intended for
use when using a UI to ask users to pick a device so that the UI can be updated
with the newly added device.
#### Event: 'usb-device-removed'
Returns:
* `event` Event
* `device` [USBDevice](structures/usb-device.md)
* `webContents` [WebContents](web-contents.md)
Emitted after `navigator.usb.requestDevice` has been called and
`select-usb-device` has fired if a device has been removed before the callback
from `select-usb-device` is called. This event is intended for use when using
a UI to ask users to pick a device so that the UI can be updated to remove the
specified device.
#### Event: 'usb-device-revoked'
Returns:
* `event` Event
* `details` Object
* `device` [USBDevice](structures/usb-device.md)
* `origin` string (optional) - The origin that the device has been revoked from.
Emitted after `USBDevice.forget()` has been called. This event can be used
to help maintain persistent storage of permissions when
`setDevicePermissionHandler` is used.
### Instance Methods
The following methods are available on instances of `Session`:
#### `ses.getCacheSize()`
Returns `Promise<Integer>` - the session's current cache size, in bytes.
#### `ses.clearCache()`
Returns `Promise<void>` - resolves when the cache clear operation is complete.
Clears the session’s HTTP cache.
#### `ses.clearStorageData([options])`
* `options` Object (optional)
* `origin` string (optional) - Should follow `window.location.origin`’s representation
`scheme://host:port`.
* `storages` string[] (optional) - The types of storages to clear, can contain:
`cookies`, `filesystem`, `indexdb`, `localstorage`,
`shadercache`, `websql`, `serviceworkers`, `cachestorage`. If not
specified, clear all storage types.
* `quotas` string[] (optional) - The types of quotas to clear, can contain:
`temporary`, `syncable`. If not specified, clear all quotas.
Returns `Promise<void>` - resolves when the storage data has been cleared.
#### `ses.flushStorageData()`
Writes any unwritten DOMStorage data to disk.
#### `ses.setProxy(config)`
* `config` Object
* `mode` string (optional) - The proxy mode. Should be one of `direct`,
`auto_detect`, `pac_script`, `fixed_servers` or `system`. If it's
unspecified, it will be automatically determined based on other specified
options.
* `direct`
In direct mode all connections are created directly, without any proxy involved.
* `auto_detect`
In auto_detect mode the proxy configuration is determined by a PAC script that can
be downloaded at http://wpad/wpad.dat.
* `pac_script`
In pac_script mode the proxy configuration is determined by a PAC script that is
retrieved from the URL specified in the `pacScript`. This is the default mode
if `pacScript` is specified.
* `fixed_servers`
In fixed_servers mode the proxy configuration is specified in `proxyRules`.
This is the default mode if `proxyRules` is specified.
* `system`
In system mode the proxy configuration is taken from the operating system.
Note that the system mode is different from setting no proxy configuration.
In the latter case, Electron falls back to the system settings
only if no command-line options influence the proxy configuration.
* `pacScript` string (optional) - The URL associated with the PAC file.
* `proxyRules` string (optional) - Rules indicating which proxies to use.
* `proxyBypassRules` string (optional) - Rules indicating which URLs should
bypass the proxy settings.
Returns `Promise<void>` - Resolves when the proxy setting process is complete.
Sets the proxy settings.
When `mode` is unspecified, `pacScript` and `proxyRules` are provided together, the `proxyRules`
option is ignored and `pacScript` configuration is applied.
You may need `ses.closeAllConnections` to close currently in flight connections to prevent
pooled sockets using previous proxy from being reused by future requests.
The `proxyRules` has to follow the rules below:
```sh
proxyRules = schemeProxies[";"<schemeProxies>]
schemeProxies = [<urlScheme>"="]<proxyURIList>
urlScheme = "http" | "https" | "ftp" | "socks"
proxyURIList = <proxyURL>[","<proxyURIList>]
proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]
```
For example:
* `http=foopy:80;ftp=foopy2` - Use HTTP proxy `foopy:80` for `http://` URLs, and
HTTP proxy `foopy2:80` for `ftp://` URLs.
* `foopy:80` - Use HTTP proxy `foopy:80` for all URLs.
* `foopy:80,bar,direct://` - Use HTTP proxy `foopy:80` for all URLs, failing
over to `bar` if `foopy:80` is unavailable, and after that using no proxy.
* `socks4://foopy` - Use SOCKS v4 proxy `foopy:1080` for all URLs.
* `http=foopy,socks5://bar.com` - Use HTTP proxy `foopy` for http URLs, and fail
over to the SOCKS5 proxy `bar.com` if `foopy` is unavailable.
* `http=foopy,direct://` - Use HTTP proxy `foopy` for http URLs, and use no
proxy if `foopy` is unavailable.
* `http=foopy;socks=foopy2` - Use HTTP proxy `foopy` for http URLs, and use
`socks4://foopy2` for all other URLs.
The `proxyBypassRules` is a comma separated list of rules described below:
* `[ URL_SCHEME "://" ] HOSTNAME_PATTERN [ ":" <port> ]`
Match all hostnames that match the pattern HOSTNAME_PATTERN.
Examples:
"foobar.com", "\*foobar.com", "\*.foobar.com", "\*foobar.com:99",
"https://x.\*.y.com:99"
* `"." HOSTNAME_SUFFIX_PATTERN [ ":" PORT ]`
Match a particular domain suffix.
Examples:
".google.com", ".com", "http://.google.com"
* `[ SCHEME "://" ] IP_LITERAL [ ":" PORT ]`
Match URLs which are IP address literals.
Examples:
"127.0.1", "\[0:0::1]", "\[::1]", "http://\[::1]:99"
* `IP_LITERAL "/" PREFIX_LENGTH_IN_BITS`
Match any URL that is to an IP literal that falls between the
given range. IP range is specified using CIDR notation.
Examples:
"192.168.1.1/16", "fefe:13::abc/33".
* `<local>`
Match local addresses. The meaning of `<local>` is whether the
host matches one of: "127.0.0.1", "::1", "localhost".
#### `ses.resolveHost(host, [options])`
* `host` string - Hostname to resolve.
* `options` Object (optional)
* `queryType` string (optional) - Requested DNS query type. If unspecified,
resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings:
* `A` - Fetch only A records
* `AAAA` - Fetch only AAAA records.
* `source` string (optional) - The source to use for resolved addresses.
Default allows the resolver to pick an appropriate source. Only affects use
of big external sources (e.g. calling the system for resolution or using
DNS). Even if a source is specified, results can still come from cache,
resolving "localhost" or IP literals, etc. One of the following values:
* `any` (default) - Resolver will pick an appropriate source. Results could
come from DNS, MulticastDNS, HOSTS file, etc
* `system` - Results will only be retrieved from the system or OS, e.g. via
the `getaddrinfo()` system call
* `dns` - Results will only come from DNS queries
* `mdns` - Results will only come from Multicast DNS queries
* `localOnly` - No external sources will be used. Results will only come
from fast local sources that are available no matter the source setting,
e.g. cache, hosts file, IP literal resolution, etc.
* `cacheUsage` string (optional) - Indicates what DNS cache entries, if any,
can be used to provide a response. One of the following values:
* `allowed` (default) - Results may come from the host cache if non-stale
* `staleAllowed` - Results may come from the host cache even if stale (by
expiration or network changes)
* `disallowed` - Results will not come from the host cache.
* `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS
behavior for this request. One of the following values:
* `allow` (default)
* `disable`
Returns [`Promise<ResolvedHost>`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`.
#### `ses.resolveProxy(url)`
* `url` URL
Returns `Promise<string>` - Resolves with the proxy information for `url`.
#### `ses.forceReloadProxyConfig()`
Returns `Promise<void>` - Resolves when the all internal states of proxy service is reset and the latest proxy configuration is reapplied if it's already available. The pac script will be fetched from `pacScript` again if the proxy mode is `pac_script`.
#### `ses.setDownloadPath(path)`
* `path` string - The download location.
Sets download saving directory. By default, the download directory will be the
`Downloads` under the respective app folder.
#### `ses.enableNetworkEmulation(options)`
* `options` Object
* `offline` boolean (optional) - Whether to emulate network outage. Defaults
to false.
* `latency` Double (optional) - RTT in ms. Defaults to 0 which will disable
latency throttling.
* `downloadThroughput` Double (optional) - Download rate in Bps. Defaults to 0
which will disable download throttling.
* `uploadThroughput` Double (optional) - Upload rate in Bps. Defaults to 0
which will disable upload throttling.
Emulates network with the given configuration for the `session`.
```javascript
const win = new BrowserWindow()
// To emulate a GPRS connection with 50kbps throughput and 500 ms latency.
win.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
})
// To emulate a network outage.
win.webContents.session.enableNetworkEmulation({ offline: true })
```
#### `ses.preconnect(options)`
* `options` Object
* `url` string - URL for preconnect. Only the origin is relevant for opening the socket.
* `numSockets` number (optional) - number of sockets to preconnect. Must be between 1 and 6. Defaults to 1.
Preconnects the given number of sockets to an origin.
#### `ses.closeAllConnections()`
Returns `Promise<void>` - Resolves when all connections are closed.
**Note:** It will terminate / fail all requests currently in flight.
#### `ses.fetch(input[, init])`
* `input` string | [GlobalRequest](https://nodejs.org/api/globals.html#request)
* `init` [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options) (optional)
Returns `Promise<GlobalResponse>` - see [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response).
Sends a request, similarly to how `fetch()` works in the renderer, using
Chrome's network stack. This differs from Node's `fetch()`, which uses
Node.js's HTTP stack.
Example:
```js
async function example () {
const response = await net.fetch('https://my.app')
if (response.ok) {
const body = await response.json()
// ... use the result.
}
}
```
See also [`net.fetch()`](net.md#netfetchinput-init), a convenience method which
issues requests from the [default session](#sessiondefaultsession).
See the MDN documentation for
[`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/fetch) for more
details.
Limitations:
* `net.fetch()` does not support the `data:` or `blob:` schemes.
* The value of the `integrity` option is ignored.
* The `.type` and `.url` values of the returned `Response` object are
incorrect.
By default, requests made with `net.fetch` can be made to [custom
protocols](protocol.md) as well as `file:`, and will trigger
[webRequest](web-request.md) handlers if present. When the non-standard
`bypassCustomProtocolHandlers` option is set in RequestInit, custom protocol
handlers will not be called for this request. This allows forwarding an
intercepted request to the built-in handler. [webRequest](web-request.md)
handlers will still be triggered when bypassing custom protocols.
```js
protocol.handle('https', (req) => {
if (req.url === 'https://my-app.com') {
return new Response('<body>my app</body>')
} else {
return net.fetch(req, { bypassCustomProtocolHandlers: true })
}
})
```
#### `ses.disableNetworkEmulation()`
Disables any network emulation already active for the `session`. Resets to
the original network configuration.
#### `ses.setCertificateVerifyProc(proc)`
* `proc` Function | null
* `request` Object
* `hostname` string
* `certificate` [Certificate](structures/certificate.md)
* `validatedCertificate` [Certificate](structures/certificate.md)
* `isIssuedByKnownRoot` boolean - `true` if Chromium recognises the root CA as a standard root. If it isn't then it's probably the case that this certificate was generated by a MITM proxy whose root has been installed locally (for example, by a corporate proxy). This should not be trusted if the `verificationResult` is not `OK`.
* `verificationResult` string - `OK` if the certificate is trusted, otherwise an error like `CERT_REVOKED`.
* `errorCode` Integer - Error code.
* `callback` Function
* `verificationResult` Integer - Value can be one of certificate error codes
from [here](https://source.chromium.org/chromium/chromium/src/+/main:net/base/net_error_list.h).
Apart from the certificate error codes, the following special codes can be used.
* `0` - Indicates success and disables Certificate Transparency verification.
* `-2` - Indicates failure.
* `-3` - Uses the verification result from chromium.
Sets the certificate verify proc for `session`, the `proc` will be called with
`proc(request, callback)` whenever a server certificate
verification is requested. Calling `callback(0)` accepts the certificate,
calling `callback(-2)` rejects it.
Calling `setCertificateVerifyProc(null)` will revert back to default certificate
verify proc.
```javascript
const { BrowserWindow } = require('electron')
const win = new BrowserWindow()
win.webContents.session.setCertificateVerifyProc((request, callback) => {
const { hostname } = request
if (hostname === 'github.com') {
callback(0)
} else {
callback(-2)
}
})
```
> **NOTE:** The result of this procedure is cached by the network service.
#### `ses.setPermissionRequestHandler(handler)`
* `handler` Function | null
* `webContents` [WebContents](web-contents.md) - WebContents requesting the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin.
* `permission` string - The type of requested permission.
* `clipboard-read` - Request access to read from the clipboard.
* `clipboard-sanitized-write` - Request access to write to the clipboard.
* `media` - Request access to media devices such as camera, microphone and speakers.
* `display-capture` - Request access to capture the screen.
* `mediaKeySystem` - Request access to DRM protected content.
* `geolocation` - Request access to user's current location.
* `notifications` - Request notification creation and the ability to display them in the user's system tray.
* `midi` - Request MIDI access in the `webmidi` API.
* `midiSysex` - Request the use of system exclusive messages in the `webmidi` API.
* `pointerLock` - Request to directly interpret mouse movements as an input method. Click [here](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) to know more. These requests always appear to originate from the main frame.
* `fullscreen` - Request for the app to enter fullscreen mode.
* `openExternal` - Request to open links in external applications.
* `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API.
* `unknown` - An unrecognized permission request
* `callback` Function
* `permissionGranted` boolean - Allow or deny the permission.
* `details` Object - Some properties are only available on certain permission types.
* `externalURL` string (optional) - The url of the `openExternal` request.
* `securityOrigin` string (optional) - The security origin of the `media` request.
* `mediaTypes` string[] (optional) - The types of media access being requested, elements can be `video`
or `audio`
* `requestingUrl` string - The last URL the requesting frame loaded
* `isMainFrame` boolean - Whether the frame making the request is the main frame
Sets the handler which can be used to respond to permission requests for the `session`.
Calling `callback(true)` will allow the permission and `callback(false)` will reject it.
To clear the handler, call `setPermissionRequestHandler(null)`. Please note that
you must also implement `setPermissionCheckHandler` to get complete permission handling.
Most web APIs do a permission check and then make a permission request if the check is denied.
```javascript
const { session } = require('electron')
session.fromPartition('some-partition').setPermissionRequestHandler((webContents, permission, callback) => {
if (webContents.getURL() === 'some-host' && permission === 'notifications') {
return callback(false) // denied.
}
callback(true)
})
```
#### `ses.setPermissionCheckHandler(handler)`
* `handler` Function\<boolean> | null
* `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively.
* `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, `serial`, or `usb`.
* `requestingOrigin` string - The origin URL of the permission check
* `details` Object - Some properties are only available on certain permission types.
* `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks.
* `securityOrigin` string (optional) - The security origin of the `media` check.
* `mediaType` string (optional) - The type of media access being requested, can be `video`,
`audio` or `unknown`
* `requestingUrl` string (optional) - The last URL the requesting frame loaded. This is not provided for cross-origin sub frames making permission checks.
* `isMainFrame` boolean - Whether the frame making the request is the main frame
Sets the handler which can be used to respond to permission checks for the `session`.
Returning `true` will allow the permission and `false` will reject it. Please note that
you must also implement `setPermissionRequestHandler` to get complete permission handling.
Most web APIs do a permission check and then make a permission request if the check is denied.
To clear the handler, call `setPermissionCheckHandler(null)`.
```javascript
const { session } = require('electron')
const url = require('url')
session.fromPartition('some-partition').setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'some-host' && permission === 'notifications') {
return true // granted
}
return false // denied
})
```
#### `ses.setDisplayMediaRequestHandler(handler)`
* `handler` Function | null
* `request` Object
* `frame` [WebFrameMain](web-frame-main.md) - Frame that is requesting access to media.
* `securityOrigin` String - Origin of the page making the request.
* `videoRequested` Boolean - true if the web content requested a video stream.
* `audioRequested` Boolean - true if the web content requested an audio stream.
* `userGesture` Boolean - Whether a user gesture was active when this request was triggered.
* `callback` Function
* `streams` Object
* `video` Object | [WebFrameMain](web-frame-main.md) (optional)
* `id` String - The id of the stream being granted. This will usually
come from a [DesktopCapturerSource](structures/desktop-capturer-source.md)
object.
* `name` String - The name of the stream being granted. This will
usually come from a [DesktopCapturerSource](structures/desktop-capturer-source.md)
object.
* `audio` String | [WebFrameMain](web-frame-main.md) (optional) - If
a string is specified, can be `loopback` or `loopbackWithMute`.
Specifying a loopback device will capture system audio, and is
currently only supported on Windows. If a WebFrameMain is specified,
will capture audio from that frame.
* `enableLocalEcho` Boolean (optional) - If `audio` is a [WebFrameMain](web-frame-main.md)
and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder`
to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers
while recording). Default is `false`.
This handler will be called when web content requests access to display media
via the `navigator.mediaDevices.getDisplayMedia` API. Use the
[desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant
access to.
```javascript
const { session, desktopCapturer } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
// Grant access to the first screen found.
callback({ video: sources[0] })
})
})
```
Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream
will capture the video or audio stream from that frame.
```javascript
const { session } = require('electron')
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
// Allow the tab to capture itself.
callback({ video: request.frame })
})
```
Passing `null` instead of a function resets the handler to its default state.
#### `ses.setDevicePermissionHandler(handler)`
* `handler` Function\<boolean> | null
* `details` Object
* `deviceType` string - The type of device that permission is being requested on, can be `hid`, `serial`, or `usb`.
* `origin` string - The origin URL of the device permission check.
* `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md) | [USBDevice](structures/usb-device.md) - the device that permission is being requested for.
Sets the handler which can be used to respond to device permission checks for the `session`.
Returning `true` will allow the device to be permitted and `false` will reject it.
To clear the handler, call `setDevicePermissionHandler(null)`.
This handler can be used to provide default permissioning to devices without first calling for permission
to devices (eg via `navigator.hid.requestDevice`). If this handler is not defined, the default device
permissions as granted through device selection (eg via `navigator.hid.requestDevice`) will be used.
Additionally, the default behavior of Electron is to store granted device permision in memory.
If longer term storage is needed, a developer can store granted device
permissions (eg when handling the `select-hid-device` event) and then read from that storage with `setDevicePermissionHandler`.
```javascript @ts-type={fetchGrantedDevices:()=>(Array<Electron.DevicePermissionHandlerHandlerDetails['device']>)}
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
if (permission === 'hid') {
// Add logic here to determine if permission should be given to allow HID selection
return true
} else if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial port selection
} else if (permission === 'usb') {
// Add logic here to determine if permission should be given to allow USB device selection
}
return false
})
// Optionally, retrieve previously persisted devices from a persistent store
const grantedDevices = fetchGrantedDevices()
win.webContents.session.setDevicePermissionHandler((details) => {
if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'hid') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
// Search through the list of devices that have previously been granted permission
return grantedDevices.some((grantedDevice) => {
return grantedDevice.vendorId === details.device.vendorId &&
grantedDevice.productId === details.device.productId &&
grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
})
} else if (details.deviceType === 'serial') {
if (details.device.vendorId === 123 && details.device.productId === 345) {
// Always allow this type of device (this allows skipping the call to `navigator.hid.requestDevice` first)
return true
}
}
return false
})
win.webContents.session.on('select-hid-device', (event, details, callback) => {
event.preventDefault()
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === 9025 && device.productId === 67
})
callback(selectedDevice?.deviceId)
})
})
```
#### `ses.setUSBProtectedClassesHandler(handler)`
* `handler` Function\<string[]> | null
* `details` Object
* `protectedClasses` string[] - The current list of protected USB classes. Possible class values are:
* `audio`
* `audio-video`
* `hid`
* `mass-storage`
* `smart-card`
* `video`
* `wireless`
Sets the handler which can be used to override which [USB classes are protected](https://wicg.github.io/webusb/#usbinterface-interface).
The return value for the handler is a string array of USB classes which should be considered protected (eg not available in the renderer). Valid values for the array are:
* `audio`
* `audio-video`
* `hid`
* `mass-storage`
* `smart-card`
* `video`
* `wireless`
Returning an empty string array from the handler will allow all USB classes; returning the passed in array will maintain the default list of protected USB classes (this is also the default behavior if a handler is not defined).
To clear the handler, call `setUSBProtectedClassesHandler(null)`.
```javascript
const { app, BrowserWindow } = require('electron')
let win = null
app.whenReady().then(() => {
win = new BrowserWindow()
win.webContents.session.setUSBProtectedClassesHandler((details) => {
// Allow all classes:
// return []
// Keep the current set of protected classes:
// return details.protectedClasses
// Selectively remove classes:
return details.protectedClasses.filter((usbClass) => {
// Exclude classes except for audio classes
return usbClass.indexOf('audio') === -1
})
})
})
```
#### `ses.setBluetoothPairingHandler(handler)` _Windows_ _Linux_
* `handler` Function | null
* `details` Object
* `deviceId` string
* `pairingKind` string - The type of pairing prompt being requested.
One of the following values:
* `confirm`
This prompt is requesting confirmation that the Bluetooth device should
be paired.
* `confirmPin`
This prompt is requesting confirmation that the provided PIN matches the
pin displayed on the device.
* `providePin`
This prompt is requesting that a pin be provided for the device.
* `frame` [WebFrameMain](web-frame-main.md)
* `pin` string (optional) - The pin value to verify if `pairingKind` is `confirmPin`.
* `callback` Function
* `response` Object
* `confirmed` boolean - `false` should be passed in if the dialog is canceled.
If the `pairingKind` is `confirm` or `confirmPin`, this value should indicate
if the pairing is confirmed. If the `pairingKind` is `providePin` the value
should be `true` when a value is provided.
* `pin` string | null (optional) - When the `pairingKind` is `providePin`
this value should be the required pin for the Bluetooth device.
Sets a handler to respond to Bluetooth pairing requests. This handler
allows developers to handle devices that require additional validation
before pairing. When a handler is not defined, any pairing on Linux or Windows
that requires additional validation will be automatically cancelled.
macOS does not require a handler because macOS handles the pairing
automatically. To clear the handler, call `setBluetoothPairingHandler(null)`.
```javascript
const { app, BrowserWindow, session } = require('electron')
const path = require('path')
function createWindow () {
let bluetoothPinCallback = null
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => {
bluetoothPinCallback = callback
// Send a IPC message to the renderer to prompt the user to confirm the pairing.
// Note that this will require logic in the renderer to handle this message and
// display a prompt to the user.
mainWindow.webContents.send('bluetooth-pairing-request', details)
})
// Listen for an IPC message from the renderer to get the response for the Bluetooth pairing.
mainWindow.webContents.ipc.on('bluetooth-pairing-response', (event, response) => {
bluetoothPinCallback(response)
})
}
app.whenReady().then(() => {
createWindow()
})
```
#### `ses.clearHostResolverCache()`
Returns `Promise<void>` - Resolves when the operation is complete.
Clears the host resolver cache.
#### `ses.allowNTLMCredentialsForDomains(domains)`
* `domains` string - A comma-separated list of servers for which
integrated authentication is enabled.
Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate
authentication.
```javascript
const { session } = require('electron')
// consider any url ending with `example.com`, `foobar.com`, `baz`
// for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz')
// consider all urls for integrated authentication.
session.defaultSession.allowNTLMCredentialsForDomains('*')
```
#### `ses.setUserAgent(userAgent[, acceptLanguages])`
* `userAgent` string
* `acceptLanguages` string (optional)
Overrides the `userAgent` and `acceptLanguages` for this session.
The `acceptLanguages` must a comma separated ordered list of language codes, for
example `"en-US,fr,de,ko,zh-CN,ja"`.
This doesn't affect existing `WebContents`, and each `WebContents` can use
`webContents.setUserAgent` to override the session-wide user agent.
#### `ses.isPersistent()`
Returns `boolean` - Whether or not this session is a persistent one. The default
`webContents` session of a `BrowserWindow` is persistent. When creating a session
from a partition, session prefixed with `persist:` will be persistent, while others
will be temporary.
#### `ses.getUserAgent()`
Returns `string` - The user agent for this session.
#### `ses.setSSLConfig(config)`
* `config` Object
* `minVersion` string (optional) - Can be `tls1`, `tls1.1`, `tls1.2` or `tls1.3`. The
minimum SSL version to allow when connecting to remote servers. Defaults to
`tls1`.
* `maxVersion` string (optional) - Can be `tls1.2` or `tls1.3`. The maximum SSL version
to allow when connecting to remote servers. Defaults to `tls1.3`.
* `disabledCipherSuites` Integer[] (optional) - List of cipher suites which
should be explicitly prevented from being used in addition to those
disabled by the net built-in policy.
Supported literal forms: 0xAABB, where AA is `cipher_suite[0]` and BB is
`cipher_suite[1]`, as defined in RFC 2246, Section 7.4.1.2. Unrecognized but
parsable cipher suites in this form will not return an error.
Ex: To disable TLS_RSA_WITH_RC4_128_MD5, specify 0x0004, while to
disable TLS_ECDH_ECDSA_WITH_RC4_128_SHA, specify 0xC002.
Note that TLSv1.3 ciphers cannot be disabled using this mechanism.
Sets the SSL configuration for the session. All subsequent network requests
will use the new configuration. Existing network connections (such as WebSocket
connections) will not be terminated, but old sockets in the pool will not be
reused for new connections.
#### `ses.getBlobData(identifier)`
* `identifier` string - Valid UUID.
Returns `Promise<Buffer>` - resolves with blob data.
#### `ses.downloadURL(url)`
* `url` string
Initiates a download of the resource at `url`.
The API will generate a [DownloadItem](download-item.md) that can be accessed
with the [will-download](#event-will-download) event.
**Note:** This does not perform any security checks that relate to a page's origin,
unlike [`webContents.downloadURL`](web-contents.md#contentsdownloadurlurl).
#### `ses.createInterruptedDownload(options)`
* `options` Object
* `path` string - Absolute path of the download.
* `urlChain` string[] - Complete URL chain for the download.
* `mimeType` string (optional)
* `offset` Integer - Start range for the download.
* `length` Integer - Total length of the download.
* `lastModified` string (optional) - Last-Modified header value.
* `eTag` string (optional) - ETag header value.
* `startTime` Double (optional) - Time when download was started in
number of seconds since UNIX epoch.
Allows resuming `cancelled` or `interrupted` downloads from previous `Session`.
The API will generate a [DownloadItem](download-item.md) that can be accessed with the [will-download](#event-will-download)
event. The [DownloadItem](download-item.md) will not have any `WebContents` associated with it and
the initial state will be `interrupted`. The download will start only when the
`resume` API is called on the [DownloadItem](download-item.md).
#### `ses.clearAuthCache()`
Returns `Promise<void>` - resolves when the session’s HTTP authentication cache has been cleared.
#### `ses.setPreloads(preloads)`
* `preloads` string[] - An array of absolute path to preload scripts
Adds scripts that will be executed on ALL web contents that are associated with
this session just before normal `preload` scripts run.
#### `ses.getPreloads()`
Returns `string[]` an array of paths to preload scripts that have been
registered.
#### `ses.setCodeCachePath(path)`
* `path` String - Absolute path to store the v8 generated JS code cache from the renderer.
Sets the directory to store the generated JS [code cache](https://v8.dev/blog/code-caching-for-devs) for this session. The directory is not required to be created by the user before this call, the runtime will create if it does not exist otherwise will use the existing directory. If directory cannot be created, then code cache will not be used and all operations related to code cache will fail silently inside the runtime. By default, the directory will be `Code Cache` under the
respective user data folder.
#### `ses.clearCodeCaches(options)`
* `options` Object
* `urls` String[] (optional) - An array of url corresponding to the resource whose generated code cache needs to be removed. If the list is empty then all entries in the cache directory will be removed.
Returns `Promise<void>` - resolves when the code cache clear operation is complete.
#### `ses.setSpellCheckerEnabled(enable)`
* `enable` boolean
Sets whether to enable the builtin spell checker.
#### `ses.isSpellCheckerEnabled()`
Returns `boolean` - Whether the builtin spell checker is enabled.
#### `ses.setSpellCheckerLanguages(languages)`
* `languages` string[] - An array of language codes to enable the spellchecker for.
The built in spellchecker does not automatically detect what language a user is typing in. In order for the
spell checker to correctly check their words you must call this API with an array of language codes. You can
get the list of supported language codes with the `ses.availableSpellCheckerLanguages` property.
**Note:** On macOS the OS spellchecker is used and will detect your language automatically. This API is a no-op on macOS.
#### `ses.getSpellCheckerLanguages()`
Returns `string[]` - An array of language codes the spellchecker is enabled for. If this list is empty the spellchecker
will fallback to using `en-US`. By default on launch if this setting is an empty list Electron will try to populate this
setting with the current OS locale. This setting is persisted across restarts.
**Note:** On macOS the OS spellchecker is used and has its own list of languages. On macOS, this API will return whichever languages have been configured by the OS.
#### `ses.setSpellCheckerDictionaryDownloadURL(url)`
* `url` string - A base URL for Electron to download hunspell dictionaries from.
By default Electron will download hunspell dictionaries from the Chromium CDN. If you want to override this
behavior you can use this API to point the dictionary downloader at your own hosted version of the hunspell
dictionaries. We publish a `hunspell_dictionaries.zip` file with each release which contains the files you need
to host here.
The file server must be **case insensitive**. If you cannot do this, you must upload each file twice: once with
the case it has in the ZIP file and once with the filename as all lowercase.
If the files present in `hunspell_dictionaries.zip` are available at `https://example.com/dictionaries/language-code.bdic`
then you should call this api with `ses.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')`. Please
note the trailing slash. The URL to the dictionaries is formed as `${url}${filename}`.
**Note:** On macOS the OS spellchecker is used and therefore we do not download any dictionary files. This API is a no-op on macOS.
#### `ses.listWordsInSpellCheckerDictionary()`
Returns `Promise<string[]>` - An array of all words in app's custom dictionary.
Resolves when the full dictionary is loaded from disk.
#### `ses.addWordToSpellCheckerDictionary(word)`
* `word` string - The word you want to add to the dictionary
Returns `boolean` - Whether the word was successfully written to the custom dictionary. This API
will not work on non-persistent (in-memory) sessions.
**Note:** On macOS and Windows 10 this word will be written to the OS custom dictionary as well
#### `ses.removeWordFromSpellCheckerDictionary(word)`
* `word` string - The word you want to remove from the dictionary
Returns `boolean` - Whether the word was successfully removed from the custom dictionary. This API
will not work on non-persistent (in-memory) sessions.
**Note:** On macOS and Windows 10 this word will be removed from the OS custom dictionary as well
#### `ses.loadExtension(path[, options])`
* `path` string - Path to a directory containing an unpacked Chrome extension
* `options` Object (optional)
* `allowFileAccess` boolean - Whether to allow the extension to read local files over `file://`
protocol and inject content scripts into `file://` pages. This is required e.g. for loading
devtools extensions on `file://` URLs. Defaults to false.
Returns `Promise<Extension>` - resolves when the extension is loaded.
This method will raise an exception if the extension could not be loaded. If
there are warnings when installing the extension (e.g. if the extension
requests an API that Electron does not support) then they will be logged to the
console.
Note that Electron does not support the full range of Chrome extensions APIs.
See [Supported Extensions APIs](extensions.md#supported-extensions-apis) for
more details on what is supported.
Note that in previous versions of Electron, extensions that were loaded would
be remembered for future runs of the application. This is no longer the case:
`loadExtension` must be called on every boot of your app if you want the
extension to be loaded.
```js
const { app, session } = require('electron')
const path = require('path')
app.whenReady().then(async () => {
await session.defaultSession.loadExtension(
path.join(__dirname, 'react-devtools'),
// allowFileAccess is required to load the devtools extension on file:// URLs.
{ allowFileAccess: true }
)
// Note that in order to use the React DevTools extension, you'll need to
// download and unzip a copy of the extension.
})
```
This API does not support loading packed (.crx) extensions.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
**Note:** Loading extensions into in-memory (non-persistent) sessions is not
supported and will throw an error.
#### `ses.removeExtension(extensionId)`
* `extensionId` string - ID of extension to remove
Unloads an extension.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
#### `ses.getExtension(extensionId)`
* `extensionId` string - ID of extension to query
Returns `Extension` | `null` - The loaded extension with the given ID.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
#### `ses.getAllExtensions()`
Returns `Extension[]` - A list of all loaded extensions.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
#### `ses.getStoragePath()`
Returns `string | null` - The absolute file system path where data for this
session is persisted on disk. For in memory sessions this returns `null`.
### Instance Properties
The following properties are available on instances of `Session`:
#### `ses.availableSpellCheckerLanguages` _Readonly_
A `string[]` array which consists of all the known available spell checker languages. Providing a language
code to the `setSpellCheckerLanguages` API that isn't in this array will result in an error.
#### `ses.spellCheckerEnabled`
A `boolean` indicating whether builtin spell checker is enabled.
#### `ses.storagePath` _Readonly_
A `string | null` indicating the absolute file system path where data for this
session is persisted on disk. For in memory sessions this returns `null`.
#### `ses.cookies` _Readonly_
A [`Cookies`](cookies.md) object for this session.
#### `ses.serviceWorkers` _Readonly_
A [`ServiceWorkers`](service-workers.md) object for this session.
#### `ses.webRequest` _Readonly_
A [`WebRequest`](web-request.md) object for this session.
#### `ses.protocol` _Readonly_
A [`Protocol`](protocol.md) object for this session.
```javascript
const { app, session } = require('electron')
const path = require('path')
app.whenReady().then(() => {
const protocol = session.fromPartition('some-partition').protocol
if (!protocol.registerFileProtocol('atom', (request, callback) => {
const url = request.url.substr(7)
callback({ path: path.normalize(path.join(__dirname, url)) })
})) {
console.error('Failed to register protocol')
}
})
```
#### `ses.netLog` _Readonly_
A [`NetLog`](net-log.md) object for this session.
```javascript
const { app, session } = require('electron')
app.whenReady().then(async () => {
const netLog = session.fromPartition('some-partition').netLog
netLog.startLogging('/path/to/net-log')
// After some network events
const path = await netLog.stopLogging()
console.log('Net-logs written to', path)
})
```
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
shell/browser/api/electron_api_session.cc
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_session.h"
#include <algorithm>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/uuid.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_url_parameters.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/value_map_pref_store.h"
#include "components/proxy_config/proxy_config_dictionary.h"
#include "components/proxy_config/proxy_config_pref_names.h"
#include "components/proxy_config/proxy_prefs.h"
#include "content/browser/code_cache/generated_code_cache_context.h" // nogncheck
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager_delegate.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/storage_partition.h"
#include "gin/arguments.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/completion_repeating_callback.h"
#include "net/base/load_flags.h"
#include "net/base/network_anonymization_key.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_auth_preferences.h"
#include "net/http/http_cache.h"
#include "net/http/http_util.h"
#include "services/network/network_service.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/clear_data_filter.mojom.h"
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_cookies.h"
#include "shell/browser/api/electron_api_data_pipe_holder.h"
#include "shell/browser/api/electron_api_download_item.h"
#include "shell/browser/api/electron_api_net_log.h"
#include "shell/browser/api/electron_api_protocol.h"
#include "shell/browser/api/electron_api_service_worker_context.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/electron_api_web_request.h"
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/media/media_device_id_salt.h"
#include "shell/browser/net/cert_verifier_client.h"
#include "shell/browser/net/resolve_host_function.h"
#include "shell/browser/session_preferences.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/media_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/usb_protected_classes_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/extension_registry.h"
#include "shell/browser/extensions/electron_extension_system.h"
#include "shell/common/gin_converters/extension_converter.h"
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck
#include "chrome/browser/spellchecker/spellcheck_service.h" // nogncheck
#include "components/spellcheck/browser/pref_names.h"
#include "components/spellcheck/common/spellcheck_common.h"
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
#include "components/spellcheck/browser/spellcheck_platform.h"
#include "components/spellcheck/common/spellcheck_features.h"
#endif
#endif
using content::BrowserThread;
using content::StoragePartition;
namespace {
struct ClearStorageDataOptions {
blink::StorageKey storage_key;
uint32_t storage_types = StoragePartition::REMOVE_DATA_MASK_ALL;
uint32_t quota_types = StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL;
};
uint32_t GetStorageMask(const std::vector<std::string>& storage_types) {
uint32_t storage_mask = 0;
for (const auto& it : storage_types) {
auto type = base::ToLowerASCII(it);
if (type == "cookies")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_COOKIES;
else if (type == "filesystem")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_FILE_SYSTEMS;
else if (type == "indexdb")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_INDEXEDDB;
else if (type == "localstorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_LOCAL_STORAGE;
else if (type == "shadercache")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE;
else if (type == "websql")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_WEBSQL;
else if (type == "serviceworkers")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_SERVICE_WORKERS;
else if (type == "cachestorage")
storage_mask |= StoragePartition::REMOVE_DATA_MASK_CACHE_STORAGE;
}
return storage_mask;
}
uint32_t GetQuotaMask(const std::vector<std::string>& quota_types) {
uint32_t quota_mask = 0;
for (const auto& it : quota_types) {
auto type = base::ToLowerASCII(it);
if (type == "temporary")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_TEMPORARY;
else if (type == "syncable")
quota_mask |= StoragePartition::QUOTA_MANAGED_STORAGE_MASK_SYNCABLE;
}
return quota_mask;
}
base::Value::Dict createProxyConfig(ProxyPrefs::ProxyMode proxy_mode,
std::string const& pac_url,
std::string const& proxy_server,
std::string const& bypass_list) {
if (proxy_mode == ProxyPrefs::MODE_DIRECT) {
return ProxyConfigDictionary::CreateDirect();
}
if (proxy_mode == ProxyPrefs::MODE_SYSTEM) {
return ProxyConfigDictionary::CreateSystem();
}
if (proxy_mode == ProxyPrefs::MODE_AUTO_DETECT) {
return ProxyConfigDictionary::CreateAutoDetect();
}
if (proxy_mode == ProxyPrefs::MODE_PAC_SCRIPT) {
const bool pac_mandatory = true;
return ProxyConfigDictionary::CreatePacScript(pac_url, pac_mandatory);
}
return ProxyConfigDictionary::CreateFixedServers(proxy_server, bypass_list);
}
} // namespace
namespace gin {
template <>
struct Converter<ClearStorageDataOptions> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
ClearStorageDataOptions* out) {
gin_helper::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
if (GURL storage_origin; options.Get("origin", &storage_origin))
out->storage_key = blink::StorageKey::CreateFirstParty(
url::Origin::Create(storage_origin));
std::vector<std::string> types;
if (options.Get("storages", &types))
out->storage_types = GetStorageMask(types);
if (options.Get("quotas", &types))
out->quota_types = GetQuotaMask(types);
return true;
}
};
bool SSLProtocolVersionFromString(const std::string& version_str,
network::mojom::SSLVersion* version) {
if (version_str == switches::kSSLVersionTLSv12) {
*version = network::mojom::SSLVersion::kTLS12;
return true;
}
if (version_str == switches::kSSLVersionTLSv13) {
*version = network::mojom::SSLVersion::kTLS13;
return true;
}
return false;
}
template <>
struct Converter<uint16_t> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
uint16_t* out) {
auto maybe = val->IntegerValue(isolate->GetCurrentContext());
if (maybe.IsNothing())
return false;
*out = maybe.FromJust();
return true;
}
};
template <>
struct Converter<network::mojom::SSLConfigPtr> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
network::mojom::SSLConfigPtr* out) {
gin_helper::Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
*out = network::mojom::SSLConfig::New();
std::string version_min_str;
if (options.Get("minVersion", &version_min_str)) {
if (!SSLProtocolVersionFromString(version_min_str, &(*out)->version_min))
return false;
}
std::string version_max_str;
if (options.Get("maxVersion", &version_max_str)) {
if (!SSLProtocolVersionFromString(version_max_str,
&(*out)->version_max) ||
(*out)->version_max < network::mojom::SSLVersion::kTLS12)
return false;
}
if (options.Has("disabledCipherSuites") &&
!options.Get("disabledCipherSuites", &(*out)->disabled_cipher_suites)) {
return false;
}
std::sort((*out)->disabled_cipher_suites.begin(),
(*out)->disabled_cipher_suites.end());
// TODO(nornagon): also support other SSLConfig properties?
return true;
}
};
} // namespace gin
namespace electron::api {
namespace {
const char kPersistPrefix[] = "persist:";
void DownloadIdCallback(content::DownloadManager* download_manager,
const base::FilePath& path,
const std::vector<GURL>& url_chain,
const std::string& mime_type,
int64_t offset,
int64_t length,
const std::string& last_modified,
const std::string& etag,
const base::Time& start_time,
uint32_t id) {
download_manager->CreateDownloadItem(
base::Uuid::GenerateRandomV4().AsLowercaseString(), id, path, path,
url_chain, GURL(),
content::StoragePartitionConfig::CreateDefault(
download_manager->GetBrowserContext()),
GURL(), GURL(), absl::nullopt, mime_type, mime_type, start_time,
base::Time(), etag, last_modified, offset, length, std::string(),
download::DownloadItem::INTERRUPTED,
download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
download::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT, false, base::Time(),
false, std::vector<download::DownloadItem::ReceivedSlice>());
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
class DictionaryObserver final : public SpellcheckCustomDictionary::Observer {
private:
std::unique_ptr<gin_helper::Promise<std::set<std::string>>> promise_;
base::WeakPtr<SpellcheckService> spellcheck_;
public:
DictionaryObserver(gin_helper::Promise<std::set<std::string>> promise,
base::WeakPtr<SpellcheckService> spellcheck)
: spellcheck_(spellcheck) {
promise_ = std::make_unique<gin_helper::Promise<std::set<std::string>>>(
std::move(promise));
if (spellcheck_)
spellcheck_->GetCustomDictionary()->AddObserver(this);
}
~DictionaryObserver() {
if (spellcheck_)
spellcheck_->GetCustomDictionary()->RemoveObserver(this);
}
void OnCustomDictionaryLoaded() override {
if (spellcheck_) {
promise_->Resolve(spellcheck_->GetCustomDictionary()->GetWords());
} else {
promise_->RejectWithErrorMessage(
"Spellcheck in unexpected state: failed to load custom dictionary.");
}
delete this;
}
void OnCustomDictionaryChanged(
const SpellcheckCustomDictionary::Change& dictionary_change) override {
// noop
}
};
#endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
struct UserDataLink : base::SupportsUserData::Data {
explicit UserDataLink(Session* ses) : session(ses) {}
raw_ptr<Session> session;
};
const void* kElectronApiSessionKey = &kElectronApiSessionKey;
} // namespace
gin::WrapperInfo Session::kWrapperInfo = {gin::kEmbedderNativeGin};
Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context)
: isolate_(isolate),
network_emulation_token_(base::UnguessableToken::Create()),
browser_context_(browser_context) {
// Observe DownloadManager to get download notifications.
browser_context->GetDownloadManager()->AddObserver(this);
SessionPreferences::CreateForBrowserContext(browser_context);
protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8());
browser_context->SetUserData(kElectronApiSessionKey,
std::make_unique<UserDataLink>(this));
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (service) {
service->SetHunspellObserver(this);
}
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionRegistry::Get(browser_context)->AddObserver(this);
#endif
}
Session::~Session() {
browser_context()->GetDownloadManager()->RemoveObserver(this);
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (service) {
service->SetHunspellObserver(nullptr);
}
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ExtensionRegistry::Get(browser_context())->RemoveObserver(this);
#endif
}
void Session::OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) {
if (item->IsSavePackageDownload())
return;
v8::HandleScope handle_scope(isolate_);
auto handle = DownloadItem::FromOrCreate(isolate_, item);
if (item->GetState() == download::DownloadItem::INTERRUPTED)
handle->SetSavePath(item->GetTargetFilePath());
content::WebContents* web_contents =
content::DownloadItemUtils::GetWebContents(item);
bool prevent_default = Emit("will-download", handle, web_contents);
if (prevent_default) {
item->Cancel(true);
item->Remove();
}
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
void Session::OnHunspellDictionaryInitialized(const std::string& language) {
Emit("spellcheck-dictionary-initialized", language);
}
void Session::OnHunspellDictionaryDownloadBegin(const std::string& language) {
Emit("spellcheck-dictionary-download-begin", language);
}
void Session::OnHunspellDictionaryDownloadSuccess(const std::string& language) {
Emit("spellcheck-dictionary-download-success", language);
}
void Session::OnHunspellDictionaryDownloadFailure(const std::string& language) {
Emit("spellcheck-dictionary-download-failure", language);
}
#endif
v8::Local<v8::Promise> Session::ResolveProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<std::string> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
GURL url;
args->GetNext(&url);
browser_context_->GetResolveProxyHelper()->ResolveProxy(
url, base::BindOnce(gin_helper::Promise<std::string>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ResolveHost(
std::string host,
absl::optional<network::mojom::ResolveHostParametersPtr> params) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto fn = base::MakeRefCounted<ResolveHostFunction>(
browser_context_, std::move(host),
params ? std::move(params.value()) : nullptr,
base::BindOnce(
[](gin_helper::Promise<gin_helper::Dictionary> promise,
int64_t net_error, const absl::optional<net::AddressList>& addrs) {
if (net_error < 0) {
promise.RejectWithErrorMessage(net::ErrorToString(net_error));
} else {
DCHECK(addrs.has_value() && !addrs->empty());
v8::HandleScope handle_scope(promise.isolate());
gin_helper::Dictionary dict =
gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("endpoints", addrs->endpoints());
promise.Resolve(dict);
}
},
std::move(promise)));
fn->Run();
return handle;
}
v8::Local<v8::Promise> Session::GetCacheSize() {
gin_helper::Promise<int64_t> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ComputeHttpCacheSize(
base::Time(), base::Time::Max(),
base::BindOnce(
[](gin_helper::Promise<int64_t> promise, bool is_upper_bound,
int64_t size_or_error) {
if (size_or_error < 0) {
promise.RejectWithErrorMessage(
net::ErrorToString(size_or_error));
} else {
promise.Resolve(size_or_error);
}
},
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearCache() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ClearHttpCache(base::Time(), base::Time::Max(), nullptr,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearStorageData(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ClearStorageDataOptions options;
args->GetNext(&options);
auto* storage_partition = browser_context()->GetStoragePartition(nullptr);
if (options.storage_types & StoragePartition::REMOVE_DATA_MASK_COOKIES) {
// Reset media device id salt when cookies are cleared.
// https://w3c.github.io/mediacapture-main/#dom-mediadeviceinfo-deviceid
MediaDeviceIDSalt::Reset(browser_context()->prefs());
}
storage_partition->ClearData(
options.storage_types, options.quota_types, options.storage_key,
base::Time(), base::Time::Max(),
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
void Session::FlushStorageData() {
auto* storage_partition = browser_context()->GetStoragePartition(nullptr);
storage_partition->Flush();
}
v8::Local<v8::Promise> Session::SetProxy(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
gin_helper::Dictionary options;
args->GetNext(&options);
if (!browser_context_->in_memory_pref_store()) {
promise.Resolve();
return handle;
}
std::string mode, proxy_rules, bypass_list, pac_url;
options.Get("pacScript", &pac_url);
options.Get("proxyRules", &proxy_rules);
options.Get("proxyBypassRules", &bypass_list);
ProxyPrefs::ProxyMode proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS;
if (!options.Get("mode", &mode)) {
// pacScript takes precedence over proxyRules.
if (!pac_url.empty()) {
proxy_mode = ProxyPrefs::MODE_PAC_SCRIPT;
} else {
proxy_mode = ProxyPrefs::MODE_FIXED_SERVERS;
}
} else {
if (!ProxyPrefs::StringToProxyMode(mode, &proxy_mode)) {
promise.RejectWithErrorMessage(
"Invalid mode, must be one of direct, auto_detect, pac_script, "
"fixed_servers or system");
return handle;
}
}
browser_context_->in_memory_pref_store()->SetValue(
proxy_config::prefs::kProxy,
base::Value{
createProxyConfig(proxy_mode, pac_url, proxy_rules, bypass_list)},
WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ForceReloadProxyConfig() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ForceReloadProxyConfig(base::BindOnce(
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}
void Session::SetDownloadPath(const base::FilePath& path) {
browser_context_->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
path);
}
void Session::EnableNetworkEmulation(const gin_helper::Dictionary& options) {
auto conditions = network::mojom::NetworkConditions::New();
options.Get("offline", &conditions->offline);
options.Get("downloadThroughput", &conditions->download_throughput);
options.Get("uploadThroughput", &conditions->upload_throughput);
double latency = 0.0;
if (options.Get("latency", &latency) && latency) {
conditions->latency = base::Milliseconds(latency);
}
auto* network_context =
browser_context_->GetDefaultStoragePartition()->GetNetworkContext();
network_context->SetNetworkConditions(network_emulation_token_,
std::move(conditions));
}
void Session::DisableNetworkEmulation() {
auto* network_context =
browser_context_->GetDefaultStoragePartition()->GetNetworkContext();
network_context->SetNetworkConditions(
network_emulation_token_, network::mojom::NetworkConditions::New());
}
void Session::SetCertVerifyProc(v8::Local<v8::Value> val,
gin::Arguments* args) {
CertVerifierClient::CertVerifyProc proc;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &proc))) {
args->ThrowTypeError("Must pass null or function");
return;
}
mojo::PendingRemote<network::mojom::CertVerifierClient>
cert_verifier_client_remote;
if (proc) {
mojo::MakeSelfOwnedReceiver(
std::make_unique<CertVerifierClient>(proc),
cert_verifier_client_remote.InitWithNewPipeAndPassReceiver());
}
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->SetCertVerifierClient(std::move(cert_verifier_client_remote));
}
void Session::SetPermissionRequestHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
if (val->IsNull()) {
permission_manager->SetPermissionRequestHandler(
ElectronPermissionManager::RequestHandler());
return;
}
auto handler = std::make_unique<ElectronPermissionManager::RequestHandler>();
if (!gin::ConvertFromV8(args->isolate(), val, handler.get())) {
args->ThrowTypeError("Must pass null or function");
return;
}
permission_manager->SetPermissionRequestHandler(base::BindRepeating(
[](ElectronPermissionManager::RequestHandler* handler,
content::WebContents* web_contents,
blink::PermissionType permission_type,
ElectronPermissionManager::StatusCallback callback,
const base::Value& details) {
handler->Run(web_contents, permission_type, std::move(callback),
details);
},
base::Owned(std::move(handler))));
}
void Session::SetPermissionCheckHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::CheckHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetPermissionCheckHandler(handler);
}
void Session::SetDisplayMediaRequestHandler(v8::Isolate* isolate,
v8::Local<v8::Value> val) {
if (val->IsNull()) {
browser_context_->SetDisplayMediaRequestHandler(
DisplayMediaRequestHandler());
return;
}
DisplayMediaRequestHandler handler;
if (!gin::ConvertFromV8(isolate, val, &handler)) {
gin_helper::ErrorThrower(isolate).ThrowTypeError(
"Display media request handler must be null or a function");
return;
}
browser_context_->SetDisplayMediaRequestHandler(handler);
}
void Session::SetDevicePermissionHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::DeviceCheckHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetDevicePermissionHandler(handler);
}
void Session::SetUSBProtectedClassesHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::ProtectedUSBHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetProtectedUSBHandler(handler);
}
void Session::SetBluetoothPairingHandler(v8::Local<v8::Value> val,
gin::Arguments* args) {
ElectronPermissionManager::BluetoothPairingHandler handler;
if (!(val->IsNull() || gin::ConvertFromV8(args->isolate(), val, &handler))) {
args->ThrowTypeError("Must pass null or function");
return;
}
auto* permission_manager = static_cast<ElectronPermissionManager*>(
browser_context()->GetPermissionControllerDelegate());
permission_manager->SetBluetoothPairingHandler(handler);
}
v8::Local<v8::Promise> Session::ClearHostResolverCache(gin::Arguments* args) {
v8::Isolate* isolate = args->isolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ClearHostCache(nullptr,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
v8::Local<v8::Promise> Session::ClearAuthCache() {
gin_helper::Promise<void> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->ClearHttpAuthCache(
base::Time(), base::Time::Max(),
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
void Session::AllowNTLMCredentialsForDomains(const std::string& domains) {
auto* command_line = base::CommandLine::ForCurrentProcess();
network::mojom::HttpAuthDynamicParamsPtr auth_dynamic_params =
network::mojom::HttpAuthDynamicParams::New();
auth_dynamic_params->server_allowlist = domains;
auth_dynamic_params->enable_negotiate_port =
command_line->HasSwitch(electron::switches::kEnableAuthNegotiatePort);
auth_dynamic_params->ntlm_v2_enabled =
!command_line->HasSwitch(electron::switches::kDisableNTLMv2);
content::GetNetworkService()->ConfigureHttpAuthPrefs(
std::move(auth_dynamic_params));
}
void Session::SetUserAgent(const std::string& user_agent,
gin::Arguments* args) {
browser_context_->SetUserAgent(user_agent);
auto* network_context =
browser_context_->GetDefaultStoragePartition()->GetNetworkContext();
network_context->SetUserAgent(user_agent);
std::string accept_lang;
if (args->GetNext(&accept_lang)) {
network_context->SetAcceptLanguage(
net::HttpUtil::GenerateAcceptLanguageHeader(accept_lang));
}
}
std::string Session::GetUserAgent() {
return browser_context_->GetUserAgent();
}
void Session::SetSSLConfig(network::mojom::SSLConfigPtr config) {
browser_context_->SetSSLConfig(std::move(config));
}
bool Session::IsPersistent() {
return !browser_context_->IsOffTheRecord();
}
v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate,
const std::string& uuid) {
gin::Handle<DataPipeHolder> holder = DataPipeHolder::From(isolate, uuid);
if (holder.IsEmpty()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("Could not get blob data handle");
return promise.GetHandle();
}
return holder->ReadAll(isolate);
}
void Session::DownloadURL(const GURL& url) {
auto* download_manager = browser_context()->GetDownloadManager();
auto download_params = std::make_unique<download::DownloadUrlParameters>(
url, MISSING_TRAFFIC_ANNOTATION);
download_manager->DownloadUrl(std::move(download_params));
}
void Session::CreateInterruptedDownload(const gin_helper::Dictionary& options) {
int64_t offset = 0, length = 0;
double start_time = base::Time::Now().ToDoubleT();
std::string mime_type, last_modified, etag;
base::FilePath path;
std::vector<GURL> url_chain;
options.Get("path", &path);
options.Get("urlChain", &url_chain);
options.Get("mimeType", &mime_type);
options.Get("offset", &offset);
options.Get("length", &length);
options.Get("lastModified", &last_modified);
options.Get("eTag", &etag);
options.Get("startTime", &start_time);
if (path.empty() || url_chain.empty() || length == 0) {
isolate_->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate_, "Must pass non-empty path, urlChain and length.")));
return;
}
if (offset >= length) {
isolate_->ThrowException(v8::Exception::Error(gin::StringToV8(
isolate_, "Must pass an offset value less than length.")));
return;
}
auto* download_manager = browser_context()->GetDownloadManager();
download_manager->GetNextId(base::BindRepeating(
&DownloadIdCallback, download_manager, path, url_chain, mime_type, offset,
length, last_modified, etag, base::Time::FromDoubleT(start_time)));
}
void Session::SetPreloads(const std::vector<base::FilePath>& preloads) {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
prefs->set_preloads(preloads);
}
std::vector<base::FilePath> Session::GetPreloads() const {
auto* prefs = SessionPreferences::FromBrowserContext(browser_context());
DCHECK(prefs);
return prefs->preloads();
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
v8::Local<v8::Promise> Session::LoadExtension(
const base::FilePath& extension_path,
gin::Arguments* args) {
gin_helper::Promise<const extensions::Extension*> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!extension_path.IsAbsolute()) {
promise.RejectWithErrorMessage(
"The path to the extension in 'loadExtension' must be absolute");
return handle;
}
if (browser_context()->IsOffTheRecord()) {
promise.RejectWithErrorMessage(
"Extensions cannot be loaded in a temporary session");
return handle;
}
int load_flags = extensions::Extension::FOLLOW_SYMLINKS_ANYWHERE;
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
bool allowFileAccess = false;
options.Get("allowFileAccess", &allowFileAccess);
if (allowFileAccess)
load_flags |= extensions::Extension::ALLOW_FILE_ACCESS;
}
auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>(
extensions::ExtensionSystem::Get(browser_context()));
extension_system->LoadExtension(
extension_path, load_flags,
base::BindOnce(
[](gin_helper::Promise<const extensions::Extension*> promise,
const extensions::Extension* extension,
const std::string& error_msg) {
if (extension) {
if (!error_msg.empty()) {
node::Environment* env =
node::Environment::GetCurrent(promise.isolate());
EmitWarning(env, error_msg, "ExtensionLoadWarning");
}
promise.Resolve(extension);
} else {
promise.RejectWithErrorMessage(error_msg);
}
},
std::move(promise)));
return handle;
}
void Session::RemoveExtension(const std::string& extension_id) {
auto* extension_system = static_cast<extensions::ElectronExtensionSystem*>(
extensions::ExtensionSystem::Get(browser_context()));
extension_system->RemoveExtension(extension_id);
}
v8::Local<v8::Value> Session::GetExtension(const std::string& extension_id) {
auto* registry = extensions::ExtensionRegistry::Get(browser_context());
const extensions::Extension* extension =
registry->GetInstalledExtension(extension_id);
if (extension) {
return gin::ConvertToV8(isolate_, extension);
} else {
return v8::Null(isolate_);
}
}
v8::Local<v8::Value> Session::GetAllExtensions() {
auto* registry = extensions::ExtensionRegistry::Get(browser_context());
const extensions::ExtensionSet extensions =
registry->GenerateInstalledExtensionsSet();
std::vector<const extensions::Extension*> extensions_vector;
for (const auto& extension : extensions) {
if (extension->location() !=
extensions::mojom::ManifestLocation::kComponent)
extensions_vector.emplace_back(extension.get());
}
return gin::ConvertToV8(isolate_, extensions_vector);
}
void Session::OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) {
Emit("extension-loaded", extension);
}
void Session::OnExtensionUnloaded(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) {
Emit("extension-unloaded", extension);
}
void Session::OnExtensionReady(content::BrowserContext* browser_context,
const extensions::Extension* extension) {
Emit("extension-ready", extension);
}
#endif
v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) {
if (cookies_.IsEmpty()) {
auto handle = Cookies::Create(isolate, browser_context());
cookies_.Reset(isolate, handle.ToV8());
}
return cookies_.Get(isolate);
}
v8::Local<v8::Value> Session::Protocol(v8::Isolate* isolate) {
return protocol_.Get(isolate);
}
v8::Local<v8::Value> Session::ServiceWorkerContext(v8::Isolate* isolate) {
if (service_worker_context_.IsEmpty()) {
v8::Local<v8::Value> handle;
handle = ServiceWorkerContext::Create(isolate, browser_context()).ToV8();
service_worker_context_.Reset(isolate, handle);
}
return service_worker_context_.Get(isolate);
}
v8::Local<v8::Value> Session::WebRequest(v8::Isolate* isolate) {
if (web_request_.IsEmpty()) {
auto handle = WebRequest::Create(isolate, browser_context());
web_request_.Reset(isolate, handle.ToV8());
}
return web_request_.Get(isolate);
}
v8::Local<v8::Value> Session::NetLog(v8::Isolate* isolate) {
if (net_log_.IsEmpty()) {
auto handle = NetLog::Create(isolate, browser_context());
net_log_.Reset(isolate, handle.ToV8());
}
return net_log_.Get(isolate);
}
static void StartPreconnectOnUI(ElectronBrowserContext* browser_context,
const GURL& url,
int num_sockets_to_preconnect) {
url::Origin origin = url::Origin::Create(url);
std::vector<predictors::PreconnectRequest> requests = {
{url::Origin::Create(url), num_sockets_to_preconnect,
net::NetworkAnonymizationKey::CreateSameSite(
net::SchemefulSite(origin))}};
browser_context->GetPreconnectManager()->Start(url, requests);
}
void Session::Preconnect(const gin_helper::Dictionary& options,
gin::Arguments* args) {
GURL url;
if (!options.Get("url", &url) || !url.is_valid()) {
args->ThrowTypeError(
"Must pass non-empty valid url to session.preconnect.");
return;
}
int num_sockets_to_preconnect = 1;
if (options.Get("numSockets", &num_sockets_to_preconnect)) {
const int kMinSocketsToPreconnect = 1;
const int kMaxSocketsToPreconnect = 6;
if (num_sockets_to_preconnect < kMinSocketsToPreconnect ||
num_sockets_to_preconnect > kMaxSocketsToPreconnect) {
args->ThrowTypeError(
base::StringPrintf("numSocketsToPreconnect is outside range [%d,%d]",
kMinSocketsToPreconnect, kMaxSocketsToPreconnect));
return;
}
}
DCHECK_GT(num_sockets_to_preconnect, 0);
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&StartPreconnectOnUI, base::Unretained(browser_context_),
url, num_sockets_to_preconnect));
}
v8::Local<v8::Promise> Session::CloseAllConnections() {
gin_helper::Promise<void> promise(isolate_);
auto handle = promise.GetHandle();
browser_context_->GetDefaultStoragePartition()
->GetNetworkContext()
->CloseAllConnections(base::BindOnce(
gin_helper::Promise<void>::ResolvePromise, std::move(promise)));
return handle;
}
v8::Local<v8::Value> Session::GetPath(v8::Isolate* isolate) {
if (browser_context_->IsOffTheRecord()) {
return v8::Null(isolate);
}
return gin::ConvertToV8(isolate, browser_context_->GetPath());
}
void Session::SetCodeCachePath(gin::Arguments* args) {
base::FilePath code_cache_path;
auto* storage_partition = browser_context_->GetDefaultStoragePartition();
auto* code_cache_context = storage_partition->GetGeneratedCodeCacheContext();
if (code_cache_context) {
if (!args->GetNext(&code_cache_path) || !code_cache_path.IsAbsolute()) {
args->ThrowTypeError(
"Absolute path must be provided to store code cache.");
return;
}
code_cache_context->Initialize(
code_cache_path, 0 /* allows disk_cache to choose the size */);
}
}
v8::Local<v8::Promise> Session::ClearCodeCaches(
const gin_helper::Dictionary& options) {
auto* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
std::set<GURL> url_list;
base::RepeatingCallback<bool(const GURL&)> url_matcher = base::NullCallback();
if (options.Get("urls", &url_list) && !url_list.empty()) {
url_matcher = base::BindRepeating(
[](const std::set<GURL>& url_list, const GURL& url) {
return base::Contains(url_list, url);
},
url_list);
}
browser_context_->GetDefaultStoragePartition()->ClearCodeCaches(
base::Time(), base::Time::Max(), url_matcher,
base::BindOnce(gin_helper::Promise<void>::ResolvePromise,
std::move(promise)));
return handle;
}
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
base::Value Session::GetSpellCheckerLanguages() {
return browser_context_->prefs()
->GetValue(spellcheck::prefs::kSpellCheckDictionaries)
.Clone();
}
void Session::SetSpellCheckerLanguages(
gin_helper::ErrorThrower thrower,
const std::vector<std::string>& languages) {
#if !BUILDFLAG(IS_MAC)
base::Value::List language_codes;
for (const std::string& lang : languages) {
std::string code = spellcheck::GetCorrespondingSpellCheckLanguage(lang);
if (code.empty()) {
thrower.ThrowError("Invalid language code provided: \"" + lang +
"\" is not a valid language code");
return;
}
language_codes.Append(code);
}
browser_context_->prefs()->Set(spellcheck::prefs::kSpellCheckDictionaries,
base::Value(std::move(language_codes)));
// Enable spellcheck if > 0 languages, disable if no languages set
browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable,
!languages.empty());
#endif
}
void SetSpellCheckerDictionaryDownloadURL(gin_helper::ErrorThrower thrower,
const GURL& url) {
#if !BUILDFLAG(IS_MAC)
if (!url.is_valid()) {
thrower.ThrowError(
"The URL you provided to setSpellCheckerDictionaryDownloadURL is not a "
"valid URL");
return;
}
SpellcheckHunspellDictionary::SetBaseDownloadURL(url);
#endif
}
v8::Local<v8::Promise> Session::ListWordsInSpellCheckerDictionary() {
gin_helper::Promise<std::set<std::string>> promise(isolate_);
v8::Local<v8::Promise> handle = promise.GetHandle();
SpellcheckService* spellcheck =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!spellcheck) {
promise.RejectWithErrorMessage(
"Spellcheck in unexpected state: failed to load custom dictionary.");
return handle;
}
if (spellcheck->GetCustomDictionary()->IsLoaded()) {
promise.Resolve(spellcheck->GetCustomDictionary()->GetWords());
} else {
new DictionaryObserver(std::move(promise), spellcheck->GetWeakPtr());
// Dictionary loads by default asynchronously,
// call the load function anyways just to be sure.
spellcheck->GetCustomDictionary()->Load();
}
return handle;
}
bool Session::AddWordToSpellCheckerDictionary(const std::string& word) {
// don't let in-memory sessions add spellchecker words
// because files will persist unintentionally
bool is_in_memory = browser_context_->IsOffTheRecord();
if (is_in_memory)
return false;
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!service)
return false;
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
if (spellcheck::UseBrowserSpellChecker()) {
spellcheck_platform::AddWord(service->platform_spell_checker(),
base::UTF8ToUTF16(word));
}
#endif
return service->GetCustomDictionary()->AddWord(word);
}
bool Session::RemoveWordFromSpellCheckerDictionary(const std::string& word) {
// don't let in-memory sessions remove spellchecker words
// because files will persist unintentionally
bool is_in_memory = browser_context_->IsOffTheRecord();
if (is_in_memory)
return false;
SpellcheckService* service =
SpellcheckServiceFactory::GetForContext(browser_context_);
if (!service)
return false;
#if BUILDFLAG(USE_BROWSER_SPELLCHECKER)
if (spellcheck::UseBrowserSpellChecker()) {
spellcheck_platform::RemoveWord(service->platform_spell_checker(),
base::UTF8ToUTF16(word));
}
#endif
return service->GetCustomDictionary()->RemoveWord(word);
}
void Session::SetSpellCheckerEnabled(bool b) {
browser_context_->prefs()->SetBoolean(spellcheck::prefs::kSpellCheckEnable,
b);
}
bool Session::IsSpellCheckerEnabled() const {
return browser_context_->prefs()->GetBoolean(
spellcheck::prefs::kSpellCheckEnable);
}
#endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
// static
Session* Session::FromBrowserContext(content::BrowserContext* context) {
auto* data =
static_cast<UserDataLink*>(context->GetUserData(kElectronApiSessionKey));
return data ? data->session : nullptr;
}
// static
gin::Handle<Session> Session::CreateFrom(
v8::Isolate* isolate,
ElectronBrowserContext* browser_context) {
Session* existing = FromBrowserContext(browser_context);
if (existing)
return gin::CreateHandle(isolate, existing);
auto handle =
gin::CreateHandle(isolate, new Session(isolate, browser_context));
// The Sessions should never be garbage collected, since the common pattern is
// to use partition strings, instead of using the Session object directly.
handle->Pin(isolate);
App::Get()->EmitWithoutEvent("session-created", handle);
return handle;
}
// static
gin::Handle<Session> Session::FromPartition(v8::Isolate* isolate,
const std::string& partition,
base::Value::Dict options) {
ElectronBrowserContext* browser_context;
if (partition.empty()) {
browser_context =
ElectronBrowserContext::From("", false, std::move(options));
} else if (base::StartsWith(partition, kPersistPrefix,
base::CompareCase::SENSITIVE)) {
std::string name = partition.substr(8);
browser_context =
ElectronBrowserContext::From(name, false, std::move(options));
} else {
browser_context =
ElectronBrowserContext::From(partition, true, std::move(options));
}
return CreateFrom(isolate, browser_context);
}
// static
absl::optional<gin::Handle<Session>> Session::FromPath(
v8::Isolate* isolate,
const base::FilePath& path,
base::Value::Dict options) {
ElectronBrowserContext* browser_context;
if (path.empty()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("An empty path was specified");
return absl::nullopt;
}
if (!path.IsAbsolute()) {
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
promise.RejectWithErrorMessage("An absolute path was not provided");
return absl::nullopt;
}
browser_context =
ElectronBrowserContext::FromPath(std::move(path), std::move(options));
return CreateFrom(isolate, browser_context);
}
// static
gin::Handle<Session> Session::New() {
gin_helper::ErrorThrower(JavascriptEnvironment::GetIsolate())
.ThrowError("Session objects cannot be created with 'new'");
return gin::Handle<Session>();
}
void Session::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::ObjectTemplateBuilder(isolate, "Session", templ)
.SetMethod("resolveHost", &Session::ResolveHost)
.SetMethod("resolveProxy", &Session::ResolveProxy)
.SetMethod("getCacheSize", &Session::GetCacheSize)
.SetMethod("clearCache", &Session::ClearCache)
.SetMethod("clearStorageData", &Session::ClearStorageData)
.SetMethod("flushStorageData", &Session::FlushStorageData)
.SetMethod("setProxy", &Session::SetProxy)
.SetMethod("forceReloadProxyConfig", &Session::ForceReloadProxyConfig)
.SetMethod("setDownloadPath", &Session::SetDownloadPath)
.SetMethod("enableNetworkEmulation", &Session::EnableNetworkEmulation)
.SetMethod("disableNetworkEmulation", &Session::DisableNetworkEmulation)
.SetMethod("setCertificateVerifyProc", &Session::SetCertVerifyProc)
.SetMethod("setPermissionRequestHandler",
&Session::SetPermissionRequestHandler)
.SetMethod("setPermissionCheckHandler",
&Session::SetPermissionCheckHandler)
.SetMethod("setDisplayMediaRequestHandler",
&Session::SetDisplayMediaRequestHandler)
.SetMethod("setDevicePermissionHandler",
&Session::SetDevicePermissionHandler)
.SetMethod("setUSBProtectedClassesHandler",
&Session::SetUSBProtectedClassesHandler)
.SetMethod("setBluetoothPairingHandler",
&Session::SetBluetoothPairingHandler)
.SetMethod("clearHostResolverCache", &Session::ClearHostResolverCache)
.SetMethod("clearAuthCache", &Session::ClearAuthCache)
.SetMethod("allowNTLMCredentialsForDomains",
&Session::AllowNTLMCredentialsForDomains)
.SetMethod("isPersistent", &Session::IsPersistent)
.SetMethod("setUserAgent", &Session::SetUserAgent)
.SetMethod("getUserAgent", &Session::GetUserAgent)
.SetMethod("setSSLConfig", &Session::SetSSLConfig)
.SetMethod("getBlobData", &Session::GetBlobData)
.SetMethod("downloadURL", &Session::DownloadURL)
.SetMethod("createInterruptedDownload",
&Session::CreateInterruptedDownload)
.SetMethod("setPreloads", &Session::SetPreloads)
.SetMethod("getPreloads", &Session::GetPreloads)
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
.SetMethod("loadExtension", &Session::LoadExtension)
.SetMethod("removeExtension", &Session::RemoveExtension)
.SetMethod("getExtension", &Session::GetExtension)
.SetMethod("getAllExtensions", &Session::GetAllExtensions)
#endif
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
.SetMethod("getSpellCheckerLanguages", &Session::GetSpellCheckerLanguages)
.SetMethod("setSpellCheckerLanguages", &Session::SetSpellCheckerLanguages)
.SetProperty("availableSpellCheckerLanguages",
&spellcheck::SpellCheckLanguages)
.SetMethod("setSpellCheckerDictionaryDownloadURL",
&SetSpellCheckerDictionaryDownloadURL)
.SetMethod("listWordsInSpellCheckerDictionary",
&Session::ListWordsInSpellCheckerDictionary)
.SetMethod("addWordToSpellCheckerDictionary",
&Session::AddWordToSpellCheckerDictionary)
.SetMethod("removeWordFromSpellCheckerDictionary",
&Session::RemoveWordFromSpellCheckerDictionary)
.SetMethod("setSpellCheckerEnabled", &Session::SetSpellCheckerEnabled)
.SetMethod("isSpellCheckerEnabled", &Session::IsSpellCheckerEnabled)
.SetProperty("spellCheckerEnabled", &Session::IsSpellCheckerEnabled,
&Session::SetSpellCheckerEnabled)
#endif
.SetMethod("preconnect", &Session::Preconnect)
.SetMethod("closeAllConnections", &Session::CloseAllConnections)
.SetMethod("getStoragePath", &Session::GetPath)
.SetMethod("setCodeCachePath", &Session::SetCodeCachePath)
.SetMethod("clearCodeCaches", &Session::ClearCodeCaches)
.SetProperty("cookies", &Session::Cookies)
.SetProperty("netLog", &Session::NetLog)
.SetProperty("protocol", &Session::Protocol)
.SetProperty("serviceWorkers", &Session::ServiceWorkerContext)
.SetProperty("webRequest", &Session::WebRequest)
.SetProperty("storagePath", &Session::GetPath)
.Build();
}
const char* Session::GetTypeName() {
return "Session";
}
} // namespace electron::api
namespace {
using electron::api::Session;
v8::Local<v8::Value> FromPartition(const std::string& partition,
gin::Arguments* args) {
if (!electron::Browser::Get()->is_ready()) {
args->ThrowTypeError("Session can only be received when app is ready");
return v8::Null(args->isolate());
}
base::Value::Dict options;
args->GetNext(&options);
return Session::FromPartition(args->isolate(), partition, std::move(options))
.ToV8();
}
v8::Local<v8::Value> FromPath(const base::FilePath& path,
gin::Arguments* args) {
if (!electron::Browser::Get()->is_ready()) {
args->ThrowTypeError("Session can only be received when app is ready");
return v8::Null(args->isolate());
}
base::Value::Dict options;
args->GetNext(&options);
absl::optional<gin::Handle<Session>> session_handle =
Session::FromPath(args->isolate(), path, std::move(options));
if (session_handle)
return session_handle.value().ToV8();
else
return v8::Null(args->isolate());
}
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("Session", Session::GetConstructor(context));
dict.SetMethod("fromPartition", &FromPartition);
dict.SetMethod("fromPath", &FromPath);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_session, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
shell/browser/api/electron_api_session.h
|
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SESSION_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SESSION_H_
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/values.h"
#include "content/public/browser/download_manager.h"
#include "electron/buildflags/buildflags.h"
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "services/network/public/mojom/host_resolver.mojom.h"
#include "services/network/public/mojom/ssl_config.mojom.h"
#include "shell/browser/event_emitter_mixin.h"
#include "shell/browser/net/resolve_proxy_helper.h"
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/function_template_extensions.h"
#include "shell/common/gin_helper/pinnable.h"
#include "shell/common/gin_helper/promise.h"
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
#include "chrome/browser/spellchecker/spellcheck_hunspell_dictionary.h" // nogncheck
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
#endif
class GURL;
namespace base {
class FilePath;
}
namespace gin_helper {
class Dictionary;
}
namespace gin {
class Arguments;
}
namespace net {
class ProxyConfig;
}
namespace electron {
class ElectronBrowserContext;
namespace api {
class Session : public gin::Wrappable<Session>,
public gin_helper::Pinnable<Session>,
public gin_helper::Constructible<Session>,
public gin_helper::EventEmitterMixin<Session>,
public gin_helper::CleanedUpAtExit,
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
public SpellcheckHunspellDictionary::Observer,
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
public extensions::ExtensionRegistryObserver,
#endif
public content::DownloadManager::Observer {
public:
// Gets or creates Session from the |browser_context|.
static gin::Handle<Session> CreateFrom(
v8::Isolate* isolate,
ElectronBrowserContext* browser_context);
static gin::Handle<Session> New(); // Dummy, do not use!
static Session* FromBrowserContext(content::BrowserContext* context);
// Gets the Session of |partition|.
static gin::Handle<Session> FromPartition(v8::Isolate* isolate,
const std::string& partition,
base::Value::Dict options = {});
// Gets the Session based on |path|.
static absl::optional<gin::Handle<Session>> FromPath(
v8::Isolate* isolate,
const base::FilePath& path,
base::Value::Dict options = {});
ElectronBrowserContext* browser_context() const { return browser_context_; }
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
const char* GetTypeName() override;
// Methods.
v8::Local<v8::Promise> ResolveHost(
std::string host,
absl::optional<network::mojom::ResolveHostParametersPtr> params);
v8::Local<v8::Promise> ResolveProxy(gin::Arguments* args);
v8::Local<v8::Promise> GetCacheSize();
v8::Local<v8::Promise> ClearCache();
v8::Local<v8::Promise> ClearStorageData(gin::Arguments* args);
void FlushStorageData();
v8::Local<v8::Promise> SetProxy(gin::Arguments* args);
v8::Local<v8::Promise> ForceReloadProxyConfig();
void SetDownloadPath(const base::FilePath& path);
void EnableNetworkEmulation(const gin_helper::Dictionary& options);
void DisableNetworkEmulation();
void SetCertVerifyProc(v8::Local<v8::Value> proc, gin::Arguments* args);
void SetPermissionRequestHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetPermissionCheckHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetDevicePermissionHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetUSBProtectedClassesHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
void SetBluetoothPairingHandler(v8::Local<v8::Value> val,
gin::Arguments* args);
v8::Local<v8::Promise> ClearHostResolverCache(gin::Arguments* args);
v8::Local<v8::Promise> ClearAuthCache();
void AllowNTLMCredentialsForDomains(const std::string& domains);
void SetUserAgent(const std::string& user_agent, gin::Arguments* args);
std::string GetUserAgent();
void SetSSLConfig(network::mojom::SSLConfigPtr config);
bool IsPersistent();
v8::Local<v8::Promise> GetBlobData(v8::Isolate* isolate,
const std::string& uuid);
void DownloadURL(const GURL& url);
void CreateInterruptedDownload(const gin_helper::Dictionary& options);
void SetPreloads(const std::vector<base::FilePath>& preloads);
std::vector<base::FilePath> GetPreloads() const;
v8::Local<v8::Value> Cookies(v8::Isolate* isolate);
v8::Local<v8::Value> Protocol(v8::Isolate* isolate);
v8::Local<v8::Value> ServiceWorkerContext(v8::Isolate* isolate);
v8::Local<v8::Value> WebRequest(v8::Isolate* isolate);
v8::Local<v8::Value> NetLog(v8::Isolate* isolate);
void Preconnect(const gin_helper::Dictionary& options, gin::Arguments* args);
v8::Local<v8::Promise> CloseAllConnections();
v8::Local<v8::Value> GetPath(v8::Isolate* isolate);
void SetCodeCachePath(gin::Arguments* args);
v8::Local<v8::Promise> ClearCodeCaches(const gin_helper::Dictionary& options);
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
base::Value GetSpellCheckerLanguages();
void SetSpellCheckerLanguages(gin_helper::ErrorThrower thrower,
const std::vector<std::string>& languages);
v8::Local<v8::Promise> ListWordsInSpellCheckerDictionary();
bool AddWordToSpellCheckerDictionary(const std::string& word);
bool RemoveWordFromSpellCheckerDictionary(const std::string& word);
void SetSpellCheckerEnabled(bool b);
bool IsSpellCheckerEnabled() const;
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
v8::Local<v8::Promise> LoadExtension(const base::FilePath& extension_path,
gin::Arguments* args);
void RemoveExtension(const std::string& extension_id);
v8::Local<v8::Value> GetExtension(const std::string& extension_id);
v8::Local<v8::Value> GetAllExtensions();
// extensions::ExtensionRegistryObserver:
void OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) override;
void OnExtensionReady(content::BrowserContext* browser_context,
const extensions::Extension* extension) override;
void OnExtensionUnloaded(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) override;
#endif
// disable copy
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
protected:
Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context);
~Session() override;
// content::DownloadManager::Observer:
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* item) override;
#if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
// SpellcheckHunspellDictionary::Observer
void OnHunspellDictionaryInitialized(const std::string& language) override;
void OnHunspellDictionaryDownloadBegin(const std::string& language) override;
void OnHunspellDictionaryDownloadSuccess(
const std::string& language) override;
void OnHunspellDictionaryDownloadFailure(
const std::string& language) override;
#endif
private:
void SetDisplayMediaRequestHandler(v8::Isolate* isolate,
v8::Local<v8::Value> val);
// Cached gin_helper::Wrappable objects.
v8::Global<v8::Value> cookies_;
v8::Global<v8::Value> protocol_;
v8::Global<v8::Value> net_log_;
v8::Global<v8::Value> service_worker_context_;
v8::Global<v8::Value> web_request_;
raw_ptr<v8::Isolate> isolate_;
// The client id to enable the network throttler.
base::UnguessableToken network_emulation_token_;
raw_ptr<ElectronBrowserContext> browser_context_;
};
} // namespace api
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SESSION_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 12,883 |
Custom headers for DownloadItem (e.g. Authorization)
|
**Is your feature request related to a problem? Please describe.**
Download Manager/DownloadItem api does not work for webRequests that require custom headers (e.g. Authorization headers with JWT token).
**Describe the solution you'd like**
Make a per-webRequest way to pass custom headers (e.g. Authorization) through the Download Manager / DownloadItem api.
For example, extend `WebContents::DownloadURL` to allow the passing of custom headers. It currently only supports passing 'url':
`electron/atom/browser/api/atom_api_web_contents.cc` `Line 1061 in cc9771a`
```
void WebContents::DownloadURL(const GURL& url) {
```
**Describe alternatives you've considered**
The only workaround I am aware of is to filter/listen for
`webRequest.onBeforeSendHeaders([filter, ]listener)`
And modify `details.requestHeaders`. But that's a hack.
**Additional context**
Needed for download manager dependent modules like https://github.com/sindresorhus/electron-dl/issues/33
See also https://github.com/electron/electron/issues/10582 which may have been closed prematurely.
|
https://github.com/electron/electron/issues/12883
|
https://github.com/electron/electron/pull/38785
|
74d73166d93e569e96721fa4aaeac03698844240
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
| 2018-05-10T20:52:48Z |
c++
| 2023-06-21T13:31:28Z |
spec/api-session-spec.ts
|
import { expect } from 'chai';
import * as http from 'node:http';
import * as https from 'node:https';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as ChildProcess from 'node:child_process';
import { app, session, BrowserWindow, net, ipcMain, Session, webFrameMain, WebFrameMain } from 'electron/main';
import * as send from 'send';
import * as auth from 'basic-auth';
import { closeAllWindows } from './lib/window-helpers';
import { defer, listen } from './lib/spec-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
describe('session module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
const url = 'http://127.0.0.1';
describe('session.defaultSession', () => {
it('returns the default session', () => {
expect(session.defaultSession).to.equal(session.fromPartition(''));
});
});
describe('session.fromPartition(partition, options)', () => {
it('returns existing session with same partition', () => {
expect(session.fromPartition('test')).to.equal(session.fromPartition('test'));
});
});
describe('session.fromPath(path)', () => {
it('returns storage path of a session which was created with an absolute path', () => {
const tmppath = require('electron').app.getPath('temp');
const ses = session.fromPath(tmppath);
expect(ses.storagePath).to.equal(tmppath);
});
});
describe('ses.cookies', () => {
const name = '0';
const value = '0';
afterEach(closeAllWindows);
// Clear cookie of defaultSession after each test.
afterEach(async () => {
const { cookies } = session.defaultSession;
const cs = await cookies.get({ url });
for (const c of cs) {
await cookies.remove(url, c.name);
}
});
it('should get cookies', async () => {
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [`${name}=${value}`]);
res.end('finished');
server.close();
});
const { port } = await listen(server);
const w = new BrowserWindow({ show: false });
await w.loadURL(`${url}:${port}`);
const list = await w.webContents.session.cookies.get({ url });
const cookie = list.find(cookie => cookie.name === name);
expect(cookie).to.exist.and.to.have.property('value', value);
});
it('sets cookies', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(false);
});
it('sets session cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '1';
await cookies.set({ url, name, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.equal(name);
expect(c.value).to.equal(value);
expect(c.session).to.equal(true);
});
it('sets cookies without name', async () => {
const { cookies } = session.defaultSession;
const value = '3';
await cookies.set({ url, value });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
});
for (const sameSite of <const>['unspecified', 'no_restriction', 'lax', 'strict']) {
it(`sets cookies with samesite=${sameSite}`, async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await cookies.set({ url, value, sameSite });
const c = (await cookies.get({ url }))[0];
expect(c.name).to.be.empty();
expect(c.value).to.equal(value);
expect(c.sameSite).to.equal(sameSite);
});
}
it('fails to set cookies with samesite=garbage', async () => {
const { cookies } = session.defaultSession;
const value = 'hithere';
await expect(cookies.set({ url, value, sameSite: 'garbage' as any })).to.eventually.be.rejectedWith('Failed to convert \'garbage\' to an appropriate cookie same site value');
});
it('gets cookies without url', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const cs = await cookies.get({ domain: '127.0.0.1' });
expect(cs.some(c => c.name === name && c.value === value)).to.equal(true);
});
it('yields an error when setting a cookie with missing required fields', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: '', name, value })
).to.eventually.be.rejectedWith('Failed to set cookie with an invalid domain attribute');
});
it('yields an error when setting a cookie with an invalid URL', async () => {
const { cookies } = session.defaultSession;
const name = '1';
const value = '1';
await expect(
cookies.set({ url: 'asdf', name, value })
).to.eventually.be.rejectedWith('Failed to set cookie with an invalid domain attribute');
});
it('should overwrite previous cookies', async () => {
const { cookies } = session.defaultSession;
const name = 'DidOverwrite';
for (const value of ['No', 'Yes']) {
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(true);
}
});
it('should remove cookies', async () => {
const { cookies } = session.defaultSession;
const name = '2';
const value = '2';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
await cookies.remove(url, name);
const list = await cookies.get({ url });
expect(list.some(cookie => cookie.name === name && cookie.value === value)).to.equal(false);
});
// DISABLED-FIXME
it('should set cookie for standard scheme', async () => {
const { cookies } = session.defaultSession;
const domain = 'fake-host';
const url = `${standardScheme}://${domain}`;
const name = 'custom';
const value = '1';
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const list = await cookies.get({ url });
expect(list).to.have.lengthOf(1);
expect(list[0]).to.have.property('name', name);
expect(list[0]).to.have.property('value', value);
expect(list[0]).to.have.property('domain', domain);
});
it('emits a changed event when a cookie is added or removed', async () => {
const { cookies } = session.fromPartition('cookies-changed');
const name = 'foo';
const value = 'bar';
const a = once(cookies, 'changed');
await cookies.set({ url, name, value, expirationDate: (+new Date()) / 1000 + 120 });
const [, setEventCookie, setEventCause, setEventRemoved] = await a;
const b = once(cookies, 'changed');
await cookies.remove(url, name);
const [, removeEventCookie, removeEventCause, removeEventRemoved] = await b;
expect(setEventCookie.name).to.equal(name);
expect(setEventCookie.value).to.equal(value);
expect(setEventCause).to.equal('explicit');
expect(setEventRemoved).to.equal(false);
expect(removeEventCookie.name).to.equal(name);
expect(removeEventCookie.value).to.equal(value);
expect(removeEventCause).to.equal('explicit');
expect(removeEventRemoved).to.equal(true);
});
describe('ses.cookies.flushStore()', async () => {
it('flushes the cookies to disk', async () => {
const name = 'foo';
const value = 'bar';
const { cookies } = session.defaultSession;
await cookies.set({ url, name, value });
await cookies.flushStore();
});
});
it('should survive an app restart for persistent partition', async function () {
this.timeout(60000);
const appPath = path.join(fixtures, 'api', 'cookie-app');
const runAppWithPhase = (phase: string) => {
return new Promise((resolve) => {
let output = '';
const appProcess = ChildProcess.spawn(
process.execPath,
[appPath],
{ env: { PHASE: phase, ...process.env } }
);
appProcess.stdout.on('data', data => { output += data; });
appProcess.on('exit', () => {
resolve(output.replace(/(\r\n|\n|\r)/gm, ''));
});
});
};
expect(await runAppWithPhase('one')).to.equal('011');
expect(await runAppWithPhase('two')).to.equal('110');
});
});
describe('ses.clearStorageData(options)', () => {
afterEach(closeAllWindows);
it('clears localstorage data', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
await w.loadFile(path.join(fixtures, 'api', 'localstorage.html'));
const options = {
origin: 'file://',
storages: ['localstorage'],
quotas: ['persistent']
};
await w.webContents.session.clearStorageData(options);
while (await w.webContents.executeJavaScript('localStorage.length') !== 0) {
// The storage clear isn't instantly visible to the renderer, so keep
// trying until it is.
}
});
});
describe('will-download event', () => {
afterEach(closeAllWindows);
it('can cancel default download behavior', async () => {
const w = new BrowserWindow({ show: false });
const mockFile = Buffer.alloc(1024);
const contentDisposition = 'inline; filename="mockFile.txt"';
const downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockFile.length,
'Content-Type': 'application/plain',
'Content-Disposition': contentDisposition
});
res.end(mockFile);
downloadServer.close();
});
const url = (await listen(downloadServer)).url;
const downloadPrevented: Promise<{itemUrl: string, itemFilename: string, item: Electron.DownloadItem}> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
e.preventDefault();
resolve({ itemUrl: item.getURL(), itemFilename: item.getFilename(), item });
});
});
w.loadURL(url);
const { item, itemUrl, itemFilename } = await downloadPrevented;
expect(itemUrl).to.equal(url + '/');
expect(itemFilename).to.equal('mockFile.txt');
// Delay till the next tick.
await new Promise(setImmediate);
expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
});
});
describe('ses.protocol', () => {
const partitionName = 'temp';
const protocolName = 'sp';
let customSession: Session;
const protocol = session.defaultSession.protocol;
const handler = (ignoredError: any, callback: Function) => {
callback({ data: '<script>require(\'electron\').ipcRenderer.send(\'hello\')</script>', mimeType: 'text/html' });
};
beforeEach(async () => {
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
});
afterEach(async () => {
await customSession.protocol.unregisterProtocol(protocolName);
customSession = null as any;
});
afterEach(closeAllWindows);
it('does not affect defaultSession', () => {
const result1 = protocol.isProtocolRegistered(protocolName);
expect(result1).to.equal(false);
const result2 = customSession.protocol.isProtocolRegistered(protocolName);
expect(result2).to.equal(true);
});
it('handles requests from partition', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: partitionName,
nodeIntegration: true,
contextIsolation: false
}
});
customSession = session.fromPartition(partitionName);
await customSession.protocol.registerStringProtocol(protocolName, handler);
w.loadURL(`${protocolName}://fake-host`);
await once(ipcMain, 'hello');
});
});
describe('ses.setProxy(options)', () => {
let server: http.Server;
let customSession: Electron.Session;
let created = false;
beforeEach(async () => {
customSession = session.fromPartition('proxyconfig');
if (!created) {
// Work around for https://github.com/electron/electron/issues/26166 to
// reduce flake
await setTimeout(100);
created = true;
}
});
afterEach(() => {
if (server) {
server.close();
}
customSession = null as any;
});
it('allows configuring proxy settings', async () => {
const config = { proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows removing the implicit bypass rules for localhost', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<-loopback>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://localhost');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with pacScript', async () => {
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:8132";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
const { url } = await listen(server);
{
const config = { pacScript: url };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
{
const config = { mode: 'pac_script' as any, pacScript: url };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal('PROXY myproxy:8132');
}
});
it('allows bypassing proxy settings', async () => {
const config = {
proxyRules: 'http=myproxy:80',
proxyBypassRules: '<local>'
};
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `direct`', async () => {
const config = { mode: 'direct' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `auto_detect`', async () => {
const config = { mode: 'auto_detect' as any };
await customSession.setProxy(config);
});
it('allows configuring proxy settings with mode `pac_script`', async () => {
const config = { mode: 'pac_script' as any };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('DIRECT');
});
it('allows configuring proxy settings with mode `fixed_servers`', async () => {
const config = { mode: 'fixed_servers' as any, proxyRules: 'http=myproxy:80' };
await customSession.setProxy(config);
const proxy = await customSession.resolveProxy('http://example.com/');
expect(proxy).to.equal('PROXY myproxy:80');
});
it('allows configuring proxy settings with mode `system`', async () => {
const config = { mode: 'system' as any };
await customSession.setProxy(config);
});
it('disallows configuring proxy settings with mode `invalid`', async () => {
const config = { mode: 'invalid' as any };
await expect(customSession.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
});
it('reload proxy configuration', async () => {
let proxyPort = 8132;
server = http.createServer((req, res) => {
const pac = `
function FindProxyForURL(url, host) {
return "PROXY myproxy:${proxyPort}";
}
`;
res.writeHead(200, {
'Content-Type': 'application/x-ns-proxy-autoconfig'
});
res.end(pac);
});
const { url } = await listen(server);
const config = { mode: 'pac_script' as any, pacScript: url };
await customSession.setProxy(config);
{
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
{
proxyPort = 8133;
await customSession.forceReloadProxyConfig();
const proxy = await customSession.resolveProxy('https://google.com');
expect(proxy).to.equal(`PROXY myproxy:${proxyPort}`);
}
});
});
describe('ses.resolveHost(host)', () => {
let customSession: Electron.Session;
beforeEach(async () => {
customSession = session.fromPartition('resolvehost');
});
afterEach(() => {
customSession = null as any;
});
it('resolves ipv4.localhost2', async () => {
const { endpoints } = await customSession.resolveHost('ipv4.localhost2');
expect(endpoints).to.be.a('array');
expect(endpoints).to.have.lengthOf(1);
expect(endpoints[0].family).to.equal('ipv4');
expect(endpoints[0].address).to.equal('10.0.0.1');
});
it('fails to resolve AAAA record for ipv4.localhost2', async () => {
await expect(customSession.resolveHost('ipv4.localhost2', {
queryType: 'AAAA'
}))
.to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
it('resolves ipv6.localhost2', async () => {
const { endpoints } = await customSession.resolveHost('ipv6.localhost2');
expect(endpoints).to.be.a('array');
expect(endpoints).to.have.lengthOf(1);
expect(endpoints[0].family).to.equal('ipv6');
expect(endpoints[0].address).to.equal('::1');
});
it('fails to resolve A record for ipv6.localhost2', async () => {
await expect(customSession.resolveHost('notfound.localhost2', {
queryType: 'A'
}))
.to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
it('fails to resolve notfound.localhost2', async () => {
await expect(customSession.resolveHost('notfound.localhost2'))
.to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
});
describe('ses.getBlobData()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const postData = JSON.stringify({
type: 'blob',
value: 'hello'
});
const content = `<html>
<script>
let fd = new FormData();
fd.append('file', new Blob(['${postData}'], {type:'application/json'}));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
expect(result.toString()).to.equal(postData);
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.getBlobData2()', () => {
const scheme = 'cors-blob';
const protocol = session.defaultSession.protocol;
const url = `${scheme}://host`;
after(async () => {
await protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
it('returns blob data for uuid', (done) => {
const content = `<html>
<script>
let fd = new FormData();
fd.append("data", new Blob(new Array(65_537).fill('a')));
fetch('${url}', {method:'POST', body: fd });
</script>
</html>`;
protocol.registerStringProtocol(scheme, (request, callback) => {
try {
if (request.method === 'GET') {
callback({ data: content, mimeType: 'text/html' });
} else if (request.method === 'POST') {
const uuid = request.uploadData![1].blobUUID;
expect(uuid).to.be.a('string');
session.defaultSession.getBlobData(uuid!).then(result => {
try {
const data = new Array(65_537).fill('a');
expect(result.toString()).to.equal(data.join(''));
done();
} catch (e) {
done(e);
}
});
}
} catch (e) {
done(e);
}
});
const w = new BrowserWindow({ show: false });
w.loadURL(url);
});
});
describe('ses.setCertificateVerifyProc(callback)', () => {
let server: http.Server;
let serverUrl: string;
beforeEach(async () => {
const certPath = path.join(fixtures, 'certificates');
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
rejectUnauthorized: false
};
server = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('<title>hello</title>');
});
serverUrl = (await listen(server)).url;
});
afterEach((done) => {
server.close(done);
});
afterEach(closeAllWindows);
it('accepts the request when the callback is called with 0', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, verificationResult, errorCode }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(errorCode).to.be.oneOf([-202, -200]);
};
callback(0);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
expect(w.webContents.getTitle()).to.equal('hello');
expect(validate!).not.to.be.undefined();
validate!();
});
it('rejects the request when the callback is called with -2', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let validate: () => void;
ses.setCertificateVerifyProc(({ hostname, certificate, verificationResult, isIssuedByKnownRoot }, callback) => {
if (hostname !== '127.0.0.1') return callback(-3);
validate = () => {
expect(certificate.issuerName).to.equal('Intermediate CA');
expect(certificate.subjectName).to.equal('localhost');
expect(certificate.issuer.commonName).to.equal('Intermediate CA');
expect(certificate.subject.commonName).to.equal('localhost');
expect(certificate.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.subject.commonName).to.equal('Intermediate CA');
expect(certificate.issuerCert.issuerCert.issuer.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.subject.commonName).to.equal('Root CA');
expect(certificate.issuerCert.issuerCert.issuerCert).to.equal(undefined);
expect(verificationResult).to.be.oneOf(['net::ERR_CERT_AUTHORITY_INVALID', 'net::ERR_CERT_COMMON_NAME_INVALID']);
expect(isIssuedByKnownRoot).to.be.false();
};
callback(-2);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(serverUrl)).to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(validate!).not.to.be.undefined();
validate!();
});
it('saves cached results', async () => {
const ses = session.fromPartition(`${Math.random()}`);
let numVerificationRequests = 0;
ses.setCertificateVerifyProc((e, callback) => {
if (e.hostname !== '127.0.0.1') return callback(-3);
numVerificationRequests++;
callback(-2);
});
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await expect(w.loadURL(serverUrl), 'first load').to.eventually.be.rejectedWith(/ERR_FAILED/);
await once(w.webContents, 'did-stop-loading');
await expect(w.loadURL(serverUrl + '/test'), 'second load').to.eventually.be.rejectedWith(/ERR_FAILED/);
expect(numVerificationRequests).to.equal(1);
});
it('does not cancel requests in other sessions', async () => {
const ses1 = session.fromPartition(`${Math.random()}`);
ses1.setCertificateVerifyProc((opts, cb) => cb(0));
const ses2 = session.fromPartition(`${Math.random()}`);
const req = net.request({ url: serverUrl, session: ses1, credentials: 'include' });
req.end();
setTimeout().then(() => {
ses2.setCertificateVerifyProc((opts, callback) => callback(0));
});
await expect(new Promise<void>((resolve, reject) => {
req.on('error', (err) => {
reject(err);
});
req.on('response', () => {
resolve();
});
})).to.eventually.be.fulfilled();
});
});
describe('ses.clearAuthCache()', () => {
it('can clear http auth info from cache', async () => {
const ses = session.fromPartition('auth-cache');
const server = http.createServer((req, res) => {
const credentials = auth(req);
if (!credentials || credentials.name !== 'test' || credentials.pass !== 'test') {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"');
res.end();
} else {
res.end('authenticated');
}
});
const { port } = await listen(server);
const fetch = (url: string) => new Promise((resolve, reject) => {
const request = net.request({ url, session: ses });
request.on('response', (response) => {
let data: string | null = null;
response.on('data', (chunk) => {
if (!data) {
data = '';
}
data += chunk;
});
response.on('end', () => {
if (!data) {
reject(new Error('Empty response'));
} else {
resolve(data);
}
});
response.on('error', (error: any) => { reject(new Error(error)); });
});
request.on('error', (error: any) => { reject(new Error(error)); });
request.end();
});
// the first time should throw due to unauthenticated
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
// passing the password should let us in
expect(await fetch(`http://test:[email protected]:${port}`)).to.equal('authenticated');
// subsequently, the credentials are cached
expect(await fetch(`http://127.0.0.1:${port}`)).to.equal('authenticated');
await ses.clearAuthCache();
// once the cache is cleared, we should get an error again
await expect(fetch(`http://127.0.0.1:${port}`)).to.eventually.be.rejected();
});
});
describe('DownloadItem', () => {
const mockPDF = Buffer.alloc(1024 * 1024 * 5);
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const protocolName = 'custom-dl';
const contentDisposition = 'inline; filename="mock.pdf"';
let port: number;
let downloadServer: http.Server;
before(async () => {
downloadServer = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Length': mockPDF.length,
'Content-Type': 'application/pdf',
'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition
});
res.end(mockPDF);
});
port = (await listen(downloadServer)).port;
});
after(async () => {
await new Promise(resolve => downloadServer.close(resolve));
});
afterEach(closeAllWindows);
const isPathEqual = (path1: string, path2: string) => {
return path.relative(path1, path2) === '';
};
const assertDownload = (state: string, item: Electron.DownloadItem, isCustom = false) => {
expect(state).to.equal('completed');
expect(item.getFilename()).to.equal('mock.pdf');
expect(path.isAbsolute(item.savePath)).to.equal(true);
expect(isPathEqual(item.savePath, downloadFilePath)).to.equal(true);
if (isCustom) {
expect(item.getURL()).to.equal(`${protocolName}://item`);
} else {
expect(item.getURL()).to.be.equal(`${url}:${port}/`);
}
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(mockPDF.length);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
fs.unlinkSync(downloadFilePath);
};
it('can download using session.downloadURL', (done) => {
session.defaultSession.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
session.defaultSession.downloadURL(`${url}:${port}`);
});
it('can download using WebContents.downloadURL', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${url}:${port}`);
});
it('can download from custom protocols using WebContents.downloadURL', (done) => {
const protocol = session.defaultSession.protocol;
const handler = (ignoredError: any, callback: Function) => {
callback({ url: `${url}:${port}` });
};
protocol.registerHttpProtocol(protocolName, handler);
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
assertDownload(state, item, true);
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`${protocolName}://item`);
});
it('can download using WebView.downloadURL', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
await w.loadURL('about:blank');
function webviewDownload ({ fixtures, url, port }: {fixtures: string, url: string, port: string}) {
const webview = new (window as any).WebView();
webview.addEventListener('did-finish-load', () => {
webview.downloadURL(`${url}:${port}/`);
});
webview.src = `file://${fixtures}/api/blank.html`;
document.body.appendChild(webview);
}
const done: Promise<[string, Electron.DownloadItem]> = new Promise(resolve => {
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
resolve([state, item]);
});
});
});
await w.webContents.executeJavaScript(`(${webviewDownload})(${JSON.stringify({ fixtures, url, port })})`);
const [state, item] = await done;
assertDownload(state, item);
});
it('can cancel download', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function (e, state) {
try {
expect(state).to.equal('cancelled');
expect(item.getFilename()).to.equal('mock.pdf');
expect(item.getMimeType()).to.equal('application/pdf');
expect(item.getReceivedBytes()).to.equal(0);
expect(item.getTotalBytes()).to.equal(mockPDF.length);
expect(item.getContentDisposition()).to.equal(contentDisposition);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/`);
});
it('can generate a default filename', function (done) {
if (process.env.APPVEYOR === 'True') {
// FIXME(alexeykuzmin): Skip the test.
// this.skip()
return done();
}
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
item.on('done', function () {
try {
expect(item.getFilename()).to.equal('download.pdf');
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}/?testFilename`);
});
it('can set options for the save dialog', (done) => {
const filePath = path.join(__dirname, 'fixtures', 'mock.pdf');
const options = {
window: null,
title: 'title',
message: 'message',
buttonLabel: 'buttonLabel',
nameFieldLabel: 'nameFieldLabel',
defaultPath: '/',
filters: [{
name: '1', extensions: ['.1', '.2']
}, {
name: '2', extensions: ['.3', '.4', '.5']
}],
showsTagField: true,
securityScopedBookmarks: true
};
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(filePath);
item.setSaveDialogOptions(options);
item.on('done', function () {
try {
expect(item.getSaveDialogOptions()).to.deep.equal(options);
done();
} catch (e) {
done(e);
}
});
item.cancel();
});
w.webContents.downloadURL(`${url}:${port}`);
});
describe('when a save path is specified and the URL is unavailable', () => {
it('does not display a save dialog and reports the done state as interrupted', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.session.once('will-download', function (e, item) {
item.savePath = downloadFilePath;
if (item.getState() === 'interrupted') {
item.resume();
}
item.on('done', function (e, state) {
try {
expect(state).to.equal('interrupted');
done();
} catch (e) {
done(e);
}
});
});
w.webContents.downloadURL(`file://${path.join(__dirname, 'does-not-exist.txt')}`);
});
});
});
describe('ses.createInterruptedDownload(options)', () => {
afterEach(closeAllWindows);
it('can create an interrupted download item', async () => {
const downloadFilePath = path.join(__dirname, '..', 'fixtures', 'mock.pdf');
const options = {
path: downloadFilePath,
urlChain: ['http://127.0.0.1/'],
mimeType: 'application/pdf',
offset: 0,
length: 5242880
};
const w = new BrowserWindow({ show: false });
const p = once(w.webContents.session, 'will-download');
w.webContents.session.createInterruptedDownload(options);
const [, item] = await p;
expect(item.getState()).to.equal('interrupted');
item.cancel();
expect(item.getURLChain()).to.deep.equal(options.urlChain);
expect(item.getMimeType()).to.equal(options.mimeType);
expect(item.getReceivedBytes()).to.equal(options.offset);
expect(item.getTotalBytes()).to.equal(options.length);
expect(item.savePath).to.equal(downloadFilePath);
});
it('can be resumed', async () => {
const downloadFilePath = path.join(fixtures, 'logo.png');
const rangeServer = http.createServer((req, res) => {
const options = { root: fixtures };
send(req, req.url!, options)
.on('error', (error: any) => { throw error; }).pipe(res);
});
try {
const { url } = await listen(rangeServer);
const w = new BrowserWindow({ show: false });
const downloadCancelled: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
item.setSavePath(downloadFilePath);
item.on('done', function () {
resolve(item);
});
item.cancel();
});
});
const downloadUrl = `${url}/assets/logo.png`;
w.webContents.downloadURL(downloadUrl);
const item = await downloadCancelled;
expect(item.getState()).to.equal('cancelled');
const options = {
path: item.savePath,
urlChain: item.getURLChain(),
mimeType: item.getMimeType(),
offset: item.getReceivedBytes(),
length: item.getTotalBytes(),
lastModified: item.getLastModifiedTime(),
eTag: item.getETag()
};
const downloadResumed: Promise<Electron.DownloadItem> = new Promise((resolve) => {
w.webContents.session.once('will-download', function (e, item) {
expect(item.getState()).to.equal('interrupted');
item.setSavePath(downloadFilePath);
item.resume();
item.on('done', function () {
resolve(item);
});
});
});
w.webContents.session.createInterruptedDownload(options);
const completedItem = await downloadResumed;
expect(completedItem.getState()).to.equal('completed');
expect(completedItem.getFilename()).to.equal('logo.png');
expect(completedItem.savePath).to.equal(downloadFilePath);
expect(completedItem.getURL()).to.equal(downloadUrl);
expect(completedItem.getMimeType()).to.equal('image/png');
expect(completedItem.getReceivedBytes()).to.equal(14022);
expect(completedItem.getTotalBytes()).to.equal(14022);
expect(fs.existsSync(downloadFilePath)).to.equal(true);
} finally {
rangeServer.close();
}
});
});
describe('ses.setPermissionRequestHandler(handler)', () => {
afterEach(closeAllWindows);
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('cancels any pending requests when cleared', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler',
nodeIntegration: true,
contextIsolation: false
}
});
const ses = w.webContents.session;
ses.setPermissionRequestHandler(() => {
ses.setPermissionRequestHandler(null);
});
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb(`<html><script>(${remote})()</script></html>`);
});
const result = once(require('electron').ipcMain, 'message');
function remote () {
(navigator as any).requestMIDIAccess({ sysex: true }).then(() => {}, (err: any) => {
require('electron').ipcRenderer.send('message', err.name);
});
}
await w.loadURL('https://myfakesite');
const [, name] = await result;
expect(name).to.deep.equal('SecurityError');
});
it('successfully resolves when calling legacy getUserMedia', async () => {
const ses = session.fromPartition('' + Math.random());
ses.setPermissionRequestHandler(
(_webContents, _permission, callback) => {
callback(true);
}
);
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const { ok, message } = await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => navigator.getUserMedia({
video: true,
audio: true,
}, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message})))
`);
expect(ok).to.be.true(message);
});
it('successfully rejects when calling legacy getUserMedia', async () => {
const ses = session.fromPartition('' + Math.random());
ses.setPermissionRequestHandler(
(_webContents, _permission, callback) => {
callback(false);
}
);
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
await expect(w.webContents.executeJavaScript(`
new Promise((resolve, reject) => navigator.getUserMedia({
video: true,
audio: true,
}, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message})))
`)).to.eventually.be.rejectedWith('Permission denied');
});
});
describe('ses.setPermissionCheckHandler(handler)', () => {
afterEach(closeAllWindows);
it('details provides requestingURL for mainFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = () => {
return w.webContents.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadURL(loadUrl);
const state = await readClipboardPermission();
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
});
it('details provides requestingURL for cross origin subFrame', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'very-temp-permission-handler'
}
});
const ses = w.webContents.session;
const loadUrl = 'https://myfakesite/';
let handlerDetails : Electron.PermissionCheckHandlerHandlerDetails;
ses.protocol.interceptStringProtocol('https', (req, cb) => {
cb('<html><script>console.log(\'test\');</script></html>');
});
ses.setPermissionCheckHandler((wc, permission, requestingOrigin, details) => {
if (permission === 'clipboard-read') {
handlerDetails = details;
return true;
}
return false;
});
const readClipboardPermission: any = (frame: WebFrameMain) => {
return frame.executeJavaScript(`
navigator.permissions.query({name: 'clipboard-read'})
.then(permission => permission.state).catch(err => err.message);
`, true);
};
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe');
iframe.src = '${loadUrl}';
document.body.appendChild(iframe);
null;
`);
const [,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-finish-load');
const state = await readClipboardPermission(webFrameMain.fromId(frameProcessId, frameRoutingId));
expect(state).to.equal('granted');
expect(handlerDetails!.requestingUrl).to.equal(loadUrl);
expect(handlerDetails!.isMainFrame).to.be.false();
expect(handlerDetails!.embeddingOrigin).to.equal('file:///');
});
});
describe('ses.isPersistent()', () => {
afterEach(closeAllWindows);
it('returns default session as persistent', () => {
const w = new BrowserWindow({
show: false
});
const ses = w.webContents.session;
expect(ses.isPersistent()).to.be.true();
});
it('returns persist: session as persistent', () => {
const ses = session.fromPartition(`persist:${Math.random()}`);
expect(ses.isPersistent()).to.be.true();
});
it('returns temporary session as not persistent', () => {
const ses = session.fromPartition(`${Math.random()}`);
expect(ses.isPersistent()).to.be.false();
});
});
describe('ses.setUserAgent()', () => {
afterEach(closeAllWindows);
it('can be retrieved with getUserAgent()', () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent);
expect(ses.getUserAgent()).to.equal(userAgent);
});
it('sets the User-Agent header for web requests made from renderers', async () => {
const userAgent = 'test-agent';
const ses = session.fromPartition('' + Math.random());
ses.setUserAgent(userAgent, 'en-US,fr,de');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
let headers: http.IncomingHttpHeaders | null = null;
const server = http.createServer((req, res) => {
headers = req.headers;
res.end();
server.close();
});
const { url } = await listen(server);
await w.loadURL(url);
expect(headers!['user-agent']).to.equal(userAgent);
expect(headers!['accept-language']).to.equal('en-US,fr;q=0.9,de;q=0.8');
});
});
describe('session-created event', () => {
it('is emitted when a session is created', async () => {
const sessionCreated = once(app, 'session-created');
const session1 = session.fromPartition('' + Math.random());
const [session2] = await sessionCreated;
expect(session1).to.equal(session2);
});
});
describe('session.storagePage', () => {
it('returns a string', () => {
expect(session.defaultSession.storagePath).to.be.a('string');
});
it('returns null for in memory sessions', () => {
expect(session.fromPartition('in-memory').storagePath).to.equal(null);
});
it('returns different paths for partitions and the default session', () => {
expect(session.defaultSession.storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
it('returns different paths for different partitions', () => {
expect(session.fromPartition('persist:one').storagePath).to.not.equal(session.fromPartition('persist:two').storagePath);
});
});
describe('session.setCodeCachePath()', () => {
it('throws when relative or empty path is provided', () => {
expect(() => {
session.defaultSession.setCodeCachePath('../fixtures');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath('');
}).to.throw('Absolute path must be provided to store code cache.');
expect(() => {
session.defaultSession.setCodeCachePath(path.join(app.getPath('userData'), 'electron-test-code-cache'));
}).to.not.throw();
});
});
describe('ses.setSSLConfig()', () => {
it('can disable cipher suites', async () => {
const ses = session.fromPartition('' + Math.random());
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
const server = https.createServer({
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.2',
ciphers: 'AES128-GCM-SHA256'
}, (req, res) => {
res.end('hi');
});
const { port } = await listen(server);
defer(() => server.close());
function request () {
return new Promise((resolve, reject) => {
const r = net.request({
url: `https://127.0.0.1:${port}`,
session: ses
});
r.on('response', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk.toString('utf8');
});
res.on('end', () => {
resolve(data);
});
});
r.on('error', (err) => {
reject(err);
});
r.end();
});
}
await expect(request()).to.be.rejectedWith(/ERR_CERT_AUTHORITY_INVALID/);
ses.setSSLConfig({
disabledCipherSuites: [0x009C]
});
await expect(request()).to.be.rejectedWith(/ERR_SSL_VERSION_OR_CIPHER_MISMATCH/);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,667 |
[Bug]: The zoom out button of the window cannot be displayed properly
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.3.12
### What operating system are you using?
Windows
### Operating System Version
windows10,windows11, windows8, windows7
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
During the process of using the BrowserWindow instance option, "titleBarStyle: hidden" and "titleBarOverlay: true" were set, and then the window's setMinimizable (false) was set through ipc; setMaximizable(false); setClosable(false); The result is obvious that the zoom in and zoom in buttons are hidden, and the close button is disabled and displayed. This is normal, but setMinimizable (true) is set in reverse through ipc; setMaximizable(true); setClosable(true); The results show that the close button, zoom in button, and zoom out button are displayed normally
### Actual Behavior
During the process of using the BrowserWindow instance option, "titleBarStyle: hidden" and "titleBarOverlay: true" were set, and then the window's setMinimizable (false) was set through ipc; setMaximizable(false); setClosable(false); The result is obvious that the zoom in and zoom in buttons are hidden, and the close button is disabled and displayed. This is normal, but setMinimizable (true) is set in reverse through ipc; setMaximizable(true); setClosable(true); The result shows that the close button and zoom in button are displayed normally, while the zoom out button cannot be displayed
### Testcase Gist URL
https://gist.github.com/4b725c80ec42886b16a957897431c750
### Additional Information
Even with the latest 25.1.0, it still performs the same!!!!
|
https://github.com/electron/electron/issues/38667
|
https://github.com/electron/electron/pull/38860
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
|
ce6fe040feefe326a557132fb81137097d4a39c1
| 2023-06-08T06:16:25Z |
c++
| 2023-06-21T18:58:33Z |
shell/browser/ui/views/win_caption_button_container.cc
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Modified from
// chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc
#include "shell/browser/ui/views/win_caption_button_container.h"
#include <memory>
#include <utility>
#include "shell/browser/ui/views/win_caption_button.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/compositor/layer.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/view_class_properties.h"
namespace electron {
namespace {
std::unique_ptr<WinCaptionButton> CreateCaptionButton(
views::Button::PressedCallback callback,
WinFrameView* frame_view,
ViewID button_type,
int accessible_name_resource_id) {
return std::make_unique<WinCaptionButton>(
std::move(callback), frame_view, button_type,
l10n_util::GetStringUTF16(accessible_name_resource_id));
}
bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) {
return button && button->GetVisible() && button->bounds().Contains(point);
}
} // anonymous namespace
WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view)
: frame_view_(frame_view),
minimize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Minimize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MINIMIZE_BUTTON,
IDS_APP_ACCNAME_MINIMIZE))),
maximize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Maximize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MAXIMIZE_BUTTON,
IDS_APP_ACCNAME_MAXIMIZE))),
restore_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Restore,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_RESTORE_BUTTON,
IDS_APP_ACCNAME_RESTORE))),
close_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::CloseWithReason,
base::Unretained(frame_view_->frame()),
views::Widget::ClosedReason::kCloseButtonClicked),
frame_view_,
VIEW_ID_CLOSE_BUTTON,
IDS_APP_ACCNAME_CLOSE))) {
// Layout is horizontal, with buttons placed at the trailing end of the view.
// This allows the container to expand to become a faux titlebar/drag handle.
auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetMainAxisAlignment(views::LayoutAlignment::kEnd)
.SetCrossAxisAlignment(views::LayoutAlignment::kStart)
.SetDefault(
views::kFlexBehaviorKey,
views::FlexSpecification(views::LayoutOrientation::kHorizontal,
views::MinimumFlexSizeRule::kPreferred,
views::MaximumFlexSizeRule::kPreferred,
/* adjust_width_for_height */ false,
views::MinimumFlexSizeRule::kScaleToZero));
}
WinCaptionButtonContainer::~WinCaptionButtonContainer() {}
int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const {
DCHECK(HitTestPoint(point))
<< "should only be called with a point inside this view's bounds";
if (HitTestCaptionButton(minimize_button_, point)) {
return HTMINBUTTON;
}
if (HitTestCaptionButton(maximize_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(restore_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(close_button_, point)) {
return HTCLOSE;
}
return HTCAPTION;
}
gfx::Size WinCaptionButtonContainer::GetButtonSize() const {
// Close button size is set the same as all the buttons
return close_button_->GetSize();
}
void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) {
minimize_button_->SetSize(size);
maximize_button_->SetSize(size);
restore_button_->SetSize(size);
close_button_->SetSize(size);
}
void WinCaptionButtonContainer::ResetWindowControls() {
minimize_button_->SetState(views::Button::STATE_NORMAL);
maximize_button_->SetState(views::Button::STATE_NORMAL);
restore_button_->SetState(views::Button::STATE_NORMAL);
close_button_->SetState(views::Button::STATE_NORMAL);
InvalidateLayout();
}
void WinCaptionButtonContainer::AddedToWidget() {
views::Widget* const widget = GetWidget();
DCHECK(!widget_observation_.IsObserving());
widget_observation_.Observe(widget);
UpdateButtons();
if (frame_view_->window()->IsWindowControlsOverlayEnabled()) {
UpdateBackground();
}
}
void WinCaptionButtonContainer::RemovedFromWidget() {
DCHECK(widget_observation_.IsObserving());
widget_observation_.Reset();
}
void WinCaptionButtonContainer::OnWidgetBoundsChanged(
views::Widget* widget,
const gfx::Rect& new_bounds) {
UpdateButtons();
}
void WinCaptionButtonContainer::UpdateBackground() {
const SkColor bg_color = frame_view_->window()->overlay_button_color();
const SkAlpha theme_alpha = SkColorGetA(bg_color);
SetBackground(views::CreateSolidBackground(bg_color));
SetPaintToLayer();
if (theme_alpha < SK_AlphaOPAQUE)
layer()->SetFillsBoundsOpaquely(false);
}
void WinCaptionButtonContainer::UpdateButtons() {
const bool is_maximized = frame_view_->frame()->IsMaximized();
restore_button_->SetVisible(is_maximized);
maximize_button_->SetVisible(!is_maximized);
const bool minimizable = frame_view_->window()->IsMinimizable();
minimize_button_->SetEnabled(minimizable);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled.
const bool is_touch = ui::TouchUiController::Get()->touch_ui();
restore_button_->SetEnabled(!is_touch);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled, unless the window is not
// maximized.
const bool maximizable = frame_view_->window()->IsMaximizable();
maximize_button_->SetEnabled(!(is_touch && is_maximized) && maximizable);
const bool closable = frame_view_->window()->IsClosable();
close_button_->SetEnabled(closable);
// If all three of closable, maximizable, and minimizable are disabled,
// Windows natively only shows the disabled closable button. Copy that
// behavior here.
if (!maximizable && !closable && !minimizable) {
minimize_button_->SetVisible(false);
maximize_button_->SetVisible(false);
}
InvalidateLayout();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,667 |
[Bug]: The zoom out button of the window cannot be displayed properly
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.3.12
### What operating system are you using?
Windows
### Operating System Version
windows10,windows11, windows8, windows7
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
During the process of using the BrowserWindow instance option, "titleBarStyle: hidden" and "titleBarOverlay: true" were set, and then the window's setMinimizable (false) was set through ipc; setMaximizable(false); setClosable(false); The result is obvious that the zoom in and zoom in buttons are hidden, and the close button is disabled and displayed. This is normal, but setMinimizable (true) is set in reverse through ipc; setMaximizable(true); setClosable(true); The results show that the close button, zoom in button, and zoom out button are displayed normally
### Actual Behavior
During the process of using the BrowserWindow instance option, "titleBarStyle: hidden" and "titleBarOverlay: true" were set, and then the window's setMinimizable (false) was set through ipc; setMaximizable(false); setClosable(false); The result is obvious that the zoom in and zoom in buttons are hidden, and the close button is disabled and displayed. This is normal, but setMinimizable (true) is set in reverse through ipc; setMaximizable(true); setClosable(true); The result shows that the close button and zoom in button are displayed normally, while the zoom out button cannot be displayed
### Testcase Gist URL
https://gist.github.com/4b725c80ec42886b16a957897431c750
### Additional Information
Even with the latest 25.1.0, it still performs the same!!!!
|
https://github.com/electron/electron/issues/38667
|
https://github.com/electron/electron/pull/38860
|
e73edb54817acb8f0e548916a97a9ed9340dfc3f
|
ce6fe040feefe326a557132fb81137097d4a39c1
| 2023-06-08T06:16:25Z |
c++
| 2023-06-21T18:58:33Z |
shell/browser/ui/views/win_caption_button_container.cc
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Modified from
// chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc
#include "shell/browser/ui/views/win_caption_button_container.h"
#include <memory>
#include <utility>
#include "shell/browser/ui/views/win_caption_button.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/compositor/layer.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/background.h"
#include "ui/views/layout/flex_layout.h"
#include "ui/views/view_class_properties.h"
namespace electron {
namespace {
std::unique_ptr<WinCaptionButton> CreateCaptionButton(
views::Button::PressedCallback callback,
WinFrameView* frame_view,
ViewID button_type,
int accessible_name_resource_id) {
return std::make_unique<WinCaptionButton>(
std::move(callback), frame_view, button_type,
l10n_util::GetStringUTF16(accessible_name_resource_id));
}
bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) {
return button && button->GetVisible() && button->bounds().Contains(point);
}
} // anonymous namespace
WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view)
: frame_view_(frame_view),
minimize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Minimize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MINIMIZE_BUTTON,
IDS_APP_ACCNAME_MINIMIZE))),
maximize_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Maximize,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_MAXIMIZE_BUTTON,
IDS_APP_ACCNAME_MAXIMIZE))),
restore_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::Restore,
base::Unretained(frame_view_->frame())),
frame_view_,
VIEW_ID_RESTORE_BUTTON,
IDS_APP_ACCNAME_RESTORE))),
close_button_(AddChildView(CreateCaptionButton(
base::BindRepeating(&views::Widget::CloseWithReason,
base::Unretained(frame_view_->frame()),
views::Widget::ClosedReason::kCloseButtonClicked),
frame_view_,
VIEW_ID_CLOSE_BUTTON,
IDS_APP_ACCNAME_CLOSE))) {
// Layout is horizontal, with buttons placed at the trailing end of the view.
// This allows the container to expand to become a faux titlebar/drag handle.
auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>());
layout->SetOrientation(views::LayoutOrientation::kHorizontal)
.SetMainAxisAlignment(views::LayoutAlignment::kEnd)
.SetCrossAxisAlignment(views::LayoutAlignment::kStart)
.SetDefault(
views::kFlexBehaviorKey,
views::FlexSpecification(views::LayoutOrientation::kHorizontal,
views::MinimumFlexSizeRule::kPreferred,
views::MaximumFlexSizeRule::kPreferred,
/* adjust_width_for_height */ false,
views::MinimumFlexSizeRule::kScaleToZero));
}
WinCaptionButtonContainer::~WinCaptionButtonContainer() {}
int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const {
DCHECK(HitTestPoint(point))
<< "should only be called with a point inside this view's bounds";
if (HitTestCaptionButton(minimize_button_, point)) {
return HTMINBUTTON;
}
if (HitTestCaptionButton(maximize_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(restore_button_, point)) {
return HTMAXBUTTON;
}
if (HitTestCaptionButton(close_button_, point)) {
return HTCLOSE;
}
return HTCAPTION;
}
gfx::Size WinCaptionButtonContainer::GetButtonSize() const {
// Close button size is set the same as all the buttons
return close_button_->GetSize();
}
void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) {
minimize_button_->SetSize(size);
maximize_button_->SetSize(size);
restore_button_->SetSize(size);
close_button_->SetSize(size);
}
void WinCaptionButtonContainer::ResetWindowControls() {
minimize_button_->SetState(views::Button::STATE_NORMAL);
maximize_button_->SetState(views::Button::STATE_NORMAL);
restore_button_->SetState(views::Button::STATE_NORMAL);
close_button_->SetState(views::Button::STATE_NORMAL);
InvalidateLayout();
}
void WinCaptionButtonContainer::AddedToWidget() {
views::Widget* const widget = GetWidget();
DCHECK(!widget_observation_.IsObserving());
widget_observation_.Observe(widget);
UpdateButtons();
if (frame_view_->window()->IsWindowControlsOverlayEnabled()) {
UpdateBackground();
}
}
void WinCaptionButtonContainer::RemovedFromWidget() {
DCHECK(widget_observation_.IsObserving());
widget_observation_.Reset();
}
void WinCaptionButtonContainer::OnWidgetBoundsChanged(
views::Widget* widget,
const gfx::Rect& new_bounds) {
UpdateButtons();
}
void WinCaptionButtonContainer::UpdateBackground() {
const SkColor bg_color = frame_view_->window()->overlay_button_color();
const SkAlpha theme_alpha = SkColorGetA(bg_color);
SetBackground(views::CreateSolidBackground(bg_color));
SetPaintToLayer();
if (theme_alpha < SK_AlphaOPAQUE)
layer()->SetFillsBoundsOpaquely(false);
}
void WinCaptionButtonContainer::UpdateButtons() {
const bool is_maximized = frame_view_->frame()->IsMaximized();
restore_button_->SetVisible(is_maximized);
maximize_button_->SetVisible(!is_maximized);
const bool minimizable = frame_view_->window()->IsMinimizable();
minimize_button_->SetEnabled(minimizable);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled.
const bool is_touch = ui::TouchUiController::Get()->touch_ui();
restore_button_->SetEnabled(!is_touch);
// In touch mode, windows cannot be taken out of fullscreen or tiled mode, so
// the maximize/restore button should be disabled, unless the window is not
// maximized.
const bool maximizable = frame_view_->window()->IsMaximizable();
maximize_button_->SetEnabled(!(is_touch && is_maximized) && maximizable);
const bool closable = frame_view_->window()->IsClosable();
close_button_->SetEnabled(closable);
// If all three of closable, maximizable, and minimizable are disabled,
// Windows natively only shows the disabled closable button. Copy that
// behavior here.
if (!maximizable && !closable && !minimizable) {
minimize_button_->SetVisible(false);
maximize_button_->SetVisible(false);
}
InvalidateLayout();
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,642 |
[Bug]: BrowserWindow.removeBrowserView will crash the app if the browserView is destroyed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
23.1.4
### What operating system are you using?
macOS
### Operating System Version
13.0
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
BrowserWindow.removeBrowserView should remove the browserView regardless of whether browserView is destroyed or not.
### Actual Behavior
The app will exit with code SIGSEGV.
### Testcase Gist URL
```Javascript
const {app, BrowserWindow, BrowserView} = require('electron')
const path = require('path')
async function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const view = new BrowserView({
preload: path.join(__dirname, 'preload.js')
});
view.webContents.on('destroyed', () => {
mainWindow.removeBrowserView(view)
});
mainWindow.addBrowserView(view);
view.setBounds({x:0, y:0, width:300, height:300});
// and load the index.html of the app.
await mainWindow.loadFile('index.html')
await view.webContents.loadFile('index.html')
view.webContents.close();
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
```
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/37642
|
https://github.com/electron/electron/pull/38842
|
ce6fe040feefe326a557132fb81137097d4a39c1
|
a00a25376d339ba78c4a1efbae2de05fd534332e
| 2023-03-22T03:57:18Z |
c++
| 2023-06-21T19:20:54Z |
shell/browser/api/electron_api_browser_view.cc
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_browser_view.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/render_widget_host_view.h"
#include "shell/browser/api/electron_api_base_window.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "ui/base/hit_test.h"
#include "ui/gfx/geometry/rect.h"
namespace gin {
template <>
struct Converter<electron::AutoResizeFlags> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::AutoResizeFlags* auto_resize_flags) {
gin_helper::Dictionary params;
if (!ConvertFromV8(isolate, val, ¶ms)) {
return false;
}
uint8_t flags = 0;
bool width = false;
if (params.Get("width", &width) && width) {
flags |= electron::kAutoResizeWidth;
}
bool height = false;
if (params.Get("height", &height) && height) {
flags |= electron::kAutoResizeHeight;
}
bool horizontal = false;
if (params.Get("horizontal", &horizontal) && horizontal) {
flags |= electron::kAutoResizeHorizontal;
}
bool vertical = false;
if (params.Get("vertical", &vertical) && vertical) {
flags |= electron::kAutoResizeVertical;
}
*auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags);
return true;
}
};
} // namespace gin
namespace {
int32_t GetNextId() {
static int32_t next_id = 1;
return next_id++;
}
} // namespace
namespace electron::api {
gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};
BrowserView::BrowserView(gin::Arguments* args,
const gin_helper::Dictionary& options)
: id_(GetNextId()) {
gin_helper::Dictionary web_preferences =
gin::Dictionary::CreateEmpty(args->isolate());
options.Get(options::kWebPreferences, &web_preferences);
web_preferences.Set("type", "browserView");
v8::Local<v8::Value> value;
// Copy the webContents option to webPreferences.
if (options.Get("webContents", &value)) {
web_preferences.SetHidden("webContents", value);
}
auto web_contents =
WebContents::CreateFromWebPreferences(args->isolate(), web_preferences);
web_contents_.Reset(args->isolate(), web_contents.ToV8());
api_web_contents_ = web_contents.get();
api_web_contents_->AddObserver(this);
Observe(web_contents->web_contents());
view_.reset(
NativeBrowserView::Create(api_web_contents_->inspectable_web_contents()));
}
void BrowserView::SetOwnerWindow(BaseWindow* window) {
// Ensure WebContents and BrowserView owner windows are in sync.
if (web_contents())
web_contents()->SetOwnerWindow(window ? window->window() : nullptr);
owner_window_ = window ? window->GetWeakPtr() : nullptr;
}
int BrowserView::NonClientHitTest(const gfx::Point& point) {
gfx::Rect bounds = GetBounds();
gfx::Point local_point(point.x() - bounds.x(), point.y() - bounds.y());
SkRegion* region = api_web_contents_->draggable_region();
if (region && region->contains(local_point.x(), local_point.y()))
return HTCAPTION;
return HTNOWHERE;
}
BrowserView::~BrowserView() {
if (web_contents()) { // destroy() called without closing WebContents
web_contents()->RemoveObserver(this);
web_contents()->Destroy();
}
}
void BrowserView::WebContentsDestroyed() {
if (owner_window())
owner_window()->window()->RemoveDraggableRegionProvider(this);
api_web_contents_ = nullptr;
web_contents_.Reset();
Unpin();
}
// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create BrowserView before app is ready");
return gin::Handle<BrowserView>();
}
gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
auto handle =
gin::CreateHandle(args->isolate(), new BrowserView(args, options));
handle->Pin(args->isolate());
return handle;
}
void BrowserView::SetAutoResize(AutoResizeFlags flags) {
view_->SetAutoResizeFlags(flags);
}
void BrowserView::SetBounds(const gfx::Rect& bounds) {
view_->SetBounds(bounds);
}
gfx::Rect BrowserView::GetBounds() {
return view_->GetBounds();
}
void BrowserView::SetBackgroundColor(const std::string& color_name) {
SkColor color = ParseCSSColor(color_name);
view_->SetBackgroundColor(color);
if (web_contents()) {
auto* wc = web_contents()->web_contents();
wc->SetPageBaseBackgroundColor(ParseCSSColor(color_name));
auto* const rwhv = wc->GetRenderWidgetHostView();
if (rwhv) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
// Ensure new color is stored in webPreferences, otherwise
// the color will be reset on the next load via HandleNewRenderFrame.
auto* web_preferences = WebContentsPreferences::From(wc);
if (web_preferences)
web_preferences->SetBackgroundColor(color);
}
}
v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate);
}
return v8::Local<v8::Value>::New(isolate, web_contents_);
}
// static
void BrowserView::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::ObjectTemplateBuilder(isolate, "BrowserView", templ)
.SetMethod("setAutoResize", &BrowserView::SetAutoResize)
.SetMethod("setBounds", &BrowserView::SetBounds)
.SetMethod("getBounds", &BrowserView::GetBounds)
.SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
.SetProperty("webContents", &BrowserView::GetWebContents)
.Build();
}
} // namespace electron::api
namespace {
using electron::api::BrowserView;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("BrowserView", BrowserView::GetConstructor(context));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,642 |
[Bug]: BrowserWindow.removeBrowserView will crash the app if the browserView is destroyed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
23.1.4
### What operating system are you using?
macOS
### Operating System Version
13.0
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
BrowserWindow.removeBrowserView should remove the browserView regardless of whether browserView is destroyed or not.
### Actual Behavior
The app will exit with code SIGSEGV.
### Testcase Gist URL
```Javascript
const {app, BrowserWindow, BrowserView} = require('electron')
const path = require('path')
async function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const view = new BrowserView({
preload: path.join(__dirname, 'preload.js')
});
view.webContents.on('destroyed', () => {
mainWindow.removeBrowserView(view)
});
mainWindow.addBrowserView(view);
view.setBounds({x:0, y:0, width:300, height:300});
// and load the index.html of the app.
await mainWindow.loadFile('index.html')
await view.webContents.loadFile('index.html')
view.webContents.close();
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
```
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/37642
|
https://github.com/electron/electron/pull/38842
|
ce6fe040feefe326a557132fb81137097d4a39c1
|
a00a25376d339ba78c4a1efbae2de05fd534332e
| 2023-03-22T03:57:18Z |
c++
| 2023-06-21T19:20:54Z |
shell/browser/api/electron_api_browser_view.h
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "content/public/browser/web_contents_observer.h"
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/extended_web_contents_observer.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/native_window.h"
#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/pinnable.h"
namespace gfx {
class Rect;
}
namespace gin_helper {
class Dictionary;
}
namespace electron::api {
class WebContents;
class BaseWindow;
class BrowserView : public gin::Wrappable<BrowserView>,
public gin_helper::Constructible<BrowserView>,
public gin_helper::Pinnable<BrowserView>,
public content::WebContentsObserver,
public ExtendedWebContentsObserver,
public DraggableRegionProvider {
public:
// gin_helper::Constructible
static gin::Handle<BrowserView> New(gin_helper::ErrorThrower thrower,
gin::Arguments* args);
static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
WebContents* web_contents() const { return api_web_contents_; }
NativeBrowserView* view() const { return view_.get(); }
BaseWindow* owner_window() const { return owner_window_.get(); }
void SetOwnerWindow(BaseWindow* window);
int32_t ID() const { return id_; }
int NonClientHitTest(const gfx::Point& point) override;
// disable copy
BrowserView(const BrowserView&) = delete;
BrowserView& operator=(const BrowserView&) = delete;
protected:
BrowserView(gin::Arguments* args, const gin_helper::Dictionary& options);
~BrowserView() override;
// content::WebContentsObserver:
void WebContentsDestroyed() override;
private:
void SetAutoResize(AutoResizeFlags flags);
void SetBounds(const gfx::Rect& bounds);
gfx::Rect GetBounds();
void SetBackgroundColor(const std::string& color_name);
v8::Local<v8::Value> GetWebContents(v8::Isolate*);
v8::Global<v8::Value> web_contents_;
class raw_ptr<WebContents> api_web_contents_ = nullptr;
std::unique_ptr<NativeBrowserView> view_;
base::WeakPtr<BaseWindow> owner_window_;
int32_t id_;
};
} // namespace electron::api
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,642 |
[Bug]: BrowserWindow.removeBrowserView will crash the app if the browserView is destroyed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
23.1.4
### What operating system are you using?
macOS
### Operating System Version
13.0
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
BrowserWindow.removeBrowserView should remove the browserView regardless of whether browserView is destroyed or not.
### Actual Behavior
The app will exit with code SIGSEGV.
### Testcase Gist URL
```Javascript
const {app, BrowserWindow, BrowserView} = require('electron')
const path = require('path')
async function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const view = new BrowserView({
preload: path.join(__dirname, 'preload.js')
});
view.webContents.on('destroyed', () => {
mainWindow.removeBrowserView(view)
});
mainWindow.addBrowserView(view);
view.setBounds({x:0, y:0, width:300, height:300});
// and load the index.html of the app.
await mainWindow.loadFile('index.html')
await view.webContents.loadFile('index.html')
view.webContents.close();
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
```
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/37642
|
https://github.com/electron/electron/pull/38842
|
ce6fe040feefe326a557132fb81137097d4a39c1
|
a00a25376d339ba78c4a1efbae2de05fd534332e
| 2023-03-22T03:57:18Z |
c++
| 2023-06-21T19:20:54Z |
spec/api-browser-view-spec.ts
|
import { expect } from 'chai';
import * as path from 'node:path';
import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main';
import { closeWindow } from './lib/window-helpers';
import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers';
import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers';
import { once } from 'node:events';
describe('BrowserView module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
let w: BrowserWindow;
let view: BrowserView;
beforeEach(() => {
expect(webContents.getAllWebContents()).to.have.length(0);
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
});
});
afterEach(async () => {
const p = once(w.webContents, 'destroyed');
await closeWindow(w);
w = null as any;
await p;
if (view && view.webContents) {
const p = once(view.webContents, 'destroyed');
view.webContents.destroy();
view = null as any;
await p;
}
expect(webContents.getAllWebContents()).to.have.length(0);
});
it('can be created with an existing webContents', async () => {
const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
await wc.loadURL('about:blank');
view = new BrowserView({ webContents: wc } as any);
expect(view.webContents.getURL()).to.equal('about:blank');
});
describe('BrowserView.setBackgroundColor()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBackgroundColor('#000');
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBackgroundColor(null as any);
}).to.throw(/conversion failure/);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('sets the background color to transparent if none is set', async () => {
const display = screen.getPrimaryDisplay();
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('successfully applies the background color', async () => {
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
const VIEW_BACKGROUND_COLOR = '#ff00ff';
const display = screen.getPrimaryDisplay();
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
w.setBackgroundColor(VIEW_BACKGROUND_COLOR);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true();
});
});
describe('BrowserView.setAutoResize()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setAutoResize({});
view.setAutoResize({ width: true, height: false });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setAutoResize(null as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.setBounds()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBounds({ x: 0, y: 0, width: 1, height: 1 });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBounds(null as any);
}).to.throw(/conversion failure/);
expect(() => {
view.setBounds({} as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.getBounds()', () => {
it('returns correct bounds on a framed window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
it('returns correct bounds on a frameless window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
});
describe('BrowserWindow.setBrowserView()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
w.setBrowserView(view);
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.setBrowserView(view);
w.setBrowserView(view);
w.setBrowserView(view);
});
});
describe('BrowserWindow.getBrowserView()', () => {
it('returns the set view', () => {
view = new BrowserView();
w.setBrowserView(view);
const view2 = w.getBrowserView();
expect(view2!.webContents.id).to.equal(view.webContents.id);
});
it('returns null if none is set', () => {
const view = w.getBrowserView();
expect(view).to.be.null('view');
});
});
describe('BrowserWindow.addBrowserView()', () => {
it('does not throw for valid args', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.addBrowserView(view);
w.addBrowserView(view);
w.addBrowserView(view);
});
it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => {
expect(() => {
const view1 = new BrowserView();
view1.webContents.destroy();
w.addBrowserView(view1);
}).to.not.throw();
});
it('does not crash if the webContents is destroyed after a URL is loaded', () => {
view = new BrowserView();
expect(async () => {
view.setBounds({ x: 0, y: 0, width: 400, height: 300 });
await view.webContents.loadURL('data:text/html,hello there');
view.webContents.destroy();
}).to.not.throw();
});
it('can handle BrowserView reparenting', async () => {
view = new BrowserView();
w.addBrowserView(view);
view.webContents.loadURL('about:blank');
await once(view.webContents, 'did-finish-load');
const w2 = new BrowserWindow({ show: false });
w2.addBrowserView(view);
w.close();
view.webContents.loadURL(`file://${fixtures}/pages/blank.html`);
await once(view.webContents, 'did-finish-load');
// Clean up - the afterEach hook assumes the webContents on w is still alive.
w = new BrowserWindow({ show: false });
w2.close();
w2.destroy();
});
});
describe('BrowserWindow.removeBrowserView()', () => {
it('does not throw if called multiple times with same view', () => {
expect(() => {
view = new BrowserView();
w.addBrowserView(view);
w.removeBrowserView(view);
w.removeBrowserView(view);
}).to.not.throw();
});
});
describe('BrowserWindow.getBrowserViews()', () => {
it('returns same views as was added', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
const views = w.getBrowserViews();
expect(views).to.have.lengthOf(2);
expect(views[0].webContents.id).to.equal(view1.webContents.id);
expect(views[1].webContents.id).to.equal(view2.webContents.id);
});
});
describe('BrowserWindow.setTopBrowserView()', () => {
it('should throw an error when a BrowserView is not attached to the window', () => {
view = new BrowserView();
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
});
it('should throw an error when a BrowserView is attached to some other window', () => {
view = new BrowserView();
const win2 = new BrowserWindow();
w.addBrowserView(view);
view.setBounds({ x: 0, y: 0, width: 100, height: 100 });
win2.addBrowserView(view);
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
win2.close();
win2.destroy();
});
});
describe('BrowserView.webContents.getOwnerBrowserWindow()', () => {
it('points to owning window', () => {
view = new BrowserView();
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
w.setBrowserView(view);
expect(view.webContents.getOwnerBrowserWindow()).to.equal(w);
w.setBrowserView(null);
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
});
});
describe('shutdown behavior', () => {
it('does not crash on exit', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { BrowserView, app } = require('electron');
// eslint-disable-next-line no-new
new BrowserView({});
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('does not crash on exit if added to a browser window', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { app, BrowserView, BrowserWindow } = require('electron');
const bv = new BrowserView();
bv.webContents.loadURL('about:blank');
const bw = new BrowserWindow({ show: false });
bw.addBrowserView(bv);
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('emits the destroyed event when webContents.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.close();
await once(view.webContents, 'destroyed');
});
it('emits the destroyed event when window.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.executeJavaScript('window.close()');
await once(view.webContents, 'destroyed');
});
});
describe('window.open()', () => {
it('works in BrowserView', (done) => {
view = new BrowserView();
w.setBrowserView(view);
view.webContents.setWindowOpenHandler(({ url, frameName }) => {
expect(url).to.equal('http://host/');
expect(frameName).to.equal('host');
done();
return { action: 'deny' };
});
view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
});
});
describe('BrowserView.capturePage(rect)', () => {
it('returns a Promise with a Buffer', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.addBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
const image = await view.webContents.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
xit('resolves after the window is hidden and capturer count is non-zero', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.setBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
const image = await view.webContents.capturePage();
expect(image.isEmpty()).to.equal(false);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,642 |
[Bug]: BrowserWindow.removeBrowserView will crash the app if the browserView is destroyed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
23.1.4
### What operating system are you using?
macOS
### Operating System Version
13.0
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
BrowserWindow.removeBrowserView should remove the browserView regardless of whether browserView is destroyed or not.
### Actual Behavior
The app will exit with code SIGSEGV.
### Testcase Gist URL
```Javascript
const {app, BrowserWindow, BrowserView} = require('electron')
const path = require('path')
async function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const view = new BrowserView({
preload: path.join(__dirname, 'preload.js')
});
view.webContents.on('destroyed', () => {
mainWindow.removeBrowserView(view)
});
mainWindow.addBrowserView(view);
view.setBounds({x:0, y:0, width:300, height:300});
// and load the index.html of the app.
await mainWindow.loadFile('index.html')
await view.webContents.loadFile('index.html')
view.webContents.close();
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
```
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/37642
|
https://github.com/electron/electron/pull/38842
|
ce6fe040feefe326a557132fb81137097d4a39c1
|
a00a25376d339ba78c4a1efbae2de05fd534332e
| 2023-03-22T03:57:18Z |
c++
| 2023-06-21T19:20:54Z |
shell/browser/api/electron_api_browser_view.cc
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_browser_view.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/render_widget_host_view.h"
#include "shell/browser/api/electron_api_base_window.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "ui/base/hit_test.h"
#include "ui/gfx/geometry/rect.h"
namespace gin {
template <>
struct Converter<electron::AutoResizeFlags> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::AutoResizeFlags* auto_resize_flags) {
gin_helper::Dictionary params;
if (!ConvertFromV8(isolate, val, ¶ms)) {
return false;
}
uint8_t flags = 0;
bool width = false;
if (params.Get("width", &width) && width) {
flags |= electron::kAutoResizeWidth;
}
bool height = false;
if (params.Get("height", &height) && height) {
flags |= electron::kAutoResizeHeight;
}
bool horizontal = false;
if (params.Get("horizontal", &horizontal) && horizontal) {
flags |= electron::kAutoResizeHorizontal;
}
bool vertical = false;
if (params.Get("vertical", &vertical) && vertical) {
flags |= electron::kAutoResizeVertical;
}
*auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags);
return true;
}
};
} // namespace gin
namespace {
int32_t GetNextId() {
static int32_t next_id = 1;
return next_id++;
}
} // namespace
namespace electron::api {
gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};
BrowserView::BrowserView(gin::Arguments* args,
const gin_helper::Dictionary& options)
: id_(GetNextId()) {
gin_helper::Dictionary web_preferences =
gin::Dictionary::CreateEmpty(args->isolate());
options.Get(options::kWebPreferences, &web_preferences);
web_preferences.Set("type", "browserView");
v8::Local<v8::Value> value;
// Copy the webContents option to webPreferences.
if (options.Get("webContents", &value)) {
web_preferences.SetHidden("webContents", value);
}
auto web_contents =
WebContents::CreateFromWebPreferences(args->isolate(), web_preferences);
web_contents_.Reset(args->isolate(), web_contents.ToV8());
api_web_contents_ = web_contents.get();
api_web_contents_->AddObserver(this);
Observe(web_contents->web_contents());
view_.reset(
NativeBrowserView::Create(api_web_contents_->inspectable_web_contents()));
}
void BrowserView::SetOwnerWindow(BaseWindow* window) {
// Ensure WebContents and BrowserView owner windows are in sync.
if (web_contents())
web_contents()->SetOwnerWindow(window ? window->window() : nullptr);
owner_window_ = window ? window->GetWeakPtr() : nullptr;
}
int BrowserView::NonClientHitTest(const gfx::Point& point) {
gfx::Rect bounds = GetBounds();
gfx::Point local_point(point.x() - bounds.x(), point.y() - bounds.y());
SkRegion* region = api_web_contents_->draggable_region();
if (region && region->contains(local_point.x(), local_point.y()))
return HTCAPTION;
return HTNOWHERE;
}
BrowserView::~BrowserView() {
if (web_contents()) { // destroy() called without closing WebContents
web_contents()->RemoveObserver(this);
web_contents()->Destroy();
}
}
void BrowserView::WebContentsDestroyed() {
if (owner_window())
owner_window()->window()->RemoveDraggableRegionProvider(this);
api_web_contents_ = nullptr;
web_contents_.Reset();
Unpin();
}
// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
if (!Browser::Get()->is_ready()) {
thrower.ThrowError("Cannot create BrowserView before app is ready");
return gin::Handle<BrowserView>();
}
gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
auto handle =
gin::CreateHandle(args->isolate(), new BrowserView(args, options));
handle->Pin(args->isolate());
return handle;
}
void BrowserView::SetAutoResize(AutoResizeFlags flags) {
view_->SetAutoResizeFlags(flags);
}
void BrowserView::SetBounds(const gfx::Rect& bounds) {
view_->SetBounds(bounds);
}
gfx::Rect BrowserView::GetBounds() {
return view_->GetBounds();
}
void BrowserView::SetBackgroundColor(const std::string& color_name) {
SkColor color = ParseCSSColor(color_name);
view_->SetBackgroundColor(color);
if (web_contents()) {
auto* wc = web_contents()->web_contents();
wc->SetPageBaseBackgroundColor(ParseCSSColor(color_name));
auto* const rwhv = wc->GetRenderWidgetHostView();
if (rwhv) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
// Ensure new color is stored in webPreferences, otherwise
// the color will be reset on the next load via HandleNewRenderFrame.
auto* web_preferences = WebContentsPreferences::From(wc);
if (web_preferences)
web_preferences->SetBackgroundColor(color);
}
}
v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) {
if (web_contents_.IsEmpty()) {
return v8::Null(isolate);
}
return v8::Local<v8::Value>::New(isolate, web_contents_);
}
// static
void BrowserView::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::ObjectTemplateBuilder(isolate, "BrowserView", templ)
.SetMethod("setAutoResize", &BrowserView::SetAutoResize)
.SetMethod("setBounds", &BrowserView::SetBounds)
.SetMethod("getBounds", &BrowserView::GetBounds)
.SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
.SetProperty("webContents", &BrowserView::GetWebContents)
.Build();
}
} // namespace electron::api
namespace {
using electron::api::BrowserView;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("BrowserView", BrowserView::GetConstructor(context));
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,642 |
[Bug]: BrowserWindow.removeBrowserView will crash the app if the browserView is destroyed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
23.1.4
### What operating system are you using?
macOS
### Operating System Version
13.0
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
BrowserWindow.removeBrowserView should remove the browserView regardless of whether browserView is destroyed or not.
### Actual Behavior
The app will exit with code SIGSEGV.
### Testcase Gist URL
```Javascript
const {app, BrowserWindow, BrowserView} = require('electron')
const path = require('path')
async function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const view = new BrowserView({
preload: path.join(__dirname, 'preload.js')
});
view.webContents.on('destroyed', () => {
mainWindow.removeBrowserView(view)
});
mainWindow.addBrowserView(view);
view.setBounds({x:0, y:0, width:300, height:300});
// and load the index.html of the app.
await mainWindow.loadFile('index.html')
await view.webContents.loadFile('index.html')
view.webContents.close();
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
```
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/37642
|
https://github.com/electron/electron/pull/38842
|
ce6fe040feefe326a557132fb81137097d4a39c1
|
a00a25376d339ba78c4a1efbae2de05fd534332e
| 2023-03-22T03:57:18Z |
c++
| 2023-06-21T19:20:54Z |
shell/browser/api/electron_api_browser_view.h
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "content/public/browser/web_contents_observer.h"
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/extended_web_contents_observer.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/native_window.h"
#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/pinnable.h"
namespace gfx {
class Rect;
}
namespace gin_helper {
class Dictionary;
}
namespace electron::api {
class WebContents;
class BaseWindow;
class BrowserView : public gin::Wrappable<BrowserView>,
public gin_helper::Constructible<BrowserView>,
public gin_helper::Pinnable<BrowserView>,
public content::WebContentsObserver,
public ExtendedWebContentsObserver,
public DraggableRegionProvider {
public:
// gin_helper::Constructible
static gin::Handle<BrowserView> New(gin_helper::ErrorThrower thrower,
gin::Arguments* args);
static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
WebContents* web_contents() const { return api_web_contents_; }
NativeBrowserView* view() const { return view_.get(); }
BaseWindow* owner_window() const { return owner_window_.get(); }
void SetOwnerWindow(BaseWindow* window);
int32_t ID() const { return id_; }
int NonClientHitTest(const gfx::Point& point) override;
// disable copy
BrowserView(const BrowserView&) = delete;
BrowserView& operator=(const BrowserView&) = delete;
protected:
BrowserView(gin::Arguments* args, const gin_helper::Dictionary& options);
~BrowserView() override;
// content::WebContentsObserver:
void WebContentsDestroyed() override;
private:
void SetAutoResize(AutoResizeFlags flags);
void SetBounds(const gfx::Rect& bounds);
gfx::Rect GetBounds();
void SetBackgroundColor(const std::string& color_name);
v8::Local<v8::Value> GetWebContents(v8::Isolate*);
v8::Global<v8::Value> web_contents_;
class raw_ptr<WebContents> api_web_contents_ = nullptr;
std::unique_ptr<NativeBrowserView> view_;
base::WeakPtr<BaseWindow> owner_window_;
int32_t id_;
};
} // namespace electron::api
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_BROWSER_VIEW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 37,642 |
[Bug]: BrowserWindow.removeBrowserView will crash the app if the browserView is destroyed
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
23.1.4
### What operating system are you using?
macOS
### Operating System Version
13.0
### What arch are you using?
x64
### Last Known Working Electron version
_No response_
### Expected Behavior
BrowserWindow.removeBrowserView should remove the browserView regardless of whether browserView is destroyed or not.
### Actual Behavior
The app will exit with code SIGSEGV.
### Testcase Gist URL
```Javascript
const {app, BrowserWindow, BrowserView} = require('electron')
const path = require('path')
async function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
const view = new BrowserView({
preload: path.join(__dirname, 'preload.js')
});
view.webContents.on('destroyed', () => {
mainWindow.removeBrowserView(view)
});
mainWindow.addBrowserView(view);
view.setBounds({x:0, y:0, width:300, height:300});
// and load the index.html of the app.
await mainWindow.loadFile('index.html')
await view.webContents.loadFile('index.html')
view.webContents.close();
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
```
### Additional Information
_No response_
|
https://github.com/electron/electron/issues/37642
|
https://github.com/electron/electron/pull/38842
|
ce6fe040feefe326a557132fb81137097d4a39c1
|
a00a25376d339ba78c4a1efbae2de05fd534332e
| 2023-03-22T03:57:18Z |
c++
| 2023-06-21T19:20:54Z |
spec/api-browser-view-spec.ts
|
import { expect } from 'chai';
import * as path from 'node:path';
import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main';
import { closeWindow } from './lib/window-helpers';
import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers';
import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers';
import { once } from 'node:events';
describe('BrowserView module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
let w: BrowserWindow;
let view: BrowserView;
beforeEach(() => {
expect(webContents.getAllWebContents()).to.have.length(0);
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
});
});
afterEach(async () => {
const p = once(w.webContents, 'destroyed');
await closeWindow(w);
w = null as any;
await p;
if (view && view.webContents) {
const p = once(view.webContents, 'destroyed');
view.webContents.destroy();
view = null as any;
await p;
}
expect(webContents.getAllWebContents()).to.have.length(0);
});
it('can be created with an existing webContents', async () => {
const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
await wc.loadURL('about:blank');
view = new BrowserView({ webContents: wc } as any);
expect(view.webContents.getURL()).to.equal('about:blank');
});
describe('BrowserView.setBackgroundColor()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBackgroundColor('#000');
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBackgroundColor(null as any);
}).to.throw(/conversion failure/);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('sets the background color to transparent if none is set', async () => {
const display = screen.getPrimaryDisplay();
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('successfully applies the background color', async () => {
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
const VIEW_BACKGROUND_COLOR = '#ff00ff';
const display = screen.getPrimaryDisplay();
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
w.setBackgroundColor(VIEW_BACKGROUND_COLOR);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true();
});
});
describe('BrowserView.setAutoResize()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setAutoResize({});
view.setAutoResize({ width: true, height: false });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setAutoResize(null as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.setBounds()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBounds({ x: 0, y: 0, width: 1, height: 1 });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBounds(null as any);
}).to.throw(/conversion failure/);
expect(() => {
view.setBounds({} as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.getBounds()', () => {
it('returns correct bounds on a framed window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
it('returns correct bounds on a frameless window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
});
describe('BrowserWindow.setBrowserView()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
w.setBrowserView(view);
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.setBrowserView(view);
w.setBrowserView(view);
w.setBrowserView(view);
});
});
describe('BrowserWindow.getBrowserView()', () => {
it('returns the set view', () => {
view = new BrowserView();
w.setBrowserView(view);
const view2 = w.getBrowserView();
expect(view2!.webContents.id).to.equal(view.webContents.id);
});
it('returns null if none is set', () => {
const view = w.getBrowserView();
expect(view).to.be.null('view');
});
});
describe('BrowserWindow.addBrowserView()', () => {
it('does not throw for valid args', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.addBrowserView(view);
w.addBrowserView(view);
w.addBrowserView(view);
});
it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => {
expect(() => {
const view1 = new BrowserView();
view1.webContents.destroy();
w.addBrowserView(view1);
}).to.not.throw();
});
it('does not crash if the webContents is destroyed after a URL is loaded', () => {
view = new BrowserView();
expect(async () => {
view.setBounds({ x: 0, y: 0, width: 400, height: 300 });
await view.webContents.loadURL('data:text/html,hello there');
view.webContents.destroy();
}).to.not.throw();
});
it('can handle BrowserView reparenting', async () => {
view = new BrowserView();
w.addBrowserView(view);
view.webContents.loadURL('about:blank');
await once(view.webContents, 'did-finish-load');
const w2 = new BrowserWindow({ show: false });
w2.addBrowserView(view);
w.close();
view.webContents.loadURL(`file://${fixtures}/pages/blank.html`);
await once(view.webContents, 'did-finish-load');
// Clean up - the afterEach hook assumes the webContents on w is still alive.
w = new BrowserWindow({ show: false });
w2.close();
w2.destroy();
});
});
describe('BrowserWindow.removeBrowserView()', () => {
it('does not throw if called multiple times with same view', () => {
expect(() => {
view = new BrowserView();
w.addBrowserView(view);
w.removeBrowserView(view);
w.removeBrowserView(view);
}).to.not.throw();
});
});
describe('BrowserWindow.getBrowserViews()', () => {
it('returns same views as was added', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
const views = w.getBrowserViews();
expect(views).to.have.lengthOf(2);
expect(views[0].webContents.id).to.equal(view1.webContents.id);
expect(views[1].webContents.id).to.equal(view2.webContents.id);
});
});
describe('BrowserWindow.setTopBrowserView()', () => {
it('should throw an error when a BrowserView is not attached to the window', () => {
view = new BrowserView();
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
});
it('should throw an error when a BrowserView is attached to some other window', () => {
view = new BrowserView();
const win2 = new BrowserWindow();
w.addBrowserView(view);
view.setBounds({ x: 0, y: 0, width: 100, height: 100 });
win2.addBrowserView(view);
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
win2.close();
win2.destroy();
});
});
describe('BrowserView.webContents.getOwnerBrowserWindow()', () => {
it('points to owning window', () => {
view = new BrowserView();
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
w.setBrowserView(view);
expect(view.webContents.getOwnerBrowserWindow()).to.equal(w);
w.setBrowserView(null);
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
});
});
describe('shutdown behavior', () => {
it('does not crash on exit', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { BrowserView, app } = require('electron');
// eslint-disable-next-line no-new
new BrowserView({});
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('does not crash on exit if added to a browser window', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { app, BrowserView, BrowserWindow } = require('electron');
const bv = new BrowserView();
bv.webContents.loadURL('about:blank');
const bw = new BrowserWindow({ show: false });
bw.addBrowserView(bv);
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('emits the destroyed event when webContents.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.close();
await once(view.webContents, 'destroyed');
});
it('emits the destroyed event when window.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.executeJavaScript('window.close()');
await once(view.webContents, 'destroyed');
});
});
describe('window.open()', () => {
it('works in BrowserView', (done) => {
view = new BrowserView();
w.setBrowserView(view);
view.webContents.setWindowOpenHandler(({ url, frameName }) => {
expect(url).to.equal('http://host/');
expect(frameName).to.equal('host');
done();
return { action: 'deny' };
});
view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
});
});
describe('BrowserView.capturePage(rect)', () => {
it('returns a Promise with a Buffer', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.addBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
const image = await view.webContents.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
xit('resolves after the window is hidden and capturer count is non-zero', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.setBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
const image = await view.webContents.capturePage();
expect(image.isEmpty()).to.equal(false);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,844 |
[Bug]: Preload script not running on child-window "top" frame
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
16.0.5
### What operating system are you using?
Ubuntu
### Operating System Version
20.04
### What arch are you using?
x64
### Last Known Working Electron version
16.0.4
### Expected Behavior
I have an app that uses the preload script on some contexts.
Recently I found out that in some scenarios the preload script is not running.
Im using the setWindowOpenHandler function in order to use the same preload in all future child window that will be created.
Electron fiddle gist is added for refrence.
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The expected behaviour is to have preload script running on this window as well.
### Actual Behavior
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The actual behaviour is that the preload script does not run at all on the top frame.
### Testcase Gist URL
https://gist.github.com/cbb4249641359cce34b87c0203b55d8a
### Additional Information
Tested also 26.0.0-alpha.7 to make sure its not something that was fixed in newer versions
Looking at the release notes this PR seems to be what's causing this bug: https://github.com/electron/electron/pull/32108
|
https://github.com/electron/electron/issues/38844
|
https://github.com/electron/electron/pull/38910
|
ff6d0df2d534efe1aa8d466e1ea75333290cb0dc
|
09669f9d215ceb96d7f02f9085d7906e27c2b301
| 2023-06-19T13:51:28Z |
c++
| 2023-06-26T21:04:54Z |
shell/renderer/electron_render_frame_observer.cc
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/electron_render_frame_observer.h"
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "content/public/renderer/render_frame.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "ipc/ipc_message_macros.h"
#include "net/base/net_module.h"
#include "net/grit/net_resources.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/common/gin_helper/microtasks_scope.h"
#include "shell/common/options_switches.h"
#include "shell/common/world_ids.h"
#include "shell/renderer/renderer_client_base.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/platform/web_isolated_world_info.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_draggable_region.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" // nogncheck
#include "ui/base/resource/resource_bundle.h"
namespace electron {
namespace {
scoped_refptr<base::RefCountedMemory> NetResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
IDR_DIR_HEADER_HTML);
}
return nullptr;
}
} // namespace
ElectronRenderFrameObserver::ElectronRenderFrameObserver(
content::RenderFrame* frame,
RendererClientBase* renderer_client)
: content::RenderFrameObserver(frame),
render_frame_(frame),
renderer_client_(renderer_client) {
// Initialise resource for directory listing.
net::NetModule::SetResourceProvider(NetResourceProvider);
}
void ElectronRenderFrameObserver::DidClearWindowObject() {
// Do a delayed Node.js initialization for child window.
// Check DidInstallConditionalFeatures below for the background.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (has_delayed_node_initialization_ && web_frame->Opener() &&
!web_frame->IsOnInitialEmptyDocument()) {
v8::Isolate* isolate = blink::MainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::Context> context = web_frame->MainWorldScriptContext();
v8::MicrotasksScope microtasks_scope(
isolate, context->GetMicrotaskQueue(),
v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Context::Scope context_scope(context);
// DidClearWindowObject only emits for the main world.
DidInstallConditionalFeatures(context, MAIN_WORLD_ID);
}
renderer_client_->DidClearWindowObject(render_frame_);
}
void ElectronRenderFrameObserver::DidInstallConditionalFeatures(
v8::Handle<v8::Context> context,
int world_id) {
// When a child window is created with window.open, its WebPreferences will
// be copied from its parent, and Chromium will initialize JS context in it
// immediately.
// Normally the WebPreferences is overridden in browser before navigation,
// but this behavior bypasses the browser side navigation and the child
// window will get wrong WebPreferences in the initialization.
// This will end up initializing Node.js in the child window with wrong
// WebPreferences, leads to problem that child window having node integration
// while "nodeIntegration=no" is passed.
// We work around this issue by delaying the child window's initialization of
// Node.js if this is the initial empty document, and only do it when the
// actual page has started to load.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (web_frame->Opener() && web_frame->IsOnInitialEmptyDocument()) {
// FIXME(zcbenz): Chromium does not do any browser side navigation for
// window.open('about:blank'), so there is no way to override WebPreferences
// of it. We should not delay Node.js initialization as there will be no
// further loadings.
// Please check http://crbug.com/1215096 for updates which may help remove
// this hack.
GURL url = web_frame->GetDocument().Url();
if (!url.IsAboutBlank()) {
has_delayed_node_initialization_ = true;
return;
}
}
has_delayed_node_initialization_ = false;
auto* isolate = context->GetIsolate();
v8::MicrotasksScope microtasks_scope(
isolate, context->GetMicrotaskQueue(),
v8::MicrotasksScope::kDoNotRunMicrotasks);
if (ShouldNotifyClient(world_id))
renderer_client_->DidCreateScriptContext(context, render_frame_);
auto prefs = render_frame_->GetBlinkPreferences();
bool use_context_isolation = prefs.context_isolation;
// This logic matches the EXPLAINED logic in electron_renderer_client.cc
// to avoid explaining it twice go check that implementation in
// DidCreateScriptContext();
bool is_main_world = IsMainWorld(world_id);
bool is_main_frame = render_frame_->IsMainFrame();
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
bool should_create_isolated_context =
use_context_isolation && is_main_world &&
(is_main_frame || allow_node_in_sub_frames);
if (should_create_isolated_context) {
CreateIsolatedWorldContext();
if (!renderer_client_->IsWebViewFrame(context, render_frame_))
renderer_client_->SetupMainWorldOverrides(context, render_frame_);
}
}
void ElectronRenderFrameObserver::DraggableRegionsChanged() {
blink::WebVector<blink::WebDraggableRegion> webregions =
render_frame_->GetWebFrame()->GetDocument().DraggableRegions();
std::vector<mojom::DraggableRegionPtr> regions;
for (auto& webregion : webregions) {
auto region = mojom::DraggableRegion::New();
render_frame_->ConvertViewportToWindow(&webregion.bounds);
region->bounds = webregion.bounds;
region->draggable = webregion.draggable;
regions.push_back(std::move(region));
}
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame_->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->UpdateDraggableRegions(std::move(regions));
}
void ElectronRenderFrameObserver::WillReleaseScriptContext(
v8::Local<v8::Context> context,
int world_id) {
if (ShouldNotifyClient(world_id))
renderer_client_->WillReleaseScriptContext(context, render_frame_);
}
void ElectronRenderFrameObserver::OnDestruct() {
delete this;
}
void ElectronRenderFrameObserver::DidMeaningfulLayout(
blink::WebMeaningfulLayout layout_type) {
if (layout_type == blink::WebMeaningfulLayout::kVisuallyNonEmpty) {
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame_->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->OnFirstNonEmptyLayout();
}
}
void ElectronRenderFrameObserver::CreateIsolatedWorldContext() {
auto* frame = render_frame_->GetWebFrame();
blink::WebIsolatedWorldInfo info;
// This maps to the name shown in the context combo box in the Console tab
// of the dev tools.
info.human_readable_name =
blink::WebString::FromUTF8("Electron Isolated Context");
// Setup document's origin policy in isolated world
info.security_origin = frame->GetDocument().GetSecurityOrigin();
blink::SetIsolatedWorldInfo(WorldIDs::ISOLATED_WORLD_ID, info);
// Create initial script context in isolated world
blink::WebScriptSource source("void 0");
frame->ExecuteScriptInIsolatedWorld(
WorldIDs::ISOLATED_WORLD_ID, source,
blink::BackForwardCacheAware::kPossiblyDisallow);
}
bool ElectronRenderFrameObserver::IsMainWorld(int world_id) {
return world_id == WorldIDs::MAIN_WORLD_ID;
}
bool ElectronRenderFrameObserver::IsIsolatedWorld(int world_id) {
return world_id == WorldIDs::ISOLATED_WORLD_ID;
}
bool ElectronRenderFrameObserver::ShouldNotifyClient(int world_id) {
auto prefs = render_frame_->GetBlinkPreferences();
// This is necessary because if an iframe is created and a source is not
// set, the iframe loads about:blank and creates a script context for the
// same. We don't want to create a Node.js environment here because if the src
// is later set, the JS necessary to do that triggers illegal access errors
// when the initial about:blank Node.js environment is cleaned up. See:
// https://source.chromium.org/chromium/chromium/src/+/main:content/renderer/render_frame_impl.h;l=870-892;drc=4b6001440a18740b76a1c63fa2a002cc941db394
GURL url = render_frame_->GetWebFrame()->GetDocument().Url();
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
if (allow_node_in_sub_frames && url.IsAboutBlank() &&
!render_frame_->IsMainFrame())
return false;
if (prefs.context_isolation &&
(render_frame_->IsMainFrame() || allow_node_in_sub_frames))
return IsIsolatedWorld(world_id);
return IsMainWorld(world_id);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,844 |
[Bug]: Preload script not running on child-window "top" frame
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
16.0.5
### What operating system are you using?
Ubuntu
### Operating System Version
20.04
### What arch are you using?
x64
### Last Known Working Electron version
16.0.4
### Expected Behavior
I have an app that uses the preload script on some contexts.
Recently I found out that in some scenarios the preload script is not running.
Im using the setWindowOpenHandler function in order to use the same preload in all future child window that will be created.
Electron fiddle gist is added for refrence.
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The expected behaviour is to have preload script running on this window as well.
### Actual Behavior
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The actual behaviour is that the preload script does not run at all on the top frame.
### Testcase Gist URL
https://gist.github.com/cbb4249641359cce34b87c0203b55d8a
### Additional Information
Tested also 26.0.0-alpha.7 to make sure its not something that was fixed in newer versions
Looking at the release notes this PR seems to be what's causing this bug: https://github.com/electron/electron/pull/32108
|
https://github.com/electron/electron/issues/38844
|
https://github.com/electron/electron/pull/38910
|
ff6d0df2d534efe1aa8d466e1ea75333290cb0dc
|
09669f9d215ceb96d7f02f9085d7906e27c2b301
| 2023-06-19T13:51:28Z |
c++
| 2023-06-26T21:04:54Z |
spec/chromium-spec.ts
|
import { expect } from 'chai';
import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import * as https from 'node:https';
import * as http from 'node:http';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as url from 'node:url';
import * as ChildProcess from 'node:child_process';
import { EventEmitter, once } from 'node:events';
import { promisify } from 'node:util';
import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
import { PipeTransport } from './pipe-transport';
import * as ws from 'ws';
import { setTimeout } from 'node:timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
describe('reporting api', () => {
it('sends a report for an intervention', async () => {
const reporting = new EventEmitter();
// The Reporting API only works on https with valid certs. To dodge having
// to set up a trusted certificate, hack the validator.
session.defaultSession.setCertificateVerifyProc((req, cb) => {
cb(0);
});
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options, (req, res) => {
if (req.url?.endsWith('report')) {
let data = '';
req.on('data', (d) => { data += d.toString('utf-8'); });
req.on('end', () => {
reporting.emit('report', JSON.parse(data));
});
}
const { port } = server.address() as any;
res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`);
res.setHeader('Content-Type', 'text/html');
res.end('<script>window.navigator.vibrate(1)</script>');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`);
const [reports] = await reportGenerated;
expect(reports).to.be.an('array').with.lengthOf(1);
const { type, url, body } = reports[0];
expect(type).to.equal('intervention');
expect(url).to.equal(url);
expect(body.id).to.equal('NavigatorVibrate');
expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/);
} finally {
bw.destroy();
server.close();
}
});
});
describe('window.postMessage', () => {
afterEach(async () => {
await closeAllWindows();
});
it('sets the source and origin correctly', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
const [, message] = await once(ipcMain, 'complete');
expect(message.data).to.equal('testing');
expect(message.origin).to.equal('file://');
expect(message.sourceEqualsOpener).to.equal(true);
expect(message.eventOrigin).to.equal('file://');
});
});
describe('focus handling', () => {
let webviewContents: WebContents;
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
contextIsolation: false
}
});
const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
const [, wvContents] = await webviewReady;
webviewContents = wvContents;
await once(webviewContents, 'did-finish-load');
w.focus();
});
afterEach(() => {
webviewContents = null as unknown as WebContents;
w.destroy();
w = null as unknown as BrowserWindow;
});
const expectFocusChange = async () => {
const [, focusedElementId] = await once(ipcMain, 'focus-changed');
return focusedElementId;
};
describe('a TAB press', () => {
const tabPressEvent: any = {
type: 'keyDown',
keyCode: 'Tab'
};
it('moves focus to the next focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
});
});
describe('a SHIFT + TAB press', () => {
const shiftTabPressEvent: any = {
type: 'keyDown',
modifiers: ['Shift'],
keyCode: 'Tab'
};
it('moves focus to the previous focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
});
});
});
describe('web security', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('engages CORB when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,<script>
const s = document.createElement('script')
s.src = "${serverUrl}"
// The script will load successfully but its body will be emptied out
// by CORB, so we don't expect a syntax error.
s.onload = () => { require('electron').ipcRenderer.send('success') }
document.documentElement.appendChild(s)
</script>`);
await p;
});
it('bypasses CORB when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,
<script>
window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
</script>
<script src="${serverUrl}"></script>`);
await p;
});
it('engages CORS when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('failed');
});
it('bypasses CORS when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('passed');
});
describe('accessing file://', () => {
async function loadFile (w: BrowserWindow) {
const thisFile = url.format({
pathname: __filename.replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
await w.loadURL(`data:text/html,<script>
function loadFile() {
return new Promise((resolve) => {
fetch('${thisFile}').then(
() => resolve('loaded'),
() => resolve('failed')
)
});
}
</script>`);
return await w.webContents.executeJavaScript('loadFile()');
}
it('is forbidden when web security is enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
const result = await loadFile(w);
expect(result).to.equal('failed');
});
it('is allowed when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
const result = await loadFile(w);
expect(result).to.equal('loaded');
});
});
describe('wasm-eval csp', () => {
async function loadWasm (csp: string) {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
enableBlinkFeatures: 'WebAssemblyCSP'
}
});
await w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
</head>
<script>
function loadWasm() {
const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
return new Promise((resolve) => {
WebAssembly.instantiate(wasmBin).then(() => {
resolve('loaded')
}).catch((error) => {
resolve(error.message)
})
});
}
</script>`);
return await w.webContents.executeJavaScript('loadWasm()');
}
it('wasm codegen is disallowed by default', async () => {
const r = await loadWasm('');
expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"');
});
it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
const r = await loadWasm("'wasm-unsafe-eval'");
expect(r).to.equal('loaded');
});
});
describe('csp', () => {
for (const sandbox of [true, false]) {
describe(`when sandbox: ${sandbox}`, () => {
for (const contextIsolation of [true, false]) {
describe(`when contextIsolation: ${contextIsolation}`, () => {
it('prevents eval from running in an inline script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
</head>
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.match(/Refused to evaluate a string/);
});
it('does not prevent eval from running in an inline script when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.equal('true');
});
it('prevents eval from running in executeJavaScript', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>');
await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected();
});
it('does not prevent eval from running in executeJavaScript when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,');
expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true();
});
});
}
});
}
});
it('does not crash when multiple WebContent are created with web security disabled', () => {
const options = { show: false, webPreferences: { webSecurity: false } };
const w1 = new BrowserWindow(options);
w1.loadURL(serverUrl);
const w2 = new BrowserWindow(options);
w2.loadURL(serverUrl);
});
});
describe('command line switches', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
describe('--lang switch', () => {
const currentLocale = app.getLocale();
const currentSystemLocale = app.getSystemLocale();
const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages());
const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
const appPath = path.join(fixturesPath, 'api', 'locale-check');
const args = [appPath, `--set-lang=${locale}`];
if (printEnv) {
args.push('--print-env');
}
appProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
let stderr = '';
appProcess.stderr.on('data', (data) => { stderr += data; });
const [code, signal] = await once(appProcess, 'exit');
if (code !== 0) {
throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
}
output = output.replace(/(\r\n|\n|\r)/gm, '');
expect(output).to.equal(result);
};
it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`));
const lcAll = String(process.env.LC_ALL);
ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
// The LC_ALL env should not be set to DOM locale string.
expect(lcAll).to.not.equal(app.getLocale());
});
ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
});
describe('--remote-debugging-pipe switch', () => {
it('should expose CDP via pipe', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(message.result.product).to.contain('Chrome');
expect(message.result.userAgent).to.contain('Electron');
});
it('should override --remote-debugging-port switch', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
let stderr = '';
appProcess.stderr.on('data', (data: string) => { stderr += data; });
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(stderr).to.not.include('DevTools listening on');
});
it('should shut down Electron upon Browser.close CDP command', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
await once(appProcess, 'exit');
});
});
describe('--remote-debugging-port switch', () => {
it('should display the discovery page', (done) => {
const electronPath = process.execPath;
let output = '';
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
appProcess.stdout.on('data', (data) => {
console.log(data);
});
appProcess.stderr.on('data', (data) => {
console.log(data);
output += data;
const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
if (m) {
appProcess!.stderr.removeAllListeners('data');
const port = m[1];
http.get(`http://127.0.0.1:${port}`, (res) => {
try {
expect(res.statusCode).to.eql(200);
expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
done();
} catch (e) {
done(e);
} finally {
res.destroy();
}
});
}
});
});
});
});
describe('chromium features', () => {
afterEach(closeAllWindows);
describe('accessing key names also used as Node.js module names', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
});
});
describe('first party sets', () => {
const fps = [
'https://fps-member1.glitch.me',
'https://fps-member2.glitch.me',
'https://fps-member3.glitch.me'
];
it('loads first party sets', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base');
const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
it('loads sets from the command line', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line');
const args = [appPath, `--use-first-party-set=${fps}`];
const fpsProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
});
describe('loading jquery', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
});
});
describe('navigator.languages', () => {
it('should return the system locale only', async () => {
const appLocale = app.getLocale();
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const languages = await w.webContents.executeJavaScript('navigator.languages');
expect(languages.length).to.be.greaterThan(0);
expect(languages).to.contain(appLocale);
});
});
describe('navigator.serviceWorker', () => {
it('should register for file scheme', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for intercepted file scheme', (done) => {
const customSession = session.fromPartition('intercept-file');
customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
const content = fs.readFileSync(path.normalize(file));
const ext = path.extname(file);
let type = 'text/html';
if (ext === '.js') type = 'application/javascript';
callback({ data: content, mimeType: type } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol('file');
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for custom scheme', (done) => {
const customSession = session.fromPartition('custom-scheme');
customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
callback({ path: path.normalize(file) } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
});
it('should not allow nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
partition: 'sw-file-scheme-worker-spec',
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`);
const data = await w.webContents.executeJavaScript(`
navigator.serviceWorker.register('worker-no-node.js', {
scope: './'
}).then(() => navigator.serviceWorker.ready)
new Promise((resolve) => {
navigator.serviceWorker.onmessage = event => resolve(event.data);
});
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
describe('navigator.geolocation', () => {
ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'geolocation-spec',
contextIsolation: false
}
});
const message = once(w.webContents, 'ipc-message');
w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'geolocation') {
callback(false);
} else {
callback(true);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
const [, channel] = await message;
expect(channel).to.equal('success', 'unexpected response from geolocation api');
});
ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'geolocation-spec'
}
});
w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => {
callback(true);
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
x => resolve({coords: x.coords, timestamp: x.timestamp}),
err => reject(new Error(err.message))))`);
expect(position).to.have.property('coords');
expect(position).to.have.property('timestamp');
});
});
describe('web workers', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
appProcess = ChildProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
it('Worker can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
worker.postMessage(message);
eventPromise.then(t => t.data)
`);
expect(data).to.equal('ping');
});
it('Worker has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker_node.js');
new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('Worker has node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/worker.html`);
const [, data] = await once(ipcMain, 'worker-result');
expect(data).to.equal('object function object function');
});
describe('SharedWorker', () => {
it('can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
worker.port.postMessage(message);
eventPromise
`);
expect(data).to.equal('ping');
});
it('has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('does not have node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
});
describe('form submit', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
res.setHeader('Content-Type', 'application/json');
req.on('end', () => {
res.end(`body:${body}`);
});
});
serverUrl = (await listen(server)).url;
});
after(async () => {
server.close();
await closeAllWindows();
});
[true, false].forEach((isSandboxEnabled) =>
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const loadPromise = once(w.webContents, 'did-finish-load');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.submit();
`);
await loadPromise;
const res = await w.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
it('posts data to a new window with target=_blank', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.target = '_blank';
form.submit();
`);
const [, newWin] = await windowCreatedPromise;
const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
})
);
});
describe('window.open', () => {
for (const show of [true, false]) {
it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
const w = new BrowserWindow({ show });
// toggle visibility
if (show) {
w.hide();
} else {
w.show();
}
defer(() => { w.close(); });
const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
const [, newWindow] = await promise;
expect(newWindow.isVisible()).to.equal(true);
});
}
// FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false')
const e = await message
b.close();
return {
eventData: e.data
}
})()`);
expect(eventData.isProcessGlobalUndefined).to.be.true();
});
it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
// NB. webSecurity is disabled because native window.open() is not
// allowed to load devtools:// URLs.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
it('can disable node integration when it is enabled on the parent window', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = require('node:url').format({
pathname: `${fixturesPath}/pages/window-no-javascript.html`,
protocol: 'file',
slashes: true
});
w.webContents.executeJavaScript(`
{ b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-finish-load');
// Click link on page
contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
const preferences = window.webContents.getLastWebPreferences();
expect(preferences!.javascript).to.be.false();
});
it('defines a window.location getter', async () => {
let targetURL: string;
if (process.platform === 'win32') {
targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
} else {
targetURL = `file://${fixturesPath}/pages/base-page.html`;
}
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(window.webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
});
it('defines a window.location setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('defines a window.location.href setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('open a blank page when no URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('open a blank page when an empty URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('does not throw an exception when the frameName is a built-in object property', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
const frameName = await new Promise((resolve) => {
w.webContents.setWindowOpenHandler(details => {
setImmediate(() => resolve(details.frameName));
return { action: 'allow' };
});
});
expect(frameName).to.equal('__proto__');
});
// FIXME(nornagon): I'm not sure this ... ever was correct?
xit('inherit options of parent window', async () => {
const w = new BrowserWindow({ show: false, width: 123, height: 456 });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const url = `file://${fixturesPath}/pages/window-open-size.html`;
const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(url)}, '', 'show=false')
const e = await message
b.close();
const width = outerWidth;
const height = outerHeight;
return {
width,
height,
eventData: e.data
}
})()`);
expect(eventData).to.equal(`size: ${width} ${height}`);
expect(eventData).to.equal('size: 123 456');
});
it('does not override child options', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`;
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData).to.equal('size: 350 450');
});
it('disables the <webview> tag when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData.isWebViewGlobalUndefined).to.be.true();
});
it('throws an exception when the arguments cannot be converted to strings', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', { toString: null })')
).to.eventually.be.rejected();
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })')
).to.eventually.be.rejected();
});
it('does not throw an exception when the features include webPreferences', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null')
).to.eventually.be.fulfilled();
});
});
describe('window.opener', () => {
it('is null for main window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
const [, channel, opener] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('opener');
expect(opener).to.equal(null);
});
it('is not null for window opened by window.open', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener.html`;
const eventData = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data);
`);
expect(eventData).to.equal('object');
});
});
describe('window.opener.postMessage', () => {
it('sets source and origin correctly', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`;
const { sourceIsChild, origin } = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({
sourceIsChild: e.source === b,
origin: e.origin
}));
`);
expect(sourceIsChild).to.be.true();
expect(origin).to.equal('file://');
});
it('supports windows opened from a <webview>', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('about:blank');
const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html'));
childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`);
const message = await w.webContents.executeJavaScript(`
const webview = new WebView();
webview.allowpopups = true;
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = ${JSON.stringify(childWindowUrl)}
const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true}));
document.body.appendChild(webview);
consoleMessage.then(e => e.message)
`);
expect(message).to.equal('message');
});
describe('targetOrigin argument', () => {
let serverURL: string;
let server: any;
beforeEach(async () => {
server = http.createServer((req, res) => {
res.writeHead(200);
const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html');
res.end(fs.readFileSync(filePath, 'utf8'));
});
serverURL = (await listen(server)).url;
});
afterEach(() => {
server.close();
});
it('delivers messages that match the origin', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const data = await w.webContents.executeJavaScript(`
window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data)
`);
expect(data).to.equal('deliver');
});
});
});
describe('navigator.mediaDevices', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can return labels of enumerated devices', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.true();
});
it('does not return labels of enumerated devices when permission denied', async () => {
session.defaultSession.setPermissionCheckHandler(() => false);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.false();
});
it('returns the same device ids across reloads', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
});
it('can return new device id when cookie storage is cleared', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
await ses.clearStorageData({ storages: ['cookies'] });
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
});
it('provides a securityOrigin to the request handler', async () => {
session.defaultSession.setPermissionRequestHandler(
(wc, permission, callback, details) => {
if (details.securityOrigin !== undefined) {
callback(true);
} else {
callback(false);
}
}
);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
video: {
mandatory: {
chromeMediaSource: "desktop",
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream) => stream.getVideoTracks())`);
expect(labels.some((l: any) => l)).to.be.true();
});
it('fails with "not supported" for getDisplayMedia', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true);
expect(ok).to.be.false();
expect(err).to.equal('Not supported');
});
});
describe('window.opener access', () => {
const scheme = 'app';
const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
const httpUrl1 = `${scheme}://origin1`;
const httpUrl2 = `${scheme}://origin2`;
const fileBlank = `file://${fixturesPath}/pages/blank.html`;
const httpBlank = `${scheme}://origin1/blank`;
const table = [
{ parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
{ parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
// {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
// {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
// NB. this is different from Chrome's behavior, which isolates file: urls from each other
{ parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
{ parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
];
const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
if (request.url.includes('blank')) {
callback(`${fixturesPath}/pages/blank.html`);
} else {
callback(`${fixturesPath}/pages/window-opener-location.html`);
}
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
describe('when opened from main window', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
for (const sandboxPopup of [false, true]) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
sandbox: sandboxPopup
}
}
}));
await w.loadURL(parent);
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
window.addEventListener('message', function f(e) {
resolve(e.data)
})
window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
}
});
describe('when opened from <webview>', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
// This test involves three contexts:
// 1. The root BrowserWindow in which the test is run,
// 2. A <webview> belonging to the root window,
// 3. A window opened by calling window.open() from within the <webview>.
// We are testing whether context (3) can access context (2) under various conditions.
// This is context (1), the base window for the test.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
const parentCode = `new Promise((resolve) => {
// This is context (3), a child window of the WebView.
const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
window.addEventListener("message", e => {
resolve(e.data)
})
})`;
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
// This is context (2), a WebView which will call window.open()
const webview = new WebView()
webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
webview.setAttribute('webpreferences', 'contextIsolation=no')
webview.setAttribute('allowpopups', 'on')
webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
webview.addEventListener('dom-ready', async () => {
webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
})
document.body.appendChild(webview)
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
});
});
describe('storage', () => {
describe('custom non standard schemes', () => {
const protocolName = 'storage';
let contents: WebContents;
before(() => {
protocol.registerFileProtocol(protocolName, (request, callback) => {
const parsedUrl = url.parse(request.url);
let filename;
switch (parsedUrl.pathname) {
case '/localStorage' : filename = 'local_storage.html'; break;
case '/sessionStorage' : filename = 'session_storage.html'; break;
case '/WebSQL' : filename = 'web_sql.html'; break;
case '/indexedDB' : filename = 'indexed_db.html'; break;
case '/cookie' : filename = 'cookie.html'; break;
default : filename = '';
}
callback({ path: `${fixturesPath}/pages/storage/${filename}` });
});
});
after(() => {
protocol.unregisterProtocol(protocolName);
});
beforeEach(() => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
});
afterEach(() => {
contents.destroy();
contents = null as any;
});
it('cannot access localStorage', async () => {
const response = once(ipcMain, 'local-storage-response');
contents.loadURL(protocolName + '://host/localStorage');
const [, error] = await response;
expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access sessionStorage', async () => {
const response = once(ipcMain, 'session-storage-response');
contents.loadURL(`${protocolName}://host/sessionStorage`);
const [, error] = await response;
expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access WebSQL database', async () => {
const response = once(ipcMain, 'web-sql-response');
contents.loadURL(`${protocolName}://host/WebSQL`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
});
it('cannot access indexedDB', async () => {
const response = once(ipcMain, 'indexed-db-response');
contents.loadURL(`${protocolName}://host/indexedDB`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
});
it('cannot access cookie', async () => {
const response = once(ipcMain, 'cookie-response');
contents.loadURL(`${protocolName}://host/cookie`);
const [, error] = await response;
expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
});
});
describe('can be accessed', () => {
let server: http.Server;
let serverUrl: string;
let serverCrossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
server = null as any;
});
afterEach(closeAllWindows);
const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
it(testTitle, async () => {
const w = new BrowserWindow({
show: false,
...extraPreferences
});
let redirected = false;
w.webContents.on('render-process-gone', () => {
expect.fail('renderer crashed / was killed');
});
w.webContents.on('did-redirect-navigation', (event, url) => {
expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
redirected = true;
});
await w.loadURL(`${serverUrl}/redirect-cross-site`);
expect(redirected).to.be.true('didnt redirect');
});
};
testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
});
describe('enableWebSQL webpreference', () => {
const origin = `${standardScheme}://fake-host`;
const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
const sqlPartition = 'web-sql-preference-test';
const sqlSession = session.fromPartition(sqlPartition);
const securityError = 'An attempt was made to break through the security policy of the user agent.';
let contents: WebContents, w: BrowserWindow;
before(() => {
sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
callback({ path: filePath });
});
});
after(() => {
sqlSession.protocol.unregisterProtocol(standardScheme);
});
afterEach(async () => {
if (contents) {
contents.destroy();
contents = null as any;
}
await closeAllWindows();
(w as any) = null;
});
it('default value allows websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
});
it('when set to false can disallow websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
});
it('when set to false does not disable indexedDB', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
const dbName = 'random';
const result = await contents.executeJavaScript(`
new Promise((resolve, reject) => {
try {
let req = window.indexedDB.open('${dbName}');
req.onsuccess = (event) => {
let db = req.result;
resolve(db.name);
}
req.onerror = (event) => { resolve(event.target.code); }
} catch (e) {
resolve(e.message);
}
});
`);
expect(result).to.equal(dbName);
});
it('child webContents can override when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents cannot override when the embedder has disallowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableWebSQL: false,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL('data:text/html,<html></html>');
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents can use websql when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.be.null();
});
});
describe('DOM storage quota increase', () => {
['localStorage', 'sessionStorage'].forEach((storageName) => {
it(`allows saving at least 40MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// Although JavaScript strings use UTF-16, the underlying
// storage provider may encode strings differently, muddling the
// translation between character and byte counts. However,
// a string of 40 * 2^20 characters will require at least 40MiB
// and presumably no more than 80MiB, a size guaranteed to
// to exceed the original 10MiB quota yet stay within the
// new 100MiB quota.
// Note that both the key name and value affect the total size.
const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
const length = 40 * Math.pow(2, 20) - testKeyName.length;
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
// Wait at least one turn of the event loop to help avoid false positives
// Although not entirely necessary, the previous version of this test case
// failed to detect a real problem (perhaps related to DOM storage data caching)
// wherein calling `getItem` immediately after `setItem` would appear to work
// but then later (e.g. next tick) it would not.
await setTimeout(1);
try {
const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`);
expect(storedLength).to.equal(length);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
});
it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
await expect((async () => {
const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
const length = 128 * Math.pow(2, 20) - testKeyName.length;
try {
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
})()).to.eventually.be.rejected();
});
});
});
describe('persistent storage', () => {
it('can be requested', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => {
navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
})`);
expect(grantedBytes).to.equal(1048576);
});
});
});
ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
const pdfSource = url.format({
pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
it('successfully loads a PDF file', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
await once(w.webContents, 'did-finish-load');
});
it('opens when loading a pdf resource as top level navigation', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
it('opens when loading a pdf resource in a iframe', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
});
describe('window.history', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// History should have current page by now.
expect((w.webContents as any).length()).to.equal(1);
const waitCommit = once(w.webContents, 'navigation-entry-committed');
w.webContents.executeJavaScript('window.history.pushState({}, "")');
await waitCommit;
// Initial page + pushed state.
expect((w.webContents as any).length()).to.equal(2);
});
});
describe('window.history.back', () => {
it('should not allow sandboxed iframe to modify main frame state', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-frame-navigate'),
once(w.webContents, 'did-navigate')
]);
w.webContents.executeJavaScript('window.history.pushState(1, "")');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-navigate-in-page')
]);
(w.webContents as any).once('navigation-entry-committed', () => {
expect.fail('Unexpected navigation-entry-committed');
});
w.webContents.once('did-navigate-in-page', () => {
expect.fail('Unexpected did-navigate-in-page');
});
await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()');
expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1);
expect((w.webContents as any).getActiveIndex()).to.equal(1);
});
});
});
describe('chrome://media-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://media-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('chrome://webrtc-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://webrtc-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('document.hasFocus', () => {
it('has correct value when multiple windows are opened', async () => {
const w1 = new BrowserWindow({ show: true });
const w2 = new BrowserWindow({ show: true });
const w3 = new BrowserWindow({ show: false });
await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id);
let focus = false;
focus = await w1.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
focus = await w2.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.true();
focus = await w3.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
});
});
// https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
describe('navigator.connection', () => {
it('returns the correct value', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt');
expect(rtt).to.be.a('number');
const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink');
expect(downlink).to.be.a('number');
const effectiveTypes = ['slow-2g', '2g', '3g', '4g'];
const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType');
expect(effectiveTypes).to.include(effectiveType);
});
});
describe('navigator.userAgentData', () => {
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
describe('is not empty', () => {
it('by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a session-wide UA override', async () => {
const ses = session.fromPartition(`${Math.random()}`);
ses.setUserAgent('foobar');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setUserAgent('foo');
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override at load time', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl, {
userAgent: 'foo'
});
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
});
describe('brand list', () => {
it('contains chromium', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
expect(brands.map((b: any) => b.brand)).to.include('Chromium');
});
});
});
describe('Badging API', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
await w.webContents.executeJavaScript('navigator.setAppBadge()');
await w.webContents.executeJavaScript('navigator.clearAppBadge()');
});
});
describe('navigator.webkitGetUserMedia', () => {
it('calls its callbacks', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript(`new Promise((resolve) => {
navigator.webkitGetUserMedia({
audio: true,
video: false
}, () => resolve(),
() => resolve());
})`);
});
});
describe('navigator.language', () => {
it('should not be empty', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
});
});
describe('heap snapshot', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
});
});
// This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761
ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => {
it('can be gotten as context in canvas', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
document.createElement('canvas').getContext('webgl') != null;
`);
expect(canWebglContextBeCreated).to.be.true();
});
});
describe('iframe', () => {
it('does not have node integration', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const result = await w.webContents.executeJavaScript(`
const iframe = document.createElement('iframe')
iframe.src = './set-global.html';
document.body.appendChild(iframe);
new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
`);
expect(result).to.equal('undefined undefined undefined');
});
});
describe('websockets', () => {
it('has user agent', async () => {
const server = http.createServer();
const { port } = await listen(server);
const wss = new ws.Server({ server: server });
const finished = new Promise<string | undefined>((resolve, reject) => {
wss.on('error', reject);
wss.on('connection', (ws, upgradeReq) => {
resolve(upgradeReq.headers['user-agent']);
});
});
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
new WebSocket('ws://127.0.0.1:${port}');
`);
expect(await finished).to.include('Electron');
});
});
describe('fetch', () => {
it('does not crash', async () => {
const server = http.createServer((req, res) => {
res.end('test');
});
defer(() => server.close());
const { port } = await listen(server);
const w = new BrowserWindow({ show: false });
w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const x = await w.webContents.executeJavaScript(`
fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
.then((reader) => {
return reader.read().then((r) => {
reader.cancel();
return r.value;
});
})
`);
expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
});
});
describe('Promise', () => {
before(() => {
ipcMain.handle('ping', (e, arg) => arg);
});
after(() => {
ipcMain.removeHandler('ping');
});
itremote('resolves correctly in Node.js calls', async () => {
await new Promise<void>((resolve, reject) => {
class XElement extends HTMLElement {}
customElements.define('x-element', XElement);
setImmediate(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('x-element');
called = true;
});
});
});
itremote('resolves correctly in Electron calls', async () => {
await new Promise<void>((resolve, reject) => {
class YElement extends HTMLElement {}
customElements.define('y-element', YElement);
require('electron').ipcRenderer.invoke('ping').then(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('y-element');
called = true;
});
});
});
});
describe('synchronous prompts', () => {
describe('window.alert(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
window.alert({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
describe('window.confirm(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
(window.confirm as any)({ toString: null }, 'title');
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('window.history', () => {
describe('window.history.go(offset)', () => {
itremote('throws an exception when the argument cannot be converted to a string', () => {
expect(() => {
(window.history.go as any)({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('console functions', () => {
itremote('should exist', () => {
expect(console.log, 'log').to.be.a('function');
expect(console.error, 'error').to.be.a('function');
expect(console.warn, 'warn').to.be.a('function');
expect(console.info, 'info').to.be.a('function');
expect(console.debug, 'debug').to.be.a('function');
expect(console.trace, 'trace').to.be.a('function');
expect(console.time, 'time').to.be.a('function');
expect(console.timeEnd, 'timeEnd').to.be.a('function');
});
});
// FIXME(nornagon): this is broken on CI, it triggers:
// [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
// trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
// (null text in SpeechSynthesisUtterance struct).
describe('SpeechSynthesis', () => {
itremote('should emit lifecycle events', async () => {
const sentence = `long sentence which will take at least a few seconds to
utter so that it's possible to pause and resume before the end`;
const utter = new SpeechSynthesisUtterance(sentence);
// Create a dummy utterance so that speech synthesis state
// is initialized for later calls.
speechSynthesis.speak(new SpeechSynthesisUtterance());
speechSynthesis.cancel();
speechSynthesis.speak(utter);
// paused state after speak()
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onstart = resolve; });
// paused state after start event
expect(speechSynthesis.paused).to.be.false();
speechSynthesis.pause();
// paused state changes async, right before the pause event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onpause = resolve; });
expect(speechSynthesis.paused).to.be.true();
speechSynthesis.resume();
await new Promise((resolve) => { utter.onresume = resolve; });
// paused state after resume event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onend = resolve; });
});
});
});
describe('font fallback', () => {
async function getRenderedFonts (html: string) {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL(`data:text/html,${html}`);
w.webContents.debugger.attach();
const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
await sendCommand('CSS.enable');
const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
return fonts;
} finally {
w.close();
}
}
it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
const html = '<body style="font-family: sans-serif">test</body>';
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') {
expect(fonts[0].familyName).to.equal('Arial');
} else if (process.platform === 'darwin') {
expect(fonts[0].familyName).to.equal('Helvetica');
} else if (process.platform === 'linux') {
expect(fonts[0].familyName).to.equal('DejaVu Sans');
} // I think this depends on the distro? We don't specify a default.
});
ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
const html = `
<html lang="ja-JP">
<head>
<meta charset="utf-8" />
</head>
<body style="font-family: sans-serif">test 智史</body>
</html>
`;
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); }
});
});
describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
const fullscreenChildHtml = promisify(fs.readFile)(
path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
);
let w: BrowserWindow;
let server: http.Server;
let crossSiteUrl: string;
beforeEach(async () => {
server = http.createServer(async (_req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(await fullscreenChildHtml);
res.end();
});
const serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
w = new BrowserWindow({
show: true,
fullscreen: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeAllWindows();
(w as any) = null;
server.close();
});
ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await setTimeout(500);
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await once(w.webContents, 'leave-html-full-screen');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
w.setFullScreen(false);
await once(w, 'leave-full-screen');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
if (process.platform === 'darwin') await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.true();
await w.webContents.executeJavaScript('document.exitFullscreen()');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
});
describe('navigator.serial', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const getPorts: any = () => {
return w.webContents.executeJavaScript(`
navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.';
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.removeAllListeners('select-serial-port');
});
it('does not return a port if select-serial-port event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not return a port when permission denied', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback(portList[0].portId);
});
session.defaultSession.setPermissionCheckHandler(() => false);
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not crash when select-serial-port is called with an invalid port', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback('i-do-not-exist');
});
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('returns a port when select-serial-port event is defined', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
const port = await getPorts();
if (havePorts) {
expect(port).to.equal('[object SerialPort]');
} else {
expect(port).to.equal(notFoundError);
}
});
it('navigator.serial.getPorts() returns values', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts).to.not.be.empty();
}
});
it('supports port.forget()', async () => {
let forgottenPortFromEvent = {};
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
w.webContents.session.on('serial-port-revoked', (event, details) => {
forgottenPortFromEvent = details.port;
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
if (grantedPorts.length > 0) {
const forgottenPort = await w.webContents.executeJavaScript(`
navigator.serial.getPorts().then(async(ports) => {
const portInfo = await ports[0].getInfo();
await ports[0].forget();
if (portInfo.usbVendorId && portInfo.usbProductId) {
return {
vendorId: '' + portInfo.usbVendorId,
productId: '' + portInfo.usbProductId
}
} else {
return {};
}
})
`);
const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length);
if (forgottenPort.vendorId && forgottenPort.productId) {
expect(forgottenPortFromEvent).to.include(forgottenPort);
}
}
}
});
});
describe('window.getScreenDetails', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
const getScreenDetails: any = () => {
return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true);
};
it('returns screens when a PermissionRequestHandler is not defined', async () => {
const screens = await getScreenDetails();
expect(screens).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(false);
} else {
callback(true);
}
});
const screens = await getScreenDetails();
expect(screens).to.equal('Permission denied.');
});
it('returns screens when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(true);
} else {
callback(false);
}
});
const screens = await getScreenDetails();
expect(screens).to.not.equal('Permission denied.');
});
});
describe('navigator.clipboard.read', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const readClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.equal('Read permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
});
describe('navigator.clipboard.write', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const writeClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.writeText('Hello World!').catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.equal('Write permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
});
ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
let w: BrowserWindow;
const expectedBadgeCount = 42;
const fireAppBadgeAction: any = (action: string, value: any) => {
return w.webContents.executeJavaScript(`
navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
};
// For some reason on macOS changing the badge count doesn't happen right away, so wait
// until it changes.
async function waitForBadgeCount (value: number) {
let badgeCount = app.getBadgeCount();
while (badgeCount !== value) {
await setTimeout(10);
badgeCount = app.getBadgeCount();
}
return badgeCount;
}
describe('in the renderer', () => {
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can set a numerical value', async () => {
const result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
});
it('setAppBadge can set an empty(dot) value', async () => {
const result = await fireAppBadgeAction('set');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
it('clearAppBadge can clear a value', async () => {
let result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
result = await fireAppBadgeAction('clear');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
});
describe('in a service worker', () => {
beforeEach(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
});
afterEach(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
});
it('clearAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'setAppBadge') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS clearing app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
});
});
});
describe('navigator.bluetooth', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
enableBlinkFeatures: 'WebBluetooth'
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
it('can request bluetooth devices', async () => {
const bluetooth = await w.webContents.executeJavaScript(`
navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
});
});
describe('navigator.hid', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-hid-device');
});
it('does not return a device if select-hid-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal('');
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal('');
});
it('returns a device when select-hid-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
} else {
expect(device).to.equal('');
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal('');
}
});
it('excludes a device when a exclusionFilter is specified', async () => {
const exclusionFilters = <any>[];
let haveDevices = false;
let checkForExcludedDevice = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
if (checkForExcludedDevice) {
const compareDevice = {
vendorId: device.vendorId,
productId: device.productId
};
expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
} else {
haveDevices = true;
exclusionFilters.push({
vendorId: device.vendorId,
productId: device.productId
});
return true;
}
}
});
}
callback();
});
await requestDevices();
if (haveDevices) {
// We have devices to exclude, so check if exclusionFilters work
checkForExcludedDevice = true;
await w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
`, true);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('hid-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice = await w.webContents.executeJavaScript(`
navigator.hid.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
name: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
describe('navigator.usb', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-usb-device');
});
it('does not return a device if select-usb-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal(notFoundError);
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal(notFoundError);
});
it('returns a device when select-usb-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
} else {
expect(device).to.equal(notFoundError);
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal(notFoundError);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('usb-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(`
navigator.usb.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
productName: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,844 |
[Bug]: Preload script not running on child-window "top" frame
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
16.0.5
### What operating system are you using?
Ubuntu
### Operating System Version
20.04
### What arch are you using?
x64
### Last Known Working Electron version
16.0.4
### Expected Behavior
I have an app that uses the preload script on some contexts.
Recently I found out that in some scenarios the preload script is not running.
Im using the setWindowOpenHandler function in order to use the same preload in all future child window that will be created.
Electron fiddle gist is added for refrence.
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The expected behaviour is to have preload script running on this window as well.
### Actual Behavior
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The actual behaviour is that the preload script does not run at all on the top frame.
### Testcase Gist URL
https://gist.github.com/cbb4249641359cce34b87c0203b55d8a
### Additional Information
Tested also 26.0.0-alpha.7 to make sure its not something that was fixed in newer versions
Looking at the release notes this PR seems to be what's causing this bug: https://github.com/electron/electron/pull/32108
|
https://github.com/electron/electron/issues/38844
|
https://github.com/electron/electron/pull/38910
|
ff6d0df2d534efe1aa8d466e1ea75333290cb0dc
|
09669f9d215ceb96d7f02f9085d7906e27c2b301
| 2023-06-19T13:51:28Z |
c++
| 2023-06-26T21:04:54Z |
shell/renderer/electron_render_frame_observer.cc
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/renderer/electron_render_frame_observer.h"
#include <utility>
#include <vector>
#include "base/command_line.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "content/public/renderer/render_frame.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "ipc/ipc_message_macros.h"
#include "net/base/net_module.h"
#include "net/grit/net_resources.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/common/gin_helper/microtasks_scope.h"
#include "shell/common/options_switches.h"
#include "shell/common/world_ids.h"
#include "shell/renderer/renderer_client_base.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/platform/web_isolated_world_info.h"
#include "third_party/blink/public/web/blink.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_draggable_region.h"
#include "third_party/blink/public/web/web_element.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" // nogncheck
#include "ui/base/resource/resource_bundle.h"
namespace electron {
namespace {
scoped_refptr<base::RefCountedMemory> NetResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes(
IDR_DIR_HEADER_HTML);
}
return nullptr;
}
} // namespace
ElectronRenderFrameObserver::ElectronRenderFrameObserver(
content::RenderFrame* frame,
RendererClientBase* renderer_client)
: content::RenderFrameObserver(frame),
render_frame_(frame),
renderer_client_(renderer_client) {
// Initialise resource for directory listing.
net::NetModule::SetResourceProvider(NetResourceProvider);
}
void ElectronRenderFrameObserver::DidClearWindowObject() {
// Do a delayed Node.js initialization for child window.
// Check DidInstallConditionalFeatures below for the background.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (has_delayed_node_initialization_ && web_frame->Opener() &&
!web_frame->IsOnInitialEmptyDocument()) {
v8::Isolate* isolate = blink::MainThreadIsolate();
v8::HandleScope handle_scope(isolate);
v8::Handle<v8::Context> context = web_frame->MainWorldScriptContext();
v8::MicrotasksScope microtasks_scope(
isolate, context->GetMicrotaskQueue(),
v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Context::Scope context_scope(context);
// DidClearWindowObject only emits for the main world.
DidInstallConditionalFeatures(context, MAIN_WORLD_ID);
}
renderer_client_->DidClearWindowObject(render_frame_);
}
void ElectronRenderFrameObserver::DidInstallConditionalFeatures(
v8::Handle<v8::Context> context,
int world_id) {
// When a child window is created with window.open, its WebPreferences will
// be copied from its parent, and Chromium will initialize JS context in it
// immediately.
// Normally the WebPreferences is overridden in browser before navigation,
// but this behavior bypasses the browser side navigation and the child
// window will get wrong WebPreferences in the initialization.
// This will end up initializing Node.js in the child window with wrong
// WebPreferences, leads to problem that child window having node integration
// while "nodeIntegration=no" is passed.
// We work around this issue by delaying the child window's initialization of
// Node.js if this is the initial empty document, and only do it when the
// actual page has started to load.
auto* web_frame =
static_cast<blink::WebLocalFrameImpl*>(render_frame_->GetWebFrame());
if (web_frame->Opener() && web_frame->IsOnInitialEmptyDocument()) {
// FIXME(zcbenz): Chromium does not do any browser side navigation for
// window.open('about:blank'), so there is no way to override WebPreferences
// of it. We should not delay Node.js initialization as there will be no
// further loadings.
// Please check http://crbug.com/1215096 for updates which may help remove
// this hack.
GURL url = web_frame->GetDocument().Url();
if (!url.IsAboutBlank()) {
has_delayed_node_initialization_ = true;
return;
}
}
has_delayed_node_initialization_ = false;
auto* isolate = context->GetIsolate();
v8::MicrotasksScope microtasks_scope(
isolate, context->GetMicrotaskQueue(),
v8::MicrotasksScope::kDoNotRunMicrotasks);
if (ShouldNotifyClient(world_id))
renderer_client_->DidCreateScriptContext(context, render_frame_);
auto prefs = render_frame_->GetBlinkPreferences();
bool use_context_isolation = prefs.context_isolation;
// This logic matches the EXPLAINED logic in electron_renderer_client.cc
// to avoid explaining it twice go check that implementation in
// DidCreateScriptContext();
bool is_main_world = IsMainWorld(world_id);
bool is_main_frame = render_frame_->IsMainFrame();
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
bool should_create_isolated_context =
use_context_isolation && is_main_world &&
(is_main_frame || allow_node_in_sub_frames);
if (should_create_isolated_context) {
CreateIsolatedWorldContext();
if (!renderer_client_->IsWebViewFrame(context, render_frame_))
renderer_client_->SetupMainWorldOverrides(context, render_frame_);
}
}
void ElectronRenderFrameObserver::DraggableRegionsChanged() {
blink::WebVector<blink::WebDraggableRegion> webregions =
render_frame_->GetWebFrame()->GetDocument().DraggableRegions();
std::vector<mojom::DraggableRegionPtr> regions;
for (auto& webregion : webregions) {
auto region = mojom::DraggableRegion::New();
render_frame_->ConvertViewportToWindow(&webregion.bounds);
region->bounds = webregion.bounds;
region->draggable = webregion.draggable;
regions.push_back(std::move(region));
}
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame_->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->UpdateDraggableRegions(std::move(regions));
}
void ElectronRenderFrameObserver::WillReleaseScriptContext(
v8::Local<v8::Context> context,
int world_id) {
if (ShouldNotifyClient(world_id))
renderer_client_->WillReleaseScriptContext(context, render_frame_);
}
void ElectronRenderFrameObserver::OnDestruct() {
delete this;
}
void ElectronRenderFrameObserver::DidMeaningfulLayout(
blink::WebMeaningfulLayout layout_type) {
if (layout_type == blink::WebMeaningfulLayout::kVisuallyNonEmpty) {
mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
web_contents_utility_remote;
render_frame_->GetRemoteAssociatedInterfaces()->GetInterface(
&web_contents_utility_remote);
web_contents_utility_remote->OnFirstNonEmptyLayout();
}
}
void ElectronRenderFrameObserver::CreateIsolatedWorldContext() {
auto* frame = render_frame_->GetWebFrame();
blink::WebIsolatedWorldInfo info;
// This maps to the name shown in the context combo box in the Console tab
// of the dev tools.
info.human_readable_name =
blink::WebString::FromUTF8("Electron Isolated Context");
// Setup document's origin policy in isolated world
info.security_origin = frame->GetDocument().GetSecurityOrigin();
blink::SetIsolatedWorldInfo(WorldIDs::ISOLATED_WORLD_ID, info);
// Create initial script context in isolated world
blink::WebScriptSource source("void 0");
frame->ExecuteScriptInIsolatedWorld(
WorldIDs::ISOLATED_WORLD_ID, source,
blink::BackForwardCacheAware::kPossiblyDisallow);
}
bool ElectronRenderFrameObserver::IsMainWorld(int world_id) {
return world_id == WorldIDs::MAIN_WORLD_ID;
}
bool ElectronRenderFrameObserver::IsIsolatedWorld(int world_id) {
return world_id == WorldIDs::ISOLATED_WORLD_ID;
}
bool ElectronRenderFrameObserver::ShouldNotifyClient(int world_id) {
auto prefs = render_frame_->GetBlinkPreferences();
// This is necessary because if an iframe is created and a source is not
// set, the iframe loads about:blank and creates a script context for the
// same. We don't want to create a Node.js environment here because if the src
// is later set, the JS necessary to do that triggers illegal access errors
// when the initial about:blank Node.js environment is cleaned up. See:
// https://source.chromium.org/chromium/chromium/src/+/main:content/renderer/render_frame_impl.h;l=870-892;drc=4b6001440a18740b76a1c63fa2a002cc941db394
GURL url = render_frame_->GetWebFrame()->GetDocument().Url();
bool allow_node_in_sub_frames = prefs.node_integration_in_sub_frames;
if (allow_node_in_sub_frames && url.IsAboutBlank() &&
!render_frame_->IsMainFrame())
return false;
if (prefs.context_isolation &&
(render_frame_->IsMainFrame() || allow_node_in_sub_frames))
return IsIsolatedWorld(world_id);
return IsMainWorld(world_id);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,844 |
[Bug]: Preload script not running on child-window "top" frame
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
16.0.5
### What operating system are you using?
Ubuntu
### Operating System Version
20.04
### What arch are you using?
x64
### Last Known Working Electron version
16.0.4
### Expected Behavior
I have an app that uses the preload script on some contexts.
Recently I found out that in some scenarios the preload script is not running.
Im using the setWindowOpenHandler function in order to use the same preload in all future child window that will be created.
Electron fiddle gist is added for refrence.
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The expected behaviour is to have preload script running on this window as well.
### Actual Behavior
Bug flow:
1. Go to gmail.com.
2. Click on the "meet" button on the left.
3. Click on "New Meeting"
4. A pop up will open up
5. The actual behaviour is that the preload script does not run at all on the top frame.
### Testcase Gist URL
https://gist.github.com/cbb4249641359cce34b87c0203b55d8a
### Additional Information
Tested also 26.0.0-alpha.7 to make sure its not something that was fixed in newer versions
Looking at the release notes this PR seems to be what's causing this bug: https://github.com/electron/electron/pull/32108
|
https://github.com/electron/electron/issues/38844
|
https://github.com/electron/electron/pull/38910
|
ff6d0df2d534efe1aa8d466e1ea75333290cb0dc
|
09669f9d215ceb96d7f02f9085d7906e27c2b301
| 2023-06-19T13:51:28Z |
c++
| 2023-06-26T21:04:54Z |
spec/chromium-spec.ts
|
import { expect } from 'chai';
import { BrowserWindow, WebContents, webFrameMain, session, ipcMain, app, protocol, webContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import * as https from 'node:https';
import * as http from 'node:http';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as url from 'node:url';
import * as ChildProcess from 'node:child_process';
import { EventEmitter, once } from 'node:events';
import { promisify } from 'node:util';
import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers';
import { PipeTransport } from './pipe-transport';
import * as ws from 'ws';
import { setTimeout } from 'node:timers/promises';
const features = process._linkedBinding('electron_common_features');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const certPath = path.join(fixturesPath, 'certificates');
describe('reporting api', () => {
it('sends a report for an intervention', async () => {
const reporting = new EventEmitter();
// The Reporting API only works on https with valid certs. To dodge having
// to set up a trusted certificate, hack the validator.
session.defaultSession.setCertificateVerifyProc((req, cb) => {
cb(0);
});
const options = {
key: fs.readFileSync(path.join(certPath, 'server.key')),
cert: fs.readFileSync(path.join(certPath, 'server.pem')),
ca: [
fs.readFileSync(path.join(certPath, 'rootCA.pem')),
fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
],
requestCert: true,
rejectUnauthorized: false
};
const server = https.createServer(options, (req, res) => {
if (req.url?.endsWith('report')) {
let data = '';
req.on('data', (d) => { data += d.toString('utf-8'); });
req.on('end', () => {
reporting.emit('report', JSON.parse(data));
});
}
const { port } = server.address() as any;
res.setHeader('Reporting-Endpoints', `default="https://localhost:${port}/report"`);
res.setHeader('Content-Type', 'text/html');
res.end('<script>window.navigator.vibrate(1)</script>');
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
const bw = new BrowserWindow({ show: false });
try {
const reportGenerated = once(reporting, 'report');
await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`);
const [reports] = await reportGenerated;
expect(reports).to.be.an('array').with.lengthOf(1);
const { type, url, body } = reports[0];
expect(type).to.equal('intervention');
expect(url).to.equal(url);
expect(body.id).to.equal('NavigatorVibrate');
expect(body.message).to.match(/Blocked call to navigator.vibrate because user hasn't tapped on the frame or any embedded frame yet/);
} finally {
bw.destroy();
server.close();
}
});
});
describe('window.postMessage', () => {
afterEach(async () => {
await closeAllWindows();
});
it('sets the source and origin correctly', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/window-open-postMessage-driver.html`);
const [, message] = await once(ipcMain, 'complete');
expect(message.data).to.equal('testing');
expect(message.origin).to.equal('file://');
expect(message.sourceEqualsOpener).to.equal(true);
expect(message.eventOrigin).to.equal('file://');
});
});
describe('focus handling', () => {
let webviewContents: WebContents;
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({
show: true,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
contextIsolation: false
}
});
const webviewReady = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
await w.loadFile(path.join(fixturesPath, 'pages', 'tab-focus-loop-elements.html'));
const [, wvContents] = await webviewReady;
webviewContents = wvContents;
await once(webviewContents, 'did-finish-load');
w.focus();
});
afterEach(() => {
webviewContents = null as unknown as WebContents;
w.destroy();
w = null as unknown as BrowserWindow;
});
const expectFocusChange = async () => {
const [, focusedElementId] = await once(ipcMain, 'focus-changed');
return focusedElementId;
};
describe('a TAB press', () => {
const tabPressEvent: any = {
type: 'keyDown',
keyCode: 'Tab'
};
it('moves focus to the next focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `should start focused in element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've moved to element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(tabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've looped back to element-1, it's instead in ${focusedElementId}`);
});
});
describe('a SHIFT + TAB press', () => {
const shiftTabPressEvent: any = {
type: 'keyDown',
modifiers: ['Shift'],
keyCode: 'Tab'
};
it('moves focus to the previous focusable item', async () => {
let focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
let focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `should start focused in element-3, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-2', `focus should've moved to the webview's element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-wv-element-1', `focus should've moved to the webview's element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
webviewContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-2', `focus should've moved to element-2, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-1', `focus should've moved to element-1, it's instead in ${focusedElementId}`);
focusChange = expectFocusChange();
w.webContents.sendInputEvent(shiftTabPressEvent);
focusedElementId = await focusChange;
expect(focusedElementId).to.equal('BUTTON-element-3', `focus should've looped back to element-3, it's instead in ${focusedElementId}`);
});
});
});
describe('web security', () => {
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('engages CORB when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,<script>
const s = document.createElement('script')
s.src = "${serverUrl}"
// The script will load successfully but its body will be emptied out
// by CORB, so we don't expect a syntax error.
s.onload = () => { require('electron').ipcRenderer.send('success') }
document.documentElement.appendChild(s)
</script>`);
await p;
});
it('bypasses CORB when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'success');
await w.loadURL(`data:text/html,
<script>
window.onerror = (e) => { require('electron').ipcRenderer.send('success', e) }
</script>
<script src="${serverUrl}"></script>`);
await p;
});
it('engages CORS when web security is not disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('failed');
});
it('bypasses CORS when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false, nodeIntegration: true, contextIsolation: false } });
const p = once(ipcMain, 'response');
await w.loadURL(`data:text/html,<script>
(async function() {
try {
await fetch('${serverUrl}');
require('electron').ipcRenderer.send('response', 'passed');
} catch {
require('electron').ipcRenderer.send('response', 'failed');
}
})();
</script>`);
const [, response] = await p;
expect(response).to.equal('passed');
});
describe('accessing file://', () => {
async function loadFile (w: BrowserWindow) {
const thisFile = url.format({
pathname: __filename.replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
await w.loadURL(`data:text/html,<script>
function loadFile() {
return new Promise((resolve) => {
fetch('${thisFile}').then(
() => resolve('loaded'),
() => resolve('failed')
)
});
}
</script>`);
return await w.webContents.executeJavaScript('loadFile()');
}
it('is forbidden when web security is enabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: true } });
const result = await loadFile(w);
expect(result).to.equal('failed');
});
it('is allowed when web security is disabled', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webSecurity: false } });
const result = await loadFile(w);
expect(result).to.equal('loaded');
});
});
describe('wasm-eval csp', () => {
async function loadWasm (csp: string) {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: true,
enableBlinkFeatures: 'WebAssemblyCSP'
}
});
await w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' ${csp}">
</head>
<script>
function loadWasm() {
const wasmBin = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])
return new Promise((resolve) => {
WebAssembly.instantiate(wasmBin).then(() => {
resolve('loaded')
}).catch((error) => {
resolve(error.message)
})
});
}
</script>`);
return await w.webContents.executeJavaScript('loadWasm()');
}
it('wasm codegen is disallowed by default', async () => {
const r = await loadWasm('');
expect(r).to.equal('WebAssembly.instantiate(): Refused to compile or instantiate WebAssembly module because \'unsafe-eval\' is not an allowed source of script in the following Content Security Policy directive: "script-src \'self\' \'unsafe-inline\'"');
});
it('wasm codegen is allowed with "wasm-unsafe-eval" csp', async () => {
const r = await loadWasm("'wasm-unsafe-eval'");
expect(r).to.equal('loaded');
});
});
describe('csp', () => {
for (const sandbox of [true, false]) {
describe(`when sandbox: ${sandbox}`, () => {
for (const contextIsolation of [true, false]) {
describe(`when contextIsolation: ${contextIsolation}`, () => {
it('prevents eval from running in an inline script', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
</head>
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.match(/Refused to evaluate a string/);
});
it('does not prevent eval from running in an inline script when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL(`data:text/html,
<script>
try {
// We use console.log here because it is easier than making a
// preload script, and the behavior under test changes when
// contextIsolation: false
console.log(eval('true'))
} catch (e) {
console.log(e.message)
}
</script>`);
const [,, message] = await once(w.webContents, 'console-message');
expect(message).to.equal('true');
});
it('prevents eval from running in executeJavaScript', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,<head><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\' \'unsafe-inline\'"></meta></head>');
await expect(w.webContents.executeJavaScript('eval("true")')).to.be.rejected();
});
it('does not prevent eval from running in executeJavaScript when there is no csp', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { sandbox, contextIsolation }
});
w.loadURL('data:text/html,');
expect(await w.webContents.executeJavaScript('eval("true")')).to.be.true();
});
});
}
});
}
});
it('does not crash when multiple WebContent are created with web security disabled', () => {
const options = { show: false, webPreferences: { webSecurity: false } };
const w1 = new BrowserWindow(options);
w1.loadURL(serverUrl);
const w2 = new BrowserWindow(options);
w2.loadURL(serverUrl);
});
});
describe('command line switches', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
describe('--lang switch', () => {
const currentLocale = app.getLocale();
const currentSystemLocale = app.getSystemLocale();
const currentPreferredLanguages = JSON.stringify(app.getPreferredSystemLanguages());
const testLocale = async (locale: string, result: string, printEnv: boolean = false) => {
const appPath = path.join(fixturesPath, 'api', 'locale-check');
const args = [appPath, `--set-lang=${locale}`];
if (printEnv) {
args.push('--print-env');
}
appProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
appProcess.stdout.on('data', (data) => { output += data; });
let stderr = '';
appProcess.stderr.on('data', (data) => { stderr += data; });
const [code, signal] = await once(appProcess, 'exit');
if (code !== 0) {
throw new Error(`Process exited with code "${code}" signal "${signal}" output "${output}" stderr "${stderr}"`);
}
output = output.replace(/(\r\n|\n|\r)/gm, '');
expect(output).to.equal(result);
};
it('should set the locale', async () => testLocale('fr', `fr|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should set the locale with country code', async () => testLocale('zh-CN', `zh-CN|${currentSystemLocale}|${currentPreferredLanguages}`));
it('should not set an invalid locale', async () => testLocale('asdfkl', `${currentLocale}|${currentSystemLocale}|${currentPreferredLanguages}`));
const lcAll = String(process.env.LC_ALL);
ifit(process.platform === 'linux')('current process has a valid LC_ALL env', async () => {
// The LC_ALL env should not be set to DOM locale string.
expect(lcAll).to.not.equal(app.getLocale());
});
ifit(process.platform === 'linux')('should not change LC_ALL', async () => testLocale('fr', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when setting invalid locale', async () => testLocale('asdfkl', lcAll, true));
ifit(process.platform === 'linux')('should not change LC_ALL when --lang is not set', async () => testLocale('', lcAll, true));
});
describe('--remote-debugging-pipe switch', () => {
it('should expose CDP via pipe', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(message.result.product).to.contain('Chrome');
expect(message.result.userAgent).to.contain('Electron');
});
it('should override --remote-debugging-port switch', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe', '--remote-debugging-port=0'], {
stdio: ['inherit', 'inherit', 'pipe', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
let stderr = '';
appProcess.stderr.on('data', (data: string) => { stderr += data; });
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
const versionPromise = new Promise(resolve => { pipe.onmessage = resolve; });
pipe.send({ id: 1, method: 'Browser.getVersion', params: {} });
const message = (await versionPromise) as any;
expect(message.id).to.equal(1);
expect(stderr).to.not.include('DevTools listening on');
});
it('should shut down Electron upon Browser.close CDP command', async () => {
const electronPath = process.execPath;
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-pipe'], {
stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe']
}) as ChildProcess.ChildProcessWithoutNullStreams;
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
await once(appProcess, 'exit');
});
});
describe('--remote-debugging-port switch', () => {
it('should display the discovery page', (done) => {
const electronPath = process.execPath;
let output = '';
appProcess = ChildProcess.spawn(electronPath, ['--remote-debugging-port=']);
appProcess.stdout.on('data', (data) => {
console.log(data);
});
appProcess.stderr.on('data', (data) => {
console.log(data);
output += data;
const m = /DevTools listening on ws:\/\/127.0.0.1:(\d+)\//.exec(output);
if (m) {
appProcess!.stderr.removeAllListeners('data');
const port = m[1];
http.get(`http://127.0.0.1:${port}`, (res) => {
try {
expect(res.statusCode).to.eql(200);
expect(parseInt(res.headers['content-length']!)).to.be.greaterThan(0);
done();
} catch (e) {
done(e);
} finally {
res.destroy();
}
});
}
});
});
});
});
describe('chromium features', () => {
afterEach(closeAllWindows);
describe('accessing key names also used as Node.js module names', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'external-string.html'));
});
});
describe('first party sets', () => {
const fps = [
'https://fps-member1.glitch.me',
'https://fps-member2.glitch.me',
'https://fps-member3.glitch.me'
];
it('loads first party sets', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'base');
const fpsProcess = ChildProcess.spawn(process.execPath, [appPath]);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
it('loads sets from the command line', async () => {
const appPath = path.join(fixturesPath, 'api', 'first-party-sets', 'command-line');
const args = [appPath, `--use-first-party-set=${fps}`];
const fpsProcess = ChildProcess.spawn(process.execPath, args);
let output = '';
fpsProcess.stdout.on('data', data => { output += data; });
await once(fpsProcess, 'exit');
expect(output).to.include(fps.join(','));
});
});
describe('loading jquery', () => {
it('does not crash', (done) => {
const w = new BrowserWindow({ show: false });
w.webContents.once('did-finish-load', () => { done(); });
w.webContents.once('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'jquery.html'));
});
});
describe('navigator.languages', () => {
it('should return the system locale only', async () => {
const appLocale = app.getLocale();
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
const languages = await w.webContents.executeJavaScript('navigator.languages');
expect(languages.length).to.be.greaterThan(0);
expect(languages).to.contain(appLocale);
});
});
describe('navigator.serviceWorker', () => {
it('should register for file scheme', (done) => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for intercepted file scheme', (done) => {
const customSession = session.fromPartition('intercept-file');
customSession.protocol.interceptBufferProtocol('file', (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
const content = fs.readFileSync(path.normalize(file));
const ext = path.extname(file);
let type = 'text/html';
if (ext === '.js') type = 'application/javascript';
callback({ data: content, mimeType: type } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol('file');
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'index.html'));
});
it('should register for custom scheme', (done) => {
const customSession = session.fromPartition('custom-scheme');
customSession.protocol.registerFileProtocol(serviceWorkerScheme, (request, callback) => {
let file = url.parse(request.url).pathname!;
if (file[0] === '/' && process.platform === 'win32') file = file.slice(1);
callback({ path: path.normalize(file) } as any);
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: customSession,
contextIsolation: false
}
});
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(`unexpected error : ${message}`);
} else if (channel === 'response') {
expect(message).to.equal('Hello from serviceWorker!');
customSession.clearStorageData({
storages: ['serviceworkers']
}).then(() => {
customSession.protocol.uninterceptProtocol(serviceWorkerScheme);
done();
});
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'custom-scheme-index.html'));
});
it('should not allow nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
partition: 'sw-file-scheme-worker-spec',
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/service-worker/empty.html`);
const data = await w.webContents.executeJavaScript(`
navigator.serviceWorker.register('worker-no-node.js', {
scope: './'
}).then(() => navigator.serviceWorker.ready)
new Promise((resolve) => {
navigator.serviceWorker.onmessage = event => resolve(event.data);
});
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
describe('navigator.geolocation', () => {
ifit(features.isFakeLocationProviderEnabled())('returns error when permission is denied', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'geolocation-spec',
contextIsolation: false
}
});
const message = once(w.webContents, 'ipc-message');
w.webContents.session.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'geolocation') {
callback(false);
} else {
callback(true);
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'geolocation', 'index.html'));
const [, channel] = await message;
expect(channel).to.equal('success', 'unexpected response from geolocation api');
});
ifit(!features.isFakeLocationProviderEnabled())('returns position when permission is granted', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
partition: 'geolocation-spec'
}
});
w.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) => {
callback(true);
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const position = await w.webContents.executeJavaScript(`new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
x => resolve({coords: x.coords, timestamp: x.timestamp}),
err => reject(new Error(err.message))))`);
expect(position).to.have.property('coords');
expect(position).to.have.property('timestamp');
});
});
describe('web workers', () => {
let appProcess: ChildProcess.ChildProcessWithoutNullStreams | undefined;
afterEach(() => {
if (appProcess && !appProcess.killed) {
appProcess.kill();
appProcess = undefined;
}
});
it('Worker with nodeIntegrationInWorker has access to self.module.paths', async () => {
const appPath = path.join(__dirname, 'fixtures', 'apps', 'self-module-paths');
appProcess = ChildProcess.spawn(process.execPath, [appPath]);
const [code] = await once(appProcess, 'exit');
expect(code).to.equal(0);
});
it('Worker can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
worker.postMessage(message);
eventPromise.then(t => t.data)
`);
expect(data).to.equal('ping');
});
it('Worker has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new Worker('../workers/worker_node.js');
new Promise((resolve) => { worker.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('Worker has node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, contextIsolation: false } });
w.loadURL(`file://${fixturesPath}/pages/worker.html`);
const [, data] = await once(ipcMain, 'worker-result');
expect(data).to.equal('object function object function');
});
describe('SharedWorker', () => {
it('can work', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker.js');
const message = 'ping';
const eventPromise = new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); });
worker.port.postMessage(message);
eventPromise
`);
expect(data).to.equal('ping');
});
it('has no node integration by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
it('does not have node integration with nodeIntegrationInWorker', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
contextIsolation: false
}
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const data = await w.webContents.executeJavaScript(`
const worker = new SharedWorker('../workers/shared_worker_node.js');
new Promise((resolve) => { worker.port.onmessage = e => resolve(e.data); })
`);
expect(data).to.equal('undefined undefined undefined undefined');
});
});
});
describe('form submit', () => {
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
res.setHeader('Content-Type', 'application/json');
req.on('end', () => {
res.end(`body:${body}`);
});
});
serverUrl = (await listen(server)).url;
});
after(async () => {
server.close();
await closeAllWindows();
});
[true, false].forEach((isSandboxEnabled) =>
describe(`sandbox=${isSandboxEnabled}`, () => {
it('posts data in the same window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const loadPromise = once(w.webContents, 'did-finish-load');
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.submit();
`);
await loadPromise;
const res = await w.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
it('posts data to a new window with target=_blank', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
sandbox: isSandboxEnabled
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'form-with-data.html'));
const windowCreatedPromise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w.webContents.executeJavaScript(`
const form = document.querySelector('form')
form.action = '${serverUrl}';
form.target = '_blank';
form.submit();
`);
const [, newWin] = await windowCreatedPromise;
const res = await newWin.webContents.executeJavaScript('document.body.innerText');
expect(res).to.equal('body:greeting=hello');
});
})
);
});
describe('window.open', () => {
for (const show of [true, false]) {
it(`shows the child regardless of parent visibility when parent {show=${show}}`, async () => {
const w = new BrowserWindow({ show });
// toggle visibility
if (show) {
w.hide();
} else {
w.show();
}
defer(() => { w.close(); });
const promise = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
w.loadFile(path.join(fixturesPath, 'pages', 'window-open.html'));
const [, newWindow] = await promise;
expect(newWindow.isVisible()).to.equal(true);
});
}
// FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-node-integration.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-node.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=false')
const e = await message
b.close();
return {
eventData: e.data
}
})()`);
expect(eventData.isProcessGlobalUndefined).to.be.true();
});
it('disables node integration when it is disabled on the parent window for chrome devtools URLs', async () => {
// NB. webSecurity is disabled because native window.open() is not
// allowed to load devtools:// URLs.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webSecurity: false } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('devtools://devtools/bundled/inspector.html', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
it('can disable node integration when it is enabled on the parent window', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
{ b = window.open('about:blank', '', 'nodeIntegration=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
const typeofProcessGlobal = await contents.executeJavaScript('typeof process');
expect(typeofProcessGlobal).to.equal('undefined');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('disables JavaScript when it is disabled on the parent window', async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = require('node:url').format({
pathname: `${fixturesPath}/pages/window-no-javascript.html`,
protocol: 'file',
slashes: true
});
w.webContents.executeJavaScript(`
{ b = window.open(${JSON.stringify(windowUrl)}, '', 'javascript=no,show=no'); null }
`);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-finish-load');
// Click link on page
contents.sendInputEvent({ type: 'mouseDown', clickCount: 1, x: 1, y: 1 });
contents.sendInputEvent({ type: 'mouseUp', clickCount: 1, x: 1, y: 1 });
const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
const preferences = window.webContents.getLastWebPreferences();
expect(preferences!.javascript).to.be.false();
});
it('defines a window.location getter', async () => {
let targetURL: string;
if (process.platform === 'win32') {
targetURL = `file:///${fixturesPath.replace(/\\/g, '/')}/pages/base-page.html`;
} else {
targetURL = `file://${fixturesPath}/pages/base-page.html`;
}
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript(`{ b = window.open(${JSON.stringify(targetURL)}); null }`);
const [, window] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(window.webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal(targetURL);
});
it('defines a window.location setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('defines a window.location.href setter', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
w.webContents.executeJavaScript('{ b = window.open("about:blank"); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
// When it loads, redirect
w.webContents.executeJavaScript(`{ b.location.href = ${JSON.stringify(`file://${fixturesPath}/pages/base-page.html`)}; null }`);
await once(webContents, 'did-finish-load');
});
it('open a blank page when no URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('open a blank page when an empty URL is specified', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\'); null }');
const [, { webContents }] = await once(app, 'browser-window-created') as [any, BrowserWindow];
await once(webContents, 'did-finish-load');
expect(await w.webContents.executeJavaScript('b.location.href')).to.equal('about:blank');
});
it('does not throw an exception when the frameName is a built-in object property', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript('{ b = window.open(\'\', \'__proto__\'); null }');
const frameName = await new Promise((resolve) => {
w.webContents.setWindowOpenHandler(details => {
setImmediate(() => resolve(details.frameName));
return { action: 'allow' };
});
});
expect(frameName).to.equal('__proto__');
});
// FIXME(nornagon): I'm not sure this ... ever was correct?
xit('inherit options of parent window', async () => {
const w = new BrowserWindow({ show: false, width: 123, height: 456 });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const url = `file://${fixturesPath}/pages/window-open-size.html`;
const { width, height, eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(url)}, '', 'show=false')
const e = await message
b.close();
const width = outerWidth;
const height = outerHeight;
return {
width,
height,
eventData: e.data
}
})()`);
expect(eventData).to.equal(`size: ${width} ${height}`);
expect(eventData).to.equal('size: 123 456');
});
it('does not override child options', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-open-size.html`;
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no,width=350,height=450')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData).to.equal('size: 350 450');
});
it('disables the <webview> tag when it is disabled on the parent window', async () => {
const windowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'window-opener-no-webview-tag.html'));
windowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-webview.html`);
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const { eventData } = await w.webContents.executeJavaScript(`(async () => {
const message = new Promise(resolve => window.addEventListener('message', resolve, {once: true}));
const b = window.open(${JSON.stringify(windowUrl)}, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no')
const e = await message
b.close();
return { eventData: e.data }
})()`);
expect(eventData.isWebViewGlobalUndefined).to.be.true();
});
it('throws an exception when the arguments cannot be converted to strings', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', { toString: null })')
).to.eventually.be.rejected();
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', { toString: 3 })')
).to.eventually.be.rejected();
});
it('does not throw an exception when the features include webPreferences', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await expect(
w.webContents.executeJavaScript('window.open(\'\', \'\', \'show=no,webPreferences=\'); null')
).to.eventually.be.fulfilled();
});
});
describe('window.opener', () => {
it('is null for main window', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'window-opener.html'));
const [, channel, opener] = await once(w.webContents, 'ipc-message');
expect(channel).to.equal('opener');
expect(opener).to.equal(null);
});
it('is not null for window opened by window.open', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener.html`;
const eventData = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data);
`);
expect(eventData).to.equal('object');
});
});
describe('window.opener.postMessage', () => {
it('sets source and origin correctly', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const windowUrl = `file://${fixturesPath}/pages/window-opener-postMessage.html`;
const { sourceIsChild, origin } = await w.webContents.executeJavaScript(`
const b = window.open(${JSON.stringify(windowUrl)}, '', 'show=no');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => ({
sourceIsChild: e.source === b,
origin: e.origin
}));
`);
expect(sourceIsChild).to.be.true();
expect(origin).to.equal('file://');
});
it('supports windows opened from a <webview>', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
w.loadURL('about:blank');
const childWindowUrl = url.pathToFileURL(path.join(fixturesPath, 'pages', 'webview-opener-postMessage.html'));
childWindowUrl.searchParams.set('p', `${fixturesPath}/pages/window-opener-postMessage.html`);
const message = await w.webContents.executeJavaScript(`
const webview = new WebView();
webview.allowpopups = true;
webview.setAttribute('webpreferences', 'contextIsolation=no');
webview.src = ${JSON.stringify(childWindowUrl)}
const consoleMessage = new Promise(resolve => webview.addEventListener('console-message', resolve, {once: true}));
document.body.appendChild(webview);
consoleMessage.then(e => e.message)
`);
expect(message).to.equal('message');
});
describe('targetOrigin argument', () => {
let serverURL: string;
let server: any;
beforeEach(async () => {
server = http.createServer((req, res) => {
res.writeHead(200);
const filePath = path.join(fixturesPath, 'pages', 'window-opener-targetOrigin.html');
res.end(fs.readFileSync(filePath, 'utf8'));
});
serverURL = (await listen(server)).url;
});
afterEach(() => {
server.close();
});
it('delivers messages that match the origin', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadFile(path.resolve(__dirname, 'fixtures', 'blank.html'));
const data = await w.webContents.executeJavaScript(`
window.open(${JSON.stringify(serverURL)}, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
new Promise(resolve => window.addEventListener('message', resolve, {once: true})).then(e => e.data)
`);
expect(data).to.equal('deliver');
});
});
});
describe('navigator.mediaDevices', () => {
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setPermissionRequestHandler(null);
});
it('can return labels of enumerated devices', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.true();
});
it('does not return labels of enumerated devices when permission denied', async () => {
session.defaultSession.setPermissionCheckHandler(() => false);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript('navigator.mediaDevices.enumerateDevices().then(ds => ds.map(d => d.label))');
expect(labels.some((l: any) => l)).to.be.false();
});
it('returns the same device ids across reloads', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.deep.equal(secondDeviceIds);
});
it('can return new device id when cookie storage is cleared', async () => {
const ses = session.fromPartition('persist:media-device-id');
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
session: ses,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'media-id-reset.html'));
const [, firstDeviceIds] = await once(ipcMain, 'deviceIds');
await ses.clearStorageData({ storages: ['cookies'] });
w.webContents.reload();
const [, secondDeviceIds] = await once(ipcMain, 'deviceIds');
expect(firstDeviceIds).to.not.deep.equal(secondDeviceIds);
});
it('provides a securityOrigin to the request handler', async () => {
session.defaultSession.setPermissionRequestHandler(
(wc, permission, callback, details) => {
if (details.securityOrigin !== undefined) {
callback(true);
} else {
callback(false);
}
}
);
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const labels = await w.webContents.executeJavaScript(`navigator.mediaDevices.getUserMedia({
video: {
mandatory: {
chromeMediaSource: "desktop",
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream) => stream.getVideoTracks())`);
expect(labels.some((l: any) => l)).to.be.true();
});
it('fails with "not supported" for getDisplayMedia', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const { ok, err } = await w.webContents.executeJavaScript('navigator.mediaDevices.getDisplayMedia({video: true}).then(s => ({ok: true}), e => ({ok: false, err: e.message}))', true);
expect(ok).to.be.false();
expect(err).to.equal('Not supported');
});
});
describe('window.opener access', () => {
const scheme = 'app';
const fileUrl = `file://${fixturesPath}/pages/window-opener-location.html`;
const httpUrl1 = `${scheme}://origin1`;
const httpUrl2 = `${scheme}://origin2`;
const fileBlank = `file://${fixturesPath}/pages/blank.html`;
const httpBlank = `${scheme}://origin1/blank`;
const table = [
{ parent: fileBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: false },
{ parent: fileBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: false },
// {parent: httpBlank, child: fileUrl, nodeIntegration: false, openerAccessible: false}, // can't window.open()
// {parent: httpBlank, child: fileUrl, nodeIntegration: true, openerAccessible: false}, // can't window.open()
// NB. this is different from Chrome's behavior, which isolates file: urls from each other
{ parent: fileBlank, child: fileUrl, nodeIntegration: false, openerAccessible: true },
{ parent: fileBlank, child: fileUrl, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: false, openerAccessible: true },
{ parent: httpBlank, child: httpUrl1, nodeIntegration: true, openerAccessible: true },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: false, openerAccessible: false },
{ parent: httpBlank, child: httpUrl2, nodeIntegration: true, openerAccessible: false }
];
const s = (url: string) => url.startsWith('file') ? 'file://...' : url;
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
if (request.url.includes('blank')) {
callback(`${fixturesPath}/pages/blank.html`);
} else {
callback(`${fixturesPath}/pages/window-opener-location.html`);
}
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
afterEach(closeAllWindows);
describe('when opened from main window', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
for (const sandboxPopup of [false, true]) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration} sandboxPopup=${sandboxPopup}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
sandbox: sandboxPopup
}
}
}));
await w.loadURL(parent);
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise(resolve => {
window.addEventListener('message', function f(e) {
resolve(e.data)
})
window.open(${JSON.stringify(child)}, "", "show=no,nodeIntegration=${nodeIntegration ? 'yes' : 'no'}")
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
}
});
describe('when opened from <webview>', () => {
for (const { parent, child, nodeIntegration, openerAccessible } of table) {
const description = `when parent=${s(parent)} opens child=${s(child)} with nodeIntegration=${nodeIntegration}, child should ${openerAccessible ? '' : 'not '}be able to access opener`;
it(description, async () => {
// This test involves three contexts:
// 1. The root BrowserWindow in which the test is run,
// 2. A <webview> belonging to the root window,
// 3. A window opened by calling window.open() from within the <webview>.
// We are testing whether context (3) can access context (2) under various conditions.
// This is context (1), the base window for the test.
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
await w.loadURL('about:blank');
const parentCode = `new Promise((resolve) => {
// This is context (3), a child window of the WebView.
const child = window.open(${JSON.stringify(child)}, "", "show=no,contextIsolation=no,nodeIntegration=yes")
window.addEventListener("message", e => {
resolve(e.data)
})
})`;
const childOpenerLocation = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
// This is context (2), a WebView which will call window.open()
const webview = new WebView()
webview.setAttribute('nodeintegration', '${nodeIntegration ? 'on' : 'off'}')
webview.setAttribute('webpreferences', 'contextIsolation=no')
webview.setAttribute('allowpopups', 'on')
webview.src = ${JSON.stringify(parent + '?p=' + encodeURIComponent(child))}
webview.addEventListener('dom-ready', async () => {
webview.executeJavaScript(${JSON.stringify(parentCode)}).then(resolve, reject)
})
document.body.appendChild(webview)
})`);
if (openerAccessible) {
expect(childOpenerLocation).to.be.a('string');
} else {
expect(childOpenerLocation).to.be.null();
}
});
}
});
});
describe('storage', () => {
describe('custom non standard schemes', () => {
const protocolName = 'storage';
let contents: WebContents;
before(() => {
protocol.registerFileProtocol(protocolName, (request, callback) => {
const parsedUrl = url.parse(request.url);
let filename;
switch (parsedUrl.pathname) {
case '/localStorage' : filename = 'local_storage.html'; break;
case '/sessionStorage' : filename = 'session_storage.html'; break;
case '/WebSQL' : filename = 'web_sql.html'; break;
case '/indexedDB' : filename = 'indexed_db.html'; break;
case '/cookie' : filename = 'cookie.html'; break;
default : filename = '';
}
callback({ path: `${fixturesPath}/pages/storage/${filename}` });
});
});
after(() => {
protocol.unregisterProtocol(protocolName);
});
beforeEach(() => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
nodeIntegration: true,
contextIsolation: false
});
});
afterEach(() => {
contents.destroy();
contents = null as any;
});
it('cannot access localStorage', async () => {
const response = once(ipcMain, 'local-storage-response');
contents.loadURL(protocolName + '://host/localStorage');
const [, error] = await response;
expect(error).to.equal('Failed to read the \'localStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access sessionStorage', async () => {
const response = once(ipcMain, 'session-storage-response');
contents.loadURL(`${protocolName}://host/sessionStorage`);
const [, error] = await response;
expect(error).to.equal('Failed to read the \'sessionStorage\' property from \'Window\': Access is denied for this document.');
});
it('cannot access WebSQL database', async () => {
const response = once(ipcMain, 'web-sql-response');
contents.loadURL(`${protocolName}://host/WebSQL`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'openDatabase\' on \'Window\': Access to the WebDatabase API is denied in this context.');
});
it('cannot access indexedDB', async () => {
const response = once(ipcMain, 'indexed-db-response');
contents.loadURL(`${protocolName}://host/indexedDB`);
const [, error] = await response;
expect(error).to.equal('Failed to execute \'open\' on \'IDBFactory\': access to the Indexed Database API is denied in this context.');
});
it('cannot access cookie', async () => {
const response = once(ipcMain, 'cookie-response');
contents.loadURL(`${protocolName}://host/cookie`);
const [, error] = await response;
expect(error).to.equal('Failed to set the \'cookie\' property on \'Document\': Access is denied for this document.');
});
});
describe('can be accessed', () => {
let server: http.Server;
let serverUrl: string;
let serverCrossSiteUrl: string;
before(async () => {
server = http.createServer((req, res) => {
const respond = () => {
if (req.url === '/redirect-cross-site') {
res.setHeader('Location', `${serverCrossSiteUrl}/redirected`);
res.statusCode = 302;
res.end();
} else if (req.url === '/redirected') {
res.end('<html><script>window.localStorage</script></html>');
} else {
res.end();
}
};
setTimeout().then(respond);
});
serverUrl = (await listen(server)).url;
serverCrossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
});
after(() => {
server.close();
server = null as any;
});
afterEach(closeAllWindows);
const testLocalStorageAfterXSiteRedirect = (testTitle: string, extraPreferences = {}) => {
it(testTitle, async () => {
const w = new BrowserWindow({
show: false,
...extraPreferences
});
let redirected = false;
w.webContents.on('render-process-gone', () => {
expect.fail('renderer crashed / was killed');
});
w.webContents.on('did-redirect-navigation', (event, url) => {
expect(url).to.equal(`${serverCrossSiteUrl}/redirected`);
redirected = true;
});
await w.loadURL(`${serverUrl}/redirect-cross-site`);
expect(redirected).to.be.true('didnt redirect');
});
};
testLocalStorageAfterXSiteRedirect('after a cross-site redirect');
testLocalStorageAfterXSiteRedirect('after a cross-site redirect in sandbox mode', { sandbox: true });
});
describe('enableWebSQL webpreference', () => {
const origin = `${standardScheme}://fake-host`;
const filePath = path.join(fixturesPath, 'pages', 'storage', 'web_sql.html');
const sqlPartition = 'web-sql-preference-test';
const sqlSession = session.fromPartition(sqlPartition);
const securityError = 'An attempt was made to break through the security policy of the user agent.';
let contents: WebContents, w: BrowserWindow;
before(() => {
sqlSession.protocol.registerFileProtocol(standardScheme, (request, callback) => {
callback({ path: filePath });
});
});
after(() => {
sqlSession.protocol.unregisterProtocol(standardScheme);
});
afterEach(async () => {
if (contents) {
contents.destroy();
contents = null as any;
}
await closeAllWindows();
(w as any) = null;
});
it('default value allows websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
});
it('when set to false can disallow websql', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
});
it('when set to false does not disable indexedDB', async () => {
contents = (webContents as typeof ElectronInternal.WebContents).create({
session: sqlSession,
nodeIntegration: true,
enableWebSQL: false,
contextIsolation: false
});
contents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.equal(securityError);
const dbName = 'random';
const result = await contents.executeJavaScript(`
new Promise((resolve, reject) => {
try {
let req = window.indexedDB.open('${dbName}');
req.onsuccess = (event) => {
let db = req.result;
resolve(db.name);
}
req.onerror = (event) => { resolve(event.target.code); }
} catch (e) {
resolve(e.message);
}
});
`);
expect(result).to.equal(dbName);
});
it('child webContents can override when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=0,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents cannot override when the embedder has disallowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
enableWebSQL: false,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL('data:text/html,<html></html>');
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.equal(securityError);
});
it('child webContents can use websql when the embedder has allowed websql', async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
webviewTag: true,
session: sqlSession,
contextIsolation: false
}
});
w.webContents.loadURL(origin);
const [, error] = await once(ipcMain, 'web-sql-response');
expect(error).to.be.null();
const webviewResult = once(ipcMain, 'web-sql-response');
await w.webContents.executeJavaScript(`
new Promise((resolve, reject) => {
const webview = new WebView();
webview.setAttribute('src', '${origin}');
webview.setAttribute('webpreferences', 'enableWebSQL=1,contextIsolation=no');
webview.setAttribute('partition', '${sqlPartition}');
webview.setAttribute('nodeIntegration', 'on');
document.body.appendChild(webview);
webview.addEventListener('dom-ready', () => resolve());
});
`);
const [, childError] = await webviewResult;
expect(childError).to.be.null();
});
});
describe('DOM storage quota increase', () => {
['localStorage', 'sessionStorage'].forEach((storageName) => {
it(`allows saving at least 40MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// Although JavaScript strings use UTF-16, the underlying
// storage provider may encode strings differently, muddling the
// translation between character and byte counts. However,
// a string of 40 * 2^20 characters will require at least 40MiB
// and presumably no more than 80MiB, a size guaranteed to
// to exceed the original 10MiB quota yet stay within the
// new 100MiB quota.
// Note that both the key name and value affect the total size.
const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
const length = 40 * Math.pow(2, 20) - testKeyName.length;
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
// Wait at least one turn of the event loop to help avoid false positives
// Although not entirely necessary, the previous version of this test case
// failed to detect a real problem (perhaps related to DOM storage data caching)
// wherein calling `getItem` immediately after `setItem` would appear to work
// but then later (e.g. next tick) it would not.
await setTimeout(1);
try {
const storedLength = await w.webContents.executeJavaScript(`${storageName}.getItem(${JSON.stringify(testKeyName)}).length`);
expect(storedLength).to.equal(length);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
});
it(`throws when attempting to use more than 128MiB in ${storageName}`, async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
await expect((async () => {
const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
const length = 128 * Math.pow(2, 20) - testKeyName.length;
try {
await w.webContents.executeJavaScript(`
${storageName}.setItem(${JSON.stringify(testKeyName)}, 'X'.repeat(${length}));
`);
} finally {
await w.webContents.executeJavaScript(`${storageName}.removeItem(${JSON.stringify(testKeyName)});`);
}
})()).to.eventually.be.rejected();
});
});
});
describe('persistent storage', () => {
it('can be requested', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const grantedBytes = await w.webContents.executeJavaScript(`new Promise(resolve => {
navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
})`);
expect(grantedBytes).to.equal(1048576);
});
});
});
ifdescribe(features.isPDFViewerEnabled())('PDF Viewer', () => {
const pdfSource = url.format({
pathname: path.join(__dirname, 'fixtures', 'cat.pdf').replace(/\\/g, '/'),
protocol: 'file',
slashes: true
});
it('successfully loads a PDF file', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
await once(w.webContents, 'did-finish-load');
});
it('opens when loading a pdf resource as top level navigation', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL(pdfSource);
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
it('opens when loading a pdf resource in a iframe', async () => {
const w = new BrowserWindow({ show: false });
w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'pdf-in-iframe.html'));
const [, contents] = await once(app, 'web-contents-created') as [any, WebContents];
await once(contents, 'did-navigate');
expect(contents.getURL()).to.equal('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/index.html');
});
});
describe('window.history', () => {
describe('window.history.pushState', () => {
it('should push state after calling history.pushState() from the same url', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
// History should have current page by now.
expect((w.webContents as any).length()).to.equal(1);
const waitCommit = once(w.webContents, 'navigation-entry-committed');
w.webContents.executeJavaScript('window.history.pushState({}, "")');
await waitCommit;
// Initial page + pushed state.
expect((w.webContents as any).length()).to.equal(2);
});
});
describe('window.history.back', () => {
it('should not allow sandboxed iframe to modify main frame state', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('data:text/html,<iframe sandbox="allow-scripts"></iframe>');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-frame-navigate'),
once(w.webContents, 'did-navigate')
]);
w.webContents.executeJavaScript('window.history.pushState(1, "")');
await Promise.all([
once(w.webContents, 'navigation-entry-committed'),
once(w.webContents, 'did-navigate-in-page')
]);
(w.webContents as any).once('navigation-entry-committed', () => {
expect.fail('Unexpected navigation-entry-committed');
});
w.webContents.once('did-navigate-in-page', () => {
expect.fail('Unexpected did-navigate-in-page');
});
await w.webContents.mainFrame.frames[0].executeJavaScript('window.history.back()');
expect(await w.webContents.executeJavaScript('window.history.state')).to.equal(1);
expect((w.webContents as any).getActiveIndex()).to.equal(1);
});
});
});
describe('chrome://media-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://media-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('chrome://webrtc-internals', () => {
it('loads the page successfully', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('chrome://webrtc-internals');
const pageExists = await w.webContents.executeJavaScript(
"window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')"
);
expect(pageExists).to.be.true();
});
});
describe('document.hasFocus', () => {
it('has correct value when multiple windows are opened', async () => {
const w1 = new BrowserWindow({ show: true });
const w2 = new BrowserWindow({ show: true });
const w3 = new BrowserWindow({ show: false });
await w1.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w2.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
await w3.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w2.webContents.id);
let focus = false;
focus = await w1.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
focus = await w2.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.true();
focus = await w3.webContents.executeJavaScript(
'document.hasFocus()'
);
expect(focus).to.be.false();
});
});
// https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
describe('navigator.connection', () => {
it('returns the correct value', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.session.enableNetworkEmulation({
latency: 500,
downloadThroughput: 6400,
uploadThroughput: 6400
});
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const rtt = await w.webContents.executeJavaScript('navigator.connection.rtt');
expect(rtt).to.be.a('number');
const downlink = await w.webContents.executeJavaScript('navigator.connection.downlink');
expect(downlink).to.be.a('number');
const effectiveTypes = ['slow-2g', '2g', '3g', '4g'];
const effectiveType = await w.webContents.executeJavaScript('navigator.connection.effectiveType');
expect(effectiveTypes).to.include(effectiveType);
});
});
describe('navigator.userAgentData', () => {
// These tests are done on an http server because navigator.userAgentData
// requires a secure context.
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('');
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
describe('is not empty', () => {
it('by default', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a session-wide UA override', async () => {
const ses = session.fromPartition(`${Math.random()}`);
ses.setUserAgent('foobar');
const w = new BrowserWindow({ show: false, webPreferences: { session: ses } });
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.setUserAgent('foo');
await w.loadURL(serverUrl);
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
it('when there is a WebContents-specific UA override at load time', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl, {
userAgent: 'foo'
});
const platform = await w.webContents.executeJavaScript('navigator.userAgentData.platform');
expect(platform).not.to.be.empty();
});
});
describe('brand list', () => {
it('contains chromium', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(serverUrl);
const brands = await w.webContents.executeJavaScript('navigator.userAgentData.brands');
expect(brands.map((b: any) => b.brand)).to.include('Chromium');
});
});
});
describe('Badging API', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript('navigator.setAppBadge(42)');
await w.webContents.executeJavaScript('navigator.setAppBadge()');
await w.webContents.executeJavaScript('navigator.clearAppBadge()');
});
});
describe('navigator.webkitGetUserMedia', () => {
it('calls its callbacks', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await w.webContents.executeJavaScript(`new Promise((resolve) => {
navigator.webkitGetUserMedia({
audio: true,
video: false
}, () => resolve(),
() => resolve());
})`);
});
});
describe('navigator.language', () => {
it('should not be empty', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(await w.webContents.executeJavaScript('navigator.language')).to.not.equal('');
});
});
describe('heap snapshot', () => {
it('does not crash', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
w.loadURL('about:blank');
await w.webContents.executeJavaScript('process._linkedBinding(\'electron_common_v8_util\').takeHeapSnapshot()');
});
});
// This is intentionally disabled on arm macs: https://chromium-review.googlesource.com/c/chromium/src/+/4143761
ifdescribe(process.platform === 'darwin' && process.arch !== 'arm64')('webgl', () => {
it('can be gotten as context in canvas', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const canWebglContextBeCreated = await w.webContents.executeJavaScript(`
document.createElement('canvas').getContext('webgl') != null;
`);
expect(canWebglContextBeCreated).to.be.true();
});
});
describe('iframe', () => {
it('does not have node integration', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const result = await w.webContents.executeJavaScript(`
const iframe = document.createElement('iframe')
iframe.src = './set-global.html';
document.body.appendChild(iframe);
new Promise(resolve => iframe.onload = e => resolve(iframe.contentWindow.test))
`);
expect(result).to.equal('undefined undefined undefined');
});
});
describe('websockets', () => {
it('has user agent', async () => {
const server = http.createServer();
const { port } = await listen(server);
const wss = new ws.Server({ server: server });
const finished = new Promise<string | undefined>((resolve, reject) => {
wss.on('error', reject);
wss.on('connection', (ws, upgradeReq) => {
resolve(upgradeReq.headers['user-agent']);
});
});
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
w.webContents.executeJavaScript(`
new WebSocket('ws://127.0.0.1:${port}');
`);
expect(await finished).to.include('Electron');
});
});
describe('fetch', () => {
it('does not crash', async () => {
const server = http.createServer((req, res) => {
res.end('test');
});
defer(() => server.close());
const { port } = await listen(server);
const w = new BrowserWindow({ show: false });
w.loadURL(`file://${fixturesPath}/pages/blank.html`);
const x = await w.webContents.executeJavaScript(`
fetch('http://127.0.0.1:${port}').then((res) => res.body.getReader())
.then((reader) => {
return reader.read().then((r) => {
reader.cancel();
return r.value;
});
})
`);
expect(x).to.deep.equal(new Uint8Array([116, 101, 115, 116]));
});
});
describe('Promise', () => {
before(() => {
ipcMain.handle('ping', (e, arg) => arg);
});
after(() => {
ipcMain.removeHandler('ping');
});
itremote('resolves correctly in Node.js calls', async () => {
await new Promise<void>((resolve, reject) => {
class XElement extends HTMLElement {}
customElements.define('x-element', XElement);
setImmediate(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('x-element');
called = true;
});
});
});
itremote('resolves correctly in Electron calls', async () => {
await new Promise<void>((resolve, reject) => {
class YElement extends HTMLElement {}
customElements.define('y-element', YElement);
require('electron').ipcRenderer.invoke('ping').then(() => {
let called = false;
Promise.resolve().then(() => {
if (called) resolve();
else reject(new Error('wrong sequence'));
});
document.createElement('y-element');
called = true;
});
});
});
});
describe('synchronous prompts', () => {
describe('window.alert(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
window.alert({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
describe('window.confirm(message, title)', () => {
itremote('throws an exception when the arguments cannot be converted to strings', () => {
expect(() => {
(window.confirm as any)({ toString: null }, 'title');
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('window.history', () => {
describe('window.history.go(offset)', () => {
itremote('throws an exception when the argument cannot be converted to a string', () => {
expect(() => {
(window.history.go as any)({ toString: null });
}).to.throw('Cannot convert object to primitive value');
});
});
});
describe('console functions', () => {
itremote('should exist', () => {
expect(console.log, 'log').to.be.a('function');
expect(console.error, 'error').to.be.a('function');
expect(console.warn, 'warn').to.be.a('function');
expect(console.info, 'info').to.be.a('function');
expect(console.debug, 'debug').to.be.a('function');
expect(console.trace, 'trace').to.be.a('function');
expect(console.time, 'time').to.be.a('function');
expect(console.timeEnd, 'timeEnd').to.be.a('function');
});
});
// FIXME(nornagon): this is broken on CI, it triggers:
// [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
// trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
// (null text in SpeechSynthesisUtterance struct).
describe('SpeechSynthesis', () => {
itremote('should emit lifecycle events', async () => {
const sentence = `long sentence which will take at least a few seconds to
utter so that it's possible to pause and resume before the end`;
const utter = new SpeechSynthesisUtterance(sentence);
// Create a dummy utterance so that speech synthesis state
// is initialized for later calls.
speechSynthesis.speak(new SpeechSynthesisUtterance());
speechSynthesis.cancel();
speechSynthesis.speak(utter);
// paused state after speak()
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onstart = resolve; });
// paused state after start event
expect(speechSynthesis.paused).to.be.false();
speechSynthesis.pause();
// paused state changes async, right before the pause event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onpause = resolve; });
expect(speechSynthesis.paused).to.be.true();
speechSynthesis.resume();
await new Promise((resolve) => { utter.onresume = resolve; });
// paused state after resume event
expect(speechSynthesis.paused).to.be.false();
await new Promise((resolve) => { utter.onend = resolve; });
});
});
});
describe('font fallback', () => {
async function getRenderedFonts (html: string) {
const w = new BrowserWindow({ show: false });
try {
await w.loadURL(`data:text/html,${html}`);
w.webContents.debugger.attach();
const sendCommand = (method: string, commandParams?: any) => w.webContents.debugger.sendCommand(method, commandParams);
const { nodeId } = (await sendCommand('DOM.getDocument')).root.children[0];
await sendCommand('CSS.enable');
const { fonts } = await sendCommand('CSS.getPlatformFontsForNode', { nodeId });
return fonts;
} finally {
w.close();
}
}
it('should use Helvetica for sans-serif on Mac, and Arial on Windows and Linux', async () => {
const html = '<body style="font-family: sans-serif">test</body>';
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') {
expect(fonts[0].familyName).to.equal('Arial');
} else if (process.platform === 'darwin') {
expect(fonts[0].familyName).to.equal('Helvetica');
} else if (process.platform === 'linux') {
expect(fonts[0].familyName).to.equal('DejaVu Sans');
} // I think this depends on the distro? We don't specify a default.
});
ifit(process.platform !== 'linux')('should fall back to Japanese font for sans-serif Japanese script', async function () {
const html = `
<html lang="ja-JP">
<head>
<meta charset="utf-8" />
</head>
<body style="font-family: sans-serif">test 智史</body>
</html>
`;
const fonts = await getRenderedFonts(html);
expect(fonts).to.be.an('array');
expect(fonts).to.have.length(1);
if (process.platform === 'win32') { expect(fonts[0].familyName).to.be.oneOf(['Meiryo', 'Yu Gothic']); } else if (process.platform === 'darwin') { expect(fonts[0].familyName).to.equal('Hiragino Kaku Gothic ProN'); }
});
});
describe('iframe using HTML fullscreen API while window is OS-fullscreened', () => {
const fullscreenChildHtml = promisify(fs.readFile)(
path.join(fixturesPath, 'pages', 'fullscreen-oopif.html')
);
let w: BrowserWindow;
let server: http.Server;
let crossSiteUrl: string;
beforeEach(async () => {
server = http.createServer(async (_req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(await fullscreenChildHtml);
res.end();
});
const serverUrl = (await listen(server)).url;
crossSiteUrl = serverUrl.replace('127.0.0.1', 'localhost');
w = new BrowserWindow({
show: true,
fullscreen: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
contextIsolation: false
}
});
});
afterEach(async () => {
await closeAllWindows();
(w as any) = null;
server.close();
});
ifit(process.platform !== 'darwin')('can fullscreen from out-of-process iframes (non-macOS)', async () => {
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await setTimeout(500);
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
ifit(process.platform === 'darwin')('can fullscreen from out-of-process iframes (macOS)', async () => {
await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
const html =
`<iframe style="width: 0" frameborder=0 src="${crossSiteUrl}" allowfullscreen></iframe>`;
w.loadURL(`data:text/html,${html}`);
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.be.true();
await w.webContents.executeJavaScript(
"document.querySelector('iframe').contentWindow.postMessage('exitFullscreen', '*')"
);
await once(w.webContents, 'leave-html-full-screen');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
w.setFullScreen(false);
await once(w, 'leave-full-screen');
});
// TODO(jkleinsc) fix this flaky test on WOA
ifit(process.platform !== 'win32' || process.arch !== 'arm64')('can fullscreen from in-process iframes', async () => {
if (process.platform === 'darwin') await once(w, 'enter-full-screen');
const fullscreenChange = once(ipcMain, 'fullscreenChange');
w.loadFile(path.join(fixturesPath, 'pages', 'fullscreen-ipif.html'));
await fullscreenChange;
const fullscreenWidth = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(fullscreenWidth > 0).to.true();
await w.webContents.executeJavaScript('document.exitFullscreen()');
const width = await w.webContents.executeJavaScript(
"document.querySelector('iframe').offsetWidth"
);
expect(width).to.equal(0);
});
});
describe('navigator.serial', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const getPorts: any = () => {
return w.webContents.executeJavaScript(`
navigator.serial.requestPort().then(port => port.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestPort\' on \'Serial\': No port selected by the user.';
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.removeAllListeners('select-serial-port');
});
it('does not return a port if select-serial-port event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not return a port when permission denied', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback(portList[0].portId);
});
session.defaultSession.setPermissionCheckHandler(() => false);
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('does not crash when select-serial-port is called with an invalid port', async () => {
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
callback('i-do-not-exist');
});
const port = await getPorts();
expect(port).to.equal(notFoundError);
});
it('returns a port when select-serial-port event is defined', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
const port = await getPorts();
if (havePorts) {
expect(port).to.equal('[object SerialPort]');
} else {
expect(port).to.equal(notFoundError);
}
});
it('navigator.serial.getPorts() returns values', async () => {
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts).to.not.be.empty();
}
});
it('supports port.forget()', async () => {
let forgottenPortFromEvent = {};
let havePorts = false;
w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
if (portList.length > 0) {
havePorts = true;
callback(portList[0].portId);
} else {
callback('');
}
});
w.webContents.session.on('serial-port-revoked', (event, details) => {
forgottenPortFromEvent = details.port;
});
await getPorts();
if (havePorts) {
const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
if (grantedPorts.length > 0) {
const forgottenPort = await w.webContents.executeJavaScript(`
navigator.serial.getPorts().then(async(ports) => {
const portInfo = await ports[0].getInfo();
await ports[0].forget();
if (portInfo.usbVendorId && portInfo.usbProductId) {
return {
vendorId: '' + portInfo.usbVendorId,
productId: '' + portInfo.usbProductId
}
} else {
return {};
}
})
`);
const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()');
expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length);
if (forgottenPort.vendorId && forgottenPort.productId) {
expect(forgottenPortFromEvent).to.include(forgottenPort);
}
}
}
});
});
describe('window.getScreenDetails', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
const getScreenDetails: any = () => {
return w.webContents.executeJavaScript('window.getScreenDetails().then(data => data.screens).catch(err => err.message)', true);
};
it('returns screens when a PermissionRequestHandler is not defined', async () => {
const screens = await getScreenDetails();
expect(screens).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(false);
} else {
callback(true);
}
});
const screens = await getScreenDetails();
expect(screens).to.equal('Permission denied.');
});
it('returns screens when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'window-management') {
callback(true);
} else {
callback(false);
}
});
const screens = await getScreenDetails();
expect(screens).to.not.equal('Permission denied.');
});
});
describe('navigator.clipboard.read', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const readClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.read().then(clipboard => clipboard.toString()).catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.equal('Read permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-read') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await readClipboard();
expect(clipboard).to.not.equal('Read permission denied.');
});
});
describe('navigator.clipboard.write', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow();
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
const writeClipboard: any = () => {
return w.webContents.executeJavaScript(`
navigator.clipboard.writeText('Hello World!').catch(err => err.message);
`, true);
};
after(closeAllWindows);
afterEach(() => {
session.defaultSession.setPermissionRequestHandler(null);
});
it('returns clipboard contents when a PermissionRequestHandler is not defined', async () => {
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
it('returns an error when permission denied', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(false);
} else {
callback(true);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.equal('Write permission denied.');
});
it('returns clipboard contents when permission is granted', async () => {
session.defaultSession.setPermissionRequestHandler((wc, permission, callback) => {
if (permission === 'clipboard-sanitized-write') {
callback(true);
} else {
callback(false);
}
});
const clipboard = await writeClipboard();
expect(clipboard).to.not.equal('Write permission denied.');
});
});
ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
let w: BrowserWindow;
const expectedBadgeCount = 42;
const fireAppBadgeAction: any = (action: string, value: any) => {
return w.webContents.executeJavaScript(`
navigator.${action}AppBadge(${value}).then(() => 'success').catch(err => err.message)`);
};
// For some reason on macOS changing the badge count doesn't happen right away, so wait
// until it changes.
async function waitForBadgeCount (value: number) {
let badgeCount = app.getBadgeCount();
while (badgeCount !== value) {
await setTimeout(10);
badgeCount = app.getBadgeCount();
}
return badgeCount;
}
describe('in the renderer', () => {
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can set a numerical value', async () => {
const result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
});
it('setAppBadge can set an empty(dot) value', async () => {
const result = await fireAppBadgeAction('set');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
it('clearAppBadge can clear a value', async () => {
let result = await fireAppBadgeAction('set', expectedBadgeCount);
expect(result).to.equal('success');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
result = await fireAppBadgeAction('clear');
expect(result).to.equal('success');
expect(waitForBadgeCount(0)).to.eventually.equal(0);
});
});
describe('in a service worker', () => {
beforeEach(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'sw-file-scheme-spec',
contextIsolation: false
}
});
});
afterEach(() => {
app.badgeCount = 0;
closeAllWindows();
});
it('setAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?setBadge' });
});
it('clearAppBadge can be called in a ServiceWorker', (done) => {
w.webContents.on('ipc-message', (event, channel, message) => {
if (channel === 'reload') {
w.webContents.reload();
} else if (channel === 'setAppBadge') {
expect(message).to.equal('SUCCESS setting app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
} else if (channel === 'error') {
done(message);
} else if (channel === 'response') {
expect(message).to.equal('SUCCESS clearing app badge');
expect(waitForBadgeCount(expectedBadgeCount)).to.eventually.equal(expectedBadgeCount);
session.fromPartition('sw-file-scheme-spec').clearStorageData({
storages: ['serviceworkers']
}).then(() => done());
}
});
w.webContents.on('render-process-gone', () => done(new Error('WebContents crashed.')));
w.loadFile(path.join(fixturesPath, 'pages', 'service-worker', 'badge-index.html'), { search: '?clearBadge' });
});
});
});
describe('navigator.bluetooth', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
show: false,
webPreferences: {
enableBlinkFeatures: 'WebBluetooth'
}
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
});
after(closeAllWindows);
it('can request bluetooth devices', async () => {
const bluetooth = await w.webContents.executeJavaScript(`
navigator.bluetooth.requestDevice({ acceptAllDevices: true}).then(device => "Found a device!").catch(err => err.message);`, true);
expect(bluetooth).to.be.oneOf(['Found a device!', 'Bluetooth adapter not available.', 'User cancelled the requestDevice() chooser.']);
});
});
describe('navigator.hid', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-hid-device');
});
it('does not return a device if select-hid-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal('');
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal('');
});
it('returns a device when select-hid-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
} else {
expect(device).to.equal('');
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.hid.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object HIDDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal('');
}
});
it('excludes a device when a exclusionFilter is specified', async () => {
const exclusionFilters = <any>[];
let haveDevices = false;
let checkForExcludedDevice = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
details.deviceList.find((device) => {
if (device.name && device.name !== '' && device.serialNumber && device.serialNumber !== '') {
if (checkForExcludedDevice) {
const compareDevice = {
vendorId: device.vendorId,
productId: device.productId
};
expect(compareDevice).to.not.equal(exclusionFilters[0], 'excluded device should not be returned');
} else {
haveDevices = true;
exclusionFilters.push({
vendorId: device.vendorId,
productId: device.productId
});
return true;
}
}
});
}
callback();
});
await requestDevices();
if (haveDevices) {
// We have devices to exclude, so check if exclusionFilters work
checkForExcludedDevice = true;
await w.webContents.executeJavaScript(`
navigator.hid.requestDevice({filters: [], exclusionFilters: ${JSON.stringify(exclusionFilters)}}).then(device => device.toString()).catch(err => err.toString());
`, true);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-hid-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('hid-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice = await w.webContents.executeJavaScript(`
navigator.hid.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
name: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.hid.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
describe('navigator.usb', () => {
let w: BrowserWindow;
let server: http.Server;
let serverUrl: string;
before(async () => {
w = new BrowserWindow({
show: false
});
await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('<body>');
});
serverUrl = (await listen(server)).url;
});
const requestDevices: any = () => {
return w.webContents.executeJavaScript(`
navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
`, true);
};
const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
after(() => {
server.close();
closeAllWindows();
});
afterEach(() => {
session.defaultSession.setPermissionCheckHandler(null);
session.defaultSession.setDevicePermissionHandler(null);
session.defaultSession.removeAllListeners('select-usb-device');
});
it('does not return a device if select-usb-device event is not defined', async () => {
w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
const device = await requestDevices();
expect(device).to.equal(notFoundError);
});
it('does not return a device when permission denied', async () => {
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
callback();
});
session.defaultSession.setPermissionCheckHandler(() => false);
const device = await requestDevices();
expect(selectFired).to.be.false();
expect(device).to.equal(notFoundError);
});
it('returns a device when select-usb-device event is defined', async () => {
let haveDevices = false;
let selectFired = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
expect(details.frame).to.have.property('frameTreeNodeId').that.is.a('number');
selectFired = true;
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
} else {
expect(device).to.equal(notFoundError);
}
if (haveDevices) {
// Verify that navigation will clear device permissions
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices).to.not.be.empty();
w.loadURL(serverUrl);
const [,,,,, frameProcessId, frameRoutingId] = await once(w.webContents, 'did-frame-navigate');
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(!!frame).to.be.true();
if (frame) {
const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevicesOnNewPage).to.be.empty();
}
}
});
it('returns a device when DevicePermissionHandler is defined', async () => {
let haveDevices = false;
let selectFired = false;
let gotDevicePerms = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
selectFired = true;
if (details.deviceList.length > 0) {
const foundDevice = details.deviceList.find((device) => {
if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
haveDevices = true;
return true;
}
});
if (foundDevice) {
callback(foundDevice.deviceId);
return;
}
}
callback();
});
session.defaultSession.setDevicePermissionHandler(() => {
gotDevicePerms = true;
return true;
});
await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
const device = await requestDevices();
expect(selectFired).to.be.true();
if (haveDevices) {
expect(device).to.contain('[object USBDevice]');
expect(gotDevicePerms).to.be.true();
} else {
expect(device).to.equal(notFoundError);
}
});
it('supports device.forget()', async () => {
let deletedDeviceFromEvent;
let haveDevices = false;
w.webContents.session.on('select-usb-device', (event, details, callback) => {
if (details.deviceList.length > 0) {
haveDevices = true;
callback(details.deviceList[0].deviceId);
} else {
callback();
}
});
w.webContents.session.on('usb-device-revoked', (event, details) => {
deletedDeviceFromEvent = details.device;
});
await requestDevices();
if (haveDevices) {
const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
if (grantedDevices.length > 0) {
const deletedDevice: Electron.USBDevice = await w.webContents.executeJavaScript(`
navigator.usb.getDevices().then(devices => {
devices[0].forget();
return {
vendorId: devices[0].vendorId,
productId: devices[0].productId,
productName: devices[0].productName
}
})
`);
const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
if (deletedDevice.productName !== '' && deletedDevice.productId && deletedDevice.vendorId) {
expect(deletedDeviceFromEvent).to.include(deletedDevice);
}
}
}
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
patches/chromium/.patches
|
build_gn.patch
dcheck.patch
accelerator.patch
blink_file_path.patch
blink_local_frame.patch
can_create_window.patch
disable_hidden.patch
dom_storage_limits.patch
render_widget_host_view_base.patch
render_widget_host_view_mac.patch
webview_cross_drag.patch
gin_enable_disable_v8_platform.patch
enable_reset_aspect_ratio.patch
boringssl_build_gn.patch
pepper_plugin_support.patch
gtk_visibility.patch
sysroot.patch
resource_file_conflict.patch
scroll_bounce_flag.patch
mas_blink_no_private_api.patch
mas_no_private_api.patch
mas-cgdisplayusesforcetogray.patch
mas_disable_remote_layer.patch
mas_disable_remote_accessibility.patch
mas_disable_custom_window_frame.patch
mas_avoid_usage_of_private_macos_apis.patch
mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch
add_didinstallconditionalfeatures.patch
desktop_media_list.patch
proxy_config_monitor.patch
gritsettings_resource_ids.patch
isolate_holder.patch
notification_provenance.patch
dump_syms.patch
command-ismediakey.patch
printing.patch
support_mixed_sandbox_with_zygote.patch
unsandboxed_ppapi_processes_skip_zygote.patch
build_add_electron_tracing_category.patch
worker_context_will_destroy.patch
frame_host_manager.patch
crashpad_pid_check.patch
network_service_allow_remote_certificate_verification_logic.patch
disable_color_correct_rendering.patch
add_contentgpuclient_precreatemessageloop_callback.patch
picture-in-picture.patch
disable_compositor_recycling.patch
allow_new_privileges_in_unsandboxed_child_processes.patch
expose_setuseragent_on_networkcontext.patch
feat_add_set_theme_source_to_allow_apps_to.patch
add_webmessageportconverter_entangleandinjectmessageportchannel.patch
ignore_rc_check.patch
remove_usage_of_incognito_apis_in_the_spellchecker.patch
allow_disabling_blink_scheduler_throttling_per_renderview.patch
hack_plugin_response_interceptor_to_point_to_electron.patch
feat_add_support_for_overriding_the_base_spellchecker_download_url.patch
feat_enable_offscreen_rendering_with_viz_compositor.patch
gpu_notify_when_dxdiag_request_fails.patch
feat_allow_embedders_to_add_observers_on_created_hunspell.patch
feat_add_onclose_to_messageport.patch
allow_in-process_windows_to_have_different_web_prefs.patch
refactor_expose_cursor_changes_to_the_webcontentsobserver.patch
crash_allow_setting_more_options.patch
upload_list_add_loadsync_method.patch
allow_setting_secondary_label_via_simplemenumodel.patch
feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch
fix_patch_out_profile_refs_in_accessibility_ui.patch
skip_atk_toolchain_check.patch
worker_feat_add_hook_to_notify_script_ready.patch
chore_provide_iswebcontentscreationoverridden_with_full_params.patch
fix_properly_honor_printing_page_ranges.patch
export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch
fix_export_zlib_symbols.patch
web_contents.patch
webview_fullscreen.patch
disable_unload_metrics.patch
fix_add_check_for_sandbox_then_result.patch
extend_apply_webpreferences.patch
build_libc_as_static_library.patch
build_do_not_depend_on_packed_resource_integrity.patch
refactor_restore_base_adaptcallbackforrepeating.patch
hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch
logging_win32_only_create_a_console_if_logging_to_stderr.patch
fix_media_key_usage_with_globalshortcuts.patch
feat_expose_raw_response_headers_from_urlloader.patch
process_singleton.patch
add_ui_scopedcliboardwriter_writeunsaferawdata.patch
feat_add_data_parameter_to_processsingleton.patch
load_v8_snapshot_in_browser_process.patch
fix_adapt_exclusive_access_for_electron_needs.patch
fix_aspect_ratio_with_max_size.patch
fix_dont_delete_SerialPortManager_on_main_thread.patch
fix_crash_when_saving_edited_pdf_files.patch
port_autofill_colors_to_the_color_pipeline.patch
build_disable_partition_alloc_on_mac.patch
fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch
build_make_libcxx_abi_unstable_false_for_electron.patch
introduce_ozoneplatform_electron_can_call_x11_property.patch
make_gtk_getlibgtk_public.patch
build_disable_print_content_analysis.patch
custom_protocols_plzserviceworker.patch
feat_filter_out_non-shareable_windows_in_the_current_application_in.patch
fix_allow_guest_webcontents_to_enter_fullscreen.patch
disable_freezing_flags_after_init_in_node.patch
short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch
chore_add_electron_deps_to_gitignores.patch
chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
add_maximized_parameter_to_linuxui_getwindowframeprovider.patch
add_electron_deps_to_license_credits_file.patch
fix_crash_loading_non-standard_schemes_in_iframes.patch
create_browser_v8_snapshot_file_name_fuse.patch
feat_configure_launch_options_for_service_process.patch
feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch
fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch
preconnect_manager.patch
fix_remove_caption-removing_style_call.patch
build_allow_electron_to_use_exec_script.patch
build_only_use_the_mas_build_config_in_the_required_components.patch
fix_tray_icon_gone_on_lock_screen.patch
chore_introduce_blocking_api_for_electron.patch
chore_patch_out_partition_attribute_dcheck_for_webviews.patch
expose_v8initializer_codegenerationcheckcallbackinmainthread.patch
chore_patch_out_profile_methods_in_profile_selections_cc.patch
add_gin_converter_support_for_arraybufferview.patch
chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
fix_remove_profiles_from_spellcheck_service.patch
chore_patch_out_profile_methods_in_chrome_browser_pdf.patch
chore_patch_out_profile_methods_in_titlebar_config.patch
fix_crash_on_nativetheme_change_during_context_menu_close.patch
fix_select_the_first_menu_item_when_opened_via_keyboard.patch
fix_return_v8_value_from_localframe_requestexecutescript.patch
revert_simplify_dwm_transitions_on_windows.patch
fix_harden_blink_scriptstate_maybefrom.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
patches/chromium/revert_simplify_dwm_transitions_on_windows.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: deepak1556 <[email protected]>
Date: Tue, 27 Jun 2023 22:05:17 +0900
Subject: Revert "Simplify DWM transitions on Windows"
This reverts commit 392e5f43aae8d225a118145cbc5f5bb104cbe541.
Can be removed once https://github.com/electron/electron/issues/38937 is resolved.
diff --git a/chrome/app/chrome_command_ids.h b/chrome/app/chrome_command_ids.h
index 15f4aac24744228c0e74ec521c18eb6ab5f59c5b..b9a71c9063d8ee573424a9161cc127af169944a9 100644
--- a/chrome/app/chrome_command_ids.h
+++ b/chrome/app/chrome_command_ids.h
@@ -59,6 +59,7 @@
#define IDC_MOVE_TAB_NEXT 34032
#define IDC_MOVE_TAB_PREVIOUS 34033
#define IDC_SEARCH 34035
+#define IDC_DEBUG_FRAME_TOGGLE 34038
#define IDC_WINDOW_MENU 34045
#define IDC_MINIMIZE_WINDOW 34046
#define IDC_MAXIMIZE_WINDOW 34047
diff --git a/chrome/browser/ui/browser_command_controller.cc b/chrome/browser/ui/browser_command_controller.cc
index b198e41661d459302ddccfab70ac3de8cd2c48b5..405c0ac7c41ef4cb6a8804c8a34a7328d796d7bd 100644
--- a/chrome/browser/ui/browser_command_controller.cc
+++ b/chrome/browser/ui/browser_command_controller.cc
@@ -1184,6 +1184,7 @@ void BrowserCommandController::InitCommandState() {
IDC_DUPLICATE_TAB, !browser_->is_type_picture_in_picture());
UpdateTabRestoreCommandState();
command_updater_.UpdateCommandEnabled(IDC_EXIT, true);
+ command_updater_.UpdateCommandEnabled(IDC_DEBUG_FRAME_TOGGLE, true);
command_updater_.UpdateCommandEnabled(IDC_NAME_WINDOW, true);
#if BUILDFLAG(IS_CHROMEOS)
command_updater_.UpdateCommandEnabled(
diff --git a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc
index fa718692b769c3bbcf83f700718cf88dc631d058..c8ed066b698ab08d5cfbc644ca1f66f23c0fbeec 100644
--- a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc
+++ b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc
@@ -397,6 +397,13 @@ void BrowserDesktopWindowTreeHostWin::HandleDestroying() {
DesktopWindowTreeHostWin::HandleDestroying();
}
+void BrowserDesktopWindowTreeHostWin::HandleFrameChanged() {
+ // Reinitialize the status bubble, since it needs to be initialized
+ // differently depending on whether or not DWM composition is enabled
+ browser_view_->InitStatusBubble();
+ DesktopWindowTreeHostWin::HandleFrameChanged();
+}
+
void BrowserDesktopWindowTreeHostWin::HandleWindowScaleFactorChanged(
float window_scale_factor) {
DesktopWindowTreeHostWin::HandleWindowScaleFactorChanged(window_scale_factor);
diff --git a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h
index 28412d00adf463a1453aecc82ca1179f0521822d..a3bd2e0cae1d341adfe9dd498886ae5914e1cba7 100644
--- a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h
+++ b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h
@@ -66,6 +66,7 @@ class BrowserDesktopWindowTreeHostWin
bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override;
void HandleCreate() override;
void HandleDestroying() override;
+ void HandleFrameChanged() override;
void HandleWindowScaleFactorChanged(float window_scale_factor) override;
bool PreHandleMSG(UINT message,
WPARAM w_param,
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc
index 6920106ba91e0d1c0c1706a28b4ce5a14b5f3aed..306affc1d9573acd475d79f30a3583f0e716f33e 100644
--- a/chrome/browser/ui/views/frame/browser_view.cc
+++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -927,8 +927,7 @@ BrowserView::BrowserView(std::unique_ptr<Browser> browser)
infobar_container_ =
AddChildView(std::make_unique<InfoBarContainerView>(this));
- status_bubble_ = std::make_unique<StatusBubbleViews>(contents_web_view_);
- contents_web_view_->SetStatusBubble(status_bubble_.get());
+ InitStatusBubble();
// Create do-nothing view for the sake of controlling the z-order of the find
// bar widget.
@@ -1049,6 +1048,11 @@ void BrowserView::SetDisableRevealerDelayForTesting(bool disable) {
g_disable_revealer_delay_for_testing = disable;
}
+void BrowserView::InitStatusBubble() {
+ status_bubble_ = std::make_unique<StatusBubbleViews>(contents_web_view_);
+ contents_web_view_->SetStatusBubble(status_bubble_.get());
+}
+
gfx::Rect BrowserView::GetFindBarBoundingBox() const {
gfx::Rect contents_bounds = contents_container_->ConvertRectToWidget(
contents_container_->GetLocalBounds());
@@ -3397,6 +3401,11 @@ ui::ImageModel BrowserView::GetWindowIcon() {
}
bool BrowserView::ExecuteWindowsCommand(int command_id) {
+ // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
+#if BUILDFLAG(IS_WIN)
+ if (command_id == IDC_DEBUG_FRAME_TOGGLE)
+ GetWidget()->DebugToggleFrameType();
+#endif
// Translate WM_APPCOMMAND command ids into a command id that the browser
// knows how to handle.
int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h
index d80a6df7380e5aec6ecba092315c905a09d7e2cc..bde91001c6f75f9918b9063eb0eaff5d56ea06c1 100644
--- a/chrome/browser/ui/views/frame/browser_view.h
+++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -164,6 +164,12 @@ class BrowserView : public BrowserWindow,
void SetDownloadShelfForTest(DownloadShelf* download_shelf);
+ // Initializes (or re-initializes) the status bubble. We try to only create
+ // the bubble once and re-use it for the life of the browser, but certain
+ // events (such as changing enabling/disabling Aero on Win) can force a need
+ // to change some of the bubble's creation parameters.
+ void InitStatusBubble();
+
// Returns the constraining bounding box that should be used to lay out the
// FindBar within. This is _not_ the size of the find bar, just the bounding
// box it should be laid out within. The coordinate system of the returned
diff --git a/chrome/browser/ui/views/frame/system_menu_model_builder.cc b/chrome/browser/ui/views/frame/system_menu_model_builder.cc
index 984929bb899dbd791443bf3ccd841f5a975a7dbd..75719ef6280ce46c176cb3277e602a11d99a45e0 100644
--- a/chrome/browser/ui/views/frame/system_menu_model_builder.cc
+++ b/chrome/browser/ui/views/frame/system_menu_model_builder.cc
@@ -69,6 +69,7 @@ void SystemMenuModelBuilder::BuildMenu(ui::SimpleMenuModel* model) {
BuildSystemMenuForBrowserWindow(model);
else
BuildSystemMenuForAppOrPopupWindow(model);
+ AddFrameToggleItems(model);
}
void SystemMenuModelBuilder::BuildSystemMenuForBrowserWindow(
@@ -157,6 +158,14 @@ void SystemMenuModelBuilder::BuildSystemMenuForAppOrPopupWindow(
AppendTeleportMenu(model);
}
+void SystemMenuModelBuilder::AddFrameToggleItems(ui::SimpleMenuModel* model) {
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kDebugEnableFrameToggle)) {
+ model->AddSeparator(ui::NORMAL_SEPARATOR);
+ model->AddItem(IDC_DEBUG_FRAME_TOGGLE, u"Toggle Frame Type");
+ }
+}
+
#if BUILDFLAG(IS_CHROMEOS)
void SystemMenuModelBuilder::AppendMoveToDesksMenu(ui::SimpleMenuModel* model) {
gfx::NativeWindow window =
diff --git a/chrome/browser/ui/views/frame/system_menu_model_builder.h b/chrome/browser/ui/views/frame/system_menu_model_builder.h
index 8f69eab1fc2b9c81d14f7b547b4f434c722b98aa..8acaa2816a03f41b19ec364eea2658682737798c 100644
--- a/chrome/browser/ui/views/frame/system_menu_model_builder.h
+++ b/chrome/browser/ui/views/frame/system_menu_model_builder.h
@@ -47,6 +47,9 @@ class SystemMenuModelBuilder {
void BuildSystemMenuForBrowserWindow(ui::SimpleMenuModel* model);
void BuildSystemMenuForAppOrPopupWindow(ui::SimpleMenuModel* model);
+ // Adds items for toggling the frame type (if necessary).
+ void AddFrameToggleItems(ui::SimpleMenuModel* model);
+
#if BUILDFLAG(IS_CHROMEOS)
// Add the submenu for move to desks.
void AppendMoveToDesksMenu(ui::SimpleMenuModel* model);
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc
index b23fbffea35f1f9936b998bbe501c9e5acdecf6a..4d635764d6c5db0b493aba9d3b2add095fc9ebe4 100644
--- a/chrome/common/chrome_switches.cc
+++ b/chrome/common/chrome_switches.cc
@@ -143,6 +143,10 @@ const char kCredits[] = "credits";
// devtools://devtools/bundled/<path>
const char kCustomDevtoolsFrontend[] = "custom-devtools-frontend";
+// Enables a frame context menu item that toggles the frame in and out of glass
+// mode (Windows Vista and up only).
+const char kDebugEnableFrameToggle[] = "debug-enable-frame-toggle";
+
// Adds debugging entries such as Inspect Element to context menus of packed
// apps.
const char kDebugPackedApps[] = "debug-packed-apps";
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h
index be1f7824d85a6705aa8c220578ac62f0d1a4114e..7ce3dd85d1cab1fbd5aff6104ea0d1b864ebcb0c 100644
--- a/chrome/common/chrome_switches.h
+++ b/chrome/common/chrome_switches.h
@@ -61,6 +61,7 @@ extern const char kCrashOnHangThreads[];
extern const char kCreateBrowserOnStartupForTests[];
extern const char kCredits[];
extern const char kCustomDevtoolsFrontend[];
+extern const char kDebugEnableFrameToggle[];
extern const char kDebugPackedApps[];
extern const char kDevToolsFlags[];
extern const char kDiagnostics[];
diff --git a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
index d0dc2b4993891837c6ac76e095833126db461032..ba1bcbc63475b7151e2335c9237124ca8ca31dc7 100644
--- a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
+++ b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
@@ -136,6 +136,30 @@ TEST_F(DesktopNativeWidgetAuraTest, WidgetNotVisibleOnlyWindowTreeHostShown) {
}
#endif
+TEST_F(DesktopNativeWidgetAuraTest, DesktopAuraWindowShowFrameless) {
+ Widget widget;
+ Widget::InitParams init_params =
+ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
+ init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
+ widget.Init(std::move(init_params));
+
+ // Make sure that changing frame type doesn't crash when there's no non-client
+ // view.
+ ASSERT_EQ(nullptr, widget.non_client_view());
+ widget.DebugToggleFrameType();
+ widget.Show();
+
+#if BUILDFLAG(IS_WIN)
+ // On Windows also make sure that handling WM_SYSCOMMAND doesn't crash with
+ // custom frame. Frame type needs to be toggled again if Aero Glass is
+ // disabled.
+ if (widget.ShouldUseNativeFrame())
+ widget.DebugToggleFrameType();
+ SendMessage(widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget(),
+ WM_SYSCOMMAND, SC_RESTORE, 0);
+#endif // BUILDFLAG(IS_WIN)
+}
+
#if BUILDFLAG(IS_CHROMEOS_ASH)
// TODO(crbug.com/916272): investigate fixing and enabling on Chrome OS.
#define MAYBE_GlobalCursorState DISABLED_GlobalCursorState
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc
index 73e76c0d940f09336bbec6db47f1afee5153ced0..61673ac08ca19816dc01c89b6687f5b2a7c289e2 100644
--- a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc
+++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc
@@ -1028,6 +1028,8 @@ void DesktopWindowTreeHostWin::HandleClientSizeChanged(
}
void DesktopWindowTreeHostWin::HandleFrameChanged() {
+ CheckForMonitorChange();
+ desktop_native_widget_aura_->UpdateWindowTransparency();
// Replace the frame and layout the contents.
if (GetWidget()->non_client_view())
GetWidget()->non_client_view()->UpdateFrame();
diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc
index 2b52ad2f63bd6924fcd3d000bbb7ed6fd9f4b0dd..3d7a2f986c38de6b2e69722e63ee3b139d257756 100644
--- a/ui/views/widget/widget.cc
+++ b/ui/views/widget/widget.cc
@@ -1209,6 +1209,21 @@ bool Widget::ShouldWindowContentsBeTransparent() const {
: false;
}
+void Widget::DebugToggleFrameType() {
+ if (!native_widget_)
+ return;
+
+ if (frame_type_ == FrameType::kDefault) {
+ frame_type_ = ShouldUseNativeFrame() ? FrameType::kForceCustom
+ : FrameType::kForceNative;
+ } else {
+ frame_type_ = frame_type_ == FrameType::kForceCustom
+ ? FrameType::kForceNative
+ : FrameType::kForceCustom;
+ }
+ FrameTypeChanged();
+}
+
void Widget::FrameTypeChanged() {
if (native_widget_)
native_widget_->FrameTypeChanged();
diff --git a/ui/views/widget/widget.h b/ui/views/widget/widget.h
index 51017b6f5dd9a9d5f26723c7ec7a6e0404c93b65..54b9e676c9423b78184fc63b80299dd7529cbd28 100644
--- a/ui/views/widget/widget.h
+++ b/ui/views/widget/widget.h
@@ -922,6 +922,10 @@ class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate,
// (for example, so that they can overhang onto the window title bar).
bool ShouldWindowContentsBeTransparent() const;
+ // Forces the frame into the alternate frame type (custom or native) depending
+ // on its current state.
+ void DebugToggleFrameType();
+
// Tell the window that something caused the frame type to change.
void FrameTypeChanged();
diff --git a/ui/views/widget/widget_unittest.cc b/ui/views/widget/widget_unittest.cc
index 9aced70287c3ac877310457c1aad3b2544a85800..35f435d3d4d5eda44b69e5e66ec9480534d3ef44 100644
--- a/ui/views/widget/widget_unittest.cc
+++ b/ui/views/widget/widget_unittest.cc
@@ -1317,6 +1317,10 @@ TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Deactivate) {
widget()->Deactivate();
}
+TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, DebugToggleFrameType) {
+ widget()->DebugToggleFrameType();
+}
+
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, DraggedView) {
widget()->dragged_view();
}
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc
index 575877b4fb0929d0cdd22af399f7078fcd713584..90dd6487fdf438a61672a81f08b545742045944a 100644
--- a/ui/views/win/hwnd_message_handler.cc
+++ b/ui/views/win/hwnd_message_handler.cc
@@ -1741,6 +1741,20 @@ void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
}
}
+void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
+ if (IsFullscreen())
+ return;
+
+ DWMNCRENDERINGPOLICY policy =
+ custom_window_region_.is_valid() ||
+ delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN
+ ? DWMNCRP_DISABLED
+ : DWMNCRP_ENABLED;
+
+ DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY, &policy,
+ sizeof(DWMNCRENDERINGPOLICY));
+}
+
LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
WPARAM w_param,
LPARAM l_param) {
@@ -3607,10 +3621,34 @@ bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
}
void HWNDMessageHandler::PerformDwmTransition() {
- CHECK(IsFrameSystemDrawn());
-
dwm_transition_desired_ = false;
+
+ UpdateDwmNcRenderingPolicy();
+ // Don't redraw the window here, because we need to hide and show the window
+ // which will also trigger a redraw.
+ ResetWindowRegion(true, false);
+ // The non-client view needs to update too.
delegate_->HandleFrameChanged();
+ // This calls DwmExtendFrameIntoClientArea which must be called when DWM
+ // composition state changes.
+ UpdateDwmFrame();
+
+ if (IsVisible() && IsFrameSystemDrawn()) {
+ // For some reason, we need to hide the window after we change from a custom
+ // frame to a native frame. If we don't, the client area will be filled
+ // with black. This seems to be related to an interaction between DWM and
+ // SetWindowRgn, but the details aren't clear. Additionally, we need to
+ // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
+ // open they will re-appear with a non-deterministic Z-order.
+ // Note: caused http://crbug.com/895855, where a laptop lid close+reopen
+ // puts window in the background but acts like a foreground window. Fixed by
+ // not calling this unless DWM composition actually changes. Finally, since
+ // we don't want windows stealing focus if they're not already active, we
+ // set SWP_NOACTIVATE.
+ UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE;
+ SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
+ SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
+ }
}
void HWNDMessageHandler::UpdateDwmFrame() {
diff --git a/ui/views/win/hwnd_message_handler.h b/ui/views/win/hwnd_message_handler.h
index 7238af3f51179145a1c1eb9639ca756c2a697554..694945c4f3a62ed13a3b80cc5fba5673e29eef4e 100644
--- a/ui/views/win/hwnd_message_handler.h
+++ b/ui/views/win/hwnd_message_handler.h
@@ -324,6 +324,11 @@ class VIEWS_EXPORT HWNDMessageHandler : public gfx::WindowImpl,
// frame windows.
void ResetWindowRegion(bool force, bool redraw);
+ // Enables or disables rendering of the non-client (glass) area by DWM,
+ // under Vista and above, depending on whether the caller has requested a
+ // custom frame.
+ void UpdateDwmNcRenderingPolicy();
+
// Calls DefWindowProc, safely wrapping the call in a ScopedRedrawLock to
// prevent frame flicker. DefWindowProc handling can otherwise render the
// classic-look window title bar directly.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
shell/browser/native_window.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/containers/contains.h"
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_features.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/window_list.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/options_switches.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/widget.h"
#if !BUILDFLAG(IS_MAC)
#include "shell/browser/ui/views/frameless_view.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#endif
#if defined(USE_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace gin {
template <>
struct Converter<electron::NativeWindow::TitleBarStyle> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindow::TitleBarStyle* out) {
using TitleBarStyle = electron::NativeWindow::TitleBarStyle;
std::string title_bar_style;
if (!ConvertFromV8(isolate, val, &title_bar_style))
return false;
if (title_bar_style == "hidden") {
*out = TitleBarStyle::kHidden;
#if BUILDFLAG(IS_MAC)
} else if (title_bar_style == "hiddenInset") {
*out = TitleBarStyle::kHiddenInset;
} else if (title_bar_style == "customButtonsOnHover") {
*out = TitleBarStyle::kCustomButtonsOnHover;
#endif
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
#if BUILDFLAG(IS_WIN)
gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) {
if (!window->transparent())
return size;
gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize(
window->GetAcceleratedWidget(), gfx::Size(64, 64));
// Some AMD drivers can't display windows that are less than 64x64 pixels,
// so expand them to be at least that size. http://crbug.com/286609
gfx::Size expanded(std::max(size.width(), min_size.width()),
std::max(size.height(), min_size.height()));
return expanded;
}
#endif
} // namespace
NativeWindow::NativeWindow(const gin_helper::Dictionary& options,
NativeWindow* parent)
: widget_(std::make_unique<views::Widget>()), parent_(parent) {
++next_id_;
options.Get(options::kFrame, &has_frame_);
options.Get(options::kTransparent, &transparent_);
options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_);
options.Get(options::kTitleBarStyle, &title_bar_style_);
v8::Local<v8::Value> titlebar_overlay;
if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) {
if (titlebar_overlay->IsBoolean()) {
options.Get(options::ktitleBarOverlay, &titlebar_overlay_);
} else if (titlebar_overlay->IsObject()) {
titlebar_overlay_ = true;
gin_helper::Dictionary titlebar_overlay_dict =
gin::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict);
int height;
if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height))
titlebar_overlay_height_ = height;
#if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC))
DCHECK(false);
#endif
}
}
if (parent)
options.Get("modal", &is_modal_);
#if defined(USE_OZONE)
// Ozone X11 likes to prefer custom frames, but we don't need them unless
// on Wayland.
if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) &&
!ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_server_side_window_decorations) {
has_client_frame_ = true;
}
#endif
WindowList::AddWindow(this);
}
NativeWindow::~NativeWindow() {
// It's possible that the windows gets destroyed before it's closed, in that
// case we need to ensure the Widget delegate gets destroyed and
// OnWindowClosed message is still notified.
if (widget_->widget_delegate())
widget_->OnNativeWidgetDestroyed();
NotifyWindowClosed();
}
void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
// Setup window from options.
int x = -1, y = -1;
bool center;
if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) {
SetPosition(gfx::Point(x, y));
#if BUILDFLAG(IS_WIN)
// FIXME(felixrieseberg): Dirty, dirty workaround for
// https://github.com/electron/electron/issues/10862
// Somehow, we need to call `SetBounds` twice to get
// usable results. The root cause is still unknown.
SetPosition(gfx::Point(x, y));
#endif
} else if (options.Get(options::kCenter, ¢er) && center) {
Center();
}
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
// On Linux and Window we may already have maximum size defined.
extensions::SizeConstraints size_constraints(
use_content_size ? GetContentSizeConstraints() : GetSizeConstraints());
int min_width = size_constraints.GetMinimumSize().width();
int min_height = size_constraints.GetMinimumSize().height();
options.Get(options::kMinWidth, &min_width);
options.Get(options::kMinHeight, &min_height);
size_constraints.set_minimum_size(gfx::Size(min_width, min_height));
gfx::Size max_size = size_constraints.GetMaximumSize();
int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX;
int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX;
bool have_max_width = options.Get(options::kMaxWidth, &max_width);
if (have_max_width && max_width <= 0)
max_width = INT_MAX;
bool have_max_height = options.Get(options::kMaxHeight, &max_height);
if (have_max_height && max_height <= 0)
max_height = INT_MAX;
// By default the window has a default maximum size that prevents it
// from being resized larger than the screen, so we should only set this
// if the user has passed in values.
if (have_max_height || have_max_width || !max_size.IsEmpty())
size_constraints.set_maximum_size(gfx::Size(max_width, max_height));
if (use_content_size) {
SetContentSizeConstraints(size_constraints);
} else {
SetSizeConstraints(size_constraints);
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
bool closable;
if (options.Get(options::kClosable, &closable)) {
SetClosable(closable);
}
#endif
bool movable;
if (options.Get(options::kMovable, &movable)) {
SetMovable(movable);
}
bool has_shadow;
if (options.Get(options::kHasShadow, &has_shadow)) {
SetHasShadow(has_shadow);
}
double opacity;
if (options.Get(options::kOpacity, &opacity)) {
SetOpacity(opacity);
}
bool top;
if (options.Get(options::kAlwaysOnTop, &top) && top) {
SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow);
}
bool fullscreenable = true;
bool fullscreen = false;
if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) {
// Disable fullscreen button if 'fullscreen' is specified to false.
#if BUILDFLAG(IS_MAC)
fullscreenable = false;
#endif
}
// Overridden by 'fullscreenable'.
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen) {
SetFullScreen(true);
}
bool skip;
if (options.Get(options::kSkipTaskbar, &skip)) {
SetSkipTaskbar(skip);
}
bool kiosk;
if (options.Get(options::kKiosk, &kiosk) && kiosk) {
SetKiosk(kiosk);
}
#if BUILDFLAG(IS_MAC)
std::string type;
if (options.Get(options::kVibrancyType, &type)) {
SetVibrancy(type);
}
#elif BUILDFLAG(IS_WIN)
std::string material;
if (options.Get(options::kBackgroundMaterial, &material)) {
SetBackgroundMaterial(material);
}
#endif
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
SetBackgroundColor(ParseCSSColor(color));
} else if (!transparent()) {
// For normal window, use white as default background.
SetBackgroundColor(SK_ColorWHITE);
}
std::string title(Browser::Get()->GetName());
options.Get(options::kTitle, &title);
SetTitle(title);
// Then show it.
bool show = true;
options.Get(options::kShow, &show);
if (show)
Show();
}
bool NativeWindow::IsClosed() const {
return is_closed_;
}
void NativeWindow::SetSize(const gfx::Size& size, bool animate) {
SetBounds(gfx::Rect(GetPosition(), size), animate);
}
gfx::Size NativeWindow::GetSize() {
return GetBounds().size();
}
void NativeWindow::SetPosition(const gfx::Point& position, bool animate) {
SetBounds(gfx::Rect(position, GetSize()), animate);
}
gfx::Point NativeWindow::GetPosition() {
return GetBounds().origin();
}
void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) {
SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate);
}
gfx::Size NativeWindow::GetContentSize() {
return GetContentBounds().size();
}
void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) {
SetBounds(ContentBoundsToWindowBounds(bounds), animate);
}
gfx::Rect NativeWindow::GetContentBounds() {
return WindowBoundsToContentBounds(GetBounds());
}
bool NativeWindow::IsNormal() {
return !IsMinimized() && !IsMaximized() && !IsFullscreen();
}
void NativeWindow::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
extensions::SizeConstraints content_constraints(GetContentSizeConstraints());
if (window_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMaximumSize()));
content_constraints.set_maximum_size(max_bounds.size());
}
if (window_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMinimumSize()));
content_constraints.set_minimum_size(min_bounds.size());
}
SetContentSizeConstraints(content_constraints);
}
extensions::SizeConstraints NativeWindow::GetSizeConstraints() const {
extensions::SizeConstraints content_constraints = GetContentSizeConstraints();
extensions::SizeConstraints window_constraints;
if (content_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMaximumSize()));
window_constraints.set_maximum_size(max_bounds.size());
}
if (content_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMinimumSize()));
window_constraints.set_minimum_size(min_bounds.size());
}
return window_constraints;
}
void NativeWindow::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
size_constraints_ = size_constraints;
}
extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const {
return size_constraints_;
}
void NativeWindow::SetMinimumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_minimum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMinimumSize() const {
return GetSizeConstraints().GetMinimumSize();
}
void NativeWindow::SetMaximumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_maximum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMaximumSize() const {
return GetSizeConstraints().GetMaximumSize();
}
gfx::Size NativeWindow::GetContentMinimumSize() const {
return GetContentSizeConstraints().GetMinimumSize();
}
gfx::Size NativeWindow::GetContentMaximumSize() const {
gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize();
#if BUILDFLAG(IS_WIN)
return GetContentSizeConstraints().HasMaximumSize()
? GetExpandedWindowSize(this, maximum_size)
: maximum_size;
#else
return maximum_size;
#endif
}
void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) {
sheet_offset_x_ = offsetX;
sheet_offset_y_ = offsetY;
}
double NativeWindow::GetSheetOffsetX() {
return sheet_offset_x_;
}
double NativeWindow::GetSheetOffsetY() {
return sheet_offset_y_;
}
bool NativeWindow::IsTabletMode() const {
return false;
}
void NativeWindow::SetRepresentedFilename(const std::string& filename) {}
std::string NativeWindow::GetRepresentedFilename() {
return "";
}
void NativeWindow::SetDocumentEdited(bool edited) {}
bool NativeWindow::IsDocumentEdited() {
return false;
}
void NativeWindow::SetFocusable(bool focusable) {}
bool NativeWindow::IsFocusable() {
return false;
}
void NativeWindow::SetMenu(ElectronMenuModel* menu) {}
void NativeWindow::SetParentWindow(NativeWindow* parent) {
parent_ = parent;
}
void NativeWindow::InvalidateShadow() {}
void NativeWindow::SetAutoHideCursor(bool auto_hide) {}
void NativeWindow::SelectPreviousTab() {}
void NativeWindow::SelectNextTab() {}
void NativeWindow::MergeAllWindows() {}
void NativeWindow::MoveTabToNewWindow() {}
void NativeWindow::ToggleTabBar() {}
bool NativeWindow::AddTabbedWindow(NativeWindow* window) {
return true; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {}
void NativeWindow::SetBackgroundMaterial(const std::string& type) {}
void NativeWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {}
void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {}
void NativeWindow::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {}
void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {}
bool NativeWindow::IsMenuBarAutoHide() {
return false;
}
void NativeWindow::SetMenuBarVisibility(bool visible) {}
bool NativeWindow::IsMenuBarVisible() {
return true;
}
double NativeWindow::GetAspectRatio() {
return aspect_ratio_;
}
gfx::Size NativeWindow::GetAspectRatioExtraSize() {
return aspect_ratio_extraSize_;
}
void NativeWindow::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
aspect_ratio_ = aspect_ratio;
aspect_ratio_extraSize_ = extra_size;
}
void NativeWindow::PreviewFile(const std::string& path,
const std::string& display_name) {}
void NativeWindow::CloseFilePreview() {}
gfx::Rect NativeWindow::GetWindowControlsOverlayRect() {
return overlay_rect_;
}
void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) {
overlay_rect_ = overlay_rect;
}
void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) {
for (NativeWindowObserver& observer : observers_)
observer.RequestPreferredWidth(width);
}
void NativeWindow::NotifyWindowCloseButtonClicked() {
// First ask the observers whether we want to close.
bool prevent_default = false;
for (NativeWindowObserver& observer : observers_)
observer.WillCloseWindow(&prevent_default);
if (prevent_default) {
WindowList::WindowCloseCancelled(this);
return;
}
// Then ask the observers how should we close the window.
for (NativeWindowObserver& observer : observers_)
observer.OnCloseButtonClicked(&prevent_default);
if (prevent_default)
return;
CloseImmediately();
}
void NativeWindow::NotifyWindowClosed() {
if (is_closed_)
return;
is_closed_ = true;
for (NativeWindowObserver& observer : observers_)
observer.OnWindowClosed();
WindowList::RemoveWindow(this);
}
void NativeWindow::NotifyWindowEndSession() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEndSession();
}
void NativeWindow::NotifyWindowBlur() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowBlur();
}
void NativeWindow::NotifyWindowFocus() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowFocus();
}
void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowIsKeyChanged(is_key);
}
void NativeWindow::NotifyWindowShow() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowShow();
}
void NativeWindow::NotifyWindowHide() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowHide();
}
void NativeWindow::NotifyWindowMaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMaximize();
}
void NativeWindow::NotifyWindowUnmaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowUnmaximize();
}
void NativeWindow::NotifyWindowMinimize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMinimize();
}
void NativeWindow::NotifyWindowRestore() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRestore();
}
void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillResize(new_bounds, edge, prevent_default);
}
void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillMove(new_bounds, prevent_default);
}
void NativeWindow::NotifyWindowResize() {
NotifyLayoutWindowControlsOverlay();
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResize();
}
void NativeWindow::NotifyWindowResized() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResized();
}
void NativeWindow::NotifyWindowMove() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMove();
}
void NativeWindow::NotifyWindowMoved() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMoved();
}
void NativeWindow::NotifyWindowEnterFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterFullScreen();
}
void NativeWindow::NotifyWindowSwipe(const std::string& direction) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSwipe(direction);
}
void NativeWindow::NotifyWindowRotateGesture(float rotation) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRotateGesture(rotation);
}
void NativeWindow::NotifyWindowSheetBegin() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetBegin();
}
void NativeWindow::NotifyWindowSheetEnd() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetEnd();
}
void NativeWindow::NotifyWindowLeaveFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveFullScreen();
}
void NativeWindow::NotifyWindowEnterHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterHtmlFullScreen();
}
void NativeWindow::NotifyWindowLeaveHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveHtmlFullScreen();
}
void NativeWindow::NotifyWindowAlwaysOnTopChanged() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowAlwaysOnTopChanged();
}
void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) {
for (NativeWindowObserver& observer : observers_)
observer.OnExecuteAppCommand(command);
}
void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details) {
for (NativeWindowObserver& observer : observers_)
observer.OnTouchBarItemResult(item_id, details);
}
void NativeWindow::NotifyNewWindowForTab() {
for (NativeWindowObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void NativeWindow::NotifyWindowSystemContextMenu(int x,
int y,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnSystemContextMenu(x, y, prevent_default);
}
void NativeWindow::NotifyLayoutWindowControlsOverlay() {
gfx::Rect bounding_rect = GetWindowControlsOverlayRect();
if (!bounding_rect.IsEmpty()) {
for (NativeWindowObserver& observer : observers_)
observer.UpdateWindowControlsOverlay(bounding_rect);
}
}
#if BUILDFLAG(IS_WIN)
void NativeWindow::NotifyWindowMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMessage(message, w_param, l_param);
}
#endif
int NativeWindow::NonClientHitTest(const gfx::Point& point) {
#if !BUILDFLAG(IS_MAC)
// We need to ensure we account for resizing borders on Windows and Linux.
if ((!has_frame() || has_client_frame()) && IsResizable()) {
auto* frame =
static_cast<FramelessView*>(widget()->non_client_view()->frame_view());
int border_hit = frame->ResizingBorderHitTest(point);
if (border_hit != HTNOWHERE)
return border_hit;
}
#endif
for (auto* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)
return hit;
}
return HTNOWHERE;
}
void NativeWindow::AddDraggableRegionProvider(
DraggableRegionProvider* provider) {
if (!base::Contains(draggable_region_providers_, provider)) {
draggable_region_providers_.push_back(provider);
}
}
void NativeWindow::RemoveDraggableRegionProvider(
DraggableRegionProvider* provider) {
draggable_region_providers_.remove_if(
[&provider](DraggableRegionProvider* p) { return p == provider; });
}
views::Widget* NativeWindow::GetWidget() {
return widget();
}
const views::Widget* NativeWindow::GetWidget() const {
return widget();
}
std::u16string NativeWindow::GetAccessibleWindowTitle() const {
if (accessible_title_.empty()) {
return views::WidgetDelegate::GetAccessibleWindowTitle();
}
return accessible_title_;
}
void NativeWindow::SetAccessibleTitle(const std::string& title) {
accessible_title_ = base::UTF8ToUTF16(title);
}
std::string NativeWindow::GetAccessibleTitle() {
return base::UTF16ToUTF8(accessible_title_);
}
void NativeWindow::HandlePendingFullscreenTransitions() {
if (pending_transitions_.empty()) {
set_fullscreen_transition_type(FullScreenTransitionType::kNone);
return;
}
bool next_transition = pending_transitions_.front();
pending_transitions_.pop();
SetFullScreen(next_transition);
}
// static
int32_t NativeWindow::next_id_ = 0;
// static
void NativeWindowRelay::CreateForWebContents(
content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window) {
DCHECK(web_contents);
if (!web_contents->GetUserData(UserDataKey())) {
web_contents->SetUserData(
UserDataKey(),
base::WrapUnique(new NativeWindowRelay(web_contents, window)));
}
}
NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window)
: content::WebContentsUserData<NativeWindowRelay>(*web_contents),
native_window_(window) {}
NativeWindowRelay::~NativeWindowRelay() = default;
WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
shell/browser/native_window.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#include <list>
#include <memory>
#include <queue>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/supports_user_data.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/web_contents_user_data.h"
#include "extensions/browser/app_window/size_constraints.h"
#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/native_window_observer.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/common/api/api.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/views/widget/widget_delegate.h"
class SkRegion;
namespace content {
struct NativeWebKeyboardEvent;
}
namespace gfx {
class Image;
class Point;
class Rect;
enum class ResizeEdge;
class Size;
} // namespace gfx
namespace gin_helper {
class Dictionary;
class PersistentDictionary;
} // namespace gin_helper
namespace electron {
class ElectronMenuModel;
class NativeBrowserView;
namespace api {
class BrowserView;
}
#if BUILDFLAG(IS_MAC)
typedef NSView* NativeWindowHandle;
#else
typedef gfx::AcceleratedWidget NativeWindowHandle;
#endif
class NativeWindow : public base::SupportsUserData,
public views::WidgetDelegate {
public:
~NativeWindow() override;
// disable copy
NativeWindow(const NativeWindow&) = delete;
NativeWindow& operator=(const NativeWindow&) = delete;
// Create window with existing WebContents, the caller is responsible for
// managing the window's live.
static NativeWindow* Create(const gin_helper::Dictionary& options,
NativeWindow* parent = nullptr);
void InitFromOptions(const gin_helper::Dictionary& options);
virtual void SetContentView(views::View* view) = 0;
virtual void Close() = 0;
virtual void CloseImmediately() = 0;
virtual bool IsClosed() const;
virtual void Focus(bool focus) = 0;
virtual bool IsFocused() = 0;
virtual void Show() = 0;
virtual void ShowInactive() = 0;
virtual void Hide() = 0;
virtual bool IsVisible() = 0;
virtual bool IsEnabled() = 0;
virtual void SetEnabled(bool enable) = 0;
virtual void Maximize() = 0;
virtual void Unmaximize() = 0;
virtual bool IsMaximized() = 0;
virtual void Minimize() = 0;
virtual void Restore() = 0;
virtual bool IsMinimized() = 0;
virtual void SetFullScreen(bool fullscreen) = 0;
virtual bool IsFullscreen() const = 0;
virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0;
virtual gfx::Rect GetBounds() = 0;
virtual void SetSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetSize();
virtual void SetPosition(const gfx::Point& position, bool animate = false);
virtual gfx::Point GetPosition();
virtual void SetContentSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetContentSize();
virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false);
virtual gfx::Rect GetContentBounds();
virtual bool IsNormal();
virtual gfx::Rect GetNormalBounds() = 0;
virtual void SetSizeConstraints(
const extensions::SizeConstraints& window_constraints);
virtual extensions::SizeConstraints GetSizeConstraints() const;
virtual void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints);
virtual extensions::SizeConstraints GetContentSizeConstraints() const;
virtual void SetMinimumSize(const gfx::Size& size);
virtual gfx::Size GetMinimumSize() const;
virtual void SetMaximumSize(const gfx::Size& size);
virtual gfx::Size GetMaximumSize() const;
virtual gfx::Size GetContentMinimumSize() const;
virtual gfx::Size GetContentMaximumSize() const;
virtual void SetSheetOffset(const double offsetX, const double offsetY);
virtual double GetSheetOffsetX();
virtual double GetSheetOffsetY();
virtual void SetResizable(bool resizable) = 0;
virtual bool MoveAbove(const std::string& sourceId) = 0;
virtual void MoveTop() = 0;
virtual bool IsResizable() = 0;
virtual void SetMovable(bool movable) = 0;
virtual bool IsMovable() = 0;
virtual void SetMinimizable(bool minimizable) = 0;
virtual bool IsMinimizable() = 0;
virtual void SetMaximizable(bool maximizable) = 0;
virtual bool IsMaximizable() = 0;
virtual void SetFullScreenable(bool fullscreenable) = 0;
virtual bool IsFullScreenable() = 0;
virtual void SetClosable(bool closable) = 0;
virtual bool IsClosable() = 0;
virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level = "floating",
int relativeLevel = 0) = 0;
virtual ui::ZOrderLevel GetZOrderLevel() = 0;
virtual void Center() = 0;
virtual void Invalidate() = 0;
virtual void SetTitle(const std::string& title) = 0;
virtual std::string GetTitle() = 0;
#if BUILDFLAG(IS_MAC)
virtual std::string GetAlwaysOnTopLevel() = 0;
virtual void SetActive(bool is_key) = 0;
virtual bool IsActive() const = 0;
virtual void RemoveChildWindow(NativeWindow* child) = 0;
virtual void AttachChildren() = 0;
virtual void DetachChildren() = 0;
#endif
// Ability to augment the window title for the screen readers.
void SetAccessibleTitle(const std::string& title);
std::string GetAccessibleTitle();
virtual void FlashFrame(bool flash) = 0;
virtual void SetSkipTaskbar(bool skip) = 0;
virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0;
virtual bool IsExcludedFromShownWindowsMenu() = 0;
virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0;
virtual bool IsSimpleFullScreen() = 0;
virtual void SetKiosk(bool kiosk) = 0;
virtual bool IsKiosk() = 0;
virtual bool IsTabletMode() const;
virtual void SetBackgroundColor(SkColor color) = 0;
virtual SkColor GetBackgroundColor() = 0;
virtual void InvalidateShadow();
virtual void SetHasShadow(bool has_shadow) = 0;
virtual bool HasShadow() = 0;
virtual void SetOpacity(const double opacity) = 0;
virtual double GetOpacity() = 0;
virtual void SetRepresentedFilename(const std::string& filename);
virtual std::string GetRepresentedFilename();
virtual void SetDocumentEdited(bool edited);
virtual bool IsDocumentEdited();
virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0;
virtual void SetContentProtection(bool enable) = 0;
virtual void SetFocusable(bool focusable);
virtual bool IsFocusable();
virtual void SetMenu(ElectronMenuModel* menu);
virtual void SetParentWindow(NativeWindow* parent);
virtual void AddBrowserView(NativeBrowserView* browser_view) = 0;
virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0;
virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0;
virtual content::DesktopMediaID GetDesktopMediaID() const = 0;
virtual gfx::NativeView GetNativeView() const = 0;
virtual gfx::NativeWindow GetNativeWindow() const = 0;
virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0;
virtual NativeWindowHandle GetNativeWindowHandle() const = 0;
// Taskbar/Dock APIs.
enum class ProgressState {
kNone, // no progress, no marking
kIndeterminate, // progress, indeterminate
kError, // progress, errored (red)
kPaused, // progress, paused (yellow)
kNormal, // progress, not marked (green)
};
virtual void SetProgressBar(double progress, const ProgressState state) = 0;
virtual void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) = 0;
// Workspace APIs.
virtual void SetVisibleOnAllWorkspaces(
bool visible,
bool visibleOnFullScreen = false,
bool skipTransformProcessType = false) = 0;
virtual bool IsVisibleOnAllWorkspaces() = 0;
virtual void SetAutoHideCursor(bool auto_hide);
// Vibrancy API
virtual void SetVibrancy(const std::string& type);
virtual void SetBackgroundMaterial(const std::string& type);
// Traffic Light API
#if BUILDFLAG(IS_MAC)
virtual void SetWindowButtonVisibility(bool visible) = 0;
virtual bool GetWindowButtonVisibility() const = 0;
virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0;
virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0;
virtual void RedrawTrafficLights() = 0;
virtual void UpdateFrame() = 0;
#endif
// whether windows should be ignored by mission control
#if BUILDFLAG(IS_MAC)
virtual bool IsHiddenInMissionControl() = 0;
virtual void SetHiddenInMissionControl(bool hidden) = 0;
#endif
// Touchbar API
virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items);
virtual void RefreshTouchBarItem(const std::string& item_id);
virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item);
// Native Tab API
virtual void SelectPreviousTab();
virtual void SelectNextTab();
virtual void MergeAllWindows();
virtual void MoveTabToNewWindow();
virtual void ToggleTabBar();
virtual bool AddTabbedWindow(NativeWindow* window);
// Toggle the menu bar.
virtual void SetAutoHideMenuBar(bool auto_hide);
virtual bool IsMenuBarAutoHide();
virtual void SetMenuBarVisibility(bool visible);
virtual bool IsMenuBarVisible();
// Set the aspect ratio when resizing window.
double GetAspectRatio();
gfx::Size GetAspectRatioExtraSize();
virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size);
// File preview APIs.
virtual void PreviewFile(const std::string& path,
const std::string& display_name);
virtual void CloseFilePreview();
virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {}
// Converts between content bounds and window bounds.
virtual gfx::Rect ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const = 0;
virtual gfx::Rect WindowBoundsToContentBounds(
const gfx::Rect& bounds) const = 0;
base::WeakPtr<NativeWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
virtual gfx::Rect GetWindowControlsOverlayRect();
virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect);
// Methods called by the WebContents.
virtual void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) {}
// Public API used by platform-dependent delegates and observers to send UI
// related notifications.
void NotifyWindowRequestPreferredWidth(int* width);
void NotifyWindowCloseButtonClicked();
void NotifyWindowClosed();
void NotifyWindowEndSession();
void NotifyWindowBlur();
void NotifyWindowFocus();
void NotifyWindowShow();
void NotifyWindowIsKeyChanged(bool is_key);
void NotifyWindowHide();
void NotifyWindowMaximize();
void NotifyWindowUnmaximize();
void NotifyWindowMinimize();
void NotifyWindowRestore();
void NotifyWindowMove();
void NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default);
void NotifyWindowResize();
void NotifyWindowResized();
void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default);
void NotifyWindowMoved();
void NotifyWindowSwipe(const std::string& direction);
void NotifyWindowRotateGesture(float rotation);
void NotifyWindowSheetBegin();
void NotifyWindowSheetEnd();
virtual void NotifyWindowEnterFullScreen();
virtual void NotifyWindowLeaveFullScreen();
void NotifyWindowEnterHtmlFullScreen();
void NotifyWindowLeaveHtmlFullScreen();
void NotifyWindowAlwaysOnTopChanged();
void NotifyWindowExecuteAppCommand(const std::string& command);
void NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details);
void NotifyNewWindowForTab();
void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default);
void NotifyLayoutWindowControlsOverlay();
#if BUILDFLAG(IS_WIN)
void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param);
#endif
void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(NativeWindowObserver* obs) {
observers_.RemoveObserver(obs);
}
// Handle fullscreen transitions.
void HandlePendingFullscreenTransitions();
enum class FullScreenTransitionState { kEntering, kExiting, kNone };
void set_fullscreen_transition_state(FullScreenTransitionState state) {
fullscreen_transition_state_ = state;
}
FullScreenTransitionState fullscreen_transition_state() const {
return fullscreen_transition_state_;
}
enum class FullScreenTransitionType { kHTML, kNative, kNone };
void set_fullscreen_transition_type(FullScreenTransitionType type) {
fullscreen_transition_type_ = type;
}
FullScreenTransitionType fullscreen_transition_type() const {
return fullscreen_transition_type_;
}
views::Widget* widget() const { return widget_.get(); }
views::View* content_view() const { return content_view_; }
enum class TitleBarStyle {
kNormal,
kHidden,
kHiddenInset,
kCustomButtonsOnHover,
};
TitleBarStyle title_bar_style() const { return title_bar_style_; }
int titlebar_overlay_height() const { return titlebar_overlay_height_; }
void set_titlebar_overlay_height(int height) {
titlebar_overlay_height_ = height;
}
bool titlebar_overlay_enabled() const { return titlebar_overlay_; }
bool has_frame() const { return has_frame_; }
void set_has_frame(bool has_frame) { has_frame_ = has_frame; }
bool has_client_frame() const { return has_client_frame_; }
bool transparent() const { return transparent_; }
bool enable_larger_than_screen() const { return enable_larger_than_screen_; }
NativeWindow* parent() const { return parent_; }
bool is_modal() const { return is_modal_; }
std::list<NativeBrowserView*> browser_views() const { return browser_views_; }
int32_t window_id() const { return next_id_; }
void add_child_window(NativeWindow* child) {
child_windows_.push_back(child);
}
int NonClientHitTest(const gfx::Point& point);
void AddDraggableRegionProvider(DraggableRegionProvider* provider);
void RemoveDraggableRegionProvider(DraggableRegionProvider* provider);
protected:
friend class api::BrowserView;
NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent);
// views::WidgetDelegate:
views::Widget* GetWidget() override;
const views::Widget* GetWidget() const override;
std::u16string GetAccessibleWindowTitle() const override;
void set_content_view(views::View* view) { content_view_ = view; }
void add_browser_view(NativeBrowserView* browser_view) {
browser_views_.push_back(browser_view);
}
void remove_browser_view(NativeBrowserView* browser_view) {
browser_views_.remove_if(
[&browser_view](NativeBrowserView* n) { return (n == browser_view); });
}
// The boolean parsing of the "titleBarOverlay" option
bool titlebar_overlay_ = false;
// The custom height parsed from the "height" option in a Object
// "titleBarOverlay"
int titlebar_overlay_height_ = 0;
// The "titleBarStyle" option.
TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal;
std::queue<bool> pending_transitions_;
FullScreenTransitionState fullscreen_transition_state_ =
FullScreenTransitionState::kNone;
FullScreenTransitionType fullscreen_transition_type_ =
FullScreenTransitionType::kNone;
std::list<NativeWindow*> child_windows_;
private:
std::unique_ptr<views::Widget> widget_;
static int32_t next_id_;
// The content view, weak ref.
raw_ptr<views::View> content_view_ = nullptr;
// Whether window has standard frame.
bool has_frame_ = true;
// Whether window has standard frame, but it's drawn by Electron (the client
// application) instead of the OS. Currently only has meaning on Linux for
// Wayland hosts.
bool has_client_frame_ = false;
// Whether window is transparent.
bool transparent_ = false;
// Minimum and maximum size, stored as content size.
extensions::SizeConstraints size_constraints_;
// Whether window can be resized larger than screen.
bool enable_larger_than_screen_ = false;
// The windows has been closed.
bool is_closed_ = false;
// Used to display sheets at the appropriate horizontal and vertical offsets
// on macOS.
double sheet_offset_x_ = 0.0;
double sheet_offset_y_ = 0.0;
// Used to maintain the aspect ratio of a view which is inside of the
// content view.
double aspect_ratio_ = 0.0;
gfx::Size aspect_ratio_extraSize_;
// The parent window, it is guaranteed to be valid during this window's life.
raw_ptr<NativeWindow> parent_ = nullptr;
// Is this a modal window.
bool is_modal_ = false;
// The browser view layer.
std::list<NativeBrowserView*> browser_views_;
std::list<DraggableRegionProvider*> draggable_region_providers_;
// Observers of this window.
base::ObserverList<NativeWindowObserver> observers_;
// Accessible title.
std::u16string accessible_title_;
gfx::Rect overlay_rect_;
base::WeakPtrFactory<NativeWindow> weak_factory_{this};
};
// This class provides a hook to get a NativeWindow from a WebContents.
class NativeWindowRelay
: public content::WebContentsUserData<NativeWindowRelay> {
public:
static void CreateForWebContents(content::WebContents*,
base::WeakPtr<NativeWindow>);
~NativeWindowRelay() override;
NativeWindow* GetNativeWindow() const { return native_window_.get(); }
WEB_CONTENTS_USER_DATA_KEY_DECL();
private:
friend class content::WebContentsUserData<NativeWindow>;
explicit NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window);
base::WeakPtr<NativeWindow> native_window_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
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 <dwmapi.h>
#include <wrl/client.h>
#endif
#include <memory>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/memory/raw_ptr.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/inspectable_web_contents.h"
#include "shell/browser/ui/views/inspectable_web_contents_view_views.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/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 "base/win/windows_version.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)
DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) {
if (material == "none") {
return DWMSBT_NONE;
} else if (material == "acrylic") {
return DWMSBT_TRANSIENTWINDOW;
} else if (material == "mica") {
return DWMSBT_MAINWINDOW;
} else if (material == "tabbed") {
return DWMSBT_TABBEDWINDOW;
}
return DWMSBT_AUTO;
}
// 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_{raw_ref<NativeWindowViews>::from_ptr(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:
const raw_ref<NativeWindowViews> window_;
};
} // namespace
NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent) {
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() {
#if BUILDFLAG(IS_WIN)
// widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a
// window or any of its parent windows are visible. We want to only check the
// current window.
bool visible =
::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE;
// WS_VISIBLE is true even if a window is miminized - explicitly check that.
return visible && !IsMinimized();
#else
return widget()->IsVisible();
#endif
}
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() && !IsMinimized()) {
// 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) {
menu_bar_visible_before_fullscreen_ = IsMenuBarVisible();
SetMenuBarVisibility(false);
} else {
SetMenuBarVisibility(!IsMenuBarAutoHide() &&
menu_bar_visible_before_fullscreen_);
menu_bar_visible_before_fullscreen_ = false;
}
#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() {
#if BUILDFLAG(IS_WIN)
if (IsMaximized() && transparent())
return restore_bounds_;
#endif
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 = std::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::SetBackgroundMaterial(const std::string& material) {
#if BUILDFLAG(IS_WIN)
// DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up.
if (base::win::GetVersion() < base::win::Version::WIN11_22H2)
return;
DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material);
HRESULT result =
DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE,
&backdrop_type, sizeof(backdrop_type));
if (FAILED(result))
LOG(WARNING) << "Failed to set background material to " << material;
#endif
}
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 base::Contains(wm_states, sticky_atom);
}
#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;
}
#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_;
}
bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) {
return NonClientHitTest(location) == HTNOWHERE;
}
views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
return new NativeWindowClientView{widget, GetContentsView(), 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
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
shell/browser/native_window_views.h
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#include "shell/browser/native_window.h"
#include <memory>
#include <set>
#include <string>
#include "base/memory/raw_ptr.h"
#include "shell/browser/ui/views/root_view.h"
#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include "ui/views/widget/widget_observer.h"
#if defined(USE_OZONE)
#include "ui/ozone/buildflags.h"
#if BUILDFLAG(OZONE_PLATFORM_X11)
#define USE_OZONE_PLATFORM_X11
#endif
#endif
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
namespace electron {
class GlobalMenuBarX11;
class WindowStateWatcher;
#if defined(USE_OZONE_PLATFORM_X11)
class EventDisabler;
#endif
#if BUILDFLAG(IS_WIN)
gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds);
#endif
class NativeWindowViews : public NativeWindow,
public views::WidgetObserver,
public ui::EventHandler {
public:
NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent);
~NativeWindowViews() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate) override;
gfx::Rect GetBounds() override;
gfx::Rect GetContentBounds() override;
gfx::Size GetContentSize() override;
gfx::Rect GetNormalBounds() override;
SkColor GetBackgroundColor() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relativeLevel) override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
bool IsTabletMode() const override;
void SetBackgroundColor(SkColor color) override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void SetMenu(ElectronMenuModel* menu_model) override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetAutoHideMenuBar(bool auto_hide) override;
bool IsMenuBarAutoHide() override;
void SetMenuBarVisibility(bool visible) override;
bool IsMenuBarVisible() override;
void SetBackgroundMaterial(const std::string& type) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetGTKDarkThemeEnabled(bool use_dark_theme) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
void IncrementChildModals();
void DecrementChildModals();
#if BUILDFLAG(IS_WIN)
// Catch-all message handling and filtering. Called before
// HWNDMessageHandler's built-in handling, which may pre-empt some
// expectations in Views/Aura if messages are consumed. Returns true if the
// message was consumed by the delegate and should not be processed further
// by the HWNDMessageHandler. In this case, |result| is returned. |result| is
// not modified otherwise.
bool PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result);
void SetIcon(HICON small_icon, HICON app_icon);
#elif BUILDFLAG(IS_LINUX)
void SetIcon(const gfx::ImageSkia& icon);
#endif
#if BUILDFLAG(IS_WIN)
TaskbarHost& taskbar_host() { return taskbar_host_; }
#endif
#if BUILDFLAG(IS_WIN)
bool IsWindowControlsOverlayEnabled() const {
return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) &&
titlebar_overlay_;
}
SkColor overlay_button_color() const { return overlay_button_color_; }
void set_overlay_button_color(SkColor color) {
overlay_button_color_ = color;
}
SkColor overlay_symbol_color() const { return overlay_symbol_color_; }
void set_overlay_symbol_color(SkColor color) {
overlay_symbol_color_ = color;
}
#endif
private:
// views::WidgetObserver:
void OnWidgetActivationChanged(views::Widget* widget, bool active) override;
void OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& bounds) override;
void OnWidgetDestroying(views::Widget* widget) override;
void OnWidgetDestroyed(views::Widget* widget) override;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override;
bool CanMaximize() const override;
bool CanMinimize() const override;
std::u16string GetWindowTitle() const override;
views::View* GetContentsView() override;
bool ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) override;
views::ClientView* CreateClientView(views::Widget* widget) override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
void OnWidgetMove() override;
#if BUILDFLAG(IS_WIN)
bool ExecuteWindowsCommand(int command_id) override;
#endif
#if BUILDFLAG(IS_WIN)
void HandleSizeEvent(WPARAM w_param, LPARAM l_param);
void ResetWindowControls();
void SetForwardMouseMessages(bool forward);
static LRESULT CALLBACK SubclassProc(HWND hwnd,
UINT msg,
WPARAM w_param,
LPARAM l_param,
UINT_PTR subclass_id,
DWORD_PTR ref_data);
static LRESULT CALLBACK MouseHookProc(int n_code,
WPARAM w_param,
LPARAM l_param);
#endif
// Enable/disable:
bool ShouldBeEnabled();
void SetEnabledInternal(bool enabled);
// NativeWindow:
void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) override;
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override;
// Returns the restore state for the window.
ui::WindowShowState GetRestoredState();
// Maintain window placement.
void MoveBehindTaskBarIfNeeded();
RootView root_view_{this};
// The view should be focused by default.
raw_ptr<views::View> focused_view_ = nullptr;
// The "resizable" flag on Linux is implemented by setting size constraints,
// we need to make sure size constraints are restored when window becomes
// resizable again. This is also used on Windows, to keep taskbar resize
// events from resizing the window.
extensions::SizeConstraints old_size_constraints_;
#if defined(USE_OZONE)
std::unique_ptr<GlobalMenuBarX11> global_menu_bar_;
#endif
#if defined(USE_OZONE_PLATFORM_X11)
// To disable the mouse events.
std::unique_ptr<EventDisabler> event_disabler_;
#endif
#if BUILDFLAG(IS_WIN)
ui::WindowShowState last_window_state_;
gfx::Rect last_normal_placement_bounds_;
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
// Memoized version of a11y check
bool checked_for_a11y_support_ = false;
// Whether to show the WS_THICKFRAME style.
bool thick_frame_ = true;
// The bounds of window before maximize/fullscreen.
gfx::Rect restore_bounds_;
// The icons of window and taskbar.
base::win::ScopedHICON window_icon_;
base::win::ScopedHICON app_icon_;
// The set of windows currently forwarding mouse messages.
static std::set<NativeWindowViews*> forwarding_windows_;
static HHOOK mouse_hook_;
bool forwarding_mouse_messages_ = false;
HWND legacy_window_ = NULL;
bool layered_ = false;
// Set to true if the window is always on top and behind the task bar.
bool behind_task_bar_ = false;
// Whether we want to set window placement without side effect.
bool is_setting_window_placement_ = false;
// Whether the window is currently being resized.
bool is_resizing_ = false;
// Whether the window is currently being moved.
bool is_moving_ = false;
absl::optional<gfx::Rect> pending_bounds_change_;
// The color to use as the theme and symbol colors respectively for Window
// Controls Overlay if enabled on Windows.
SkColor overlay_button_color_;
SkColor overlay_symbol_color_;
#endif
// Handles unhandled keyboard messages coming back from the renderer process.
views::UnhandledKeyboardEventHandler keyboard_event_handler_;
// Whether the menubar is visible before the window enters fullscreen
bool menu_bar_visible_before_fullscreen_ = false;
// Whether the window should be enabled based on user calls to SetEnabled()
bool is_enabled_ = true;
// How many modal children this window has;
// used to determine enabled state
unsigned int num_modal_children_ = 0;
bool use_content_size_ = false;
bool movable_ = true;
bool resizable_ = true;
bool maximizable_ = true;
bool minimizable_ = true;
bool fullscreenable_ = true;
std::string title_;
gfx::Size widget_size_;
double opacity_ = 1.0;
bool widget_destroyed_ = false;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
patches/chromium/.patches
|
build_gn.patch
dcheck.patch
accelerator.patch
blink_file_path.patch
blink_local_frame.patch
can_create_window.patch
disable_hidden.patch
dom_storage_limits.patch
render_widget_host_view_base.patch
render_widget_host_view_mac.patch
webview_cross_drag.patch
gin_enable_disable_v8_platform.patch
enable_reset_aspect_ratio.patch
boringssl_build_gn.patch
pepper_plugin_support.patch
gtk_visibility.patch
sysroot.patch
resource_file_conflict.patch
scroll_bounce_flag.patch
mas_blink_no_private_api.patch
mas_no_private_api.patch
mas-cgdisplayusesforcetogray.patch
mas_disable_remote_layer.patch
mas_disable_remote_accessibility.patch
mas_disable_custom_window_frame.patch
mas_avoid_usage_of_private_macos_apis.patch
mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch
add_didinstallconditionalfeatures.patch
desktop_media_list.patch
proxy_config_monitor.patch
gritsettings_resource_ids.patch
isolate_holder.patch
notification_provenance.patch
dump_syms.patch
command-ismediakey.patch
printing.patch
support_mixed_sandbox_with_zygote.patch
unsandboxed_ppapi_processes_skip_zygote.patch
build_add_electron_tracing_category.patch
worker_context_will_destroy.patch
frame_host_manager.patch
crashpad_pid_check.patch
network_service_allow_remote_certificate_verification_logic.patch
disable_color_correct_rendering.patch
add_contentgpuclient_precreatemessageloop_callback.patch
picture-in-picture.patch
disable_compositor_recycling.patch
allow_new_privileges_in_unsandboxed_child_processes.patch
expose_setuseragent_on_networkcontext.patch
feat_add_set_theme_source_to_allow_apps_to.patch
add_webmessageportconverter_entangleandinjectmessageportchannel.patch
ignore_rc_check.patch
remove_usage_of_incognito_apis_in_the_spellchecker.patch
allow_disabling_blink_scheduler_throttling_per_renderview.patch
hack_plugin_response_interceptor_to_point_to_electron.patch
feat_add_support_for_overriding_the_base_spellchecker_download_url.patch
feat_enable_offscreen_rendering_with_viz_compositor.patch
gpu_notify_when_dxdiag_request_fails.patch
feat_allow_embedders_to_add_observers_on_created_hunspell.patch
feat_add_onclose_to_messageport.patch
allow_in-process_windows_to_have_different_web_prefs.patch
refactor_expose_cursor_changes_to_the_webcontentsobserver.patch
crash_allow_setting_more_options.patch
upload_list_add_loadsync_method.patch
allow_setting_secondary_label_via_simplemenumodel.patch
feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch
fix_patch_out_profile_refs_in_accessibility_ui.patch
skip_atk_toolchain_check.patch
worker_feat_add_hook_to_notify_script_ready.patch
chore_provide_iswebcontentscreationoverridden_with_full_params.patch
fix_properly_honor_printing_page_ranges.patch
export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch
fix_export_zlib_symbols.patch
web_contents.patch
webview_fullscreen.patch
disable_unload_metrics.patch
fix_add_check_for_sandbox_then_result.patch
extend_apply_webpreferences.patch
build_libc_as_static_library.patch
build_do_not_depend_on_packed_resource_integrity.patch
refactor_restore_base_adaptcallbackforrepeating.patch
hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch
logging_win32_only_create_a_console_if_logging_to_stderr.patch
fix_media_key_usage_with_globalshortcuts.patch
feat_expose_raw_response_headers_from_urlloader.patch
process_singleton.patch
add_ui_scopedcliboardwriter_writeunsaferawdata.patch
feat_add_data_parameter_to_processsingleton.patch
load_v8_snapshot_in_browser_process.patch
fix_adapt_exclusive_access_for_electron_needs.patch
fix_aspect_ratio_with_max_size.patch
fix_dont_delete_SerialPortManager_on_main_thread.patch
fix_crash_when_saving_edited_pdf_files.patch
port_autofill_colors_to_the_color_pipeline.patch
build_disable_partition_alloc_on_mac.patch
fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch
build_make_libcxx_abi_unstable_false_for_electron.patch
introduce_ozoneplatform_electron_can_call_x11_property.patch
make_gtk_getlibgtk_public.patch
build_disable_print_content_analysis.patch
custom_protocols_plzserviceworker.patch
feat_filter_out_non-shareable_windows_in_the_current_application_in.patch
fix_allow_guest_webcontents_to_enter_fullscreen.patch
disable_freezing_flags_after_init_in_node.patch
short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch
chore_add_electron_deps_to_gitignores.patch
chore_allow_chromium_to_handle_synthetic_mouse_events_for_touch.patch
add_maximized_parameter_to_linuxui_getwindowframeprovider.patch
add_electron_deps_to_license_credits_file.patch
fix_crash_loading_non-standard_schemes_in_iframes.patch
create_browser_v8_snapshot_file_name_fuse.patch
feat_configure_launch_options_for_service_process.patch
feat_ensure_mas_builds_of_the_same_application_can_use_safestorage.patch
fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch
preconnect_manager.patch
fix_remove_caption-removing_style_call.patch
build_allow_electron_to_use_exec_script.patch
build_only_use_the_mas_build_config_in_the_required_components.patch
fix_tray_icon_gone_on_lock_screen.patch
chore_introduce_blocking_api_for_electron.patch
chore_patch_out_partition_attribute_dcheck_for_webviews.patch
expose_v8initializer_codegenerationcheckcallbackinmainthread.patch
chore_patch_out_profile_methods_in_profile_selections_cc.patch
add_gin_converter_support_for_arraybufferview.patch
chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
fix_remove_profiles_from_spellcheck_service.patch
chore_patch_out_profile_methods_in_chrome_browser_pdf.patch
chore_patch_out_profile_methods_in_titlebar_config.patch
fix_crash_on_nativetheme_change_during_context_menu_close.patch
fix_select_the_first_menu_item_when_opened_via_keyboard.patch
fix_return_v8_value_from_localframe_requestexecutescript.patch
revert_simplify_dwm_transitions_on_windows.patch
fix_harden_blink_scriptstate_maybefrom.patch
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
patches/chromium/revert_simplify_dwm_transitions_on_windows.patch
|
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: deepak1556 <[email protected]>
Date: Tue, 27 Jun 2023 22:05:17 +0900
Subject: Revert "Simplify DWM transitions on Windows"
This reverts commit 392e5f43aae8d225a118145cbc5f5bb104cbe541.
Can be removed once https://github.com/electron/electron/issues/38937 is resolved.
diff --git a/chrome/app/chrome_command_ids.h b/chrome/app/chrome_command_ids.h
index 15f4aac24744228c0e74ec521c18eb6ab5f59c5b..b9a71c9063d8ee573424a9161cc127af169944a9 100644
--- a/chrome/app/chrome_command_ids.h
+++ b/chrome/app/chrome_command_ids.h
@@ -59,6 +59,7 @@
#define IDC_MOVE_TAB_NEXT 34032
#define IDC_MOVE_TAB_PREVIOUS 34033
#define IDC_SEARCH 34035
+#define IDC_DEBUG_FRAME_TOGGLE 34038
#define IDC_WINDOW_MENU 34045
#define IDC_MINIMIZE_WINDOW 34046
#define IDC_MAXIMIZE_WINDOW 34047
diff --git a/chrome/browser/ui/browser_command_controller.cc b/chrome/browser/ui/browser_command_controller.cc
index b198e41661d459302ddccfab70ac3de8cd2c48b5..405c0ac7c41ef4cb6a8804c8a34a7328d796d7bd 100644
--- a/chrome/browser/ui/browser_command_controller.cc
+++ b/chrome/browser/ui/browser_command_controller.cc
@@ -1184,6 +1184,7 @@ void BrowserCommandController::InitCommandState() {
IDC_DUPLICATE_TAB, !browser_->is_type_picture_in_picture());
UpdateTabRestoreCommandState();
command_updater_.UpdateCommandEnabled(IDC_EXIT, true);
+ command_updater_.UpdateCommandEnabled(IDC_DEBUG_FRAME_TOGGLE, true);
command_updater_.UpdateCommandEnabled(IDC_NAME_WINDOW, true);
#if BUILDFLAG(IS_CHROMEOS)
command_updater_.UpdateCommandEnabled(
diff --git a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc
index fa718692b769c3bbcf83f700718cf88dc631d058..c8ed066b698ab08d5cfbc644ca1f66f23c0fbeec 100644
--- a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc
+++ b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.cc
@@ -397,6 +397,13 @@ void BrowserDesktopWindowTreeHostWin::HandleDestroying() {
DesktopWindowTreeHostWin::HandleDestroying();
}
+void BrowserDesktopWindowTreeHostWin::HandleFrameChanged() {
+ // Reinitialize the status bubble, since it needs to be initialized
+ // differently depending on whether or not DWM composition is enabled
+ browser_view_->InitStatusBubble();
+ DesktopWindowTreeHostWin::HandleFrameChanged();
+}
+
void BrowserDesktopWindowTreeHostWin::HandleWindowScaleFactorChanged(
float window_scale_factor) {
DesktopWindowTreeHostWin::HandleWindowScaleFactorChanged(window_scale_factor);
diff --git a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h
index 28412d00adf463a1453aecc82ca1179f0521822d..a3bd2e0cae1d341adfe9dd498886ae5914e1cba7 100644
--- a/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h
+++ b/chrome/browser/ui/views/frame/browser_desktop_window_tree_host_win.h
@@ -66,6 +66,7 @@ class BrowserDesktopWindowTreeHostWin
bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override;
void HandleCreate() override;
void HandleDestroying() override;
+ void HandleFrameChanged() override;
void HandleWindowScaleFactorChanged(float window_scale_factor) override;
bool PreHandleMSG(UINT message,
WPARAM w_param,
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc
index 6920106ba91e0d1c0c1706a28b4ce5a14b5f3aed..306affc1d9573acd475d79f30a3583f0e716f33e 100644
--- a/chrome/browser/ui/views/frame/browser_view.cc
+++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -927,8 +927,7 @@ BrowserView::BrowserView(std::unique_ptr<Browser> browser)
infobar_container_ =
AddChildView(std::make_unique<InfoBarContainerView>(this));
- status_bubble_ = std::make_unique<StatusBubbleViews>(contents_web_view_);
- contents_web_view_->SetStatusBubble(status_bubble_.get());
+ InitStatusBubble();
// Create do-nothing view for the sake of controlling the z-order of the find
// bar widget.
@@ -1049,6 +1048,11 @@ void BrowserView::SetDisableRevealerDelayForTesting(bool disable) {
g_disable_revealer_delay_for_testing = disable;
}
+void BrowserView::InitStatusBubble() {
+ status_bubble_ = std::make_unique<StatusBubbleViews>(contents_web_view_);
+ contents_web_view_->SetStatusBubble(status_bubble_.get());
+}
+
gfx::Rect BrowserView::GetFindBarBoundingBox() const {
gfx::Rect contents_bounds = contents_container_->ConvertRectToWidget(
contents_container_->GetLocalBounds());
@@ -3397,6 +3401,11 @@ ui::ImageModel BrowserView::GetWindowIcon() {
}
bool BrowserView::ExecuteWindowsCommand(int command_id) {
+ // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
+#if BUILDFLAG(IS_WIN)
+ if (command_id == IDC_DEBUG_FRAME_TOGGLE)
+ GetWidget()->DebugToggleFrameType();
+#endif
// Translate WM_APPCOMMAND command ids into a command id that the browser
// knows how to handle.
int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h
index d80a6df7380e5aec6ecba092315c905a09d7e2cc..bde91001c6f75f9918b9063eb0eaff5d56ea06c1 100644
--- a/chrome/browser/ui/views/frame/browser_view.h
+++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -164,6 +164,12 @@ class BrowserView : public BrowserWindow,
void SetDownloadShelfForTest(DownloadShelf* download_shelf);
+ // Initializes (or re-initializes) the status bubble. We try to only create
+ // the bubble once and re-use it for the life of the browser, but certain
+ // events (such as changing enabling/disabling Aero on Win) can force a need
+ // to change some of the bubble's creation parameters.
+ void InitStatusBubble();
+
// Returns the constraining bounding box that should be used to lay out the
// FindBar within. This is _not_ the size of the find bar, just the bounding
// box it should be laid out within. The coordinate system of the returned
diff --git a/chrome/browser/ui/views/frame/system_menu_model_builder.cc b/chrome/browser/ui/views/frame/system_menu_model_builder.cc
index 984929bb899dbd791443bf3ccd841f5a975a7dbd..75719ef6280ce46c176cb3277e602a11d99a45e0 100644
--- a/chrome/browser/ui/views/frame/system_menu_model_builder.cc
+++ b/chrome/browser/ui/views/frame/system_menu_model_builder.cc
@@ -69,6 +69,7 @@ void SystemMenuModelBuilder::BuildMenu(ui::SimpleMenuModel* model) {
BuildSystemMenuForBrowserWindow(model);
else
BuildSystemMenuForAppOrPopupWindow(model);
+ AddFrameToggleItems(model);
}
void SystemMenuModelBuilder::BuildSystemMenuForBrowserWindow(
@@ -157,6 +158,14 @@ void SystemMenuModelBuilder::BuildSystemMenuForAppOrPopupWindow(
AppendTeleportMenu(model);
}
+void SystemMenuModelBuilder::AddFrameToggleItems(ui::SimpleMenuModel* model) {
+ if (base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kDebugEnableFrameToggle)) {
+ model->AddSeparator(ui::NORMAL_SEPARATOR);
+ model->AddItem(IDC_DEBUG_FRAME_TOGGLE, u"Toggle Frame Type");
+ }
+}
+
#if BUILDFLAG(IS_CHROMEOS)
void SystemMenuModelBuilder::AppendMoveToDesksMenu(ui::SimpleMenuModel* model) {
gfx::NativeWindow window =
diff --git a/chrome/browser/ui/views/frame/system_menu_model_builder.h b/chrome/browser/ui/views/frame/system_menu_model_builder.h
index 8f69eab1fc2b9c81d14f7b547b4f434c722b98aa..8acaa2816a03f41b19ec364eea2658682737798c 100644
--- a/chrome/browser/ui/views/frame/system_menu_model_builder.h
+++ b/chrome/browser/ui/views/frame/system_menu_model_builder.h
@@ -47,6 +47,9 @@ class SystemMenuModelBuilder {
void BuildSystemMenuForBrowserWindow(ui::SimpleMenuModel* model);
void BuildSystemMenuForAppOrPopupWindow(ui::SimpleMenuModel* model);
+ // Adds items for toggling the frame type (if necessary).
+ void AddFrameToggleItems(ui::SimpleMenuModel* model);
+
#if BUILDFLAG(IS_CHROMEOS)
// Add the submenu for move to desks.
void AppendMoveToDesksMenu(ui::SimpleMenuModel* model);
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc
index b23fbffea35f1f9936b998bbe501c9e5acdecf6a..4d635764d6c5db0b493aba9d3b2add095fc9ebe4 100644
--- a/chrome/common/chrome_switches.cc
+++ b/chrome/common/chrome_switches.cc
@@ -143,6 +143,10 @@ const char kCredits[] = "credits";
// devtools://devtools/bundled/<path>
const char kCustomDevtoolsFrontend[] = "custom-devtools-frontend";
+// Enables a frame context menu item that toggles the frame in and out of glass
+// mode (Windows Vista and up only).
+const char kDebugEnableFrameToggle[] = "debug-enable-frame-toggle";
+
// Adds debugging entries such as Inspect Element to context menus of packed
// apps.
const char kDebugPackedApps[] = "debug-packed-apps";
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h
index be1f7824d85a6705aa8c220578ac62f0d1a4114e..7ce3dd85d1cab1fbd5aff6104ea0d1b864ebcb0c 100644
--- a/chrome/common/chrome_switches.h
+++ b/chrome/common/chrome_switches.h
@@ -61,6 +61,7 @@ extern const char kCrashOnHangThreads[];
extern const char kCreateBrowserOnStartupForTests[];
extern const char kCredits[];
extern const char kCustomDevtoolsFrontend[];
+extern const char kDebugEnableFrameToggle[];
extern const char kDebugPackedApps[];
extern const char kDevToolsFlags[];
extern const char kDiagnostics[];
diff --git a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
index d0dc2b4993891837c6ac76e095833126db461032..ba1bcbc63475b7151e2335c9237124ca8ca31dc7 100644
--- a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
+++ b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
@@ -136,6 +136,30 @@ TEST_F(DesktopNativeWidgetAuraTest, WidgetNotVisibleOnlyWindowTreeHostShown) {
}
#endif
+TEST_F(DesktopNativeWidgetAuraTest, DesktopAuraWindowShowFrameless) {
+ Widget widget;
+ Widget::InitParams init_params =
+ CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
+ init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
+ widget.Init(std::move(init_params));
+
+ // Make sure that changing frame type doesn't crash when there's no non-client
+ // view.
+ ASSERT_EQ(nullptr, widget.non_client_view());
+ widget.DebugToggleFrameType();
+ widget.Show();
+
+#if BUILDFLAG(IS_WIN)
+ // On Windows also make sure that handling WM_SYSCOMMAND doesn't crash with
+ // custom frame. Frame type needs to be toggled again if Aero Glass is
+ // disabled.
+ if (widget.ShouldUseNativeFrame())
+ widget.DebugToggleFrameType();
+ SendMessage(widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget(),
+ WM_SYSCOMMAND, SC_RESTORE, 0);
+#endif // BUILDFLAG(IS_WIN)
+}
+
#if BUILDFLAG(IS_CHROMEOS_ASH)
// TODO(crbug.com/916272): investigate fixing and enabling on Chrome OS.
#define MAYBE_GlobalCursorState DISABLED_GlobalCursorState
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc
index 73e76c0d940f09336bbec6db47f1afee5153ced0..61673ac08ca19816dc01c89b6687f5b2a7c289e2 100644
--- a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc
+++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc
@@ -1028,6 +1028,8 @@ void DesktopWindowTreeHostWin::HandleClientSizeChanged(
}
void DesktopWindowTreeHostWin::HandleFrameChanged() {
+ CheckForMonitorChange();
+ desktop_native_widget_aura_->UpdateWindowTransparency();
// Replace the frame and layout the contents.
if (GetWidget()->non_client_view())
GetWidget()->non_client_view()->UpdateFrame();
diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc
index 2b52ad2f63bd6924fcd3d000bbb7ed6fd9f4b0dd..3d7a2f986c38de6b2e69722e63ee3b139d257756 100644
--- a/ui/views/widget/widget.cc
+++ b/ui/views/widget/widget.cc
@@ -1209,6 +1209,21 @@ bool Widget::ShouldWindowContentsBeTransparent() const {
: false;
}
+void Widget::DebugToggleFrameType() {
+ if (!native_widget_)
+ return;
+
+ if (frame_type_ == FrameType::kDefault) {
+ frame_type_ = ShouldUseNativeFrame() ? FrameType::kForceCustom
+ : FrameType::kForceNative;
+ } else {
+ frame_type_ = frame_type_ == FrameType::kForceCustom
+ ? FrameType::kForceNative
+ : FrameType::kForceCustom;
+ }
+ FrameTypeChanged();
+}
+
void Widget::FrameTypeChanged() {
if (native_widget_)
native_widget_->FrameTypeChanged();
diff --git a/ui/views/widget/widget.h b/ui/views/widget/widget.h
index 51017b6f5dd9a9d5f26723c7ec7a6e0404c93b65..54b9e676c9423b78184fc63b80299dd7529cbd28 100644
--- a/ui/views/widget/widget.h
+++ b/ui/views/widget/widget.h
@@ -922,6 +922,10 @@ class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate,
// (for example, so that they can overhang onto the window title bar).
bool ShouldWindowContentsBeTransparent() const;
+ // Forces the frame into the alternate frame type (custom or native) depending
+ // on its current state.
+ void DebugToggleFrameType();
+
// Tell the window that something caused the frame type to change.
void FrameTypeChanged();
diff --git a/ui/views/widget/widget_unittest.cc b/ui/views/widget/widget_unittest.cc
index 9aced70287c3ac877310457c1aad3b2544a85800..35f435d3d4d5eda44b69e5e66ec9480534d3ef44 100644
--- a/ui/views/widget/widget_unittest.cc
+++ b/ui/views/widget/widget_unittest.cc
@@ -1317,6 +1317,10 @@ TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Deactivate) {
widget()->Deactivate();
}
+TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, DebugToggleFrameType) {
+ widget()->DebugToggleFrameType();
+}
+
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, DraggedView) {
widget()->dragged_view();
}
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc
index 575877b4fb0929d0cdd22af399f7078fcd713584..90dd6487fdf438a61672a81f08b545742045944a 100644
--- a/ui/views/win/hwnd_message_handler.cc
+++ b/ui/views/win/hwnd_message_handler.cc
@@ -1741,6 +1741,20 @@ void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
}
}
+void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
+ if (IsFullscreen())
+ return;
+
+ DWMNCRENDERINGPOLICY policy =
+ custom_window_region_.is_valid() ||
+ delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN
+ ? DWMNCRP_DISABLED
+ : DWMNCRP_ENABLED;
+
+ DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY, &policy,
+ sizeof(DWMNCRENDERINGPOLICY));
+}
+
LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
WPARAM w_param,
LPARAM l_param) {
@@ -3607,10 +3621,34 @@ bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
}
void HWNDMessageHandler::PerformDwmTransition() {
- CHECK(IsFrameSystemDrawn());
-
dwm_transition_desired_ = false;
+
+ UpdateDwmNcRenderingPolicy();
+ // Don't redraw the window here, because we need to hide and show the window
+ // which will also trigger a redraw.
+ ResetWindowRegion(true, false);
+ // The non-client view needs to update too.
delegate_->HandleFrameChanged();
+ // This calls DwmExtendFrameIntoClientArea which must be called when DWM
+ // composition state changes.
+ UpdateDwmFrame();
+
+ if (IsVisible() && IsFrameSystemDrawn()) {
+ // For some reason, we need to hide the window after we change from a custom
+ // frame to a native frame. If we don't, the client area will be filled
+ // with black. This seems to be related to an interaction between DWM and
+ // SetWindowRgn, but the details aren't clear. Additionally, we need to
+ // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
+ // open they will re-appear with a non-deterministic Z-order.
+ // Note: caused http://crbug.com/895855, where a laptop lid close+reopen
+ // puts window in the background but acts like a foreground window. Fixed by
+ // not calling this unless DWM composition actually changes. Finally, since
+ // we don't want windows stealing focus if they're not already active, we
+ // set SWP_NOACTIVATE.
+ UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE;
+ SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
+ SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
+ }
}
void HWNDMessageHandler::UpdateDwmFrame() {
diff --git a/ui/views/win/hwnd_message_handler.h b/ui/views/win/hwnd_message_handler.h
index 7238af3f51179145a1c1eb9639ca756c2a697554..694945c4f3a62ed13a3b80cc5fba5673e29eef4e 100644
--- a/ui/views/win/hwnd_message_handler.h
+++ b/ui/views/win/hwnd_message_handler.h
@@ -324,6 +324,11 @@ class VIEWS_EXPORT HWNDMessageHandler : public gfx::WindowImpl,
// frame windows.
void ResetWindowRegion(bool force, bool redraw);
+ // Enables or disables rendering of the non-client (glass) area by DWM,
+ // under Vista and above, depending on whether the caller has requested a
+ // custom frame.
+ void UpdateDwmNcRenderingPolicy();
+
// Calls DefWindowProc, safely wrapping the call in a ScopedRedrawLock to
// prevent frame flicker. DefWindowProc handling can otherwise render the
// classic-look window title bar directly.
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
shell/browser/native_window.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_window.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/containers/contains.h"
#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/web_contents_user_data.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_window_features.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/window_list.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/options_switches.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/views/widget/widget.h"
#if !BUILDFLAG(IS_MAC)
#include "shell/browser/ui/views/frameless_view.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#endif
#if defined(USE_OZONE)
#include "ui/base/ui_base_features.h"
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace gin {
template <>
struct Converter<electron::NativeWindow::TitleBarStyle> {
static bool FromV8(v8::Isolate* isolate,
v8::Handle<v8::Value> val,
electron::NativeWindow::TitleBarStyle* out) {
using TitleBarStyle = electron::NativeWindow::TitleBarStyle;
std::string title_bar_style;
if (!ConvertFromV8(isolate, val, &title_bar_style))
return false;
if (title_bar_style == "hidden") {
*out = TitleBarStyle::kHidden;
#if BUILDFLAG(IS_MAC)
} else if (title_bar_style == "hiddenInset") {
*out = TitleBarStyle::kHiddenInset;
} else if (title_bar_style == "customButtonsOnHover") {
*out = TitleBarStyle::kCustomButtonsOnHover;
#endif
} else {
return false;
}
return true;
}
};
} // namespace gin
namespace electron {
namespace {
#if BUILDFLAG(IS_WIN)
gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) {
if (!window->transparent())
return size;
gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize(
window->GetAcceleratedWidget(), gfx::Size(64, 64));
// Some AMD drivers can't display windows that are less than 64x64 pixels,
// so expand them to be at least that size. http://crbug.com/286609
gfx::Size expanded(std::max(size.width(), min_size.width()),
std::max(size.height(), min_size.height()));
return expanded;
}
#endif
} // namespace
NativeWindow::NativeWindow(const gin_helper::Dictionary& options,
NativeWindow* parent)
: widget_(std::make_unique<views::Widget>()), parent_(parent) {
++next_id_;
options.Get(options::kFrame, &has_frame_);
options.Get(options::kTransparent, &transparent_);
options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_);
options.Get(options::kTitleBarStyle, &title_bar_style_);
v8::Local<v8::Value> titlebar_overlay;
if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) {
if (titlebar_overlay->IsBoolean()) {
options.Get(options::ktitleBarOverlay, &titlebar_overlay_);
} else if (titlebar_overlay->IsObject()) {
titlebar_overlay_ = true;
gin_helper::Dictionary titlebar_overlay_dict =
gin::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict);
int height;
if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height))
titlebar_overlay_height_ = height;
#if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC))
DCHECK(false);
#endif
}
}
if (parent)
options.Get("modal", &is_modal_);
#if defined(USE_OZONE)
// Ozone X11 likes to prefer custom frames, but we don't need them unless
// on Wayland.
if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) &&
!ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_server_side_window_decorations) {
has_client_frame_ = true;
}
#endif
WindowList::AddWindow(this);
}
NativeWindow::~NativeWindow() {
// It's possible that the windows gets destroyed before it's closed, in that
// case we need to ensure the Widget delegate gets destroyed and
// OnWindowClosed message is still notified.
if (widget_->widget_delegate())
widget_->OnNativeWidgetDestroyed();
NotifyWindowClosed();
}
void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
// Setup window from options.
int x = -1, y = -1;
bool center;
if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) {
SetPosition(gfx::Point(x, y));
#if BUILDFLAG(IS_WIN)
// FIXME(felixrieseberg): Dirty, dirty workaround for
// https://github.com/electron/electron/issues/10862
// Somehow, we need to call `SetBounds` twice to get
// usable results. The root cause is still unknown.
SetPosition(gfx::Point(x, y));
#endif
} else if (options.Get(options::kCenter, ¢er) && center) {
Center();
}
bool use_content_size = false;
options.Get(options::kUseContentSize, &use_content_size);
// On Linux and Window we may already have maximum size defined.
extensions::SizeConstraints size_constraints(
use_content_size ? GetContentSizeConstraints() : GetSizeConstraints());
int min_width = size_constraints.GetMinimumSize().width();
int min_height = size_constraints.GetMinimumSize().height();
options.Get(options::kMinWidth, &min_width);
options.Get(options::kMinHeight, &min_height);
size_constraints.set_minimum_size(gfx::Size(min_width, min_height));
gfx::Size max_size = size_constraints.GetMaximumSize();
int max_width = max_size.width() > 0 ? max_size.width() : INT_MAX;
int max_height = max_size.height() > 0 ? max_size.height() : INT_MAX;
bool have_max_width = options.Get(options::kMaxWidth, &max_width);
if (have_max_width && max_width <= 0)
max_width = INT_MAX;
bool have_max_height = options.Get(options::kMaxHeight, &max_height);
if (have_max_height && max_height <= 0)
max_height = INT_MAX;
// By default the window has a default maximum size that prevents it
// from being resized larger than the screen, so we should only set this
// if the user has passed in values.
if (have_max_height || have_max_width || !max_size.IsEmpty())
size_constraints.set_maximum_size(gfx::Size(max_width, max_height));
if (use_content_size) {
SetContentSizeConstraints(size_constraints);
} else {
SetSizeConstraints(size_constraints);
}
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
bool resizable;
if (options.Get(options::kResizable, &resizable)) {
SetResizable(resizable);
}
bool closable;
if (options.Get(options::kClosable, &closable)) {
SetClosable(closable);
}
#endif
bool movable;
if (options.Get(options::kMovable, &movable)) {
SetMovable(movable);
}
bool has_shadow;
if (options.Get(options::kHasShadow, &has_shadow)) {
SetHasShadow(has_shadow);
}
double opacity;
if (options.Get(options::kOpacity, &opacity)) {
SetOpacity(opacity);
}
bool top;
if (options.Get(options::kAlwaysOnTop, &top) && top) {
SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow);
}
bool fullscreenable = true;
bool fullscreen = false;
if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) {
// Disable fullscreen button if 'fullscreen' is specified to false.
#if BUILDFLAG(IS_MAC)
fullscreenable = false;
#endif
}
// Overridden by 'fullscreenable'.
options.Get(options::kFullScreenable, &fullscreenable);
SetFullScreenable(fullscreenable);
if (fullscreen) {
SetFullScreen(true);
}
bool skip;
if (options.Get(options::kSkipTaskbar, &skip)) {
SetSkipTaskbar(skip);
}
bool kiosk;
if (options.Get(options::kKiosk, &kiosk) && kiosk) {
SetKiosk(kiosk);
}
#if BUILDFLAG(IS_MAC)
std::string type;
if (options.Get(options::kVibrancyType, &type)) {
SetVibrancy(type);
}
#elif BUILDFLAG(IS_WIN)
std::string material;
if (options.Get(options::kBackgroundMaterial, &material)) {
SetBackgroundMaterial(material);
}
#endif
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
SetBackgroundColor(ParseCSSColor(color));
} else if (!transparent()) {
// For normal window, use white as default background.
SetBackgroundColor(SK_ColorWHITE);
}
std::string title(Browser::Get()->GetName());
options.Get(options::kTitle, &title);
SetTitle(title);
// Then show it.
bool show = true;
options.Get(options::kShow, &show);
if (show)
Show();
}
bool NativeWindow::IsClosed() const {
return is_closed_;
}
void NativeWindow::SetSize(const gfx::Size& size, bool animate) {
SetBounds(gfx::Rect(GetPosition(), size), animate);
}
gfx::Size NativeWindow::GetSize() {
return GetBounds().size();
}
void NativeWindow::SetPosition(const gfx::Point& position, bool animate) {
SetBounds(gfx::Rect(position, GetSize()), animate);
}
gfx::Point NativeWindow::GetPosition() {
return GetBounds().origin();
}
void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) {
SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate);
}
gfx::Size NativeWindow::GetContentSize() {
return GetContentBounds().size();
}
void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) {
SetBounds(ContentBoundsToWindowBounds(bounds), animate);
}
gfx::Rect NativeWindow::GetContentBounds() {
return WindowBoundsToContentBounds(GetBounds());
}
bool NativeWindow::IsNormal() {
return !IsMinimized() && !IsMaximized() && !IsFullscreen();
}
void NativeWindow::SetSizeConstraints(
const extensions::SizeConstraints& window_constraints) {
extensions::SizeConstraints content_constraints(GetContentSizeConstraints());
if (window_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMaximumSize()));
content_constraints.set_maximum_size(max_bounds.size());
}
if (window_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = WindowBoundsToContentBounds(
gfx::Rect(window_constraints.GetMinimumSize()));
content_constraints.set_minimum_size(min_bounds.size());
}
SetContentSizeConstraints(content_constraints);
}
extensions::SizeConstraints NativeWindow::GetSizeConstraints() const {
extensions::SizeConstraints content_constraints = GetContentSizeConstraints();
extensions::SizeConstraints window_constraints;
if (content_constraints.HasMaximumSize()) {
gfx::Rect max_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMaximumSize()));
window_constraints.set_maximum_size(max_bounds.size());
}
if (content_constraints.HasMinimumSize()) {
gfx::Rect min_bounds = ContentBoundsToWindowBounds(
gfx::Rect(content_constraints.GetMinimumSize()));
window_constraints.set_minimum_size(min_bounds.size());
}
return window_constraints;
}
void NativeWindow::SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) {
size_constraints_ = size_constraints;
}
extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const {
return size_constraints_;
}
void NativeWindow::SetMinimumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_minimum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMinimumSize() const {
return GetSizeConstraints().GetMinimumSize();
}
void NativeWindow::SetMaximumSize(const gfx::Size& size) {
extensions::SizeConstraints size_constraints;
size_constraints.set_maximum_size(size);
SetSizeConstraints(size_constraints);
}
gfx::Size NativeWindow::GetMaximumSize() const {
return GetSizeConstraints().GetMaximumSize();
}
gfx::Size NativeWindow::GetContentMinimumSize() const {
return GetContentSizeConstraints().GetMinimumSize();
}
gfx::Size NativeWindow::GetContentMaximumSize() const {
gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize();
#if BUILDFLAG(IS_WIN)
return GetContentSizeConstraints().HasMaximumSize()
? GetExpandedWindowSize(this, maximum_size)
: maximum_size;
#else
return maximum_size;
#endif
}
void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) {
sheet_offset_x_ = offsetX;
sheet_offset_y_ = offsetY;
}
double NativeWindow::GetSheetOffsetX() {
return sheet_offset_x_;
}
double NativeWindow::GetSheetOffsetY() {
return sheet_offset_y_;
}
bool NativeWindow::IsTabletMode() const {
return false;
}
void NativeWindow::SetRepresentedFilename(const std::string& filename) {}
std::string NativeWindow::GetRepresentedFilename() {
return "";
}
void NativeWindow::SetDocumentEdited(bool edited) {}
bool NativeWindow::IsDocumentEdited() {
return false;
}
void NativeWindow::SetFocusable(bool focusable) {}
bool NativeWindow::IsFocusable() {
return false;
}
void NativeWindow::SetMenu(ElectronMenuModel* menu) {}
void NativeWindow::SetParentWindow(NativeWindow* parent) {
parent_ = parent;
}
void NativeWindow::InvalidateShadow() {}
void NativeWindow::SetAutoHideCursor(bool auto_hide) {}
void NativeWindow::SelectPreviousTab() {}
void NativeWindow::SelectNextTab() {}
void NativeWindow::MergeAllWindows() {}
void NativeWindow::MoveTabToNewWindow() {}
void NativeWindow::ToggleTabBar() {}
bool NativeWindow::AddTabbedWindow(NativeWindow* window) {
return true; // for non-Mac platforms
}
void NativeWindow::SetVibrancy(const std::string& type) {}
void NativeWindow::SetBackgroundMaterial(const std::string& type) {}
void NativeWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {}
void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {}
void NativeWindow::SetEscapeTouchBarItem(
gin_helper::PersistentDictionary item) {}
void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {}
bool NativeWindow::IsMenuBarAutoHide() {
return false;
}
void NativeWindow::SetMenuBarVisibility(bool visible) {}
bool NativeWindow::IsMenuBarVisible() {
return true;
}
double NativeWindow::GetAspectRatio() {
return aspect_ratio_;
}
gfx::Size NativeWindow::GetAspectRatioExtraSize() {
return aspect_ratio_extraSize_;
}
void NativeWindow::SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) {
aspect_ratio_ = aspect_ratio;
aspect_ratio_extraSize_ = extra_size;
}
void NativeWindow::PreviewFile(const std::string& path,
const std::string& display_name) {}
void NativeWindow::CloseFilePreview() {}
gfx::Rect NativeWindow::GetWindowControlsOverlayRect() {
return overlay_rect_;
}
void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) {
overlay_rect_ = overlay_rect;
}
void NativeWindow::NotifyWindowRequestPreferredWidth(int* width) {
for (NativeWindowObserver& observer : observers_)
observer.RequestPreferredWidth(width);
}
void NativeWindow::NotifyWindowCloseButtonClicked() {
// First ask the observers whether we want to close.
bool prevent_default = false;
for (NativeWindowObserver& observer : observers_)
observer.WillCloseWindow(&prevent_default);
if (prevent_default) {
WindowList::WindowCloseCancelled(this);
return;
}
// Then ask the observers how should we close the window.
for (NativeWindowObserver& observer : observers_)
observer.OnCloseButtonClicked(&prevent_default);
if (prevent_default)
return;
CloseImmediately();
}
void NativeWindow::NotifyWindowClosed() {
if (is_closed_)
return;
is_closed_ = true;
for (NativeWindowObserver& observer : observers_)
observer.OnWindowClosed();
WindowList::RemoveWindow(this);
}
void NativeWindow::NotifyWindowEndSession() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEndSession();
}
void NativeWindow::NotifyWindowBlur() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowBlur();
}
void NativeWindow::NotifyWindowFocus() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowFocus();
}
void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowIsKeyChanged(is_key);
}
void NativeWindow::NotifyWindowShow() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowShow();
}
void NativeWindow::NotifyWindowHide() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowHide();
}
void NativeWindow::NotifyWindowMaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMaximize();
}
void NativeWindow::NotifyWindowUnmaximize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowUnmaximize();
}
void NativeWindow::NotifyWindowMinimize() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMinimize();
}
void NativeWindow::NotifyWindowRestore() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRestore();
}
void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillResize(new_bounds, edge, prevent_default);
}
void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowWillMove(new_bounds, prevent_default);
}
void NativeWindow::NotifyWindowResize() {
NotifyLayoutWindowControlsOverlay();
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResize();
}
void NativeWindow::NotifyWindowResized() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowResized();
}
void NativeWindow::NotifyWindowMove() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMove();
}
void NativeWindow::NotifyWindowMoved() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMoved();
}
void NativeWindow::NotifyWindowEnterFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterFullScreen();
}
void NativeWindow::NotifyWindowSwipe(const std::string& direction) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSwipe(direction);
}
void NativeWindow::NotifyWindowRotateGesture(float rotation) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowRotateGesture(rotation);
}
void NativeWindow::NotifyWindowSheetBegin() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetBegin();
}
void NativeWindow::NotifyWindowSheetEnd() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowSheetEnd();
}
void NativeWindow::NotifyWindowLeaveFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveFullScreen();
}
void NativeWindow::NotifyWindowEnterHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowEnterHtmlFullScreen();
}
void NativeWindow::NotifyWindowLeaveHtmlFullScreen() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowLeaveHtmlFullScreen();
}
void NativeWindow::NotifyWindowAlwaysOnTopChanged() {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowAlwaysOnTopChanged();
}
void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) {
for (NativeWindowObserver& observer : observers_)
observer.OnExecuteAppCommand(command);
}
void NativeWindow::NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details) {
for (NativeWindowObserver& observer : observers_)
observer.OnTouchBarItemResult(item_id, details);
}
void NativeWindow::NotifyNewWindowForTab() {
for (NativeWindowObserver& observer : observers_)
observer.OnNewWindowForTab();
}
void NativeWindow::NotifyWindowSystemContextMenu(int x,
int y,
bool* prevent_default) {
for (NativeWindowObserver& observer : observers_)
observer.OnSystemContextMenu(x, y, prevent_default);
}
void NativeWindow::NotifyLayoutWindowControlsOverlay() {
gfx::Rect bounding_rect = GetWindowControlsOverlayRect();
if (!bounding_rect.IsEmpty()) {
for (NativeWindowObserver& observer : observers_)
observer.UpdateWindowControlsOverlay(bounding_rect);
}
}
#if BUILDFLAG(IS_WIN)
void NativeWindow::NotifyWindowMessage(UINT message,
WPARAM w_param,
LPARAM l_param) {
for (NativeWindowObserver& observer : observers_)
observer.OnWindowMessage(message, w_param, l_param);
}
#endif
int NativeWindow::NonClientHitTest(const gfx::Point& point) {
#if !BUILDFLAG(IS_MAC)
// We need to ensure we account for resizing borders on Windows and Linux.
if ((!has_frame() || has_client_frame()) && IsResizable()) {
auto* frame =
static_cast<FramelessView*>(widget()->non_client_view()->frame_view());
int border_hit = frame->ResizingBorderHitTest(point);
if (border_hit != HTNOWHERE)
return border_hit;
}
#endif
for (auto* provider : draggable_region_providers_) {
int hit = provider->NonClientHitTest(point);
if (hit != HTNOWHERE)
return hit;
}
return HTNOWHERE;
}
void NativeWindow::AddDraggableRegionProvider(
DraggableRegionProvider* provider) {
if (!base::Contains(draggable_region_providers_, provider)) {
draggable_region_providers_.push_back(provider);
}
}
void NativeWindow::RemoveDraggableRegionProvider(
DraggableRegionProvider* provider) {
draggable_region_providers_.remove_if(
[&provider](DraggableRegionProvider* p) { return p == provider; });
}
views::Widget* NativeWindow::GetWidget() {
return widget();
}
const views::Widget* NativeWindow::GetWidget() const {
return widget();
}
std::u16string NativeWindow::GetAccessibleWindowTitle() const {
if (accessible_title_.empty()) {
return views::WidgetDelegate::GetAccessibleWindowTitle();
}
return accessible_title_;
}
void NativeWindow::SetAccessibleTitle(const std::string& title) {
accessible_title_ = base::UTF8ToUTF16(title);
}
std::string NativeWindow::GetAccessibleTitle() {
return base::UTF16ToUTF8(accessible_title_);
}
void NativeWindow::HandlePendingFullscreenTransitions() {
if (pending_transitions_.empty()) {
set_fullscreen_transition_type(FullScreenTransitionType::kNone);
return;
}
bool next_transition = pending_transitions_.front();
pending_transitions_.pop();
SetFullScreen(next_transition);
}
// static
int32_t NativeWindow::next_id_ = 0;
// static
void NativeWindowRelay::CreateForWebContents(
content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window) {
DCHECK(web_contents);
if (!web_contents->GetUserData(UserDataKey())) {
web_contents->SetUserData(
UserDataKey(),
base::WrapUnique(new NativeWindowRelay(web_contents, window)));
}
}
NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window)
: content::WebContentsUserData<NativeWindowRelay>(*web_contents),
native_window_(window) {}
NativeWindowRelay::~NativeWindowRelay() = default;
WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay);
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
shell/browser/native_window.h
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
#include <list>
#include <memory>
#include <queue>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/supports_user_data.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/web_contents_user_data.h"
#include "extensions/browser/app_window/size_constraints.h"
#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/native_window_observer.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/common/api/api.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/views/widget/widget_delegate.h"
class SkRegion;
namespace content {
struct NativeWebKeyboardEvent;
}
namespace gfx {
class Image;
class Point;
class Rect;
enum class ResizeEdge;
class Size;
} // namespace gfx
namespace gin_helper {
class Dictionary;
class PersistentDictionary;
} // namespace gin_helper
namespace electron {
class ElectronMenuModel;
class NativeBrowserView;
namespace api {
class BrowserView;
}
#if BUILDFLAG(IS_MAC)
typedef NSView* NativeWindowHandle;
#else
typedef gfx::AcceleratedWidget NativeWindowHandle;
#endif
class NativeWindow : public base::SupportsUserData,
public views::WidgetDelegate {
public:
~NativeWindow() override;
// disable copy
NativeWindow(const NativeWindow&) = delete;
NativeWindow& operator=(const NativeWindow&) = delete;
// Create window with existing WebContents, the caller is responsible for
// managing the window's live.
static NativeWindow* Create(const gin_helper::Dictionary& options,
NativeWindow* parent = nullptr);
void InitFromOptions(const gin_helper::Dictionary& options);
virtual void SetContentView(views::View* view) = 0;
virtual void Close() = 0;
virtual void CloseImmediately() = 0;
virtual bool IsClosed() const;
virtual void Focus(bool focus) = 0;
virtual bool IsFocused() = 0;
virtual void Show() = 0;
virtual void ShowInactive() = 0;
virtual void Hide() = 0;
virtual bool IsVisible() = 0;
virtual bool IsEnabled() = 0;
virtual void SetEnabled(bool enable) = 0;
virtual void Maximize() = 0;
virtual void Unmaximize() = 0;
virtual bool IsMaximized() = 0;
virtual void Minimize() = 0;
virtual void Restore() = 0;
virtual bool IsMinimized() = 0;
virtual void SetFullScreen(bool fullscreen) = 0;
virtual bool IsFullscreen() const = 0;
virtual void SetBounds(const gfx::Rect& bounds, bool animate = false) = 0;
virtual gfx::Rect GetBounds() = 0;
virtual void SetSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetSize();
virtual void SetPosition(const gfx::Point& position, bool animate = false);
virtual gfx::Point GetPosition();
virtual void SetContentSize(const gfx::Size& size, bool animate = false);
virtual gfx::Size GetContentSize();
virtual void SetContentBounds(const gfx::Rect& bounds, bool animate = false);
virtual gfx::Rect GetContentBounds();
virtual bool IsNormal();
virtual gfx::Rect GetNormalBounds() = 0;
virtual void SetSizeConstraints(
const extensions::SizeConstraints& window_constraints);
virtual extensions::SizeConstraints GetSizeConstraints() const;
virtual void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints);
virtual extensions::SizeConstraints GetContentSizeConstraints() const;
virtual void SetMinimumSize(const gfx::Size& size);
virtual gfx::Size GetMinimumSize() const;
virtual void SetMaximumSize(const gfx::Size& size);
virtual gfx::Size GetMaximumSize() const;
virtual gfx::Size GetContentMinimumSize() const;
virtual gfx::Size GetContentMaximumSize() const;
virtual void SetSheetOffset(const double offsetX, const double offsetY);
virtual double GetSheetOffsetX();
virtual double GetSheetOffsetY();
virtual void SetResizable(bool resizable) = 0;
virtual bool MoveAbove(const std::string& sourceId) = 0;
virtual void MoveTop() = 0;
virtual bool IsResizable() = 0;
virtual void SetMovable(bool movable) = 0;
virtual bool IsMovable() = 0;
virtual void SetMinimizable(bool minimizable) = 0;
virtual bool IsMinimizable() = 0;
virtual void SetMaximizable(bool maximizable) = 0;
virtual bool IsMaximizable() = 0;
virtual void SetFullScreenable(bool fullscreenable) = 0;
virtual bool IsFullScreenable() = 0;
virtual void SetClosable(bool closable) = 0;
virtual bool IsClosable() = 0;
virtual void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level = "floating",
int relativeLevel = 0) = 0;
virtual ui::ZOrderLevel GetZOrderLevel() = 0;
virtual void Center() = 0;
virtual void Invalidate() = 0;
virtual void SetTitle(const std::string& title) = 0;
virtual std::string GetTitle() = 0;
#if BUILDFLAG(IS_MAC)
virtual std::string GetAlwaysOnTopLevel() = 0;
virtual void SetActive(bool is_key) = 0;
virtual bool IsActive() const = 0;
virtual void RemoveChildWindow(NativeWindow* child) = 0;
virtual void AttachChildren() = 0;
virtual void DetachChildren() = 0;
#endif
// Ability to augment the window title for the screen readers.
void SetAccessibleTitle(const std::string& title);
std::string GetAccessibleTitle();
virtual void FlashFrame(bool flash) = 0;
virtual void SetSkipTaskbar(bool skip) = 0;
virtual void SetExcludedFromShownWindowsMenu(bool excluded) = 0;
virtual bool IsExcludedFromShownWindowsMenu() = 0;
virtual void SetSimpleFullScreen(bool simple_fullscreen) = 0;
virtual bool IsSimpleFullScreen() = 0;
virtual void SetKiosk(bool kiosk) = 0;
virtual bool IsKiosk() = 0;
virtual bool IsTabletMode() const;
virtual void SetBackgroundColor(SkColor color) = 0;
virtual SkColor GetBackgroundColor() = 0;
virtual void InvalidateShadow();
virtual void SetHasShadow(bool has_shadow) = 0;
virtual bool HasShadow() = 0;
virtual void SetOpacity(const double opacity) = 0;
virtual double GetOpacity() = 0;
virtual void SetRepresentedFilename(const std::string& filename);
virtual std::string GetRepresentedFilename();
virtual void SetDocumentEdited(bool edited);
virtual bool IsDocumentEdited();
virtual void SetIgnoreMouseEvents(bool ignore, bool forward) = 0;
virtual void SetContentProtection(bool enable) = 0;
virtual void SetFocusable(bool focusable);
virtual bool IsFocusable();
virtual void SetMenu(ElectronMenuModel* menu);
virtual void SetParentWindow(NativeWindow* parent);
virtual void AddBrowserView(NativeBrowserView* browser_view) = 0;
virtual void RemoveBrowserView(NativeBrowserView* browser_view) = 0;
virtual void SetTopBrowserView(NativeBrowserView* browser_view) = 0;
virtual content::DesktopMediaID GetDesktopMediaID() const = 0;
virtual gfx::NativeView GetNativeView() const = 0;
virtual gfx::NativeWindow GetNativeWindow() const = 0;
virtual gfx::AcceleratedWidget GetAcceleratedWidget() const = 0;
virtual NativeWindowHandle GetNativeWindowHandle() const = 0;
// Taskbar/Dock APIs.
enum class ProgressState {
kNone, // no progress, no marking
kIndeterminate, // progress, indeterminate
kError, // progress, errored (red)
kPaused, // progress, paused (yellow)
kNormal, // progress, not marked (green)
};
virtual void SetProgressBar(double progress, const ProgressState state) = 0;
virtual void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) = 0;
// Workspace APIs.
virtual void SetVisibleOnAllWorkspaces(
bool visible,
bool visibleOnFullScreen = false,
bool skipTransformProcessType = false) = 0;
virtual bool IsVisibleOnAllWorkspaces() = 0;
virtual void SetAutoHideCursor(bool auto_hide);
// Vibrancy API
virtual void SetVibrancy(const std::string& type);
virtual void SetBackgroundMaterial(const std::string& type);
// Traffic Light API
#if BUILDFLAG(IS_MAC)
virtual void SetWindowButtonVisibility(bool visible) = 0;
virtual bool GetWindowButtonVisibility() const = 0;
virtual void SetWindowButtonPosition(absl::optional<gfx::Point> position) = 0;
virtual absl::optional<gfx::Point> GetWindowButtonPosition() const = 0;
virtual void RedrawTrafficLights() = 0;
virtual void UpdateFrame() = 0;
#endif
// whether windows should be ignored by mission control
#if BUILDFLAG(IS_MAC)
virtual bool IsHiddenInMissionControl() = 0;
virtual void SetHiddenInMissionControl(bool hidden) = 0;
#endif
// Touchbar API
virtual void SetTouchBar(std::vector<gin_helper::PersistentDictionary> items);
virtual void RefreshTouchBarItem(const std::string& item_id);
virtual void SetEscapeTouchBarItem(gin_helper::PersistentDictionary item);
// Native Tab API
virtual void SelectPreviousTab();
virtual void SelectNextTab();
virtual void MergeAllWindows();
virtual void MoveTabToNewWindow();
virtual void ToggleTabBar();
virtual bool AddTabbedWindow(NativeWindow* window);
// Toggle the menu bar.
virtual void SetAutoHideMenuBar(bool auto_hide);
virtual bool IsMenuBarAutoHide();
virtual void SetMenuBarVisibility(bool visible);
virtual bool IsMenuBarVisible();
// Set the aspect ratio when resizing window.
double GetAspectRatio();
gfx::Size GetAspectRatioExtraSize();
virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size);
// File preview APIs.
virtual void PreviewFile(const std::string& path,
const std::string& display_name);
virtual void CloseFilePreview();
virtual void SetGTKDarkThemeEnabled(bool use_dark_theme) {}
// Converts between content bounds and window bounds.
virtual gfx::Rect ContentBoundsToWindowBounds(
const gfx::Rect& bounds) const = 0;
virtual gfx::Rect WindowBoundsToContentBounds(
const gfx::Rect& bounds) const = 0;
base::WeakPtr<NativeWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
virtual gfx::Rect GetWindowControlsOverlayRect();
virtual void SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect);
// Methods called by the WebContents.
virtual void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) {}
// Public API used by platform-dependent delegates and observers to send UI
// related notifications.
void NotifyWindowRequestPreferredWidth(int* width);
void NotifyWindowCloseButtonClicked();
void NotifyWindowClosed();
void NotifyWindowEndSession();
void NotifyWindowBlur();
void NotifyWindowFocus();
void NotifyWindowShow();
void NotifyWindowIsKeyChanged(bool is_key);
void NotifyWindowHide();
void NotifyWindowMaximize();
void NotifyWindowUnmaximize();
void NotifyWindowMinimize();
void NotifyWindowRestore();
void NotifyWindowMove();
void NotifyWindowWillResize(const gfx::Rect& new_bounds,
const gfx::ResizeEdge& edge,
bool* prevent_default);
void NotifyWindowResize();
void NotifyWindowResized();
void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default);
void NotifyWindowMoved();
void NotifyWindowSwipe(const std::string& direction);
void NotifyWindowRotateGesture(float rotation);
void NotifyWindowSheetBegin();
void NotifyWindowSheetEnd();
virtual void NotifyWindowEnterFullScreen();
virtual void NotifyWindowLeaveFullScreen();
void NotifyWindowEnterHtmlFullScreen();
void NotifyWindowLeaveHtmlFullScreen();
void NotifyWindowAlwaysOnTopChanged();
void NotifyWindowExecuteAppCommand(const std::string& command);
void NotifyTouchBarItemInteraction(const std::string& item_id,
base::Value::Dict details);
void NotifyNewWindowForTab();
void NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default);
void NotifyLayoutWindowControlsOverlay();
#if BUILDFLAG(IS_WIN)
void NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param);
#endif
void AddObserver(NativeWindowObserver* obs) { observers_.AddObserver(obs); }
void RemoveObserver(NativeWindowObserver* obs) {
observers_.RemoveObserver(obs);
}
// Handle fullscreen transitions.
void HandlePendingFullscreenTransitions();
enum class FullScreenTransitionState { kEntering, kExiting, kNone };
void set_fullscreen_transition_state(FullScreenTransitionState state) {
fullscreen_transition_state_ = state;
}
FullScreenTransitionState fullscreen_transition_state() const {
return fullscreen_transition_state_;
}
enum class FullScreenTransitionType { kHTML, kNative, kNone };
void set_fullscreen_transition_type(FullScreenTransitionType type) {
fullscreen_transition_type_ = type;
}
FullScreenTransitionType fullscreen_transition_type() const {
return fullscreen_transition_type_;
}
views::Widget* widget() const { return widget_.get(); }
views::View* content_view() const { return content_view_; }
enum class TitleBarStyle {
kNormal,
kHidden,
kHiddenInset,
kCustomButtonsOnHover,
};
TitleBarStyle title_bar_style() const { return title_bar_style_; }
int titlebar_overlay_height() const { return titlebar_overlay_height_; }
void set_titlebar_overlay_height(int height) {
titlebar_overlay_height_ = height;
}
bool titlebar_overlay_enabled() const { return titlebar_overlay_; }
bool has_frame() const { return has_frame_; }
void set_has_frame(bool has_frame) { has_frame_ = has_frame; }
bool has_client_frame() const { return has_client_frame_; }
bool transparent() const { return transparent_; }
bool enable_larger_than_screen() const { return enable_larger_than_screen_; }
NativeWindow* parent() const { return parent_; }
bool is_modal() const { return is_modal_; }
std::list<NativeBrowserView*> browser_views() const { return browser_views_; }
int32_t window_id() const { return next_id_; }
void add_child_window(NativeWindow* child) {
child_windows_.push_back(child);
}
int NonClientHitTest(const gfx::Point& point);
void AddDraggableRegionProvider(DraggableRegionProvider* provider);
void RemoveDraggableRegionProvider(DraggableRegionProvider* provider);
protected:
friend class api::BrowserView;
NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent);
// views::WidgetDelegate:
views::Widget* GetWidget() override;
const views::Widget* GetWidget() const override;
std::u16string GetAccessibleWindowTitle() const override;
void set_content_view(views::View* view) { content_view_ = view; }
void add_browser_view(NativeBrowserView* browser_view) {
browser_views_.push_back(browser_view);
}
void remove_browser_view(NativeBrowserView* browser_view) {
browser_views_.remove_if(
[&browser_view](NativeBrowserView* n) { return (n == browser_view); });
}
// The boolean parsing of the "titleBarOverlay" option
bool titlebar_overlay_ = false;
// The custom height parsed from the "height" option in a Object
// "titleBarOverlay"
int titlebar_overlay_height_ = 0;
// The "titleBarStyle" option.
TitleBarStyle title_bar_style_ = TitleBarStyle::kNormal;
std::queue<bool> pending_transitions_;
FullScreenTransitionState fullscreen_transition_state_ =
FullScreenTransitionState::kNone;
FullScreenTransitionType fullscreen_transition_type_ =
FullScreenTransitionType::kNone;
std::list<NativeWindow*> child_windows_;
private:
std::unique_ptr<views::Widget> widget_;
static int32_t next_id_;
// The content view, weak ref.
raw_ptr<views::View> content_view_ = nullptr;
// Whether window has standard frame.
bool has_frame_ = true;
// Whether window has standard frame, but it's drawn by Electron (the client
// application) instead of the OS. Currently only has meaning on Linux for
// Wayland hosts.
bool has_client_frame_ = false;
// Whether window is transparent.
bool transparent_ = false;
// Minimum and maximum size, stored as content size.
extensions::SizeConstraints size_constraints_;
// Whether window can be resized larger than screen.
bool enable_larger_than_screen_ = false;
// The windows has been closed.
bool is_closed_ = false;
// Used to display sheets at the appropriate horizontal and vertical offsets
// on macOS.
double sheet_offset_x_ = 0.0;
double sheet_offset_y_ = 0.0;
// Used to maintain the aspect ratio of a view which is inside of the
// content view.
double aspect_ratio_ = 0.0;
gfx::Size aspect_ratio_extraSize_;
// The parent window, it is guaranteed to be valid during this window's life.
raw_ptr<NativeWindow> parent_ = nullptr;
// Is this a modal window.
bool is_modal_ = false;
// The browser view layer.
std::list<NativeBrowserView*> browser_views_;
std::list<DraggableRegionProvider*> draggable_region_providers_;
// Observers of this window.
base::ObserverList<NativeWindowObserver> observers_;
// Accessible title.
std::u16string accessible_title_;
gfx::Rect overlay_rect_;
base::WeakPtrFactory<NativeWindow> weak_factory_{this};
};
// This class provides a hook to get a NativeWindow from a WebContents.
class NativeWindowRelay
: public content::WebContentsUserData<NativeWindowRelay> {
public:
static void CreateForWebContents(content::WebContents*,
base::WeakPtr<NativeWindow>);
~NativeWindowRelay() override;
NativeWindow* GetNativeWindow() const { return native_window_.get(); }
WEB_CONTENTS_USER_DATA_KEY_DECL();
private:
friend class content::WebContentsUserData<NativeWindow>;
explicit NativeWindowRelay(content::WebContents* web_contents,
base::WeakPtr<NativeWindow> window);
base::WeakPtr<NativeWindow> native_window_;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
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 <dwmapi.h>
#include <wrl/client.h>
#endif
#include <memory>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/memory/raw_ptr.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/inspectable_web_contents.h"
#include "shell/browser/ui/views/inspectable_web_contents_view_views.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/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 "base/win/windows_version.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)
DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) {
if (material == "none") {
return DWMSBT_NONE;
} else if (material == "acrylic") {
return DWMSBT_TRANSIENTWINDOW;
} else if (material == "mica") {
return DWMSBT_MAINWINDOW;
} else if (material == "tabbed") {
return DWMSBT_TABBEDWINDOW;
}
return DWMSBT_AUTO;
}
// 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_{raw_ref<NativeWindowViews>::from_ptr(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:
const raw_ref<NativeWindowViews> window_;
};
} // namespace
NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent)
: NativeWindow(options, parent) {
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() {
#if BUILDFLAG(IS_WIN)
// widget()->IsVisible() calls ::IsWindowVisible, which returns non-zero if a
// window or any of its parent windows are visible. We want to only check the
// current window.
bool visible =
::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_VISIBLE;
// WS_VISIBLE is true even if a window is miminized - explicitly check that.
return visible && !IsMinimized();
#else
return widget()->IsVisible();
#endif
}
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() && !IsMinimized()) {
// 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) {
menu_bar_visible_before_fullscreen_ = IsMenuBarVisible();
SetMenuBarVisibility(false);
} else {
SetMenuBarVisibility(!IsMenuBarAutoHide() &&
menu_bar_visible_before_fullscreen_);
menu_bar_visible_before_fullscreen_ = false;
}
#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() {
#if BUILDFLAG(IS_WIN)
if (IsMaximized() && transparent())
return restore_bounds_;
#endif
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 = std::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::SetBackgroundMaterial(const std::string& material) {
#if BUILDFLAG(IS_WIN)
// DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up.
if (base::win::GetVersion() < base::win::Version::WIN11_22H2)
return;
DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material);
HRESULT result =
DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE,
&backdrop_type, sizeof(backdrop_type));
if (FAILED(result))
LOG(WARNING) << "Failed to set background material to " << material;
#endif
}
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 base::Contains(wm_states, sticky_atom);
}
#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;
}
#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_;
}
bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) {
return NonClientHitTest(location) == HTNOWHERE;
}
views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
return new NativeWindowClientView{widget, GetContentsView(), 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
| 38,937 |
[Test]: Failing BrowserWindow.setAspectRatio(ratio) doesn\'t change bounds when maximum size is set
|
https://chromium-review.googlesource.com/c/chromium/src/+/4575565 that comes as part of the roll https://github.com/electron/electron/pull/38891 breaks the calculation of content bounds when adjusting the maximum/minimum size.
The calculation done as part of https://github.com/electron/electron/blob/09669f9d215ceb96d7f02f9085d7906e27c2b301/shell/browser/native_window_views.cc#L1526-L1528 conflicts with the adjustments in https://github.com/electron/electron/blob/main/patches/chromium/fix_aspect_ratio_with_max_size.patch leading to the following dcheck failure in the said test
```
FATAL:resize_utils.cc(48)] Check failed: Rect(rect.origin(), *max_window_size).Contains(rect). 312,164 400x400 is larger than the maximum size 390x390
```
I tried to resolve this via the following patch which address the failing test but introduces regression in other bound calculations. @zcbenz can you take a look at this, thanks!
```patch
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a1581d98d0..48bc8ac23e 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1521,11 +1521,10 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#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);
+ RECT rect, client_rect;
+ GetClientRect(hwnd, &client_rect);
+ GetWindowRect(hwnd, &rect);
+ CR_DEFLATE_RECT(&rect, &client_rect);
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());
```
|
https://github.com/electron/electron/issues/38937
|
https://github.com/electron/electron/pull/38974
|
52fe76ca28286400ab61927b2b4e937c52ae9ab5
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
| 2023-06-27T13:33:18Z |
c++
| 2023-07-05T15:02:05Z |
shell/browser/native_window_views.h
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#define ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
#include "shell/browser/native_window.h"
#include <memory>
#include <set>
#include <string>
#include "base/memory/raw_ptr.h"
#include "shell/browser/ui/views/root_view.h"
#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include "ui/views/widget/widget_observer.h"
#if defined(USE_OZONE)
#include "ui/ozone/buildflags.h"
#if BUILDFLAG(OZONE_PLATFORM_X11)
#define USE_OZONE_PLATFORM_X11
#endif
#endif
#if BUILDFLAG(IS_WIN)
#include "base/win/scoped_gdi_object.h"
#include "shell/browser/ui/win/taskbar_host.h"
#endif
namespace electron {
class GlobalMenuBarX11;
class WindowStateWatcher;
#if defined(USE_OZONE_PLATFORM_X11)
class EventDisabler;
#endif
#if BUILDFLAG(IS_WIN)
gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds);
#endif
class NativeWindowViews : public NativeWindow,
public views::WidgetObserver,
public ui::EventHandler {
public:
NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent);
~NativeWindowViews() override;
// NativeWindow:
void SetContentView(views::View* view) override;
void Close() override;
void CloseImmediately() override;
void Focus(bool focus) override;
bool IsFocused() override;
void Show() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsEnabled() override;
void SetEnabled(bool enable) override;
void Maximize() override;
void Unmaximize() override;
bool IsMaximized() override;
void Minimize() override;
void Restore() override;
bool IsMinimized() override;
void SetFullScreen(bool fullscreen) override;
bool IsFullscreen() const override;
void SetBounds(const gfx::Rect& bounds, bool animate) override;
gfx::Rect GetBounds() override;
gfx::Rect GetContentBounds() override;
gfx::Size GetContentSize() override;
gfx::Rect GetNormalBounds() override;
SkColor GetBackgroundColor() override;
void SetContentSizeConstraints(
const extensions::SizeConstraints& size_constraints) override;
void SetResizable(bool resizable) override;
bool MoveAbove(const std::string& sourceId) override;
void MoveTop() override;
bool IsResizable() override;
void SetAspectRatio(double aspect_ratio,
const gfx::Size& extra_size) override;
void SetMovable(bool movable) override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;
void SetMaximizable(bool maximizable) override;
bool IsMaximizable() override;
void SetFullScreenable(bool fullscreenable) override;
bool IsFullScreenable() override;
void SetClosable(bool closable) override;
bool IsClosable() override;
void SetAlwaysOnTop(ui::ZOrderLevel z_order,
const std::string& level,
int relativeLevel) override;
ui::ZOrderLevel GetZOrderLevel() override;
void Center() override;
void Invalidate() override;
void SetTitle(const std::string& title) override;
std::string GetTitle() override;
void FlashFrame(bool flash) override;
void SetSkipTaskbar(bool skip) override;
void SetExcludedFromShownWindowsMenu(bool excluded) override;
bool IsExcludedFromShownWindowsMenu() override;
void SetSimpleFullScreen(bool simple_fullscreen) override;
bool IsSimpleFullScreen() override;
void SetKiosk(bool kiosk) override;
bool IsKiosk() override;
bool IsTabletMode() const override;
void SetBackgroundColor(SkColor color) override;
void SetHasShadow(bool has_shadow) override;
bool HasShadow() override;
void SetOpacity(const double opacity) override;
double GetOpacity() override;
void SetIgnoreMouseEvents(bool ignore, bool forward) override;
void SetContentProtection(bool enable) override;
void SetFocusable(bool focusable) override;
bool IsFocusable() override;
void SetMenu(ElectronMenuModel* menu_model) override;
void AddBrowserView(NativeBrowserView* browser_view) override;
void RemoveBrowserView(NativeBrowserView* browser_view) override;
void SetTopBrowserView(NativeBrowserView* browser_view) override;
void SetParentWindow(NativeWindow* parent) override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
void SetOverlayIcon(const gfx::Image& overlay,
const std::string& description) override;
void SetProgressBar(double progress, const ProgressState state) override;
void SetAutoHideMenuBar(bool auto_hide) override;
bool IsMenuBarAutoHide() override;
void SetMenuBarVisibility(bool visible) override;
bool IsMenuBarVisible() override;
void SetBackgroundMaterial(const std::string& type) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
bool skipTransformProcessType) override;
bool IsVisibleOnAllWorkspaces() override;
void SetGTKDarkThemeEnabled(bool use_dark_theme) override;
content::DesktopMediaID GetDesktopMediaID() const override;
gfx::AcceleratedWidget GetAcceleratedWidget() const override;
NativeWindowHandle GetNativeWindowHandle() const override;
gfx::Rect ContentBoundsToWindowBounds(const gfx::Rect& bounds) const override;
gfx::Rect WindowBoundsToContentBounds(const gfx::Rect& bounds) const override;
void IncrementChildModals();
void DecrementChildModals();
#if BUILDFLAG(IS_WIN)
// Catch-all message handling and filtering. Called before
// HWNDMessageHandler's built-in handling, which may pre-empt some
// expectations in Views/Aura if messages are consumed. Returns true if the
// message was consumed by the delegate and should not be processed further
// by the HWNDMessageHandler. In this case, |result| is returned. |result| is
// not modified otherwise.
bool PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result);
void SetIcon(HICON small_icon, HICON app_icon);
#elif BUILDFLAG(IS_LINUX)
void SetIcon(const gfx::ImageSkia& icon);
#endif
#if BUILDFLAG(IS_WIN)
TaskbarHost& taskbar_host() { return taskbar_host_; }
#endif
#if BUILDFLAG(IS_WIN)
bool IsWindowControlsOverlayEnabled() const {
return (title_bar_style_ == NativeWindowViews::TitleBarStyle::kHidden) &&
titlebar_overlay_;
}
SkColor overlay_button_color() const { return overlay_button_color_; }
void set_overlay_button_color(SkColor color) {
overlay_button_color_ = color;
}
SkColor overlay_symbol_color() const { return overlay_symbol_color_; }
void set_overlay_symbol_color(SkColor color) {
overlay_symbol_color_ = color;
}
#endif
private:
// views::WidgetObserver:
void OnWidgetActivationChanged(views::Widget* widget, bool active) override;
void OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& bounds) override;
void OnWidgetDestroying(views::Widget* widget) override;
void OnWidgetDestroyed(views::Widget* widget) override;
// views::WidgetDelegate:
views::View* GetInitiallyFocusedView() override;
bool CanMaximize() const override;
bool CanMinimize() const override;
std::u16string GetWindowTitle() const override;
views::View* GetContentsView() override;
bool ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) override;
views::ClientView* CreateClientView(views::Widget* widget) override;
std::unique_ptr<views::NonClientFrameView> CreateNonClientFrameView(
views::Widget* widget) override;
void OnWidgetMove() override;
#if BUILDFLAG(IS_WIN)
bool ExecuteWindowsCommand(int command_id) override;
#endif
#if BUILDFLAG(IS_WIN)
void HandleSizeEvent(WPARAM w_param, LPARAM l_param);
void ResetWindowControls();
void SetForwardMouseMessages(bool forward);
static LRESULT CALLBACK SubclassProc(HWND hwnd,
UINT msg,
WPARAM w_param,
LPARAM l_param,
UINT_PTR subclass_id,
DWORD_PTR ref_data);
static LRESULT CALLBACK MouseHookProc(int n_code,
WPARAM w_param,
LPARAM l_param);
#endif
// Enable/disable:
bool ShouldBeEnabled();
void SetEnabledInternal(bool enabled);
// NativeWindow:
void HandleKeyboardEvent(
content::WebContents*,
const content::NativeWebKeyboardEvent& event) override;
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override;
// Returns the restore state for the window.
ui::WindowShowState GetRestoredState();
// Maintain window placement.
void MoveBehindTaskBarIfNeeded();
RootView root_view_{this};
// The view should be focused by default.
raw_ptr<views::View> focused_view_ = nullptr;
// The "resizable" flag on Linux is implemented by setting size constraints,
// we need to make sure size constraints are restored when window becomes
// resizable again. This is also used on Windows, to keep taskbar resize
// events from resizing the window.
extensions::SizeConstraints old_size_constraints_;
#if defined(USE_OZONE)
std::unique_ptr<GlobalMenuBarX11> global_menu_bar_;
#endif
#if defined(USE_OZONE_PLATFORM_X11)
// To disable the mouse events.
std::unique_ptr<EventDisabler> event_disabler_;
#endif
#if BUILDFLAG(IS_WIN)
ui::WindowShowState last_window_state_;
gfx::Rect last_normal_placement_bounds_;
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;
// Memoized version of a11y check
bool checked_for_a11y_support_ = false;
// Whether to show the WS_THICKFRAME style.
bool thick_frame_ = true;
// The bounds of window before maximize/fullscreen.
gfx::Rect restore_bounds_;
// The icons of window and taskbar.
base::win::ScopedHICON window_icon_;
base::win::ScopedHICON app_icon_;
// The set of windows currently forwarding mouse messages.
static std::set<NativeWindowViews*> forwarding_windows_;
static HHOOK mouse_hook_;
bool forwarding_mouse_messages_ = false;
HWND legacy_window_ = NULL;
bool layered_ = false;
// Set to true if the window is always on top and behind the task bar.
bool behind_task_bar_ = false;
// Whether we want to set window placement without side effect.
bool is_setting_window_placement_ = false;
// Whether the window is currently being resized.
bool is_resizing_ = false;
// Whether the window is currently being moved.
bool is_moving_ = false;
absl::optional<gfx::Rect> pending_bounds_change_;
// The color to use as the theme and symbol colors respectively for Window
// Controls Overlay if enabled on Windows.
SkColor overlay_button_color_;
SkColor overlay_symbol_color_;
#endif
// Handles unhandled keyboard messages coming back from the renderer process.
views::UnhandledKeyboardEventHandler keyboard_event_handler_;
// Whether the menubar is visible before the window enters fullscreen
bool menu_bar_visible_before_fullscreen_ = false;
// Whether the window should be enabled based on user calls to SetEnabled()
bool is_enabled_ = true;
// How many modal children this window has;
// used to determine enabled state
unsigned int num_modal_children_ = 0;
bool use_content_size_ = false;
bool movable_ = true;
bool resizable_ = true;
bool maximizable_ = true;
bool minimizable_ = true;
bool fullscreenable_ = true;
std::string title_;
gfx::Size widget_size_;
double opacity_ = 1.0;
bool widget_destroyed_ = false;
};
} // namespace electron
#endif // ELECTRON_SHELL_BROWSER_NATIVE_WINDOW_VIEWS_H_
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 34,499 |
[Feature Request]: Improve Documentation on BrowserWindow `type` attribute
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
The docs regarding the `type` property of the BrowserWindow lacks explanation:
https://www.electronjs.org/de/docs/latest/api/browser-window
```
The possible values and behaviors of the type option are platform dependent. Mögliche Werte sind:
On Linux, possible types are desktop, dock, toolbar, splash, notification.
On macOS, possible types are desktop, textured.
The textured type adds metal gradient appearance (NSTexturedBackgroundWindowMask).
The desktop type places the window at the desktop background window level (kCGDesktopWindowLevel - 1). Note that desktop window will not receive focus, keyboard or mouse events, but you can use globalShortcut to receive input sparingly.
On Windows, possible type is toolbar.
```
It is not clear what the effects of the seperate options are, e.g.
A frameless window on linux with type `splash` is not draggable, even if the style property on the body contains `-webkit-app-region: drag`
### Proposed Solution
Add some context for the values e.g.
On Linux, possible types are:
- desktop: ...
- dock: ...
- toolbar: ...
- splash: Window type `splash` does x,y and prevents the window from being draged
- notification: ...
### Alternatives Considered
None
### Additional Information
I have chosen "splash" as type of my BrowserWindows, for a reason i cant remember. On my windows machine i have been able to move the window, on linux not.
The search for the reason have more or less been "try and error" -> comment everything until it works
After i found the culprint, window type `splash`, i wanted to check what are the side effects if i remove this setting but the docs didnt have any information.
|
https://github.com/electron/electron/issues/34499
|
https://github.com/electron/electron/pull/38666
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
|
ec4c9024b9795d360fbd96b09684fdb228966781
| 2022-06-10T13:01:28Z |
c++
| 2023-07-05T20:26:39Z |
docs/api/structures/browser-window-options.md
|
# BrowserWindowConstructorOptions Object
* `width` Integer (optional) - Window's width in pixels. Default is `800`.
* `height` Integer (optional) - Window's height in pixels. Default is `600`.
* `x` Integer (optional) - (**required** if y is used) Window's left offset from screen.
Default is to center the window.
* `y` Integer (optional) - (**required** if x is used) Window's top offset from screen.
Default is to center the window.
* `useContentSize` boolean (optional) - The `width` and `height` would be used as web
page's size, which means the actual window's size will include window
frame's size and be slightly larger. Default is `false`.
* `center` boolean (optional) - Show window in the center of the screen. Default is `false`.
* `minWidth` Integer (optional) - Window's minimum width. Default is `0`.
* `minHeight` Integer (optional) - Window's minimum height. Default is `0`.
* `maxWidth` Integer (optional) - Window's maximum width. Default is no limit.
* `maxHeight` Integer (optional) - Window's maximum height. Default is no limit.
* `resizable` boolean (optional) - Whether window is resizable. Default is `true`.
* `movable` boolean (optional) _macOS_ _Windows_ - Whether window is
movable. This is not implemented on Linux. Default is `true`.
* `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is
minimizable. This is not implemented on Linux. Default is `true`.
* `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is
maximizable. This is not implemented on Linux. Default is `true`.
* `closable` boolean (optional) _macOS_ _Windows_ - Whether window is
closable. This is not implemented on Linux. Default is `true`.
* `focusable` boolean (optional) - Whether the window can be focused. Default is
`true`. On Windows setting `focusable: false` also implies setting
`skipTaskbar: true`. On Linux setting `focusable: false` makes the window
stop interacting with wm, so the window will always stay on top in all
workspaces.
* `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of
other windows. Default is `false`.
* `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When
explicitly set to `false` the fullscreen button will be hidden or disabled
on macOS. Default is `false`.
* `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen
mode. On macOS, also whether the maximize/zoom button should toggle full
screen mode or maximize window. Default is `true`.
* `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on
macOS. Default is `false`.
* `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar.
Default is `false`.
* `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control.
* `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`.
* `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored.
* `icon` ([NativeImage](../native-image.md) | string) (optional) - The window icon. On Windows it is
recommended to use `ICO` icons to get best visual effects, you can also
leave it undefined so the executable's icon will be used.
* `show` boolean (optional) - Whether window should be shown when created. Default is
`true`.
* `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`.
* `frame` boolean (optional) - Specify `false` to create a
[frameless window](../../tutorial/window-customization.md#create-frameless-windows). Default is `true`.
* `parent` BrowserWindow (optional) - Specify parent window. Default is `null`.
* `modal` boolean (optional) - Whether this is a modal window. This only works when the
window is a child window. Default is `false`.
* `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an
inactive window will also click through to the web contents. Default is
`false` on macOS. This option is not configurable on other platforms.
* `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing.
Default is `false`.
* `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt`
key is pressed. Default is `false`.
* `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to
be resized larger than screen. Only relevant for macOS, as other OSes
allow larger-than-screen windows by default. Default is `false`.
* `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](../browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information.
* `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`.
* `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of
the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This
is only implemented on Windows and macOS.
* `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on
some GTK+3 desktop environments. Default is `false`.
* `transparent` boolean (optional) - Makes the window [transparent](../../tutorial/window-customization.md#create-transparent-windows).
Default is `false`. On Windows, does not work unless the window is frameless.
* `type` string (optional) - The type of window, default is normal window. See more about
this below.
* `visualEffectState` string (optional) _macOS_ - Specify how the material
appearance should reflect window activity state on macOS. Must be used
with the `vibrancy` property. Possible values are:
* `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default.
* `active` - The backdrop should always appear active.
* `inactive` - The backdrop should always appear inactive.
* `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar.
Default is `default`. Possible values are:
* `default` - Results in the standard title bar for macOS or Windows respectively.
* `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown.
* `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar
with an alternative look where the traffic light buttons are slightly
more inset from the window edge.
* `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden
title bar and a full size content window, the traffic light buttons will
display when being hovered over in the top left of the window.
**Note:** This option is currently experimental.
* `trafficLightPosition` [Point](point.md) (optional) _macOS_ -
Set a custom position for the traffic light buttons in frameless windows.
* `roundedCorners` boolean (optional) _macOS_ - Whether frameless window
should have rounded corners on macOS. Default is `true`. Setting this property
to `false` will prevent the window from being fullscreenable.
* `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows
the title in the title bar in full screen mode on macOS for `hiddenInset`
titleBarStyle. Default is `false`.
* `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on
Windows, which adds standard window frame. Setting it to `false` will remove
window shadow and window animations. Default is `true`.
* `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to
the window, only on macOS. Can be `appearance-based`, `titlebar`, `selection`,
`menu`, `popover`, `sidebar`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`,
`tooltip`, `content`, `under-window`, or `under-page`.
* `backgroundMaterial` string (optional) _Windows_ - Set the window's
system-drawn background material, including behind the non-client area.
Can be `auto`, `none`, `mica`, `acrylic` or `tabbed`. See [win.setBackgroundMaterial](../browser-window.md#winsetbackgroundmaterialmaterial-windows) for more information.
* `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on
macOS when option-clicking the green stoplight button on the toolbar or by
clicking the Window > Zoom menu item. If `true`, the window will grow to
the preferred width of the web page when zoomed, `false` will cause it to
zoom to the width of the screen. This will also affect the behavior when
calling `maximize()` directly. Default is `false`.
* `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows
opening the window as a native tab. Windows with the same
tabbing identifier will be grouped together. This also adds a native new
tab button to your window's tab bar and allows your `app` and window to
receive the `new-window-for-tab` event.
* `webPreferences` [WebPreferences](web-preferences.md?inline) (optional) - Settings of web page's features.
* `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`.
* `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color.
* `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color.
* `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height.
When setting minimum or maximum window size with `minWidth`/`maxWidth`/
`minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from
passing a size that does not follow size constraints to `setBounds`/`setSize` or
to the constructor of `BrowserWindow`.
The possible values and behaviors of the `type` option are platform dependent.
Possible values are:
* On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`,
`notification`.
* On macOS, possible types are `desktop`, `textured`, `panel`.
* The `textured` type adds metal gradient appearance
(`NSWindowStyleMaskTexturedBackground`).
* The `desktop` type places the window at the desktop background window level
(`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive
focus, keyboard or mouse events, but you can use `globalShortcut` to receive
input sparingly.
* The `panel` type enables the window to float on top of full-screened apps
by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally
reserved for NSPanel, at runtime. Also, the window will appear on all
spaces (desktops).
* On Windows, possible type is `toolbar`.
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 34,499 |
[Feature Request]: Improve Documentation on BrowserWindow `type` attribute
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success.
### Problem Description
The docs regarding the `type` property of the BrowserWindow lacks explanation:
https://www.electronjs.org/de/docs/latest/api/browser-window
```
The possible values and behaviors of the type option are platform dependent. Mögliche Werte sind:
On Linux, possible types are desktop, dock, toolbar, splash, notification.
On macOS, possible types are desktop, textured.
The textured type adds metal gradient appearance (NSTexturedBackgroundWindowMask).
The desktop type places the window at the desktop background window level (kCGDesktopWindowLevel - 1). Note that desktop window will not receive focus, keyboard or mouse events, but you can use globalShortcut to receive input sparingly.
On Windows, possible type is toolbar.
```
It is not clear what the effects of the seperate options are, e.g.
A frameless window on linux with type `splash` is not draggable, even if the style property on the body contains `-webkit-app-region: drag`
### Proposed Solution
Add some context for the values e.g.
On Linux, possible types are:
- desktop: ...
- dock: ...
- toolbar: ...
- splash: Window type `splash` does x,y and prevents the window from being draged
- notification: ...
### Alternatives Considered
None
### Additional Information
I have chosen "splash" as type of my BrowserWindows, for a reason i cant remember. On my windows machine i have been able to move the window, on linux not.
The search for the reason have more or less been "try and error" -> comment everything until it works
After i found the culprint, window type `splash`, i wanted to check what are the side effects if i remove this setting but the docs didnt have any information.
|
https://github.com/electron/electron/issues/34499
|
https://github.com/electron/electron/pull/38666
|
3fa15ebb7e8aef2029cd23370fdc96f382c9d161
|
ec4c9024b9795d360fbd96b09684fdb228966781
| 2022-06-10T13:01:28Z |
c++
| 2023-07-05T20:26:39Z |
docs/api/structures/browser-window-options.md
|
# BrowserWindowConstructorOptions Object
* `width` Integer (optional) - Window's width in pixels. Default is `800`.
* `height` Integer (optional) - Window's height in pixels. Default is `600`.
* `x` Integer (optional) - (**required** if y is used) Window's left offset from screen.
Default is to center the window.
* `y` Integer (optional) - (**required** if x is used) Window's top offset from screen.
Default is to center the window.
* `useContentSize` boolean (optional) - The `width` and `height` would be used as web
page's size, which means the actual window's size will include window
frame's size and be slightly larger. Default is `false`.
* `center` boolean (optional) - Show window in the center of the screen. Default is `false`.
* `minWidth` Integer (optional) - Window's minimum width. Default is `0`.
* `minHeight` Integer (optional) - Window's minimum height. Default is `0`.
* `maxWidth` Integer (optional) - Window's maximum width. Default is no limit.
* `maxHeight` Integer (optional) - Window's maximum height. Default is no limit.
* `resizable` boolean (optional) - Whether window is resizable. Default is `true`.
* `movable` boolean (optional) _macOS_ _Windows_ - Whether window is
movable. This is not implemented on Linux. Default is `true`.
* `minimizable` boolean (optional) _macOS_ _Windows_ - Whether window is
minimizable. This is not implemented on Linux. Default is `true`.
* `maximizable` boolean (optional) _macOS_ _Windows_ - Whether window is
maximizable. This is not implemented on Linux. Default is `true`.
* `closable` boolean (optional) _macOS_ _Windows_ - Whether window is
closable. This is not implemented on Linux. Default is `true`.
* `focusable` boolean (optional) - Whether the window can be focused. Default is
`true`. On Windows setting `focusable: false` also implies setting
`skipTaskbar: true`. On Linux setting `focusable: false` makes the window
stop interacting with wm, so the window will always stay on top in all
workspaces.
* `alwaysOnTop` boolean (optional) - Whether the window should always stay on top of
other windows. Default is `false`.
* `fullscreen` boolean (optional) - Whether the window should show in fullscreen. When
explicitly set to `false` the fullscreen button will be hidden or disabled
on macOS. Default is `false`.
* `fullscreenable` boolean (optional) - Whether the window can be put into fullscreen
mode. On macOS, also whether the maximize/zoom button should toggle full
screen mode or maximize window. Default is `true`.
* `simpleFullscreen` boolean (optional) _macOS_ - Use pre-Lion fullscreen on
macOS. Default is `false`.
* `skipTaskbar` boolean (optional) _macOS_ _Windows_ - Whether to show the window in taskbar.
Default is `false`.
* `hiddenInMissionControl` boolean (optional) _macOS_ - Whether window should be hidden when the user toggles into mission control.
* `kiosk` boolean (optional) - Whether the window is in kiosk mode. Default is `false`.
* `title` string (optional) - Default window title. Default is `"Electron"`. If the HTML tag `<title>` is defined in the HTML file loaded by `loadURL()`, this property will be ignored.
* `icon` ([NativeImage](../native-image.md) | string) (optional) - The window icon. On Windows it is
recommended to use `ICO` icons to get best visual effects, you can also
leave it undefined so the executable's icon will be used.
* `show` boolean (optional) - Whether window should be shown when created. Default is
`true`.
* `paintWhenInitiallyHidden` boolean (optional) - Whether the renderer should be active when `show` is `false` and it has just been created. In order for `document.visibilityState` to work correctly on first load with `show: false` you should set this to `false`. Setting this to `false` will cause the `ready-to-show` event to not fire. Default is `true`.
* `frame` boolean (optional) - Specify `false` to create a
[frameless window](../../tutorial/window-customization.md#create-frameless-windows). Default is `true`.
* `parent` BrowserWindow (optional) - Specify parent window. Default is `null`.
* `modal` boolean (optional) - Whether this is a modal window. This only works when the
window is a child window. Default is `false`.
* `acceptFirstMouse` boolean (optional) _macOS_ - Whether clicking an
inactive window will also click through to the web contents. Default is
`false` on macOS. This option is not configurable on other platforms.
* `disableAutoHideCursor` boolean (optional) - Whether to hide cursor when typing.
Default is `false`.
* `autoHideMenuBar` boolean (optional) - Auto hide the menu bar unless the `Alt`
key is pressed. Default is `false`.
* `enableLargerThanScreen` boolean (optional) _macOS_ - Enable the window to
be resized larger than screen. Only relevant for macOS, as other OSes
allow larger-than-screen windows by default. Default is `false`.
* `backgroundColor` string (optional) - The window's background color in Hex, RGB, RGBA, HSL, HSLA or named CSS color format. Alpha in #AARRGGBB format is supported if `transparent` is set to `true`. Default is `#FFF` (white). See [win.setBackgroundColor](../browser-window.md#winsetbackgroundcolorbackgroundcolor) for more information.
* `hasShadow` boolean (optional) - Whether window should have a shadow. Default is `true`.
* `opacity` number (optional) _macOS_ _Windows_ - Set the initial opacity of
the window, between 0.0 (fully transparent) and 1.0 (fully opaque). This
is only implemented on Windows and macOS.
* `darkTheme` boolean (optional) - Forces using dark theme for the window, only works on
some GTK+3 desktop environments. Default is `false`.
* `transparent` boolean (optional) - Makes the window [transparent](../../tutorial/window-customization.md#create-transparent-windows).
Default is `false`. On Windows, does not work unless the window is frameless.
* `type` string (optional) - The type of window, default is normal window. See more about
this below.
* `visualEffectState` string (optional) _macOS_ - Specify how the material
appearance should reflect window activity state on macOS. Must be used
with the `vibrancy` property. Possible values are:
* `followWindow` - The backdrop should automatically appear active when the window is active, and inactive when it is not. This is the default.
* `active` - The backdrop should always appear active.
* `inactive` - The backdrop should always appear inactive.
* `titleBarStyle` string (optional) _macOS_ _Windows_ - The style of window title bar.
Default is `default`. Possible values are:
* `default` - Results in the standard title bar for macOS or Windows respectively.
* `hidden` - Results in a hidden title bar and a full size content window. On macOS, the window still has the standard window controls (“traffic lights”) in the top left. On Windows, when combined with `titleBarOverlay: true` it will activate the Window Controls Overlay (see `titleBarOverlay` for more information), otherwise no window controls will be shown.
* `hiddenInset` _macOS_ - Only on macOS, results in a hidden title bar
with an alternative look where the traffic light buttons are slightly
more inset from the window edge.
* `customButtonsOnHover` _macOS_ - Only on macOS, results in a hidden
title bar and a full size content window, the traffic light buttons will
display when being hovered over in the top left of the window.
**Note:** This option is currently experimental.
* `trafficLightPosition` [Point](point.md) (optional) _macOS_ -
Set a custom position for the traffic light buttons in frameless windows.
* `roundedCorners` boolean (optional) _macOS_ - Whether frameless window
should have rounded corners on macOS. Default is `true`. Setting this property
to `false` will prevent the window from being fullscreenable.
* `fullscreenWindowTitle` boolean (optional) _macOS_ _Deprecated_ - Shows
the title in the title bar in full screen mode on macOS for `hiddenInset`
titleBarStyle. Default is `false`.
* `thickFrame` boolean (optional) - Use `WS_THICKFRAME` style for frameless windows on
Windows, which adds standard window frame. Setting it to `false` will remove
window shadow and window animations. Default is `true`.
* `vibrancy` string (optional) _macOS_ - Add a type of vibrancy effect to
the window, only on macOS. Can be `appearance-based`, `titlebar`, `selection`,
`menu`, `popover`, `sidebar`, `header`, `sheet`, `window`, `hud`, `fullscreen-ui`,
`tooltip`, `content`, `under-window`, or `under-page`.
* `backgroundMaterial` string (optional) _Windows_ - Set the window's
system-drawn background material, including behind the non-client area.
Can be `auto`, `none`, `mica`, `acrylic` or `tabbed`. See [win.setBackgroundMaterial](../browser-window.md#winsetbackgroundmaterialmaterial-windows) for more information.
* `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on
macOS when option-clicking the green stoplight button on the toolbar or by
clicking the Window > Zoom menu item. If `true`, the window will grow to
the preferred width of the web page when zoomed, `false` will cause it to
zoom to the width of the screen. This will also affect the behavior when
calling `maximize()` directly. Default is `false`.
* `tabbingIdentifier` string (optional) _macOS_ - Tab group name, allows
opening the window as a native tab. Windows with the same
tabbing identifier will be grouped together. This also adds a native new
tab button to your window's tab bar and allows your `app` and window to
receive the `new-window-for-tab` event.
* `webPreferences` [WebPreferences](web-preferences.md?inline) (optional) - Settings of web page's features.
* `titleBarOverlay` Object | Boolean (optional) - When using a frameless window in conjunction with `win.setWindowButtonVisibility(true)` on macOS or using a `titleBarStyle` so that the standard window controls ("traffic lights" on macOS) are visible, this property enables the Window Controls Overlay [JavaScript APIs][overlay-javascript-apis] and [CSS Environment Variables][overlay-css-env-vars]. Specifying `true` will result in an overlay with default system colors. Default is `false`.
* `color` String (optional) _Windows_ - The CSS color of the Window Controls Overlay when enabled. Default is the system color.
* `symbolColor` String (optional) _Windows_ - The CSS color of the symbols on the Window Controls Overlay when enabled. Default is the system color.
* `height` Integer (optional) _macOS_ _Windows_ - The height of the title bar and Window Controls Overlay in pixels. Default is system height.
When setting minimum or maximum window size with `minWidth`/`maxWidth`/
`minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from
passing a size that does not follow size constraints to `setBounds`/`setSize` or
to the constructor of `BrowserWindow`.
The possible values and behaviors of the `type` option are platform dependent.
Possible values are:
* On Linux, possible types are `desktop`, `dock`, `toolbar`, `splash`,
`notification`.
* On macOS, possible types are `desktop`, `textured`, `panel`.
* The `textured` type adds metal gradient appearance
(`NSWindowStyleMaskTexturedBackground`).
* The `desktop` type places the window at the desktop background window level
(`kCGDesktopWindowLevel - 1`). Note that desktop window will not receive
focus, keyboard or mouse events, but you can use `globalShortcut` to receive
input sparingly.
* The `panel` type enables the window to float on top of full-screened apps
by adding the `NSWindowStyleMaskNonactivatingPanel` style mask,normally
reserved for NSPanel, at runtime. Also, the window will appear on all
spaces (desktops).
* On Windows, possible type is `toolbar`.
[overlay-css-env-vars]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#css-environment-variables
[overlay-javascript-apis]: https://github.com/WICG/window-controls-overlay/blob/main/explainer.md#javascript-apis
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,994 |
[Bug]: BrowserView setBounds behavior inconsistent between Mac and Windows
|
```js
bv.setBounds({x: 0, y: 0, width: 500, height: 40})
```
gives different results on different platforms:
mac:

windows:

Regressed in #34713 I believe. cc @codebytere
|
https://github.com/electron/electron/issues/35994
|
https://github.com/electron/electron/pull/38981
|
ec4c9024b9795d360fbd96b09684fdb228966781
|
5a77c75753f560bbc4fe6560441ba88433a561f8
| 2022-10-11T23:15:30Z |
c++
| 2023-07-06T07:50:08Z |
shell/browser/native_browser_view_mac.mm
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "skia/ext/skia_utils_mac.h"
#include "ui/gfx/geometry/rect.h"
// Match view::Views behavior where the view sticks to the top-left origin.
const NSAutoresizingMaskOptions kDefaultAutoResizingMask =
NSViewMaxXMargin | NSViewMinYMargin;
namespace electron {
NativeBrowserViewMac::NativeBrowserViewMac(
InspectableWebContents* inspectable_web_contents)
: NativeBrowserView(inspectable_web_contents) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
view.autoresizingMask = kDefaultAutoResizingMask;
}
NativeBrowserViewMac::~NativeBrowserViewMac() = default;
void NativeBrowserViewMac::SetAutoResizeFlags(uint8_t flags) {
NSAutoresizingMaskOptions autoresizing_mask = kDefaultAutoResizingMask;
if (flags & kAutoResizeWidth) {
autoresizing_mask |= NSViewWidthSizable;
}
if (flags & kAutoResizeHeight) {
autoresizing_mask |= NSViewHeightSizable;
}
if (flags & kAutoResizeHorizontal) {
autoresizing_mask |=
NSViewMaxXMargin | NSViewMinXMargin | NSViewWidthSizable;
}
if (flags & kAutoResizeVertical) {
autoresizing_mask |=
NSViewMaxYMargin | NSViewMinYMargin | NSViewHeightSizable;
}
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
view.autoresizingMask = autoresizing_mask;
}
void NativeBrowserViewMac::SetBounds(const gfx::Rect& bounds) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
auto* superview = view.superview;
const auto superview_height = superview ? superview.frame.size.height : 0;
// We need to use the content rect to calculate the titlebar height if the
// superview is an framed NSWindow, otherwise it will be offset incorrectly by
// the height of the titlebar.
auto titlebar_height = 0;
if (auto* win = [superview window]) {
const auto content_rect_height =
[win contentRectForFrameRect:superview.frame].size.height;
titlebar_height = superview_height - content_rect_height;
}
auto new_height =
superview_height - bounds.y() - bounds.height() + titlebar_height;
view.frame =
NSMakeRect(bounds.x(), new_height, bounds.width(), bounds.height());
}
gfx::Rect NativeBrowserViewMac::GetBounds() {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return gfx::Rect();
NSView* view = iwc_view->GetNativeView().GetNativeNSView();
auto* superview = view.superview;
const int superview_height = superview ? superview.frame.size.height : 0;
// We need to use the content rect to calculate the titlebar height if the
// superview is an framed NSWindow, otherwise it will be offset incorrectly by
// the height of the titlebar.
auto titlebar_height = 0;
if (auto* win = [superview window]) {
const auto content_rect_height =
[win contentRectForFrameRect:superview.frame].size.height;
titlebar_height = superview_height - content_rect_height;
}
auto new_height = superview_height - view.frame.origin.y -
view.frame.size.height + titlebar_height;
return gfx::Rect(view.frame.origin.x, new_height, view.frame.size.width,
view.frame.size.height);
}
void NativeBrowserViewMac::SetBackgroundColor(SkColor color) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
view.wantsLayer = YES;
view.layer.backgroundColor = skia::CGColorCreateFromSkColor(color);
}
// static
NativeBrowserView* NativeBrowserView::Create(
InspectableWebContents* inspectable_web_contents) {
return new NativeBrowserViewMac(inspectable_web_contents);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,994 |
[Bug]: BrowserView setBounds behavior inconsistent between Mac and Windows
|
```js
bv.setBounds({x: 0, y: 0, width: 500, height: 40})
```
gives different results on different platforms:
mac:

windows:

Regressed in #34713 I believe. cc @codebytere
|
https://github.com/electron/electron/issues/35994
|
https://github.com/electron/electron/pull/38981
|
ec4c9024b9795d360fbd96b09684fdb228966781
|
5a77c75753f560bbc4fe6560441ba88433a561f8
| 2022-10-11T23:15:30Z |
c++
| 2023-07-06T07:50:08Z |
spec/api-browser-view-spec.ts
|
import { expect } from 'chai';
import * as path from 'node:path';
import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main';
import { closeWindow } from './lib/window-helpers';
import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers';
import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers';
import { once } from 'node:events';
describe('BrowserView module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
let w: BrowserWindow;
let view: BrowserView;
beforeEach(() => {
expect(webContents.getAllWebContents()).to.have.length(0);
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
});
});
afterEach(async () => {
const p = once(w.webContents, 'destroyed');
await closeWindow(w);
w = null as any;
await p;
if (view && view.webContents) {
const p = once(view.webContents, 'destroyed');
view.webContents.destroy();
view = null as any;
await p;
}
expect(webContents.getAllWebContents()).to.have.length(0);
});
it('can be created with an existing webContents', async () => {
const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
await wc.loadURL('about:blank');
view = new BrowserView({ webContents: wc } as any);
expect(view.webContents.getURL()).to.equal('about:blank');
});
describe('BrowserView.setBackgroundColor()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBackgroundColor('#000');
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBackgroundColor(null as any);
}).to.throw(/conversion failure/);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('sets the background color to transparent if none is set', async () => {
const display = screen.getPrimaryDisplay();
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('successfully applies the background color', async () => {
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
const VIEW_BACKGROUND_COLOR = '#ff00ff';
const display = screen.getPrimaryDisplay();
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
w.setBackgroundColor(VIEW_BACKGROUND_COLOR);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true();
});
});
describe('BrowserView.setAutoResize()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setAutoResize({});
view.setAutoResize({ width: true, height: false });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setAutoResize(null as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.setBounds()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBounds({ x: 0, y: 0, width: 1, height: 1 });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBounds(null as any);
}).to.throw(/conversion failure/);
expect(() => {
view.setBounds({} as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.getBounds()', () => {
it('returns correct bounds on a framed window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
it('returns correct bounds on a frameless window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
});
describe('BrowserWindow.setBrowserView()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
w.setBrowserView(view);
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.setBrowserView(view);
w.setBrowserView(view);
w.setBrowserView(view);
});
});
describe('BrowserWindow.getBrowserView()', () => {
it('returns the set view', () => {
view = new BrowserView();
w.setBrowserView(view);
const view2 = w.getBrowserView();
expect(view2!.webContents.id).to.equal(view.webContents.id);
});
it('returns null if none is set', () => {
const view = w.getBrowserView();
expect(view).to.be.null('view');
});
});
describe('BrowserWindow.addBrowserView()', () => {
it('does not throw for valid args', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.addBrowserView(view);
w.addBrowserView(view);
w.addBrowserView(view);
});
it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => {
expect(() => {
const view1 = new BrowserView();
view1.webContents.destroy();
w.addBrowserView(view1);
}).to.not.throw();
});
it('does not crash if the webContents is destroyed after a URL is loaded', () => {
view = new BrowserView();
expect(async () => {
view.setBounds({ x: 0, y: 0, width: 400, height: 300 });
await view.webContents.loadURL('data:text/html,hello there');
view.webContents.destroy();
}).to.not.throw();
});
it('can handle BrowserView reparenting', async () => {
view = new BrowserView();
w.addBrowserView(view);
view.webContents.loadURL('about:blank');
await once(view.webContents, 'did-finish-load');
const w2 = new BrowserWindow({ show: false });
w2.addBrowserView(view);
w.close();
view.webContents.loadURL(`file://${fixtures}/pages/blank.html`);
await once(view.webContents, 'did-finish-load');
// Clean up - the afterEach hook assumes the webContents on w is still alive.
w = new BrowserWindow({ show: false });
w2.close();
w2.destroy();
});
});
describe('BrowserWindow.removeBrowserView()', () => {
it('does not throw if called multiple times with same view', () => {
expect(() => {
view = new BrowserView();
w.addBrowserView(view);
w.removeBrowserView(view);
w.removeBrowserView(view);
}).to.not.throw();
});
it('can be called on a BrowserView with a destroyed webContents', (done) => {
view = new BrowserView();
w.addBrowserView(view);
view.webContents.on('destroyed', () => {
w.removeBrowserView(view);
done();
});
view.webContents.loadURL('data:text/html,hello there').then(() => {
view.webContents.close();
});
});
});
describe('BrowserWindow.getBrowserViews()', () => {
it('returns same views as was added', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
const views = w.getBrowserViews();
expect(views).to.have.lengthOf(2);
expect(views[0].webContents.id).to.equal(view1.webContents.id);
expect(views[1].webContents.id).to.equal(view2.webContents.id);
});
});
describe('BrowserWindow.setTopBrowserView()', () => {
it('should throw an error when a BrowserView is not attached to the window', () => {
view = new BrowserView();
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
});
it('should throw an error when a BrowserView is attached to some other window', () => {
view = new BrowserView();
const win2 = new BrowserWindow();
w.addBrowserView(view);
view.setBounds({ x: 0, y: 0, width: 100, height: 100 });
win2.addBrowserView(view);
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
win2.close();
win2.destroy();
});
});
describe('BrowserView.webContents.getOwnerBrowserWindow()', () => {
it('points to owning window', () => {
view = new BrowserView();
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
w.setBrowserView(view);
expect(view.webContents.getOwnerBrowserWindow()).to.equal(w);
w.setBrowserView(null);
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
});
});
describe('shutdown behavior', () => {
it('does not crash on exit', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { BrowserView, app } = require('electron');
// eslint-disable-next-line no-new
new BrowserView({});
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('does not crash on exit if added to a browser window', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { app, BrowserView, BrowserWindow } = require('electron');
const bv = new BrowserView();
bv.webContents.loadURL('about:blank');
const bw = new BrowserWindow({ show: false });
bw.addBrowserView(bv);
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('emits the destroyed event when webContents.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.close();
await once(view.webContents, 'destroyed');
});
it('emits the destroyed event when window.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.executeJavaScript('window.close()');
await once(view.webContents, 'destroyed');
});
});
describe('window.open()', () => {
it('works in BrowserView', (done) => {
view = new BrowserView();
w.setBrowserView(view);
view.webContents.setWindowOpenHandler(({ url, frameName }) => {
expect(url).to.equal('http://host/');
expect(frameName).to.equal('host');
done();
return { action: 'deny' };
});
view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
});
});
describe('BrowserView.capturePage(rect)', () => {
it('returns a Promise with a Buffer', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.addBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
const image = await view.webContents.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
xit('resolves after the window is hidden and capturer count is non-zero', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.setBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
const image = await view.webContents.capturePage();
expect(image.isEmpty()).to.equal(false);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,994 |
[Bug]: BrowserView setBounds behavior inconsistent between Mac and Windows
|
```js
bv.setBounds({x: 0, y: 0, width: 500, height: 40})
```
gives different results on different platforms:
mac:

windows:

Regressed in #34713 I believe. cc @codebytere
|
https://github.com/electron/electron/issues/35994
|
https://github.com/electron/electron/pull/38981
|
ec4c9024b9795d360fbd96b09684fdb228966781
|
5a77c75753f560bbc4fe6560441ba88433a561f8
| 2022-10-11T23:15:30Z |
c++
| 2023-07-06T07:50:08Z |
shell/browser/native_browser_view_mac.mm
|
// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_browser_view_mac.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "skia/ext/skia_utils_mac.h"
#include "ui/gfx/geometry/rect.h"
// Match view::Views behavior where the view sticks to the top-left origin.
const NSAutoresizingMaskOptions kDefaultAutoResizingMask =
NSViewMaxXMargin | NSViewMinYMargin;
namespace electron {
NativeBrowserViewMac::NativeBrowserViewMac(
InspectableWebContents* inspectable_web_contents)
: NativeBrowserView(inspectable_web_contents) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
view.autoresizingMask = kDefaultAutoResizingMask;
}
NativeBrowserViewMac::~NativeBrowserViewMac() = default;
void NativeBrowserViewMac::SetAutoResizeFlags(uint8_t flags) {
NSAutoresizingMaskOptions autoresizing_mask = kDefaultAutoResizingMask;
if (flags & kAutoResizeWidth) {
autoresizing_mask |= NSViewWidthSizable;
}
if (flags & kAutoResizeHeight) {
autoresizing_mask |= NSViewHeightSizable;
}
if (flags & kAutoResizeHorizontal) {
autoresizing_mask |=
NSViewMaxXMargin | NSViewMinXMargin | NSViewWidthSizable;
}
if (flags & kAutoResizeVertical) {
autoresizing_mask |=
NSViewMaxYMargin | NSViewMinYMargin | NSViewHeightSizable;
}
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
view.autoresizingMask = autoresizing_mask;
}
void NativeBrowserViewMac::SetBounds(const gfx::Rect& bounds) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
auto* superview = view.superview;
const auto superview_height = superview ? superview.frame.size.height : 0;
// We need to use the content rect to calculate the titlebar height if the
// superview is an framed NSWindow, otherwise it will be offset incorrectly by
// the height of the titlebar.
auto titlebar_height = 0;
if (auto* win = [superview window]) {
const auto content_rect_height =
[win contentRectForFrameRect:superview.frame].size.height;
titlebar_height = superview_height - content_rect_height;
}
auto new_height =
superview_height - bounds.y() - bounds.height() + titlebar_height;
view.frame =
NSMakeRect(bounds.x(), new_height, bounds.width(), bounds.height());
}
gfx::Rect NativeBrowserViewMac::GetBounds() {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return gfx::Rect();
NSView* view = iwc_view->GetNativeView().GetNativeNSView();
auto* superview = view.superview;
const int superview_height = superview ? superview.frame.size.height : 0;
// We need to use the content rect to calculate the titlebar height if the
// superview is an framed NSWindow, otherwise it will be offset incorrectly by
// the height of the titlebar.
auto titlebar_height = 0;
if (auto* win = [superview window]) {
const auto content_rect_height =
[win contentRectForFrameRect:superview.frame].size.height;
titlebar_height = superview_height - content_rect_height;
}
auto new_height = superview_height - view.frame.origin.y -
view.frame.size.height + titlebar_height;
return gfx::Rect(view.frame.origin.x, new_height, view.frame.size.width,
view.frame.size.height);
}
void NativeBrowserViewMac::SetBackgroundColor(SkColor color) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetNativeView().GetNativeNSView();
view.wantsLayer = YES;
view.layer.backgroundColor = skia::CGColorCreateFromSkColor(color);
}
// static
NativeBrowserView* NativeBrowserView::Create(
InspectableWebContents* inspectable_web_contents) {
return new NativeBrowserViewMac(inspectable_web_contents);
}
} // namespace electron
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 35,994 |
[Bug]: BrowserView setBounds behavior inconsistent between Mac and Windows
|
```js
bv.setBounds({x: 0, y: 0, width: 500, height: 40})
```
gives different results on different platforms:
mac:

windows:

Regressed in #34713 I believe. cc @codebytere
|
https://github.com/electron/electron/issues/35994
|
https://github.com/electron/electron/pull/38981
|
ec4c9024b9795d360fbd96b09684fdb228966781
|
5a77c75753f560bbc4fe6560441ba88433a561f8
| 2022-10-11T23:15:30Z |
c++
| 2023-07-06T07:50:08Z |
spec/api-browser-view-spec.ts
|
import { expect } from 'chai';
import * as path from 'node:path';
import { BrowserView, BrowserWindow, screen, webContents } from 'electron/main';
import { closeWindow } from './lib/window-helpers';
import { defer, ifit, startRemoteControlApp } from './lib/spec-helpers';
import { areColorsSimilar, captureScreen, getPixelColor } from './lib/screen-helpers';
import { once } from 'node:events';
describe('BrowserView module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
let w: BrowserWindow;
let view: BrowserView;
beforeEach(() => {
expect(webContents.getAllWebContents()).to.have.length(0);
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
});
});
afterEach(async () => {
const p = once(w.webContents, 'destroyed');
await closeWindow(w);
w = null as any;
await p;
if (view && view.webContents) {
const p = once(view.webContents, 'destroyed');
view.webContents.destroy();
view = null as any;
await p;
}
expect(webContents.getAllWebContents()).to.have.length(0);
});
it('can be created with an existing webContents', async () => {
const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true });
await wc.loadURL('about:blank');
view = new BrowserView({ webContents: wc } as any);
expect(view.webContents.getURL()).to.equal('about:blank');
});
describe('BrowserView.setBackgroundColor()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBackgroundColor('#000');
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBackgroundColor(null as any);
}).to.throw(/conversion failure/);
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('sets the background color to transparent if none is set', async () => {
const display = screen.getPrimaryDisplay();
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, WINDOW_BACKGROUND_COLOR)).to.be.true();
});
// Linux and arm64 platforms (WOA and macOS) do not return any capture sources
ifit(process.platform === 'darwin' && process.arch === 'x64')('successfully applies the background color', async () => {
const WINDOW_BACKGROUND_COLOR = '#55ccbb';
const VIEW_BACKGROUND_COLOR = '#ff00ff';
const display = screen.getPrimaryDisplay();
w.show();
w.setBounds(display.bounds);
w.setBackgroundColor(WINDOW_BACKGROUND_COLOR);
await w.loadURL('about:blank');
view = new BrowserView();
view.setBounds(display.bounds);
w.setBrowserView(view);
w.setBackgroundColor(VIEW_BACKGROUND_COLOR);
await view.webContents.loadURL('data:text/html,hello there');
const screenCapture = await captureScreen();
const centerColor = getPixelColor(screenCapture, {
x: display.size.width / 2,
y: display.size.height / 2
});
expect(areColorsSimilar(centerColor, VIEW_BACKGROUND_COLOR)).to.be.true();
});
});
describe('BrowserView.setAutoResize()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setAutoResize({});
view.setAutoResize({ width: true, height: false });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setAutoResize(null as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.setBounds()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
view.setBounds({ x: 0, y: 0, width: 1, height: 1 });
});
it('throws for invalid args', () => {
view = new BrowserView();
expect(() => {
view.setBounds(null as any);
}).to.throw(/conversion failure/);
expect(() => {
view.setBounds({} as any);
}).to.throw(/conversion failure/);
});
});
describe('BrowserView.getBounds()', () => {
it('returns correct bounds on a framed window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
it('returns correct bounds on a frameless window', () => {
view = new BrowserView();
const bounds = { x: 10, y: 20, width: 30, height: 40 };
view.setBounds(bounds);
expect(view.getBounds()).to.deep.equal(bounds);
});
});
describe('BrowserWindow.setBrowserView()', () => {
it('does not throw for valid args', () => {
view = new BrowserView();
w.setBrowserView(view);
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.setBrowserView(view);
w.setBrowserView(view);
w.setBrowserView(view);
});
});
describe('BrowserWindow.getBrowserView()', () => {
it('returns the set view', () => {
view = new BrowserView();
w.setBrowserView(view);
const view2 = w.getBrowserView();
expect(view2!.webContents.id).to.equal(view.webContents.id);
});
it('returns null if none is set', () => {
const view = w.getBrowserView();
expect(view).to.be.null('view');
});
});
describe('BrowserWindow.addBrowserView()', () => {
it('does not throw for valid args', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
});
it('does not throw if called multiple times with same view', () => {
view = new BrowserView();
w.addBrowserView(view);
w.addBrowserView(view);
w.addBrowserView(view);
});
it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => {
expect(() => {
const view1 = new BrowserView();
view1.webContents.destroy();
w.addBrowserView(view1);
}).to.not.throw();
});
it('does not crash if the webContents is destroyed after a URL is loaded', () => {
view = new BrowserView();
expect(async () => {
view.setBounds({ x: 0, y: 0, width: 400, height: 300 });
await view.webContents.loadURL('data:text/html,hello there');
view.webContents.destroy();
}).to.not.throw();
});
it('can handle BrowserView reparenting', async () => {
view = new BrowserView();
w.addBrowserView(view);
view.webContents.loadURL('about:blank');
await once(view.webContents, 'did-finish-load');
const w2 = new BrowserWindow({ show: false });
w2.addBrowserView(view);
w.close();
view.webContents.loadURL(`file://${fixtures}/pages/blank.html`);
await once(view.webContents, 'did-finish-load');
// Clean up - the afterEach hook assumes the webContents on w is still alive.
w = new BrowserWindow({ show: false });
w2.close();
w2.destroy();
});
});
describe('BrowserWindow.removeBrowserView()', () => {
it('does not throw if called multiple times with same view', () => {
expect(() => {
view = new BrowserView();
w.addBrowserView(view);
w.removeBrowserView(view);
w.removeBrowserView(view);
}).to.not.throw();
});
it('can be called on a BrowserView with a destroyed webContents', (done) => {
view = new BrowserView();
w.addBrowserView(view);
view.webContents.on('destroyed', () => {
w.removeBrowserView(view);
done();
});
view.webContents.loadURL('data:text/html,hello there').then(() => {
view.webContents.close();
});
});
});
describe('BrowserWindow.getBrowserViews()', () => {
it('returns same views as was added', () => {
const view1 = new BrowserView();
defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
const views = w.getBrowserViews();
expect(views).to.have.lengthOf(2);
expect(views[0].webContents.id).to.equal(view1.webContents.id);
expect(views[1].webContents.id).to.equal(view2.webContents.id);
});
});
describe('BrowserWindow.setTopBrowserView()', () => {
it('should throw an error when a BrowserView is not attached to the window', () => {
view = new BrowserView();
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
});
it('should throw an error when a BrowserView is attached to some other window', () => {
view = new BrowserView();
const win2 = new BrowserWindow();
w.addBrowserView(view);
view.setBounds({ x: 0, y: 0, width: 100, height: 100 });
win2.addBrowserView(view);
expect(() => {
w.setTopBrowserView(view);
}).to.throw(/is not attached/);
win2.close();
win2.destroy();
});
});
describe('BrowserView.webContents.getOwnerBrowserWindow()', () => {
it('points to owning window', () => {
view = new BrowserView();
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
w.setBrowserView(view);
expect(view.webContents.getOwnerBrowserWindow()).to.equal(w);
w.setBrowserView(null);
expect(view.webContents.getOwnerBrowserWindow()).to.be.null('owner browser window');
});
});
describe('shutdown behavior', () => {
it('does not crash on exit', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { BrowserView, app } = require('electron');
// eslint-disable-next-line no-new
new BrowserView({});
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('does not crash on exit if added to a browser window', async () => {
const rc = await startRemoteControlApp();
await rc.remotely(() => {
const { app, BrowserView, BrowserWindow } = require('electron');
const bv = new BrowserView();
bv.webContents.loadURL('about:blank');
const bw = new BrowserWindow({ show: false });
bw.addBrowserView(bv);
setTimeout(() => {
app.quit();
});
});
const [code] = await once(rc.process, 'exit');
expect(code).to.equal(0);
});
it('emits the destroyed event when webContents.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.close();
await once(view.webContents, 'destroyed');
});
it('emits the destroyed event when window.close() is called', async () => {
view = new BrowserView();
w.setBrowserView(view);
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
view.webContents.executeJavaScript('window.close()');
await once(view.webContents, 'destroyed');
});
});
describe('window.open()', () => {
it('works in BrowserView', (done) => {
view = new BrowserView();
w.setBrowserView(view);
view.webContents.setWindowOpenHandler(({ url, frameName }) => {
expect(url).to.equal('http://host/');
expect(frameName).to.equal('host');
done();
return { action: 'deny' };
});
view.webContents.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
});
});
describe('BrowserView.capturePage(rect)', () => {
it('returns a Promise with a Buffer', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.addBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
const image = await view.webContents.capturePage({
x: 0,
y: 0,
width: 100,
height: 100
});
expect(image.isEmpty()).to.equal(true);
});
xit('resolves after the window is hidden and capturer count is non-zero', async () => {
view = new BrowserView({
webPreferences: {
backgroundThrottling: false
}
});
w.setBrowserView(view);
view.setBounds({
...w.getBounds(),
x: 0,
y: 0
});
await view.webContents.loadFile(path.join(fixtures, 'pages', 'a.html'));
const image = await view.webContents.capturePage();
expect(image.isEmpty()).to.equal(false);
});
});
});
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,941 |
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.preventDefault().
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0 or higher
### What operating system are you using?
Windows
### Operating System Version
windows 11 22h2
### What arch are you using?
x64
### Last Known Working Electron version
21.4.4
### Expected Behavior
Not crash.
### Actual Behavior
Crash.
### Testcase Gist URL
https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52
### Additional Information
npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
|
https://github.com/electron/electron/issues/38941
|
https://github.com/electron/electron/pull/38996
|
5a77c75753f560bbc4fe6560441ba88433a561f8
|
c7a64ab994de826ed6e4c300cce75d9fd88efa20
| 2023-06-28T07:41:44Z |
c++
| 2023-07-06T08:20:34Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
#include "shell/browser/electron_pdf_web_contents_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents.get(),
std::make_unique<ElectronPDFWebContentsHelperClient>());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
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) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details =
gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
auto weak_this = GetWeakPtr();
Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
// User might destroy WebContents in the crashed event.
if (!weak_this || !web_contents())
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// ⚠️WARNING!⚠️
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessID(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.Set("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::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) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// ⚠️WARNING!⚠️
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url) {
auto* browser_context = web_contents()->GetBrowserContext();
auto* download_manager = browser_context->GetDownloadManager();
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
#if BUILDFLAG(IS_WIN)
auto* win = static_cast<NativeWindowViews*>(owner_window());
// Force a detached state when WCO is enabled to match Chrome
// behavior and prevent occlusion of DevTools.
if (win && win->IsWindowControlsOverlayEnabled())
state = "detach";
#endif
bool activate = true;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
gin_helper::Dictionary margins =
gin::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = "WebContents";
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return "WebContents";
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,941 |
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.preventDefault().
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0 or higher
### What operating system are you using?
Windows
### Operating System Version
windows 11 22h2
### What arch are you using?
x64
### Last Known Working Electron version
21.4.4
### Expected Behavior
Not crash.
### Actual Behavior
Crash.
### Testcase Gist URL
https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52
### Additional Information
npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
|
https://github.com/electron/electron/issues/38941
|
https://github.com/electron/electron/pull/38996
|
5a77c75753f560bbc4fe6560441ba88433a561f8
|
c7a64ab994de826ed6e4c300cce75d9fd88efa20
| 2023-06-28T07:41:44Z |
c++
| 2023-07-06T08:20:34Z |
spec/fixtures/crash-cases/webview-remove-on-wc-close/index.html
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,941 |
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.preventDefault().
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0 or higher
### What operating system are you using?
Windows
### Operating System Version
windows 11 22h2
### What arch are you using?
x64
### Last Known Working Electron version
21.4.4
### Expected Behavior
Not crash.
### Actual Behavior
Crash.
### Testcase Gist URL
https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52
### Additional Information
npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
|
https://github.com/electron/electron/issues/38941
|
https://github.com/electron/electron/pull/38996
|
5a77c75753f560bbc4fe6560441ba88433a561f8
|
c7a64ab994de826ed6e4c300cce75d9fd88efa20
| 2023-06-28T07:41:44Z |
c++
| 2023-07-06T08:20:34Z |
spec/fixtures/crash-cases/webview-remove-on-wc-close/index.js
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,941 |
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.preventDefault().
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0 or higher
### What operating system are you using?
Windows
### Operating System Version
windows 11 22h2
### What arch are you using?
x64
### Last Known Working Electron version
21.4.4
### Expected Behavior
Not crash.
### Actual Behavior
Crash.
### Testcase Gist URL
https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52
### Additional Information
npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
|
https://github.com/electron/electron/issues/38941
|
https://github.com/electron/electron/pull/38996
|
5a77c75753f560bbc4fe6560441ba88433a561f8
|
c7a64ab994de826ed6e4c300cce75d9fd88efa20
| 2023-06-28T07:41:44Z |
c++
| 2023-07-06T08:20:34Z |
spec/fixtures/crash-cases/webview-remove-on-wc-close/webview.html
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,941 |
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.preventDefault().
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0 or higher
### What operating system are you using?
Windows
### Operating System Version
windows 11 22h2
### What arch are you using?
x64
### Last Known Working Electron version
21.4.4
### Expected Behavior
Not crash.
### Actual Behavior
Crash.
### Testcase Gist URL
https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52
### Additional Information
npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
|
https://github.com/electron/electron/issues/38941
|
https://github.com/electron/electron/pull/38996
|
5a77c75753f560bbc4fe6560441ba88433a561f8
|
c7a64ab994de826ed6e4c300cce75d9fd88efa20
| 2023-06-28T07:41:44Z |
c++
| 2023-07-06T08:20:34Z |
shell/browser/api/electron_api_web_contents.cc
|
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/containers/contains.h"
#include "base/containers/fixed_flat_map.h"
#include "base/containers/id_map.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/current_thread.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
#include "chrome/browser/ui/views/eye_dropper/eye_dropper.h"
#include "chrome/common/pref_names.h"
#include "components/embedder_support/user_agent_utils.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/security_state/content/content_utils.h"
#include "components/security_state/core/security_state.h"
#include "content/browser/renderer_host/frame_tree_node.h" // nogncheck
#include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/context_menu_params.h"
#include "content/public/browser/desktop_media_id.h"
#include "content/public/browser/desktop_streams_registry.h"
#include "content/public/browser/download_request_utils.h"
#include "content/public/browser/favicon_status.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "content/public/browser/navigation_details.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/result_codes.h"
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
#include "media/base/mime_util.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ppapi/buildflags/buildflags.h"
#include "printing/buildflags/buildflags.h"
#include "printing/print_job_constants.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/electron_api_browser_window.h"
#include "shell/browser/api/electron_api_debugger.h"
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_frame_main.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_javascript_dialog_manager.h"
#include "shell/browser/electron_navigation_throttle.h"
#include "shell/browser/file_select_helper.h"
#include "shell/browser/native_window.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_web_contents_view.h"
#include "shell/browser/session_preferences.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/ui/file_dialog.h"
#include "shell/browser/ui/inspectable_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/base_converter.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/image_converter.h"
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_converters/optional_converter.h"
#include "shell/common/gin_converters/value_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "storage/browser/file_system/isolated_context.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h"
#include "third_party/blink/public/common/page/page_zoom.h"
#include "third_party/blink/public/mojom/frame/find_in_page.mojom.h"
#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h"
#include "third_party/blink/public/mojom/renderer_preferences.mojom.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
#if BUILDFLAG(IS_WIN)
#include "shell/browser/native_window_views.h"
#endif
#if !BUILDFLAG(IS_MAC)
#include "ui/aura/window.h"
#else
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
#include "ui/gfx/font_render_params.h"
#endif
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include "extensions/browser/script_executor.h"
#include "extensions/browser/view_type_utils.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "shell/browser/extensions/electron_extension_web_contents_observer.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_manager_utils.h"
#include "components/printing/browser/print_to_pdf/pdf_print_result.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/backend/print_backend.h" // nogncheck
#include "printing/mojom/print.mojom.h" // nogncheck
#include "printing/page_range.h"
#include "shell/browser/printing/print_view_manager_electron.h"
#if BUILDFLAG(IS_WIN)
#include "printing/backend/win_helper.h"
#endif
#endif // BUILDFLAG(ENABLE_PRINTING)
#if BUILDFLAG(ENABLE_PDF_VIEWER)
#include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
#include "shell/browser/electron_pdf_web_contents_helper_client.h"
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
#include "content/public/browser/plugin_service.h"
#endif
#if !IS_MAS_BUILD()
#include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck
#endif
namespace gin {
#if BUILDFLAG(ENABLE_PRINTING)
template <>
struct Converter<printing::mojom::MarginType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::MarginType* out) {
using Val = printing::mojom::MarginType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"custom", Val::kCustomMargins},
{"default", Val::kDefaultMargins},
{"none", Val::kNoMargins},
{"printableArea", Val::kPrintableAreaMargins},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<printing::mojom::DuplexMode> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
printing::mojom::DuplexMode* out) {
using Val = printing::mojom::DuplexMode;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"longEdge", Val::kLongEdge},
{"shortEdge", Val::kShortEdge},
{"simplex", Val::kSimplex},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
#endif
template <>
struct Converter<WindowOpenDisposition> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
WindowOpenDisposition val) {
std::string disposition = "other";
switch (val) {
case WindowOpenDisposition::CURRENT_TAB:
disposition = "default";
break;
case WindowOpenDisposition::NEW_FOREGROUND_TAB:
disposition = "foreground-tab";
break;
case WindowOpenDisposition::NEW_BACKGROUND_TAB:
disposition = "background-tab";
break;
case WindowOpenDisposition::NEW_POPUP:
case WindowOpenDisposition::NEW_WINDOW:
disposition = "new-window";
break;
case WindowOpenDisposition::SAVE_TO_DISK:
disposition = "save-to-disk";
break;
default:
break;
}
return gin::ConvertToV8(isolate, disposition);
}
};
template <>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
content::SavePageType* out) {
using Val = content::SavePageType;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML},
{"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML},
{"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML},
});
return FromV8WithLowerLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<electron::api::WebContents::Type> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
electron::api::WebContents::Type val) {
using Type = electron::api::WebContents::Type;
std::string type;
switch (val) {
case Type::kBackgroundPage:
type = "backgroundPage";
break;
case Type::kBrowserWindow:
type = "window";
break;
case Type::kBrowserView:
type = "browserView";
break;
case Type::kRemote:
type = "remote";
break;
case Type::kWebView:
type = "webview";
break;
case Type::kOffScreen:
type = "offscreen";
break;
default:
break;
}
return gin::ConvertToV8(isolate, type);
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
electron::api::WebContents::Type* out) {
using Val = electron::api::WebContents::Type;
static constexpr auto Lookup =
base::MakeFixedFlatMapSorted<base::StringPiece, Val>({
{"backgroundPage", Val::kBackgroundPage},
{"browserView", Val::kBrowserView},
{"offscreen", Val::kOffScreen},
{"webview", Val::kWebView},
});
return FromV8WithLookup(isolate, val, Lookup, out);
}
};
template <>
struct Converter<scoped_refptr<content::DevToolsAgentHost>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
const scoped_refptr<content::DevToolsAgentHost>& val) {
gin_helper::Dictionary dict(isolate, v8::Object::New(isolate));
dict.Set("id", val->GetId());
dict.Set("url", val->GetURL().spec());
return dict.GetHandle();
}
};
} // namespace gin
namespace electron::api {
namespace {
constexpr base::StringPiece CursorTypeToString(
ui::mojom::CursorType cursor_type) {
switch (cursor_type) {
case ui::mojom::CursorType::kPointer:
return "pointer";
case ui::mojom::CursorType::kCross:
return "crosshair";
case ui::mojom::CursorType::kHand:
return "hand";
case ui::mojom::CursorType::kIBeam:
return "text";
case ui::mojom::CursorType::kWait:
return "wait";
case ui::mojom::CursorType::kHelp:
return "help";
case ui::mojom::CursorType::kEastResize:
return "e-resize";
case ui::mojom::CursorType::kNorthResize:
return "n-resize";
case ui::mojom::CursorType::kNorthEastResize:
return "ne-resize";
case ui::mojom::CursorType::kNorthWestResize:
return "nw-resize";
case ui::mojom::CursorType::kSouthResize:
return "s-resize";
case ui::mojom::CursorType::kSouthEastResize:
return "se-resize";
case ui::mojom::CursorType::kSouthWestResize:
return "sw-resize";
case ui::mojom::CursorType::kWestResize:
return "w-resize";
case ui::mojom::CursorType::kNorthSouthResize:
return "ns-resize";
case ui::mojom::CursorType::kEastWestResize:
return "ew-resize";
case ui::mojom::CursorType::kNorthEastSouthWestResize:
return "nesw-resize";
case ui::mojom::CursorType::kNorthWestSouthEastResize:
return "nwse-resize";
case ui::mojom::CursorType::kColumnResize:
return "col-resize";
case ui::mojom::CursorType::kRowResize:
return "row-resize";
case ui::mojom::CursorType::kMiddlePanning:
return "m-panning";
case ui::mojom::CursorType::kMiddlePanningVertical:
return "m-panning-vertical";
case ui::mojom::CursorType::kMiddlePanningHorizontal:
return "m-panning-horizontal";
case ui::mojom::CursorType::kEastPanning:
return "e-panning";
case ui::mojom::CursorType::kNorthPanning:
return "n-panning";
case ui::mojom::CursorType::kNorthEastPanning:
return "ne-panning";
case ui::mojom::CursorType::kNorthWestPanning:
return "nw-panning";
case ui::mojom::CursorType::kSouthPanning:
return "s-panning";
case ui::mojom::CursorType::kSouthEastPanning:
return "se-panning";
case ui::mojom::CursorType::kSouthWestPanning:
return "sw-panning";
case ui::mojom::CursorType::kWestPanning:
return "w-panning";
case ui::mojom::CursorType::kMove:
return "move";
case ui::mojom::CursorType::kVerticalText:
return "vertical-text";
case ui::mojom::CursorType::kCell:
return "cell";
case ui::mojom::CursorType::kContextMenu:
return "context-menu";
case ui::mojom::CursorType::kAlias:
return "alias";
case ui::mojom::CursorType::kProgress:
return "progress";
case ui::mojom::CursorType::kNoDrop:
return "nodrop";
case ui::mojom::CursorType::kCopy:
return "copy";
case ui::mojom::CursorType::kNone:
return "none";
case ui::mojom::CursorType::kNotAllowed:
return "not-allowed";
case ui::mojom::CursorType::kZoomIn:
return "zoom-in";
case ui::mojom::CursorType::kZoomOut:
return "zoom-out";
case ui::mojom::CursorType::kGrab:
return "grab";
case ui::mojom::CursorType::kGrabbing:
return "grabbing";
case ui::mojom::CursorType::kCustom:
return "custom";
case ui::mojom::CursorType::kNull:
return "null";
case ui::mojom::CursorType::kDndNone:
return "drag-drop-none";
case ui::mojom::CursorType::kDndMove:
return "drag-drop-move";
case ui::mojom::CursorType::kDndCopy:
return "drag-drop-copy";
case ui::mojom::CursorType::kDndLink:
return "drag-drop-link";
case ui::mojom::CursorType::kNorthSouthNoResize:
return "ns-no-resize";
case ui::mojom::CursorType::kEastWestNoResize:
return "ew-no-resize";
case ui::mojom::CursorType::kNorthEastSouthWestNoResize:
return "nesw-no-resize";
case ui::mojom::CursorType::kNorthWestSouthEastNoResize:
return "nwse-no-resize";
default:
return "default";
}
}
base::IDMap<WebContents*>& GetAllWebContents() {
static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents;
return *s_all_web_contents;
}
void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise,
base::ScopedClosureRunner capture_handle,
const SkBitmap& bitmap) {
// Hack to enable transparency in captured image
promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap));
capture_handle.RunAndReset();
}
absl::optional<base::TimeDelta> GetCursorBlinkInterval() {
#if BUILDFLAG(IS_MAC)
absl::optional<base::TimeDelta> system_value(
ui::TextInsertionCaretBlinkPeriodFromDefaults());
if (system_value)
return *system_value;
#elif BUILDFLAG(IS_LINUX)
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetCursorBlinkInterval();
#elif BUILDFLAG(IS_WIN)
const auto system_msec = ::GetCaretBlinkTime();
if (system_msec != 0) {
return (system_msec == INFINITE) ? base::TimeDelta()
: base::Milliseconds(system_msec);
}
#endif
return absl::nullopt;
}
#if BUILDFLAG(ENABLE_PRINTING)
// This will return false if no printer with the provided device_name can be
// found on the network. We need to check this because Chromium does not do
// sanity checking of device_name validity and so will crash on invalid names.
bool IsDeviceNameValid(const std::u16string& device_name) {
#if BUILDFLAG(IS_MAC)
base::ScopedCFTypeRef<CFStringRef> new_printer_id(
base::SysUTF16ToCFStringRef(device_name));
PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get());
bool printer_exists = new_printer != nullptr;
PMRelease(new_printer);
return printer_exists;
#else
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
return print_backend->IsValidPrinter(base::UTF16ToUTF8(device_name));
#endif
}
// This function returns a validated device name.
// If the user passed one to webContents.print(), we check that it's valid and
// return it or fail if the network doesn't recognize it. If the user didn't
// pass a device name, we first try to return the system default printer. If one
// isn't set, then pull all the printers and use the first one or fail if none
// exist.
std::pair<std::string, std::u16string> GetDeviceNameToUse(
const std::u16string& device_name) {
#if BUILDFLAG(IS_WIN)
// Blocking is needed here because Windows printer drivers are oftentimes
// not thread-safe and have to be accessed on the UI thread.
ScopedAllowBlockingForElectron allow_blocking;
#endif
if (!device_name.empty()) {
if (!IsDeviceNameValid(device_name))
return std::make_pair("Invalid deviceName provided", std::u16string());
return std::make_pair(std::string(), device_name);
}
scoped_refptr<printing::PrintBackend> print_backend =
printing::PrintBackend::CreateInstance(
g_browser_process->GetApplicationLocale());
std::string printer_name;
printing::mojom::ResultCode code =
print_backend->GetDefaultPrinterName(printer_name);
// We don't want to return if this fails since some devices won't have a
// default printer.
if (code != printing::mojom::ResultCode::kSuccess)
LOG(ERROR) << "Failed to get default printer name";
if (printer_name.empty()) {
printing::PrinterList printers;
if (print_backend->EnumeratePrinters(printers) !=
printing::mojom::ResultCode::kSuccess)
return std::make_pair("Failed to enumerate printers", std::u16string());
if (printers.empty())
return std::make_pair("No printers available on the network",
std::u16string());
printer_name = printers.front().printer_name;
}
return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name));
}
// Copied from
// chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54
scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() {
// USER_VISIBLE because the result is displayed in the print preview dialog.
#if !BUILDFLAG(IS_WIN)
static constexpr base::TaskTraits kTraits = {
base::MayBlock(), base::TaskPriority::USER_VISIBLE};
#endif
#if defined(USE_CUPS)
// CUPS is thread safe.
return base::ThreadPool::CreateTaskRunner(kTraits);
#elif BUILDFLAG(IS_WIN)
// Windows drivers are likely not thread-safe and need to be accessed on the
// UI thread.
return content::GetUIThreadTaskRunner({base::TaskPriority::USER_VISIBLE});
#else
// Be conservative on unsupported platforms.
return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits);
#endif
}
#endif
struct UserDataLink : public base::SupportsUserData::Data {
explicit UserDataLink(base::WeakPtr<WebContents> contents)
: web_contents(contents) {}
base::WeakPtr<WebContents> web_contents;
};
const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
FileSystem() = default;
FileSystem(const std::string& type,
const std::string& file_system_name,
const std::string& root_url,
const std::string& file_system_path)
: type(type),
file_system_name(file_system_name),
root_url(root_url),
file_system_path(file_system_path) {}
std::string type;
std::string file_system_name;
std::string root_url;
std::string file_system_path;
};
std::string RegisterFileSystem(content::WebContents* web_contents,
const base::FilePath& path) {
auto* isolated_context = storage::IsolatedContext::GetInstance();
std::string root_name(kRootName);
storage::IsolatedContext::ScopedFSHandle file_system =
isolated_context->RegisterFileSystemForPath(
storage::kFileSystemTypeLocal, std::string(), path, &root_name);
content::ChildProcessSecurityPolicy* policy =
content::ChildProcessSecurityPolicy::GetInstance();
content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
int renderer_id = render_view_host->GetProcess()->GetID();
policy->GrantReadFileSystem(renderer_id, file_system.id());
policy->GrantWriteFileSystem(renderer_id, file_system.id());
policy->GrantCreateFileForFileSystem(renderer_id, file_system.id());
policy->GrantDeleteFromFileSystem(renderer_id, file_system.id());
if (!policy->CanReadFile(renderer_id, path))
policy->GrantReadFile(renderer_id, path);
return file_system.id();
}
FileSystem CreateFileSystemStruct(content::WebContents* web_contents,
const std::string& file_system_id,
const std::string& file_system_path,
const std::string& type) {
const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL();
std::string file_system_name =
storage::GetIsolatedFileSystemName(origin, file_system_id);
std::string root_url = storage::GetIsolatedFileSystemRootURIString(
origin, file_system_id, kRootName);
return FileSystem(type, file_system_name, root_url, file_system_path);
}
base::Value::Dict CreateFileSystemValue(const FileSystem& file_system) {
base::Value::Dict value;
value.Set("type", file_system.type);
value.Set("fileSystemName", file_system.file_system_name);
value.Set("rootURL", file_system.root_url);
value.Set("fileSystemPath", file_system.file_system_path);
return value;
}
void WriteToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::WriteFile(path, content.data(), content.size());
}
void AppendToFile(const base::FilePath& path, const std::string& content) {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::WILL_BLOCK);
DCHECK(!path.empty());
base::AppendToFile(path, content);
}
PrefService* GetPrefService(content::WebContents* web_contents) {
auto* context = web_contents->GetBrowserContext();
return static_cast<electron::ElectronBrowserContext*>(context)->prefs();
}
std::map<std::string, std::string> GetAddedFileSystemPaths(
content::WebContents* web_contents) {
auto* pref_service = GetPrefService(web_contents);
const base::Value::Dict& file_system_paths =
pref_service->GetDict(prefs::kDevToolsFileSystemPaths);
std::map<std::string, std::string> result;
for (auto it : file_system_paths) {
std::string type =
it.second.is_string() ? it.second.GetString() : std::string();
result[it.first] = type;
}
return result;
}
bool IsDevToolsFileSystemAdded(content::WebContents* web_contents,
const std::string& file_system_path) {
return base::Contains(GetAddedFileSystemPaths(web_contents),
file_system_path);
}
void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) {
rwhv->SetBackgroundColor(color);
static_cast<content::RenderWidgetHostViewBase*>(rwhv)
->SetContentBackgroundColor(color);
}
content::RenderFrameHost* GetRenderFrameHost(
content::NavigationHandle* navigation_handle) {
int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId();
content::FrameTreeNode* frame_tree_node =
content::FrameTreeNode::GloballyFindByID(frame_tree_node_id);
content::RenderFrameHostManager* render_manager =
frame_tree_node->render_manager();
content::RenderFrameHost* frame_host = nullptr;
if (render_manager) {
frame_host = render_manager->speculative_frame_host();
if (!frame_host)
frame_host = render_manager->current_frame_host();
}
return frame_host;
}
} // namespace
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) {
switch (view_type) {
case extensions::mojom::ViewType::kExtensionBackgroundPage:
return WebContents::Type::kBackgroundPage;
case extensions::mojom::ViewType::kAppWindow:
case extensions::mojom::ViewType::kComponent:
case extensions::mojom::ViewType::kExtensionDialog:
case extensions::mojom::ViewType::kExtensionPopup:
case extensions::mojom::ViewType::kBackgroundContents:
case extensions::mojom::ViewType::kExtensionGuest:
case extensions::mojom::ViewType::kTabContents:
case extensions::mojom::ViewType::kOffscreenDocument:
case extensions::mojom::ViewType::kExtensionSidePanel:
case extensions::mojom::ViewType::kInvalid:
return WebContents::Type::kRemote;
}
}
#endif
WebContents::WebContents(v8::Isolate* isolate,
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents),
type_(Type::kRemote),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// WebContents created by extension host will have valid ViewType set.
extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents);
if (view_type != extensions::mojom::ViewType::kInvalid) {
InitWithExtensionView(isolate, web_contents, view_type);
}
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents);
script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents);
#endif
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
SetUserAgent(GetBrowserContext()->GetUserAgent());
web_contents->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type)
: content::WebContentsObserver(web_contents.get()),
type_(type),
id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
DCHECK(type != Type::kRemote)
<< "Can't take ownership of a remote WebContents";
auto session = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, session.ToV8());
InitWithSessionAndOptions(isolate, std::move(web_contents), session,
gin::Dictionary::CreateEmpty(isolate));
}
WebContents::WebContents(v8::Isolate* isolate,
const gin_helper::Dictionary& options)
: id_(GetAllWebContents().Add(this))
#if BUILDFLAG(ENABLE_PRINTING)
,
print_task_runner_(CreatePrinterHandlerTaskRunner())
#endif
{
// Read options.
options.Get("backgroundThrottling", &background_throttling_);
// Get type
options.Get("type", &type_);
bool b = false;
if (options.Get(options::kOffscreen, &b) && b)
type_ = Type::kOffScreen;
// Init embedder earlier
options.Get("embedder", &embedder_);
// Whether to enable DevTools.
options.Get("devTools", &enable_devtools_);
// BrowserViews are not attached to a window initially so they should start
// off as hidden. This is also important for compositor recycling. See:
// https://github.com/electron/electron/pull/21372
bool initially_shown = type_ != Type::kBrowserView;
options.Get(options::kShow, &initially_shown);
// Obtain the session.
std::string partition;
gin::Handle<api::Session> session;
if (options.Get("session", &session) && !session.IsEmpty()) {
} else if (options.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
session_.Reset(isolate, session.ToV8());
std::unique_ptr<content::WebContents> web_contents;
if (IsGuest()) {
scoped_refptr<content::SiteInstance> site_instance =
content::SiteInstance::CreateForURL(session->browser_context(),
GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(session->browser_context(),
site_instance);
guest_delegate_ =
std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this);
params.guest_delegate = guest_delegate_.get();
if (embedder_ && embedder_->IsOffScreen()) {
auto* view = new OffScreenWebContentsView(
false,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
web_contents = content::WebContents::Create(params);
}
} else if (IsOffScreen()) {
// webPreferences does not have a transparent option, so if the window needs
// to be transparent, that will be set at electron_api_browser_window.cc#L57
// and we then need to pull it back out and check it here.
std::string background_color;
options.GetHidden(options::kBackgroundColor, &background_color);
bool transparent = ParseCSSColor(background_color) == SK_ColorTRANSPARENT;
content::WebContents::CreateParams params(session->browser_context());
auto* view = new OffScreenWebContentsView(
transparent,
base::BindRepeating(&WebContents::OnPaint, base::Unretained(this)));
params.view = view;
params.delegate_view = view;
web_contents = content::WebContents::Create(params);
view->SetWebContents(web_contents.get());
} else {
content::WebContents::CreateParams params(session->browser_context());
params.initially_hidden = !initially_shown;
web_contents = content::WebContents::Create(params);
}
InitWithSessionAndOptions(isolate, std::move(web_contents), session, options);
}
void WebContents::InitZoomController(content::WebContents* web_contents,
const gin_helper::Dictionary& options) {
WebContentsZoomController::CreateForWebContents(web_contents);
zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents);
double zoom_factor;
if (options.Get(options::kZoomFactor, &zoom_factor))
zoom_controller_->SetDefaultZoomFactor(zoom_factor);
// Nothing to do with ZoomController, but this function gets called in all
// init cases!
content::RenderViewHost* host = web_contents->GetRenderViewHost();
if (host)
host->GetWidget()->AddInputEventObserver(this);
}
void WebContents::InitWithSessionAndOptions(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> owned_web_contents,
gin::Handle<api::Session> session,
const gin_helper::Dictionary& options) {
Observe(owned_web_contents.get());
InitWithWebContents(std::move(owned_web_contents), session->browser_context(),
IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
auto* prefs = web_contents()->GetMutableRendererPrefs();
// Collect preferred languages from OS and browser process. accept_languages
// effects HTTP header, navigator.languages, and CJK fallback font selection.
//
// Note that an application locale set to the browser process might be
// different with the one set to the preference list.
// (e.g. overridden with --lang)
std::string accept_languages =
g_browser_process->GetApplicationLocale() + ",";
for (auto const& language : electron::GetPreferredLanguages()) {
if (language == g_browser_process->GetApplicationLocale())
continue;
accept_languages += language + ",";
}
accept_languages.pop_back();
prefs->accept_languages = accept_languages;
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
// Update font settings.
static const gfx::FontRenderParams params(
gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr));
prefs->should_antialias_text = params.antialiasing;
prefs->use_subpixel_positioning = params.subpixel_positioning;
prefs->hinting = params.hinting;
prefs->use_autohinter = params.autohinter;
prefs->use_bitmaps = params.use_bitmaps;
prefs->subpixel_rendering = params.subpixel_rendering;
#endif
// Honor the system's cursor blink rate settings
if (auto interval = GetCursorBlinkInterval())
prefs->caret_blink_interval = *interval;
// Save the preferences in C++.
// If there's already a WebContentsPreferences object, we created it as part
// of the webContents.setWindowOpenHandler path, so don't overwrite it.
if (!WebContentsPreferences::From(web_contents())) {
new WebContentsPreferences(web_contents(), options);
}
// Trigger re-calculation of webkit prefs.
web_contents()->NotifyPreferencesChanged();
WebContentsPermissionHelper::CreateForWebContents(web_contents());
InitZoomController(web_contents(), options);
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
extensions::ElectronExtensionWebContentsObserver::CreateForWebContents(
web_contents());
script_executor_ =
std::make_unique<extensions::ScriptExecutor>(web_contents());
#endif
AutofillDriverFactory::CreateForWebContents(web_contents());
SetUserAgent(GetBrowserContext()->GetUserAgent());
if (IsGuest()) {
NativeWindow* owner_window = nullptr;
if (embedder_) {
// New WebContents's owner_window is the embedder's owner_window.
auto* relay =
NativeWindowRelay::FromWebContents(embedder_->web_contents());
if (relay)
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
}
web_contents()->SetUserData(kElectronApiWebContentsKey,
std::make_unique<UserDataLink>(GetWeakPtr()));
}
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
void WebContents::InitWithExtensionView(v8::Isolate* isolate,
content::WebContents* web_contents,
extensions::mojom::ViewType view_type) {
// Must reassign type prior to calling `Init`.
type_ = GetTypeFromViewType(view_type);
if (type_ == Type::kRemote)
return;
if (type_ == Type::kBackgroundPage)
// non-background-page WebContents are retained by other classes. We need
// to pin here to prevent background-page WebContents from being GC'd.
// The background page api::WebContents will live until the underlying
// content::WebContents is destroyed.
Pin(isolate);
// Allow toggling DevTools for background pages
Observe(web_contents);
InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents),
GetBrowserContext(), IsGuest());
inspectable_web_contents_->GetView()->SetDelegate(this);
}
#endif
void WebContents::InitWithWebContents(
std::unique_ptr<content::WebContents> web_contents,
ElectronBrowserContext* browser_context,
bool is_guest) {
browser_context_ = browser_context;
web_contents->SetDelegate(this);
#if BUILDFLAG(ENABLE_PRINTING)
PrintViewManagerElectron::CreateForWebContents(web_contents.get());
#endif
#if BUILDFLAG(ENABLE_PDF_VIEWER)
pdf::PDFWebContentsHelper::CreateForWebContentsWithClient(
web_contents.get(),
std::make_unique<ElectronPDFWebContentsHelperClient>());
#endif
// Determine whether the WebContents is offscreen.
auto* web_preferences = WebContentsPreferences::From(web_contents.get());
offscreen_ = web_preferences && web_preferences->IsOffscreen();
// Create InspectableWebContents.
inspectable_web_contents_ = std::make_unique<InspectableWebContents>(
std::move(web_contents), browser_context->prefs(), is_guest);
inspectable_web_contents_->SetDelegate(this);
}
WebContents::~WebContents() {
if (web_contents()) {
content::RenderViewHost* host = web_contents()->GetRenderViewHost();
if (host)
host->GetWidget()->RemoveInputEventObserver(this);
}
if (!inspectable_web_contents_) {
WebContentsDestroyed();
return;
}
inspectable_web_contents_->GetView()->SetDelegate(nullptr);
// This event is only for internal use, which is emitted when WebContents is
// being destroyed.
Emit("will-destroy");
// For guest view based on OOPIF, the WebContents is released by the embedder
// frame, and we need to clear the reference to the memory.
bool not_owned_by_this = IsGuest() && attached_;
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
// And background pages are owned by extensions::ExtensionHost.
if (type_ == Type::kBackgroundPage)
not_owned_by_this = true;
#endif
if (not_owned_by_this) {
inspectable_web_contents_->ReleaseWebContents();
WebContentsDestroyed();
}
// InspectableWebContents will be automatically destroyed.
}
void WebContents::DeleteThisIfAlive() {
// It is possible that the FirstWeakCallback has been called but the
// SecondWeakCallback has not, in this case the garbage collection of
// WebContents has already started and we should not |delete this|.
// Calling |GetWrapper| can detect this corner case.
auto* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
delete this;
}
void WebContents::Destroy() {
// The content::WebContents should be destroyed asynchronously when possible
// as user may choose to destroy WebContents during an event of it.
if (Browser::Get()->is_shutting_down() || IsGuest()) {
DeleteThisIfAlive();
} else {
content::GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(&WebContents::DeleteThisIfAlive, GetWeakPtr()));
}
}
void WebContents::Close(absl::optional<gin_helper::Dictionary> options) {
bool dispatch_beforeunload = false;
if (options)
options->Get("waitForBeforeUnload", &dispatch_beforeunload);
if (dispatch_beforeunload &&
web_contents()->NeedToFireBeforeUnloadOrUnloadEvents()) {
NotifyUserActivation();
web_contents()->DispatchBeforeUnload(false /* auto_cancel */);
} else {
web_contents()->Close();
}
}
bool WebContents::DidAddMessageToConsole(
content::WebContents* source,
blink::mojom::ConsoleMessageLevel level,
const std::u16string& message,
int32_t line_no,
const std::u16string& source_id) {
return Emit("console-message", static_cast<int32_t>(level), message, line_no,
source_id);
}
void WebContents::OnCreateWindow(
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const std::string& features,
const scoped_refptr<network::ResourceRequestBody>& body) {
Emit("-new-window", target_url, frame_name, disposition, features, referrer,
body);
}
void WebContents::WebContentsCreatedWithFullParams(
content::WebContents* source_contents,
int opener_render_process_id,
int opener_render_frame_id,
const content::mojom::CreateNewWindowParams& params,
content::WebContents* new_contents) {
ChildWebContentsTracker::CreateForWebContents(new_contents);
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents);
tracker->url = params.target_url;
tracker->frame_name = params.frame_name;
tracker->referrer = params.referrer.To<content::Referrer>();
tracker->raw_features = params.raw_features;
tracker->body = params.body;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary dict;
gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate),
&dict);
pending_child_web_preferences_.Reset();
// Associate the preferences passed in via `setWindowOpenHandler` with the
// content::WebContents that was just created for the child window. These
// preferences will be picked up by the RenderWidgetHost via its call to the
// delegate's OverrideWebkitPrefs.
new WebContentsPreferences(new_contents, dict);
}
bool WebContents::IsWebContentsCreationOverridden(
content::SiteInstance* source_site_instance,
content::mojom::WindowContainerType window_container_type,
const GURL& opener_url,
const content::mojom::CreateNewWindowParams& params) {
bool default_prevented = Emit(
"-will-add-new-contents", params.target_url, params.frame_name,
params.raw_features, params.disposition, *params.referrer, params.body);
// If the app prevented the default, redirect to CreateCustomWebContents,
// which always returns nullptr, which will result in the window open being
// prevented (window.open() will return null in the renderer).
return default_prevented;
}
void WebContents::SetNextChildWebPreferences(
const gin_helper::Dictionary preferences) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
// Store these prefs for when Chrome calls WebContentsCreatedWithFullParams
// with the new child contents.
pending_child_web_preferences_.Reset(isolate, preferences.GetHandle());
}
content::WebContents* WebContents::CreateCustomWebContents(
content::RenderFrameHost* opener,
content::SiteInstance* source_site_instance,
bool is_new_browsing_instance,
const GURL& opener_url,
const std::string& frame_name,
const GURL& target_url,
const content::StoragePartitionConfig& partition_config,
content::SessionStorageNamespace* session_storage_namespace) {
return nullptr;
}
void WebContents::AddNewContents(
content::WebContents* source,
std::unique_ptr<content::WebContents> new_contents,
const GURL& target_url,
WindowOpenDisposition disposition,
const blink::mojom::WindowFeatures& window_features,
bool user_gesture,
bool* was_blocked) {
auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get());
DCHECK(tracker);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto api_web_contents =
CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow);
// We call RenderFrameCreated here as at this point the empty "about:blank"
// render frame has already been created. If the window never navigates again
// RenderFrameCreated won't be called and certain prefs like
// "kBackgroundColor" will not be applied.
auto* frame = api_web_contents->MainFrame();
if (frame) {
api_web_contents->HandleNewRenderFrame(frame);
}
if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture,
window_features.bounds.x(), window_features.bounds.y(),
window_features.bounds.width(), window_features.bounds.height(),
tracker->url, tracker->frame_name, tracker->referrer,
tracker->raw_features, tracker->body)) {
api_web_contents->Destroy();
}
}
content::WebContents* WebContents::OpenURLFromTab(
content::WebContents* source,
const content::OpenURLParams& params) {
auto weak_this = GetWeakPtr();
if (params.disposition != WindowOpenDisposition::CURRENT_TAB) {
Emit("-new-window", params.url, "", params.disposition, "", params.referrer,
params.post_data);
return nullptr;
}
if (!weak_this || !web_contents())
return nullptr;
content::NavigationController::LoadURLParams load_url_params(params.url);
load_url_params.referrer = params.referrer;
load_url_params.transition_type = params.transition;
load_url_params.extra_headers = params.extra_headers;
load_url_params.should_replace_current_entry =
params.should_replace_current_entry;
load_url_params.is_renderer_initiated = params.is_renderer_initiated;
load_url_params.started_from_context_menu = params.started_from_context_menu;
load_url_params.initiator_origin = params.initiator_origin;
load_url_params.source_site_instance = params.source_site_instance;
load_url_params.frame_tree_node_id = params.frame_tree_node_id;
load_url_params.redirect_chain = params.redirect_chain;
load_url_params.has_user_gesture = params.user_gesture;
load_url_params.blob_url_loader_factory = params.blob_url_loader_factory;
load_url_params.href_translate = params.href_translate;
load_url_params.reload_type = params.reload_type;
if (params.post_data) {
load_url_params.load_type =
content::NavigationController::LOAD_TYPE_HTTP_POST;
load_url_params.post_data = params.post_data;
}
source->GetController().LoadURLWithParams(load_url_params);
return source;
}
void WebContents::BeforeUnloadFired(content::WebContents* tab,
bool proceed,
bool* proceed_to_fire_unload) {
if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen ||
type_ == Type::kBrowserView)
*proceed_to_fire_unload = proceed;
else
*proceed_to_fire_unload = true;
// Note that Chromium does not emit this for navigations.
Emit("before-unload-fired", proceed);
}
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
if (!Emit("content-bounds-updated", rect))
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
Emit("close");
auto* autofill_driver_factory =
AutofillDriverFactory::FromWebContents(web_contents());
if (autofill_driver_factory) {
autofill_driver_factory->CloseAllPopups();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnCloseContents();
Destroy();
}
void WebContents::ActivateContents(content::WebContents* source) {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnActivateContents();
}
void WebContents::UpdateTargetURL(content::WebContents* source,
const GURL& url) {
Emit("update-target-url", url);
}
bool WebContents::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (type_ == Type::kWebView && embedder_) {
// Send the unhandled keyboard events back to the embedder.
return embedder_->HandleKeyboardEvent(source, event);
} else {
return PlatformHandleKeyboardEvent(source, event);
}
}
#if !BUILDFLAG(IS_MAC)
// NOTE: The macOS version of this function is found in
// electron_api_web_contents_mac.mm, as it requires calling into objective-C
// code.
bool WebContents::PlatformHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
// Escape exits tabbed fullscreen mode.
if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) {
ExitFullscreenModeForTab(source);
return true;
}
// Check if the webContents has preferences and to ignore shortcuts
auto* web_preferences = WebContentsPreferences::From(source);
if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts())
return false;
// Let the NativeWindow handle other parts.
if (owner_window()) {
owner_window()->HandleKeyboardEvent(source, event);
return true;
}
return false;
}
#endif
content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
if (exclusive_access_manager_.HandleUserKeyEvent(event))
return content::KeyboardEventProcessingResult::HANDLED;
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown ||
event.GetType() == blink::WebInputEvent::Type::kKeyUp) {
// For backwards compatibility, pretend that `kRawKeyDown` events are
// actually `kKeyDown`.
content::NativeWebKeyboardEvent tweaked_event(event);
if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown)
tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown);
bool prevent_default = Emit("before-input-event", tweaked_event);
if (prevent_default) {
return content::KeyboardEventProcessingResult::HANDLED;
}
}
return content::KeyboardEventProcessingResult::NOT_HANDLED;
}
void WebContents::ContentsZoomChange(bool zoom_in) {
Emit("zoom-changed", zoom_in ? "in" : "out");
}
Profile* WebContents::GetProfile() {
return nullptr;
}
bool WebContents::IsFullscreen() const {
if (!owner_window())
return false;
return owner_window()->IsFullscreen() || is_html_fullscreen();
}
void WebContents::EnterFullscreen(const GURL& url,
ExclusiveAccessBubbleType bubble_type,
const int64_t display_id) {}
void WebContents::ExitFullscreen() {}
void WebContents::UpdateExclusiveAccessExitBubbleContent(
const GURL& url,
ExclusiveAccessBubbleType bubble_type,
ExclusiveAccessBubbleHideCallback bubble_first_hide_callback,
bool notify_download,
bool force_update) {}
void WebContents::OnExclusiveAccessUserInput() {}
content::WebContents* WebContents::GetActiveWebContents() {
return web_contents();
}
bool WebContents::CanUserExitFullscreen() const {
return true;
}
bool WebContents::IsExclusiveAccessBubbleDisplayed() const {
return false;
}
void WebContents::EnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options) {
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
auto* permission_helper =
WebContentsPermissionHelper::FromWebContents(source);
auto callback =
base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab,
base::Unretained(this), requesting_frame, options);
permission_helper->RequestFullscreenPermission(requesting_frame, callback);
}
void WebContents::OnEnterFullscreenModeForTab(
content::RenderFrameHost* requesting_frame,
const blink::mojom::FullscreenOptions& options,
bool allowed) {
if (!allowed || !owner_window())
return;
auto* source = content::WebContents::FromRenderFrameHost(requesting_frame);
if (IsFullscreenForTabOrPending(source)) {
DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame());
return;
}
owner_window()->set_fullscreen_transition_type(
NativeWindow::FullScreenTransitionType::kHTML);
exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab(
requesting_frame, options.display_id);
SetHtmlApiFullscreen(true);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::ExitFullscreenModeForTab(content::WebContents* source) {
if (!owner_window())
return;
// This needs to be called before we exit fullscreen on the native window,
// or the controller will incorrectly think we weren't fullscreen and bail.
exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab(
source);
SetHtmlApiFullscreen(false);
if (native_fullscreen_) {
// Explicitly trigger a view resize, as the size is not actually changing if
// the browser is fullscreened, too. Chrome does this indirectly from
// `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`.
source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties();
}
}
void WebContents::RendererUnresponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host,
base::RepeatingClosure hang_monitor_restarter) {
Emit("unresponsive");
}
void WebContents::RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) {
Emit("responsive");
}
bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) {
Emit("context-menu", std::make_pair(params, &render_frame_host));
return true;
}
void WebContents::FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
const gfx::Rect& selection_rect,
int active_match_ordinal,
bool final_update) {
if (!final_update)
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
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) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin::Dictionary dict(isolate, event_object);
dict.Set("audible", audible);
EmitWithoutEvent("audio-state-changed", event);
}
void WebContents::BeforeUnloadFired(bool proceed) {
// Do nothing, we override this method just to avoid compilation error since
// there are two virtual functions named BeforeUnloadFired.
}
void WebContents::HandleNewRenderFrame(
content::RenderFrameHost* render_frame_host) {
auto* rwhv = render_frame_host->GetView();
if (!rwhv)
return;
// Set the background color of RenderWidgetHostView.
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences) {
auto maybe_color = web_preferences->GetBackgroundColor();
bool guest = IsGuest() || type_ == Type::kBrowserView;
// If webPreferences has no color stored we need to explicitly set guest
// webContents background color to transparent.
auto bg_color =
maybe_color.value_or(guest ? SK_ColorTRANSPARENT : SK_ColorWHITE);
web_contents()->SetPageBaseBackgroundColor(bg_color);
SetBackgroundColor(rwhv, bg_color);
}
if (!background_throttling_)
render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false);
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (rwh_impl)
rwh_impl->disable_hidden_ = !background_throttling_;
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->MaybeSetupMojoConnection();
}
void WebContents::OnBackgroundColorChanged() {
absl::optional<SkColor> color = web_contents()->GetBackgroundColor();
if (color.has_value()) {
auto* const view = web_contents()->GetRenderWidgetHostView();
static_cast<content::RenderWidgetHostViewBase*>(view)
->SetContentBackgroundColor(color.value());
}
}
void WebContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
HandleNewRenderFrame(render_frame_host);
// RenderFrameCreated is called for speculative frames which may not be
// used in certain cross-origin navigations. Invoking
// RenderFrameHost::GetLifecycleState currently crashes when called for
// speculative frames so we need to filter it out for now. Check
// https://crbug.com/1183639 for details on when this can be removed.
auto* rfh_impl =
static_cast<content::RenderFrameHostImpl*>(render_frame_host);
if (rfh_impl->lifecycle_state() ==
content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) {
return;
}
content::RenderFrameHost::LifecycleState lifecycle_state =
render_frame_host->GetLifecycleState();
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details =
gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
}
void WebContents::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
// A RenderFrameHost can be deleted when:
// - A WebContents is removed and its containing frames are disposed.
// - An <iframe> is removed from the DOM.
// - Cross-origin navigation creates a new RFH in a separate process which
// is swapped by content::RenderFrameHostManager.
//
// WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID
// to find an existing instance of WebFrameMain. During a cross-origin
// navigation, the deleted RFH will be the old host which was swapped out. In
// this special case, we need to also ensure that WebFrameMain's internal RFH
// matches before marking it as disposed.
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame && web_frame->render_frame_host() == render_frame_host)
web_frame->MarkRenderFrameDisposed();
}
void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host,
content::RenderFrameHost* new_host) {
if (new_host->IsInPrimaryMainFrame()) {
if (old_host)
old_host->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (new_host)
new_host->GetRenderWidgetHost()->AddInputEventObserver(this);
}
// During cross-origin navigation, a FrameTreeNode will swap out its RFH.
// If an instance of WebFrameMain exists, it will need to have its RFH
// swapped as well.
//
// |old_host| can be a nullptr so we use |new_host| for looking up the
// WebFrameMain instance.
auto* web_frame = WebFrameMain::FromRenderFrameHost(new_host);
if (web_frame) {
web_frame->UpdateRenderFrameHost(new_host);
}
}
void WebContents::FrameDeleted(int frame_tree_node_id) {
auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id);
if (web_frame)
web_frame->Destroyed();
}
void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) {
// This event is necessary for tracking any states with respect to
// intermediate render view hosts aka speculative render view hosts. Currently
// used by object-registry.js to ref count remote objects.
Emit("render-view-deleted", render_view_host->GetProcess()->GetID());
if (web_contents()->GetRenderViewHost() == render_view_host) {
// When the RVH that has been deleted is the current RVH it means that the
// the web contents are being closed. This is communicated by this event.
// Currently tracked by guest-window-manager.ts to destroy the
// BrowserWindow.
Emit("current-render-view-deleted",
render_view_host->GetProcess()->GetID());
}
}
void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
auto weak_this = GetWeakPtr();
Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED);
// User might destroy WebContents in the crashed event.
if (!weak_this || !web_contents())
return;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
}
void WebContents::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
#if BUILDFLAG(ENABLE_PLUGINS)
content::WebPluginInfo info;
auto* plugin_service = content::PluginService::GetInstance();
plugin_service->GetPluginInfoByPath(plugin_path, &info);
Emit("plugin-crashed", info.name, info.version);
#endif // BUILDFLAG(ENABLE_PLUGINS)
}
void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id) {
Emit("media-started-playing");
}
void WebContents::MediaStoppedPlaying(
const MediaPlayerInfo& video_type,
const content::MediaPlayerId& id,
content::WebContentsObserver::MediaStoppedReason reason) {
Emit("media-paused");
}
void WebContents::DidChangeThemeColor() {
auto theme_color = web_contents()->GetThemeColor();
if (theme_color) {
Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value()));
} else {
Emit("did-change-theme-color", nullptr);
}
}
void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) {
set_fullscreen_frame(rfh);
}
void WebContents::OnWebContentsFocused(
content::RenderWidgetHost* render_widget_host) {
Emit("focus");
}
void WebContents::OnWebContentsLostFocus(
content::RenderWidgetHost* render_widget_host) {
Emit("blur");
}
void WebContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host);
if (web_frame)
web_frame->DOMContentLoaded();
if (!render_frame_host->GetParent())
Emit("dom-ready");
}
void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
auto weak_this = GetWeakPtr();
Emit("did-frame-finish-load", is_main_frame, frame_process_id,
frame_routing_id);
// ⚠️WARNING!⚠️
// Emit() triggers JS which can call destroy() on |this|. It's not safe to
// assume that |this| points to valid memory at this point.
if (is_main_frame && weak_this && web_contents())
Emit("did-finish-load");
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
const GURL& url,
int error_code) {
// See DocumentLoader::StartLoadingResponse() - when we navigate to a media
// resource the original request for the media resource, which resulted in a
// committed navigation, is simply discarded. The media element created
// inside the MediaDocument then makes *another new* request for the same
// media resource.
bool is_media_document =
media::IsSupportedMediaMimeType(web_contents()->GetContentsMimeType());
if (error_code == net::ERR_ABORTED && is_media_document)
return;
bool is_main_frame = !render_frame_host->GetParent();
int frame_process_id = render_frame_host->GetProcess()->GetID();
int frame_routing_id = render_frame_host->GetRoutingID();
Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id,
frame_routing_id);
}
void WebContents::DidStartLoading() {
Emit("did-start-loading");
}
void WebContents::DidStopLoading() {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (web_preferences && web_preferences->ShouldUsePreferredSizeMode())
web_contents()->GetRenderViewHost()->EnablePreferredSizeMode();
Emit("did-stop-loading");
}
bool WebContents::EmitNavigationEvent(
const std::string& event_name,
content::NavigationHandle* navigation_handle) {
bool is_main_frame = navigation_handle->IsInMainFrame();
int frame_process_id = -1, frame_routing_id = -1;
content::RenderFrameHost* frame_host = GetRenderFrameHost(navigation_handle);
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
bool is_same_document = navigation_handle->IsSameDocument();
auto url = navigation_handle->GetURL();
content::RenderFrameHost* initiator_frame_host =
navigation_handle->GetInitiatorFrameToken().has_value()
? content::RenderFrameHost::FromFrameToken(
navigation_handle->GetInitiatorProcessID(),
navigation_handle->GetInitiatorFrameToken().value())
: nullptr;
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>();
gin_helper::Dictionary dict(isolate, event_object);
dict.Set("url", url);
dict.Set("isSameDocument", is_same_document);
dict.Set("isMainFrame", is_main_frame);
dict.Set("frame", frame_host);
dict.SetGetter("initiator", initiator_frame_host);
EmitWithoutEvent(event_name, event, url, is_same_document, is_main_frame,
frame_process_id, frame_routing_id);
return event->GetDefaultPrevented();
}
void WebContents::Message(bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Message", "channel", channel);
// webContents.emit('-ipc-message', new Event(), internal, channel,
// arguments);
EmitWithSender("-ipc-message", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), internal,
channel, std::move(arguments));
}
void WebContents::Invoke(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::InvokeCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel);
// webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments);
EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::OnFirstNonEmptyLayout(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents()->GetPrimaryMainFrame()) {
Emit("ready-to-show");
}
}
// This object wraps the InvokeCallback so that if it gets GC'd by V8, we can
// still call the callback and send an error. Not doing so causes a Mojo DCHECK,
// since Mojo requires callbacks to be called before they are destroyed.
class ReplyChannel : public gin::Wrappable<ReplyChannel> {
public:
using InvokeCallback = electron::mojom::ElectronApiIPC::InvokeCallback;
static gin::Handle<ReplyChannel> Create(v8::Isolate* isolate,
InvokeCallback callback) {
return gin::CreateHandle(isolate, new ReplyChannel(std::move(callback)));
}
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override {
return gin::Wrappable<ReplyChannel>::GetObjectTemplateBuilder(isolate)
.SetMethod("sendReply", &ReplyChannel::SendReply);
}
const char* GetTypeName() override { return "ReplyChannel"; }
void SendError(const std::string& msg) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
// If there's no current context, it means we're shutting down, so we
// don't need to send an event.
if (!isolate->GetCurrentContext().IsEmpty()) {
v8::HandleScope scope(isolate);
auto message = gin::DataObjectBuilder(isolate).Set("error", msg).Build();
SendReply(isolate, message);
}
}
private:
explicit ReplyChannel(InvokeCallback callback)
: callback_(std::move(callback)) {}
~ReplyChannel() override {
if (callback_)
SendError("reply was never sent");
}
bool SendReply(v8::Isolate* isolate, v8::Local<v8::Value> arg) {
if (!callback_)
return false;
blink::CloneableMessage message;
if (!gin::ConvertFromV8(isolate, arg, &message)) {
return false;
}
std::move(callback_).Run(std::move(message));
return true;
}
InvokeCallback callback_;
};
gin::WrapperInfo ReplyChannel::kWrapperInfo = {gin::kEmbedderNativeGin};
gin::Handle<gin_helper::internal::Event> WebContents::MakeEventWithSender(
v8::Isolate* isolate,
content::RenderFrameHost* frame,
electron::mojom::ElectronApiIPC::InvokeCallback callback) {
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper)) {
if (callback) {
// We must always invoke the callback if present.
ReplyChannel::Create(isolate, std::move(callback))
->SendError("WebContents was destroyed");
}
return gin::Handle<gin_helper::internal::Event>();
}
gin::Handle<gin_helper::internal::Event> event =
gin_helper::internal::Event::New(isolate);
gin_helper::Dictionary dict(isolate, event.ToV8().As<v8::Object>());
if (callback)
dict.Set("_replyChannel",
ReplyChannel::Create(isolate, std::move(callback)));
if (frame) {
dict.Set("frameId", frame->GetRoutingID());
dict.Set("processId", frame->GetProcess()->GetID());
}
return event;
}
void WebContents::ReceivePostMessage(
const std::string& channel,
blink::TransferableMessage message,
content::RenderFrameHost* render_frame_host) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto wrapped_ports =
MessagePort::EntanglePorts(isolate, std::move(message.ports));
v8::Local<v8::Value> message_value =
electron::DeserializeV8Value(isolate, message);
EmitWithSender("-ipc-ports", render_frame_host,
electron::mojom::ElectronApiIPC::InvokeCallback(), false,
channel, message_value, std::move(wrapped_ports));
}
void WebContents::MessageSync(
bool internal,
const std::string& channel,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host) {
TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel);
// webContents.emit('-ipc-message-sync', new Event(sender, message), internal,
// channel, arguments);
EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback),
internal, channel, std::move(arguments));
}
void WebContents::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) {
if (owner_window() && owner_window()->has_frame())
return;
draggable_region_ = DraggableRegionsToSkRegion(regions);
}
void WebContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-start-navigation", navigation_handle);
}
void WebContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
EmitNavigationEvent("did-redirect-navigation", navigation_handle);
}
void WebContents::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
// Don't focus content in an inactive window.
if (!owner_window())
return;
#if BUILDFLAG(IS_MAC)
if (!owner_window()->IsActive())
return;
#else
if (!owner_window()->widget()->IsActive())
return;
#endif
// Don't focus content after subframe navigations.
if (!navigation_handle->IsInMainFrame())
return;
// Only focus for top-level contents.
if (type_ != Type::kBrowserWindow)
return;
web_contents()->SetInitialFocus();
}
void WebContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (owner_window_) {
owner_window_->NotifyLayoutWindowControlsOverlay();
}
if (!navigation_handle->HasCommitted())
return;
bool is_main_frame = navigation_handle->IsInMainFrame();
content::RenderFrameHost* frame_host =
navigation_handle->GetRenderFrameHost();
int frame_process_id = -1, frame_routing_id = -1;
if (frame_host) {
frame_process_id = frame_host->GetProcess()->GetID();
frame_routing_id = frame_host->GetRoutingID();
}
if (!navigation_handle->IsErrorPage()) {
// FIXME: All the Emit() calls below could potentially result in |this|
// being destroyed (by JS listening for the event and calling
// webContents.destroy()).
auto url = navigation_handle->GetURL();
bool is_same_document = navigation_handle->IsSameDocument();
if (is_same_document) {
Emit("did-navigate-in-page", url, is_main_frame, frame_process_id,
frame_routing_id);
} else {
const net::HttpResponseHeaders* http_response =
navigation_handle->GetResponseHeaders();
std::string http_status_text;
int http_response_code = -1;
if (http_response) {
http_status_text = http_response->GetStatusText();
http_response_code = http_response->response_code();
}
Emit("did-frame-navigate", url, http_response_code, http_status_text,
is_main_frame, frame_process_id, frame_routing_id);
if (is_main_frame) {
Emit("did-navigate", url, http_response_code, http_status_text);
}
}
if (IsGuest())
Emit("load-commit", url, is_main_frame);
} else {
auto url = navigation_handle->GetURL();
int code = navigation_handle->GetNetErrorCode();
auto description = net::ErrorToShortString(code);
Emit("did-fail-provisional-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
// Do not emit "did-fail-load" for canceled requests.
if (code != net::ERR_ABORTED) {
EmitWarning(
node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()),
"Failed to load URL: " + url.possibly_invalid_spec() +
" with error: " + description,
"electron");
Emit("did-fail-load", code, description, url, is_main_frame,
frame_process_id, frame_routing_id);
}
}
content::NavigationEntry* entry = navigation_handle->GetNavigationEntry();
// This check is needed due to an issue in Chromium
// Check the Chromium issue to keep updated:
// https://bugs.chromium.org/p/chromium/issues/detail?id=1178663
// If a history entry has been made and the forward/back call has been made,
// proceed with setting the new title
if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK))
WebContents::TitleWasSet(entry);
}
void WebContents::TitleWasSet(content::NavigationEntry* entry) {
std::u16string final_title;
bool explicit_set = true;
if (entry) {
auto title = entry->GetTitle();
auto url = entry->GetURL();
if (url.SchemeIsFile() && title.empty()) {
final_title = base::UTF8ToUTF16(url.ExtractFileName());
explicit_set = false;
} else {
final_title = title;
}
} else {
final_title = web_contents()->GetTitle();
}
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnPageTitleUpdated(final_title, explicit_set);
Emit("page-title-updated", final_title, explicit_set);
}
void WebContents::DidUpdateFaviconURL(
content::RenderFrameHost* render_frame_host,
const std::vector<blink::mojom::FaviconURLPtr>& urls) {
std::set<GURL> unique_urls;
for (const auto& iter : urls) {
if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon)
continue;
const GURL& url = iter->icon_url;
if (url.is_valid())
unique_urls.insert(url);
}
Emit("page-favicon-updated", unique_urls);
}
void WebContents::DevToolsReloadPage() {
Emit("devtools-reload-page");
}
void WebContents::DevToolsFocused() {
Emit("devtools-focused");
}
void WebContents::DevToolsOpened() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
DCHECK(inspectable_web_contents_);
DCHECK(inspectable_web_contents_->GetDevToolsWebContents());
auto handle = FromOrCreate(
isolate, inspectable_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate, handle.ToV8());
// Set inspected tabID.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "setInspectedTabId", base::Value(ID()));
// Inherit owner window in devtools when it doesn't have one.
auto* devtools = inspectable_web_contents_->GetDevToolsWebContents();
bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey());
if (owner_window() && !has_window)
handle->SetOwnerWindow(devtools, owner_window());
Emit("devtools-opened");
}
void WebContents::DevToolsClosed() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void WebContents::DevToolsResized() {
for (ExtendedWebContentsObserver& observer : observers_)
observer.OnDevToolsResized();
}
void WebContents::SetOwnerWindow(NativeWindow* owner_window) {
SetOwnerWindow(GetWebContents(), owner_window);
}
void WebContents::SetOwnerWindow(content::WebContents* web_contents,
NativeWindow* owner_window) {
if (owner_window) {
owner_window_ = owner_window->GetWeakPtr();
NativeWindowRelay::CreateForWebContents(web_contents,
owner_window->GetWeakPtr());
} else {
owner_window_ = nullptr;
web_contents->RemoveUserData(NativeWindowRelay::UserDataKey());
}
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetNativeWindow(owner_window);
}
content::WebContents* WebContents::GetWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetWebContents();
}
content::WebContents* WebContents::GetDevToolsWebContents() const {
if (!inspectable_web_contents_)
return nullptr;
return inspectable_web_contents_->GetDevToolsWebContents();
}
void WebContents::WebContentsDestroyed() {
// Clear the pointer stored in wrapper.
if (GetAllWebContents().Lookup(id_))
GetAllWebContents().Remove(id_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::Object> wrapper;
if (!GetWrapper(isolate).ToLocal(&wrapper))
return;
wrapper->SetAlignedPointerInInternalField(0, nullptr);
// Tell WebViewGuestDelegate that the WebContents has been destroyed.
if (guest_delegate_)
guest_delegate_->WillDestroy();
Observe(nullptr);
Emit("destroyed");
}
void WebContents::NavigationEntryCommitted(
const content::LoadCommittedDetails& details) {
Emit("navigation-entry-committed", details.entry->GetURL(),
details.is_same_document, details.did_replace_entry);
}
bool WebContents::GetBackgroundThrottling() const {
return background_throttling_;
}
void WebContents::SetBackgroundThrottling(bool allowed) {
background_throttling_ = allowed;
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (!rfh)
return;
auto* rwhv = rfh->GetView();
if (!rwhv)
return;
auto* rwh_impl =
static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost());
if (!rwh_impl)
return;
rwh_impl->disable_hidden_ = !background_throttling_;
web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed);
if (rwh_impl->is_hidden()) {
rwh_impl->WasShown({});
}
}
int WebContents::GetProcessID() const {
return web_contents()->GetPrimaryMainFrame()->GetProcess()->GetID();
}
base::ProcessId WebContents::GetOSProcessID() const {
base::ProcessHandle process_handle = web_contents()
->GetPrimaryMainFrame()
->GetProcess()
->GetProcess()
.Handle();
return base::GetProcId(process_handle);
}
WebContents::Type WebContents::GetType() const {
return type_;
}
bool WebContents::Equal(const WebContents* web_contents) const {
return ID() == web_contents->ID();
}
GURL WebContents::GetURL() const {
return web_contents()->GetLastCommittedURL();
}
void WebContents::LoadURL(const GURL& url,
const gin_helper::Dictionary& options) {
if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) {
Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL),
net::ErrorToShortString(net::ERR_INVALID_URL),
url.possibly_invalid_spec(), true);
return;
}
content::NavigationController::LoadURLParams params(url);
if (!options.Get("httpReferrer", ¶ms.referrer)) {
GURL http_referrer;
if (options.Get("httpReferrer", &http_referrer))
params.referrer =
content::Referrer(http_referrer.GetAsReferrer(),
network::mojom::ReferrerPolicy::kDefault);
}
std::string user_agent;
if (options.Get("userAgent", &user_agent))
SetUserAgent(user_agent);
std::string extra_headers;
if (options.Get("extraHeaders", &extra_headers))
params.extra_headers = extra_headers;
scoped_refptr<network::ResourceRequestBody> body;
if (options.Get("postData", &body)) {
params.post_data = body;
params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST;
}
GURL base_url_for_data_url;
if (options.Get("baseURLForDataURL", &base_url_for_data_url)) {
params.base_url_for_data_url = base_url_for_data_url;
params.load_type = content::NavigationController::LOAD_TYPE_DATA;
}
bool reload_ignoring_cache = false;
if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) &&
reload_ignoring_cache) {
params.reload_type = content::ReloadType::BYPASSING_CACHE;
}
// Calling LoadURLWithParams() can trigger JS which destroys |this|.
auto weak_this = GetWeakPtr();
params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE;
// Discard non-committed entries to ensure that we don't re-use a pending
// entry
web_contents()->GetController().DiscardNonCommittedEntries();
web_contents()->GetController().LoadURLWithParams(params);
// ⚠️WARNING!⚠️
// LoadURLWithParams() triggers JS events which can call destroy() on |this|.
// It's not safe to assume that |this| points to valid memory at this point.
if (!weak_this || !web_contents())
return;
// Required to make beforeunload handler work.
NotifyUserActivation();
}
// TODO(MarshallOfSound): Figure out what we need to do with post data here, I
// believe the default behavior when we pass "true" is to phone out to the
// delegate and then the controller expects this method to be called again with
// "false" if the user approves the reload. For now this would result in
// ".reload()" calls on POST data domains failing silently. Passing false would
// result in them succeeding, but reposting which although more correct could be
// considering a breaking change.
void WebContents::Reload() {
web_contents()->GetController().Reload(content::ReloadType::NORMAL,
/* check_for_repost */ true);
}
void WebContents::ReloadIgnoringCache() {
web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE,
/* check_for_repost */ true);
}
void WebContents::DownloadURL(const GURL& url) {
auto* browser_context = web_contents()->GetBrowserContext();
auto* download_manager = browser_context->GetDownloadManager();
std::unique_ptr<download::DownloadUrlParameters> download_params(
content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame(
web_contents(), url, MISSING_TRAFFIC_ANNOTATION));
download_manager->DownloadUrl(std::move(download_params));
}
std::u16string WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
bool WebContents::IsLoading() const {
return web_contents()->IsLoading();
}
bool WebContents::IsLoadingMainFrame() const {
return web_contents()->ShouldShowLoadingUI();
}
bool WebContents::IsWaitingForResponse() const {
return web_contents()->IsWaitingForResponse();
}
void WebContents::Stop() {
web_contents()->Stop();
}
bool WebContents::CanGoBack() const {
return web_contents()->GetController().CanGoBack();
}
void WebContents::GoBack() {
if (CanGoBack())
web_contents()->GetController().GoBack();
}
bool WebContents::CanGoForward() const {
return web_contents()->GetController().CanGoForward();
}
void WebContents::GoForward() {
if (CanGoForward())
web_contents()->GetController().GoForward();
}
bool WebContents::CanGoToOffset(int offset) const {
return web_contents()->GetController().CanGoToOffset(offset);
}
void WebContents::GoToOffset(int offset) {
if (CanGoToOffset(offset))
web_contents()->GetController().GoToOffset(offset);
}
bool WebContents::CanGoToIndex(int index) const {
return index >= 0 && index < GetHistoryLength();
}
void WebContents::GoToIndex(int index) {
if (CanGoToIndex(index))
web_contents()->GetController().GoToIndex(index);
}
int WebContents::GetActiveIndex() const {
return web_contents()->GetController().GetCurrentEntryIndex();
}
void WebContents::ClearHistory() {
// In some rare cases (normally while there is no real history) we are in a
// state where we can't prune navigation entries
if (web_contents()->GetController().CanPruneAllButLastCommitted()) {
web_contents()->GetController().PruneAllButLastCommitted();
}
}
int WebContents::GetHistoryLength() const {
return web_contents()->GetController().GetEntryCount();
}
const std::string WebContents::GetWebRTCIPHandlingPolicy() const {
return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy;
}
void WebContents::SetWebRTCIPHandlingPolicy(
const std::string& webrtc_ip_handling_policy) {
if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy)
return;
web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy =
webrtc_ip_handling_policy;
web_contents()->SyncRendererPrefs();
}
std::string WebContents::GetMediaSourceID(
content::WebContents* request_web_contents) {
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host)
return std::string();
content::DesktopMediaID media_id(
content::DesktopMediaID::TYPE_WEB_CONTENTS,
content::DesktopMediaID::kNullId,
content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(),
frame_host->GetRoutingID()));
auto* request_frame_host = request_web_contents->GetPrimaryMainFrame();
if (!request_frame_host)
return std::string();
std::string id =
content::DesktopStreamsRegistry::GetInstance()->RegisterStream(
request_frame_host->GetProcess()->GetID(),
request_frame_host->GetRoutingID(),
url::Origin::Create(request_frame_host->GetLastCommittedURL()
.DeprecatedGetOriginAsURL()),
media_id, content::kRegistryStreamTypeTab);
return id;
}
bool WebContents::IsCrashed() const {
return web_contents()->IsCrashed();
}
void WebContents::ForcefullyCrashRenderer() {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
if (!rwh)
return;
content::RenderProcessHost* rph = rwh->GetProcess();
if (rph) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// A generic |CrashDumpHungChildProcess()| is not implemented for Linux.
// Instead we send an explicit IPC to crash on the renderer's IO thread.
rph->ForceCrash();
#else
// Try to generate a crash report for the hung process.
#if !IS_MAS_BUILD()
CrashDumpHungChildProcess(rph->GetProcess().Handle());
#endif
rph->Shutdown(content::RESULT_CODE_HUNG);
#endif
}
}
void WebContents::SetUserAgent(const std::string& user_agent) {
blink::UserAgentOverride ua_override;
ua_override.ua_string_override = user_agent;
if (!user_agent.empty())
ua_override.ua_metadata_override = embedder_support::GetUserAgentMetadata();
web_contents()->SetUserAgentOverride(ua_override, false);
}
std::string WebContents::GetUserAgent() {
return web_contents()->GetUserAgentOverride().ua_string_override;
}
v8::Local<v8::Promise> WebContents::SavePage(
const base::FilePath& full_file_path,
const content::SavePageType& save_type) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
if (!full_file_path.IsAbsolute()) {
promise.RejectWithErrorMessage("Path must be absolute");
return handle;
}
auto* handler = new SavePageHandler(web_contents(), std::move(promise));
handler->Handle(full_file_path, save_type);
return handle;
}
void WebContents::OpenDevTools(gin::Arguments* args) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
std::string state;
if (type_ == Type::kWebView || type_ == Type::kBackgroundPage ||
!owner_window()) {
state = "detach";
}
#if BUILDFLAG(IS_WIN)
auto* win = static_cast<NativeWindowViews*>(owner_window());
// Force a detached state when WCO is enabled to match Chrome
// behavior and prevent occlusion of DevTools.
if (win && win->IsWindowControlsOverlayEnabled())
state = "detach";
#endif
bool activate = true;
if (args && args->Length() == 1) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("mode", &state);
options.Get("activate", &activate);
}
}
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->SetDockState(state);
inspectable_web_contents_->ShowDevTools(activate);
}
void WebContents::CloseDevTools() {
if (type_ == Type::kRemote)
return;
DCHECK(inspectable_web_contents_);
inspectable_web_contents_->CloseDevTools();
}
bool WebContents::IsDevToolsOpened() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->IsDevToolsViewShowing();
}
bool WebContents::IsDevToolsFocused() {
if (type_ == Type::kRemote)
return false;
DCHECK(inspectable_web_contents_);
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void WebContents::EnableDeviceEmulation(
const blink::DeviceEmulationParams& params) {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->EnableDeviceEmulation(params);
}
}
}
void WebContents::DisableDeviceEmulation() {
if (type_ == Type::kRemote)
return;
DCHECK(web_contents());
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (frame_host) {
auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>(
frame_host->GetView()->GetRenderWidgetHost());
if (widget_host_impl) {
auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget();
frame_widget->DisableDeviceEmulation();
}
}
}
void WebContents::ToggleDevTools() {
if (IsDevToolsOpened())
CloseDevTools();
else
OpenDevTools(nullptr);
}
void WebContents::InspectElement(int x, int y) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
DCHECK(inspectable_web_contents_);
if (!inspectable_web_contents_->GetDevToolsWebContents())
OpenDevTools(nullptr);
inspectable_web_contents_->InspectElement(x, y);
}
void WebContents::InspectSharedWorkerById(const std::string& workerId) {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
if (agent_host->GetId() == workerId) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
}
std::vector<scoped_refptr<content::DevToolsAgentHost>>
WebContents::GetAllSharedWorkers() {
std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers;
if (type_ == Type::kRemote)
return shared_workers;
if (!enable_devtools_)
return shared_workers;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
shared_workers.push_back(agent_host);
}
}
return shared_workers;
}
void WebContents::InspectSharedWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeSharedWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::InspectServiceWorker() {
if (type_ == Type::kRemote)
return;
if (!enable_devtools_)
return;
for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) {
if (agent_host->GetType() ==
content::DevToolsAgentHost::kTypeServiceWorker) {
OpenDevTools(nullptr);
inspectable_web_contents_->AttachTo(agent_host);
break;
}
}
}
void WebContents::SetIgnoreMenuShortcuts(bool ignore) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
DCHECK(web_preferences);
web_preferences->SetIgnoreMenuShortcuts(ignore);
}
void WebContents::SetAudioMuted(bool muted) {
web_contents()->SetAudioMuted(muted);
}
bool WebContents::IsAudioMuted() {
return web_contents()->IsAudioMuted();
}
bool WebContents::IsCurrentlyAudible() {
return web_contents()->IsCurrentlyAudible();
}
#if BUILDFLAG(ENABLE_PRINTING)
void WebContents::OnGetDeviceNameToUse(
base::Value::Dict print_settings,
printing::CompletionCallback print_callback,
bool silent,
// <error, device_name>
std::pair<std::string, std::u16string> info) {
// The content::WebContents might be already deleted at this point, and the
// PrintViewManagerElectron class does not do null check.
if (!web_contents()) {
if (print_callback)
std::move(print_callback).Run(false, "failed");
return;
}
if (!info.first.empty()) {
if (print_callback)
std::move(print_callback).Run(false, info.first);
return;
}
// If the user has passed a deviceName use it, otherwise use default printer.
print_settings.Set(printing::kSettingDeviceName, info.second);
auto* print_view_manager =
PrintViewManagerElectron::FromWebContents(web_contents());
if (!print_view_manager)
return;
auto* focused_frame = web_contents()->GetFocusedFrame();
auto* rfh = focused_frame && focused_frame->HasSelection()
? focused_frame
: web_contents()->GetPrimaryMainFrame();
print_view_manager->PrintNow(rfh, silent, std::move(print_settings),
std::move(print_callback));
}
void WebContents::Print(gin::Arguments* args) {
gin_helper::Dictionary options =
gin::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid print settings specified.");
return;
}
printing::CompletionCallback callback;
if (args->Length() == 2 && !args->GetNext(&callback)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("webContents.print(): Invalid optional callback provided.");
return;
}
// Set optional silent printing
bool silent = false;
options.Get("silent", &silent);
bool print_background = false;
options.Get("printBackground", &print_background);
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
gin_helper::Dictionary margins =
gin::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
margins.Get("marginType", &margin_type);
settings.Set(printing::kSettingMarginsType, static_cast<int>(margin_type));
if (margin_type == printing::mojom::MarginType::kCustomMargins) {
base::Value::Dict custom_margins;
int top = 0;
margins.Get("top", &top);
custom_margins.Set(printing::kSettingMarginTop, top);
int bottom = 0;
margins.Get("bottom", &bottom);
custom_margins.Set(printing::kSettingMarginBottom, bottom);
int left = 0;
margins.Get("left", &left);
custom_margins.Set(printing::kSettingMarginLeft, left);
int right = 0;
margins.Get("right", &right);
custom_margins.Set(printing::kSettingMarginRight, right);
settings.Set(printing::kSettingMarginsCustom, std::move(custom_margins));
}
} else {
settings.Set(
printing::kSettingMarginsType,
static_cast<int>(printing::mojom::MarginType::kDefaultMargins));
}
// Set whether to print color or greyscale
bool print_color = true;
options.Get("color", &print_color);
auto const color_model = print_color ? printing::mojom::ColorModel::kColor
: printing::mojom::ColorModel::kGray;
settings.Set(printing::kSettingColor, static_cast<int>(color_model));
// Is the orientation landscape or portrait.
bool landscape = false;
options.Get("landscape", &landscape);
settings.Set(printing::kSettingLandscape, landscape);
// We set the default to the system's default printer and only update
// if at the Chromium level if the user overrides.
// Printer device name as opened by the OS.
std::u16string device_name;
options.Get("deviceName", &device_name);
int scale_factor = 100;
options.Get("scaleFactor", &scale_factor);
settings.Set(printing::kSettingScaleFactor, scale_factor);
int pages_per_sheet = 1;
options.Get("pagesPerSheet", &pages_per_sheet);
settings.Set(printing::kSettingPagesPerSheet, pages_per_sheet);
// True if the user wants to print with collate.
bool collate = true;
options.Get("collate", &collate);
settings.Set(printing::kSettingCollate, collate);
// The number of individual copies to print
int copies = 1;
options.Get("copies", &copies);
settings.Set(printing::kSettingCopies, copies);
// Strings to be printed as headers and footers if requested by the user.
std::string header;
options.Get("header", &header);
std::string footer;
options.Get("footer", &footer);
if (!(header.empty() && footer.empty())) {
settings.Set(printing::kSettingHeaderFooterEnabled, true);
settings.Set(printing::kSettingHeaderFooterTitle, header);
settings.Set(printing::kSettingHeaderFooterURL, footer);
} else {
settings.Set(printing::kSettingHeaderFooterEnabled, false);
}
// We don't want to allow the user to enable these settings
// but we need to set them or a CHECK is hit.
settings.Set(printing::kSettingPrinterType,
static_cast<int>(printing::mojom::PrinterType::kLocal));
settings.Set(printing::kSettingShouldPrintSelectionOnly, false);
settings.Set(printing::kSettingRasterizePdf, false);
// Set custom page ranges to print
std::vector<gin_helper::Dictionary> page_ranges;
if (options.Get("pageRanges", &page_ranges)) {
base::Value::List page_range_list;
for (auto& range : page_ranges) {
int from, to;
if (range.Get("from", &from) && range.Get("to", &to)) {
base::Value::Dict range_dict;
// Chromium uses 1-based page ranges, so increment each by 1.
range_dict.Set(printing::kSettingPageRangeFrom, from + 1);
range_dict.Set(printing::kSettingPageRangeTo, to + 1);
page_range_list.Append(std::move(range_dict));
} else {
continue;
}
}
if (!page_range_list.empty())
settings.Set(printing::kSettingPageRange, std::move(page_range_list));
}
// Duplex type user wants to use.
printing::mojom::DuplexMode duplex_mode =
printing::mojom::DuplexMode::kSimplex;
options.Get("duplexMode", &duplex_mode);
settings.Set(printing::kSettingDuplexMode, static_cast<int>(duplex_mode));
// We've already done necessary parameter sanitization at the
// JS level, so we can simply pass this through.
base::Value media_size(base::Value::Type::DICT);
if (options.Get("mediaSize", &media_size))
settings.Set(printing::kSettingMediaSize, std::move(media_size));
// Set custom dots per inch (dpi)
gin_helper::Dictionary dpi_settings;
int dpi = 72;
if (options.Get("dpi", &dpi_settings)) {
int horizontal = 72;
dpi_settings.Get("horizontal", &horizontal);
settings.Set(printing::kSettingDpiHorizontal, horizontal);
int vertical = 72;
dpi_settings.Get("vertical", &vertical);
settings.Set(printing::kSettingDpiVertical, vertical);
} else {
settings.Set(printing::kSettingDpiHorizontal, dpi);
settings.Set(printing::kSettingDpiVertical, dpi);
}
print_task_runner_->PostTaskAndReplyWithResult(
FROM_HERE, base::BindOnce(&GetDeviceNameToUse, device_name),
base::BindOnce(&WebContents::OnGetDeviceNameToUse,
weak_factory_.GetWeakPtr(), std::move(settings),
std::move(callback), silent));
}
// Partially duplicated and modified from
// headless/lib/browser/protocol/page_handler.cc;l=41
v8::Local<v8::Promise> WebContents::PrintToPDF(const base::Value& settings) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
gin_helper::Promise<v8::Local<v8::Value>> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
// This allows us to track headless printing calls.
auto unique_id = settings.GetDict().FindInt(printing::kPreviewRequestID);
auto landscape = settings.GetDict().FindBool("landscape");
auto display_header_footer =
settings.GetDict().FindBool("displayHeaderFooter");
auto print_background = settings.GetDict().FindBool("shouldPrintBackgrounds");
auto scale = settings.GetDict().FindDouble("scale");
auto paper_width = settings.GetDict().FindDouble("paperWidth");
auto paper_height = settings.GetDict().FindDouble("paperHeight");
auto margin_top = settings.GetDict().FindDouble("marginTop");
auto margin_bottom = settings.GetDict().FindDouble("marginBottom");
auto margin_left = settings.GetDict().FindDouble("marginLeft");
auto margin_right = settings.GetDict().FindDouble("marginRight");
auto page_ranges = *settings.GetDict().FindString("pageRanges");
auto header_template = *settings.GetDict().FindString("headerTemplate");
auto footer_template = *settings.GetDict().FindString("footerTemplate");
auto prefer_css_page_size = settings.GetDict().FindBool("preferCSSPageSize");
absl::variant<printing::mojom::PrintPagesParamsPtr, std::string>
print_pages_params = print_to_pdf::GetPrintPagesParams(
web_contents()->GetPrimaryMainFrame()->GetLastCommittedURL(),
landscape, display_header_footer, print_background, scale,
paper_width, paper_height, margin_top, margin_bottom, margin_left,
margin_right, absl::make_optional(header_template),
absl::make_optional(footer_template), prefer_css_page_size);
if (absl::holds_alternative<std::string>(print_pages_params)) {
auto error = absl::get<std::string>(print_pages_params);
promise.RejectWithErrorMessage("Invalid print parameters: " + error);
return handle;
}
auto* manager = PrintViewManagerElectron::FromWebContents(web_contents());
if (!manager) {
promise.RejectWithErrorMessage("Failed to find print manager");
return handle;
}
auto params = std::move(
absl::get<printing::mojom::PrintPagesParamsPtr>(print_pages_params));
params->params->document_cookie = unique_id.value_or(0);
manager->PrintToPdf(web_contents()->GetPrimaryMainFrame(), page_ranges,
std::move(params),
base::BindOnce(&WebContents::OnPDFCreated, GetWeakPtr(),
std::move(promise)));
return handle;
}
void WebContents::OnPDFCreated(
gin_helper::Promise<v8::Local<v8::Value>> promise,
print_to_pdf::PdfPrintResult print_result,
scoped_refptr<base::RefCountedMemory> data) {
if (print_result != print_to_pdf::PdfPrintResult::kPrintSuccess) {
promise.RejectWithErrorMessage(
"Failed to generate PDF: " +
print_to_pdf::PdfPrintResultToString(print_result));
return;
}
v8::Isolate* isolate = promise.isolate();
gin_helper::Locker locker(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(
v8::Local<v8::Context>::New(isolate, promise.GetContext()));
v8::Local<v8::Value> buffer =
node::Buffer::Copy(isolate, reinterpret_cast<const char*>(data->front()),
data->size())
.ToLocalChecked();
promise.Resolve(buffer);
}
#endif
void WebContents::AddWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(std::string(), path);
}
void WebContents::RemoveWorkSpace(gin::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
}
void WebContents::Undo() {
web_contents()->Undo();
}
void WebContents::Redo() {
web_contents()->Redo();
}
void WebContents::Cut() {
web_contents()->Cut();
}
void WebContents::Copy() {
web_contents()->Copy();
}
void WebContents::CenterSelection() {
web_contents()->CenterSelection();
}
void WebContents::Paste() {
web_contents()->Paste();
}
void WebContents::PasteAndMatchStyle() {
web_contents()->PasteAndMatchStyle();
}
void WebContents::Delete() {
web_contents()->Delete();
}
void WebContents::SelectAll() {
web_contents()->SelectAll();
}
void WebContents::Unselect() {
web_contents()->CollapseSelection();
}
void WebContents::ScrollToTopOfDocument() {
web_contents()->ScrollToTopOfDocument();
}
void WebContents::ScrollToBottomOfDocument() {
web_contents()->ScrollToBottomOfDocument();
}
void WebContents::AdjustSelectionByCharacterOffset(gin::Arguments* args) {
int start_adjust = 0;
int end_adjust = 0;
gin_helper::Dictionary dict;
if (args->GetNext(&dict)) {
dict.Get("start", &start_adjust);
dict.Get("matchCase", &end_adjust);
}
// The selection menu is a Chrome-specific piece of UI.
// TODO(codebytere): maybe surface as an event in the future?
web_contents()->AdjustSelectionByCharacterOffset(
start_adjust, end_adjust, false /* show_selection_menu */);
}
void WebContents::Replace(const std::u16string& word) {
web_contents()->Replace(word);
}
void WebContents::ReplaceMisspelling(const std::u16string& word) {
web_contents()->ReplaceMisspelling(word);
}
uint32_t WebContents::FindInPage(gin::Arguments* args) {
std::u16string search_text;
if (!args->GetNext(&search_text) || search_text.empty()) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must provide a non-empty search content");
return 0;
}
uint32_t request_id = ++find_in_page_request_id_;
gin_helper::Dictionary dict;
auto options = blink::mojom::FindOptions::New();
if (args->GetNext(&dict)) {
dict.Get("forward", &options->forward);
dict.Get("matchCase", &options->match_case);
dict.Get("findNext", &options->new_session);
}
web_contents()->Find(request_id, search_text, std::move(options));
return request_id;
}
void WebContents::StopFindInPage(content::StopFindAction action) {
web_contents()->StopFinding(action);
}
void WebContents::ShowDefinitionForSelection() {
#if BUILDFLAG(IS_MAC)
auto* const view = web_contents()->GetRenderWidgetHostView();
if (view)
view->ShowDefinitionForSelection();
#endif
}
void WebContents::CopyImageAt(int x, int y) {
auto* const host = web_contents()->GetPrimaryMainFrame();
if (host)
host->CopyImageAt(x, y);
}
void WebContents::Focus() {
// Focusing on WebContents does not automatically focus the window on macOS
// and Linux, do it manually to match the behavior on Windows.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
if (owner_window())
owner_window()->Focus(true);
#endif
web_contents()->Focus();
}
#if !BUILDFLAG(IS_MAC)
bool WebContents::IsFocused() const {
auto* view = web_contents()->GetRenderWidgetHostView();
if (!view)
return false;
if (GetType() != Type::kBackgroundPage) {
auto* window = web_contents()->GetNativeView()->GetToplevelWindow();
if (window && !window->IsVisible())
return false;
}
return view->HasFocus();
}
#endif
void WebContents::SendInputEvent(v8::Isolate* isolate,
v8::Local<v8::Value> input_event) {
content::RenderWidgetHostView* view =
web_contents()->GetRenderWidgetHostView();
if (!view)
return;
content::RenderWidgetHost* rwh = view->GetRenderWidgetHost();
blink::WebInputEvent::Type type =
gin::GetWebInputEventType(isolate, input_event);
if (blink::WebInputEvent::IsMouseEventType(type)) {
blink::WebMouseEvent mouse_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event);
} else {
rwh->ForwardMouseEvent(mouse_event);
}
return;
}
} else if (blink::WebInputEvent::IsKeyboardEventType(type)) {
content::NativeWebKeyboardEvent keyboard_event(
blink::WebKeyboardEvent::Type::kRawKeyDown,
blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow());
if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) {
// For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`.
if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown)
keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown);
rwh->ForwardKeyboardEvent(keyboard_event);
return;
}
} else if (type == blink::WebInputEvent::Type::kMouseWheel) {
blink::WebMouseWheelEvent mouse_wheel_event;
if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) {
if (IsOffScreen()) {
GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent(
mouse_wheel_event);
} else {
// Chromium expects phase info in wheel events (and applies a
// DCHECK to verify it). See: https://crbug.com/756524.
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
// Send a synthetic wheel event with phaseEnded to finish scrolling.
mouse_wheel_event.has_synthetic_phase = true;
mouse_wheel_event.delta_x = 0;
mouse_wheel_event.delta_y = 0;
mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded;
mouse_wheel_event.dispatch_type =
blink::WebInputEvent::DispatchType::kEventNonBlocking;
rwh->ForwardWheelEvent(mouse_wheel_event);
}
return;
}
}
isolate->ThrowException(
v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object")));
}
void WebContents::BeginFrameSubscription(gin::Arguments* args) {
bool only_dirty = false;
FrameSubscriber::FrameCaptureCallback callback;
if (args->Length() > 1) {
if (!args->GetNext(&only_dirty)) {
args->ThrowError();
return;
}
}
if (!args->GetNext(&callback)) {
args->ThrowError();
return;
}
frame_subscriber_ =
std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty);
}
void WebContents::EndFrameSubscription() {
frame_subscriber_.reset();
}
void WebContents::StartDrag(const gin_helper::Dictionary& item,
gin::Arguments* args) {
base::FilePath file;
std::vector<base::FilePath> files;
if (!item.Get("files", &files) && item.Get("file", &file)) {
files.push_back(file);
}
v8::Local<v8::Value> icon_value;
if (!item.Get("icon", &icon_value)) {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("'icon' parameter is required");
return;
}
NativeImage* icon = nullptr;
if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) ||
icon->image().IsEmpty()) {
return;
}
// Start dragging.
if (!files.empty()) {
base::CurrentThread::ScopedAllowApplicationTasksInNativeNestedLoop allow;
DragFileItems(files, icon->image(), web_contents()->GetNativeView());
} else {
gin_helper::ErrorThrower(args->isolate())
.ThrowError("Must specify either 'file' or 'files' option");
}
}
v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) {
gin_helper::Promise<gfx::Image> promise(args->isolate());
v8::Local<v8::Promise> handle = promise.GetHandle();
gfx::Rect rect;
args->GetNext(&rect);
bool stay_hidden = false;
bool stay_awake = false;
if (args && args->Length() == 2) {
gin_helper::Dictionary options;
if (args->GetNext(&options)) {
options.Get("stayHidden", &stay_hidden);
options.Get("stayAwake", &stay_awake);
}
}
auto* const view = web_contents()->GetRenderWidgetHostView();
if (!view) {
promise.Resolve(gfx::Image());
return handle;
}
#if !BUILDFLAG(IS_MAC)
// If the view's renderer is suspended this may fail on Windows/Linux -
// bail if so. See CopyFromSurface in
// content/public/browser/render_widget_host_view.h.
auto* rfh = web_contents()->GetPrimaryMainFrame();
if (rfh &&
rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) {
promise.Resolve(gfx::Image());
return handle;
}
#endif // BUILDFLAG(IS_MAC)
auto capture_handle = web_contents()->IncrementCapturerCount(
rect.size(), stay_hidden, stay_awake);
// Capture full page if user doesn't specify a |rect|.
const gfx::Size view_size =
rect.IsEmpty() ? view->GetViewBounds().size() : rect.size();
// By default, the requested bitmap size is the view size in screen
// coordinates. However, if there's more pixel detail available on the
// current system, increase the requested bitmap size to capture it all.
gfx::Size bitmap_size = view_size;
const gfx::NativeView native_view = view->GetNativeView();
const float scale = display::Screen::GetScreen()
->GetDisplayNearestView(native_view)
.device_scale_factor();
if (scale > 1.0f)
bitmap_size = gfx::ScaleToCeiledSize(view_size, scale);
view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size,
base::BindOnce(&OnCapturePageDone, std::move(promise),
std::move(capture_handle)));
return handle;
}
bool WebContents::IsBeingCaptured() {
return web_contents()->IsBeingCaptured();
}
void WebContents::OnCursorChanged(const ui::Cursor& cursor) {
if (cursor.type() == ui::mojom::CursorType::kCustom) {
Emit("cursor-changed", CursorTypeToString(cursor.type()),
gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()),
cursor.image_scale_factor(),
gfx::Size(cursor.custom_bitmap().width(),
cursor.custom_bitmap().height()),
cursor.custom_hotspot());
} else {
Emit("cursor-changed", CursorTypeToString(cursor.type()));
}
}
bool WebContents::IsGuest() const {
return type_ == Type::kWebView;
}
void WebContents::AttachToIframe(content::WebContents* embedder_web_contents,
int embedder_frame_id) {
attached_ = true;
if (guest_delegate_)
guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id);
}
bool WebContents::IsOffScreen() const {
return type_ == Type::kOffScreen;
}
void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) {
Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap));
}
void WebContents::StartPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(true);
}
void WebContents::StopPainting() {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetPainting(false);
}
bool WebContents::IsPainting() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv && osr_wcv->IsPainting();
}
void WebContents::SetFrameRate(int frame_rate) {
auto* osr_wcv = GetOffScreenWebContentsView();
if (osr_wcv)
osr_wcv->SetFrameRate(frame_rate);
}
int WebContents::GetFrameRate() const {
auto* osr_wcv = GetOffScreenWebContentsView();
return osr_wcv ? osr_wcv->GetFrameRate() : 0;
}
void WebContents::Invalidate() {
if (IsOffScreen()) {
auto* osr_rwhv = GetOffScreenRenderWidgetHostView();
if (osr_rwhv)
osr_rwhv->Invalidate();
} else {
auto* const window = owner_window();
if (window)
window->Invalidate();
}
}
gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) {
if (IsOffScreen() && wc == web_contents()) {
auto* relay = NativeWindowRelay::FromWebContents(web_contents());
if (relay) {
auto* owner_window = relay->GetNativeWindow();
return owner_window ? owner_window->GetSize() : gfx::Size();
}
}
return gfx::Size();
}
void WebContents::SetZoomLevel(double level) {
zoom_controller_->SetZoomLevel(level);
}
double WebContents::GetZoomLevel() const {
return zoom_controller_->GetZoomLevel();
}
void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower,
double factor) {
if (factor < std::numeric_limits<double>::epsilon()) {
thrower.ThrowError("'zoomFactor' must be a double greater than 0.0");
return;
}
auto level = blink::PageZoomFactorToZoomLevel(factor);
SetZoomLevel(level);
}
double WebContents::GetZoomFactor() const {
auto level = GetZoomLevel();
return blink::PageZoomLevelToZoomFactor(level);
}
void WebContents::SetTemporaryZoomLevel(double level) {
zoom_controller_->SetTemporaryZoomLevel(level);
}
void WebContents::DoGetZoomLevel(
electron::mojom::ElectronWebContentsUtility::DoGetZoomLevelCallback
callback) {
std::move(callback).Run(GetZoomLevel());
}
std::vector<base::FilePath> WebContents::GetPreloadPaths() const {
auto result = SessionPreferences::GetValidPreloads(GetBrowserContext());
if (auto* web_preferences = WebContentsPreferences::From(web_contents())) {
base::FilePath preload;
if (web_preferences->GetPreloadPath(&preload)) {
result.emplace_back(preload);
}
}
return result;
}
v8::Local<v8::Value> WebContents::GetLastWebPreferences(
v8::Isolate* isolate) const {
auto* web_preferences = WebContentsPreferences::From(web_contents());
if (!web_preferences)
return v8::Null(isolate);
return gin::ConvertToV8(isolate, *web_preferences->last_preference());
}
v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow(
v8::Isolate* isolate) const {
if (owner_window())
return BrowserWindow::From(isolate, owner_window());
else
return v8::Null(isolate);
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
return v8::Local<v8::Value>::New(isolate, session_);
}
content::WebContents* WebContents::HostWebContents() const {
if (!embedder_)
return nullptr;
return embedder_->web_contents();
}
void WebContents::SetEmbedder(const WebContents* embedder) {
if (embedder) {
NativeWindow* owner_window = nullptr;
auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents());
if (relay) {
owner_window = relay->GetNativeWindow();
}
if (owner_window)
SetOwnerWindow(owner_window);
content::RenderWidgetHostView* rwhv =
web_contents()->GetRenderWidgetHostView();
if (rwhv) {
rwhv->Hide();
rwhv->Show();
}
}
}
void WebContents::SetDevToolsWebContents(const WebContents* devtools) {
if (inspectable_web_contents_)
inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents());
}
v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const {
gfx::NativeView ptr = web_contents()->GetNativeView();
auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr),
sizeof(gfx::NativeView));
if (buffer.IsEmpty())
return v8::Null(isolate);
else
return buffer.ToLocalChecked();
}
v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) {
if (devtools_web_contents_.IsEmpty())
return v8::Null(isolate);
else
return v8::Local<v8::Value>::New(isolate, devtools_web_contents_);
}
v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) {
if (debugger_.IsEmpty()) {
auto handle = electron::api::Debugger::Create(isolate, web_contents());
debugger_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, debugger_);
}
content::RenderFrameHost* WebContents::MainFrame() {
return web_contents()->GetPrimaryMainFrame();
}
content::RenderFrameHost* WebContents::Opener() {
return web_contents()->GetOpener();
}
void WebContents::NotifyUserActivation() {
content::RenderFrameHost* frame = web_contents()->GetPrimaryMainFrame();
if (frame)
frame->NotifyUserActivation(
blink::mojom::UserActivationNotificationType::kInteraction);
}
void WebContents::SetImageAnimationPolicy(const std::string& new_policy) {
auto* web_preferences = WebContentsPreferences::From(web_contents());
web_preferences->SetImageAnimationPolicy(new_policy);
web_contents()->OnWebPreferencesChanged();
}
void WebContents::OnInputEvent(const blink::WebInputEvent& event) {
Emit("input-event", event);
}
v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) {
gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage("Failed to create memory dump");
return handle;
}
auto pid = frame_host->GetProcess()->GetProcess().Pid();
v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext());
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestGlobalDumpForPid(
pid, std::vector<std::string>(),
base::BindOnce(&ElectronBindings::DidReceiveMemoryDump,
std::move(context), std::move(promise), pid));
return handle;
}
v8::Local<v8::Promise> WebContents::TakeHeapSnapshot(
v8::Isolate* isolate,
const base::FilePath& file_path) {
gin_helper::Promise<void> promise(isolate);
v8::Local<v8::Promise> handle = promise.GetHandle();
ScopedAllowBlockingForElectron allow_blocking;
uint32_t flags = base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE;
// The snapshot file is passed to an untrusted process.
flags = base::File::AddFlagsForPassingToUntrustedProcess(flags);
base::File file(file_path, flags);
if (!file.IsValid()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid file path " +
#if BUILDFLAG(IS_WIN)
base::WideToUTF8(file_path.value()));
#else
file_path.value());
#endif
return handle;
}
auto* frame_host = web_contents()->GetPrimaryMainFrame();
if (!frame_host) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with invalid webContents main frame");
return handle;
}
if (!frame_host->IsRenderFrameLive()) {
promise.RejectWithErrorMessage(
"Failed to take heap snapshot with nonexistent render frame");
return handle;
}
// This dance with `base::Owned` is to ensure that the interface stays alive
// until the callback is called. Otherwise it would be closed at the end of
// this function.
auto electron_renderer =
std::make_unique<mojo::Remote<mojom::ElectronRenderer>>();
frame_host->GetRemoteInterfaces()->GetInterface(
electron_renderer->BindNewPipeAndPassReceiver());
auto* raw_ptr = electron_renderer.get();
(*raw_ptr)->TakeHeapSnapshot(
mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())),
base::BindOnce(
[](mojo::Remote<mojom::ElectronRenderer>* ep,
gin_helper::Promise<void> promise, bool success) {
if (success) {
promise.Resolve();
} else {
promise.RejectWithErrorMessage("Failed to take heap snapshot");
}
},
base::Owned(std::move(electron_renderer)), std::move(promise)));
return handle;
}
void WebContents::UpdatePreferredSize(content::WebContents* web_contents,
const gfx::Size& pref_size) {
Emit("preferred-size-changed", pref_size);
}
bool WebContents::CanOverscrollContent() {
return false;
}
std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper(
content::RenderFrameHost* frame,
content::EyeDropperListener* listener) {
return ShowEyeDropper(frame, listener);
}
void WebContents::RunFileChooser(
content::RenderFrameHost* render_frame_host,
scoped_refptr<content::FileSelectListener> listener,
const blink::mojom::FileChooserParams& params) {
FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener),
params);
}
void WebContents::EnumerateDirectory(
content::WebContents* web_contents,
scoped_refptr<content::FileSelectListener> listener,
const base::FilePath& path) {
FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path);
}
bool WebContents::IsFullscreenForTabOrPending(
const content::WebContents* source) {
if (!owner_window())
return is_html_fullscreen();
bool in_transition = owner_window()->fullscreen_transition_state() !=
NativeWindow::FullScreenTransitionState::kNone;
bool is_html_transition = owner_window()->fullscreen_transition_type() ==
NativeWindow::FullScreenTransitionType::kHTML;
return is_html_fullscreen() || (in_transition && is_html_transition);
}
content::FullscreenState WebContents::GetFullscreenState(
const content::WebContents* source) const {
// `const_cast` here because EAM does not have const getters
return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_)
->fullscreen_controller()
->GetFullscreenState(source);
}
bool WebContents::TakeFocus(content::WebContents* source, bool reverse) {
if (source && source->GetOutermostWebContents() == source) {
// If this is the outermost web contents and the user has tabbed or
// shift + tabbed through all the elements, reset the focus back to
// the first or last element so that it doesn't stay in the body.
source->FocusThroughTabTraversal(reverse);
return true;
}
return false;
}
content::PictureInPictureResult WebContents::EnterPictureInPicture(
content::WebContents* web_contents) {
return PictureInPictureWindowManager::GetInstance()
->EnterVideoPictureInPicture(web_contents);
}
void WebContents::ExitPictureInPicture() {
PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture();
}
void WebContents::DevToolsSaveToFile(const std::string& url,
const std::string& content,
bool save_as) {
base::FilePath path;
auto it = saved_files_.find(url);
if (it != saved_files_.end() && !save_as) {
path = it->second;
} else {
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.title = url;
settings.default_path = base::FilePath::FromUTF8Unsafe(url);
if (!file_dialog::ShowSaveDialogSync(settings, &path)) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "canceledSaveURL", base::Value(url));
return;
}
}
saved_files_[url] = path;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "savedURL", base::Value(url),
base::Value(path.AsUTF8Unsafe()));
file_task_runner_->PostTask(FROM_HERE,
base::BindOnce(&WriteToFile, path, content));
}
void WebContents::DevToolsAppendToFile(const std::string& url,
const std::string& content) {
auto it = saved_files_.find(url);
if (it == saved_files_.end())
return;
// Notify DevTools.
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "appendedToURL",
base::Value(url));
file_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&AppendToFile, it->second, content));
}
void WebContents::DevToolsRequestFileSystems() {
auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents());
if (file_system_paths.empty()) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded", base::Value(base::Value::List()));
return;
}
std::vector<FileSystem> file_systems;
for (const auto& file_system_path : file_system_paths) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(file_system_path.first);
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
FileSystem file_system =
CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id,
file_system_path.first, file_system_path.second);
file_systems.push_back(file_system);
}
base::Value::List file_system_value;
for (const auto& file_system : file_systems)
file_system_value.Append(CreateFileSystemValue(file_system));
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemsLoaded",
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsAddFileSystem(
const std::string& type,
const base::FilePath& file_system_path) {
base::FilePath path = file_system_path;
if (path.empty()) {
std::vector<base::FilePath> paths;
file_dialog::DialogSettings settings;
settings.parent_window = owner_window();
settings.force_detached = offscreen_;
settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY;
if (!file_dialog::ShowOpenDialogSync(settings, &paths))
return;
path = paths[0];
}
std::string file_system_id =
RegisterFileSystem(GetDevToolsWebContents(), path);
if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe()))
return;
FileSystem file_system = CreateFileSystemStruct(
GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type);
base::Value::Dict file_system_value = CreateFileSystemValue(file_system);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Set(path.AsUTF8Unsafe(), type);
std::string error = ""; // No error
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemAdded", base::Value(error),
base::Value(std::move(file_system_value)));
}
void WebContents::DevToolsRemoveFileSystem(
const base::FilePath& file_system_path) {
if (!inspectable_web_contents_)
return;
std::string path = file_system_path.AsUTF8Unsafe();
storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath(
file_system_path);
auto* pref_service = GetPrefService(GetDevToolsWebContents());
ScopedDictPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths);
update->Remove(path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "fileSystemRemoved", base::Value(path));
}
void WebContents::DevToolsIndexPath(
int request_id,
const std::string& file_system_path,
const std::string& excluded_folders_message) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsIndexingDone(request_id, file_system_path);
return;
}
if (devtools_indexing_jobs_.count(request_id) != 0)
return;
std::vector<std::string> excluded_folders;
absl::optional<base::Value> parsed_excluded_folders =
base::JSONReader::Read(excluded_folders_message);
if (parsed_excluded_folders && parsed_excluded_folders->is_list()) {
for (const base::Value& folder_path : parsed_excluded_folders->GetList()) {
if (folder_path.is_string())
excluded_folders.push_back(folder_path.GetString());
}
}
devtools_indexing_jobs_[request_id] =
scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>(
devtools_file_system_indexer_->IndexPath(
file_system_path, excluded_folders,
base::BindRepeating(
&WebContents::OnDevToolsIndexingWorkCalculated,
weak_factory_.GetWeakPtr(), request_id, file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingWorked,
weak_factory_.GetWeakPtr(), request_id,
file_system_path),
base::BindRepeating(&WebContents::OnDevToolsIndexingDone,
weak_factory_.GetWeakPtr(), request_id,
file_system_path)));
}
void WebContents::DevToolsStopIndexing(int request_id) {
auto it = devtools_indexing_jobs_.find(request_id);
if (it == devtools_indexing_jobs_.end())
return;
it->second->Stop();
devtools_indexing_jobs_.erase(it);
}
void WebContents::DevToolsOpenInNewTab(const std::string& url) {
Emit("devtools-open-url", url);
}
void WebContents::DevToolsSearchInPath(int request_id,
const std::string& file_system_path,
const std::string& query) {
if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) {
OnDevToolsSearchCompleted(request_id, file_system_path,
std::vector<std::string>());
return;
}
devtools_file_system_indexer_->SearchInPath(
file_system_path, query,
base::BindRepeating(&WebContents::OnDevToolsSearchCompleted,
weak_factory_.GetWeakPtr(), request_id,
file_system_path));
}
void WebContents::DevToolsSetEyeDropperActive(bool active) {
auto* web_contents = GetWebContents();
if (!web_contents)
return;
if (active) {
eye_dropper_ = std::make_unique<DevToolsEyeDropper>(
web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper,
base::Unretained(this)));
} else {
eye_dropper_.reset();
}
}
void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) {
base::Value::Dict color;
color.Set("r", r);
color.Set("g", g);
color.Set("b", b);
color.Set("a", a);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "eyeDropperPickedColor", base::Value(std::move(color)));
}
#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
ui::ImageModel WebContents::GetDevToolsWindowIcon() {
return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{};
}
#endif
#if BUILDFLAG(IS_LINUX)
void WebContents::GetDevToolsWindowWMClass(std::string* name,
std::string* class_name) {
*class_name = Browser::Get()->GetName();
*name = base::ToLowerASCII(*class_name);
}
#endif
void WebContents::OnDevToolsIndexingWorkCalculated(
int request_id,
const std::string& file_system_path,
int total_work) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingTotalWorkCalculated", base::Value(request_id),
base::Value(file_system_path), base::Value(total_work));
}
void WebContents::OnDevToolsIndexingWorked(int request_id,
const std::string& file_system_path,
int worked) {
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "indexingWorked", base::Value(request_id),
base::Value(file_system_path), base::Value(worked));
}
void WebContents::OnDevToolsIndexingDone(int request_id,
const std::string& file_system_path) {
devtools_indexing_jobs_.erase(request_id);
inspectable_web_contents_->CallClientFunction("DevToolsAPI", "indexingDone",
base::Value(request_id),
base::Value(file_system_path));
}
void WebContents::OnDevToolsSearchCompleted(
int request_id,
const std::string& file_system_path,
const std::vector<std::string>& file_paths) {
base::Value::List file_paths_value;
for (const auto& file_path : file_paths)
file_paths_value.Append(file_path);
inspectable_web_contents_->CallClientFunction(
"DevToolsAPI", "searchCompleted", base::Value(request_id),
base::Value(file_system_path), base::Value(std::move(file_paths_value)));
}
void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) {
// Window is already in fullscreen mode, save the state.
if (enter_fullscreen && owner_window()->IsFullscreen()) {
native_fullscreen_ = true;
UpdateHtmlApiFullscreen(true);
return;
}
// Exit html fullscreen state but not window's fullscreen mode.
if (!enter_fullscreen && native_fullscreen_) {
UpdateHtmlApiFullscreen(false);
return;
}
// Set fullscreen on window if allowed.
auto* web_preferences = WebContentsPreferences::From(GetWebContents());
bool html_fullscreenable =
web_preferences
? !web_preferences->ShouldDisableHtmlFullscreenWindowResize()
: true;
if (html_fullscreenable)
owner_window_->SetFullScreen(enter_fullscreen);
UpdateHtmlApiFullscreen(enter_fullscreen);
native_fullscreen_ = false;
}
void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) {
if (fullscreen == is_html_fullscreen())
return;
html_fullscreen_ = fullscreen;
// Notify renderer of the html fullscreen change.
web_contents()
->GetRenderViewHost()
->GetWidget()
->SynchronizeVisualProperties();
// The embedder WebContents is separated from the frame tree of webview, so
// we must manually sync their fullscreen states.
if (embedder_)
embedder_->SetHtmlApiFullscreen(fullscreen);
if (fullscreen) {
Emit("enter-html-full-screen");
owner_window_->NotifyWindowEnterHtmlFullScreen();
} else {
Emit("leave-html-full-screen");
owner_window_->NotifyWindowLeaveHtmlFullScreen();
}
// Make sure all child webviews quit html fullscreen.
if (!fullscreen && !IsGuest()) {
auto* manager = WebViewManager::GetWebViewManager(web_contents());
manager->ForEachGuest(
web_contents(), base::BindRepeating([](content::WebContents* guest) {
WebContents* api_web_contents = WebContents::From(guest);
api_web_contents->SetHtmlApiFullscreen(false);
return false;
}));
}
}
// static
void WebContents::FillObjectTemplate(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> templ) {
gin::InvokerOptions options;
options.holder_is_first_argument = true;
options.holder_type = "WebContents";
templ->Set(
gin::StringToSymbol(isolate, "isDestroyed"),
gin::CreateFunctionTemplate(
isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed),
options));
// We use gin_helper::ObjectTemplateBuilder instead of
// gin::ObjectTemplateBuilder here to handle the fact that WebContents is
// destroyable.
gin_helper::ObjectTemplateBuilder(isolate, templ)
.SetMethod("destroy", &WebContents::Destroy)
.SetMethod("close", &WebContents::Close)
.SetMethod("getBackgroundThrottling",
&WebContents::GetBackgroundThrottling)
.SetMethod("setBackgroundThrottling",
&WebContents::SetBackgroundThrottling)
.SetMethod("getProcessId", &WebContents::GetProcessID)
.SetMethod("getOSProcessId", &WebContents::GetOSProcessID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadURL", &WebContents::LoadURL)
.SetMethod("reload", &WebContents::Reload)
.SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache)
.SetMethod("downloadURL", &WebContents::DownloadURL)
.SetMethod("getURL", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
.SetMethod("stop", &WebContents::Stop)
.SetMethod("canGoBack", &WebContents::CanGoBack)
.SetMethod("goBack", &WebContents::GoBack)
.SetMethod("canGoForward", &WebContents::CanGoForward)
.SetMethod("goForward", &WebContents::GoForward)
.SetMethod("canGoToOffset", &WebContents::CanGoToOffset)
.SetMethod("goToOffset", &WebContents::GoToOffset)
.SetMethod("canGoToIndex", &WebContents::CanGoToIndex)
.SetMethod("goToIndex", &WebContents::GoToIndex)
.SetMethod("getActiveIndex", &WebContents::GetActiveIndex)
.SetMethod("clearHistory", &WebContents::ClearHistory)
.SetMethod("length", &WebContents::GetHistoryLength)
.SetMethod("isCrashed", &WebContents::IsCrashed)
.SetMethod("forcefullyCrashRenderer",
&WebContents::ForcefullyCrashRenderer)
.SetMethod("setUserAgent", &WebContents::SetUserAgent)
.SetMethod("getUserAgent", &WebContents::GetUserAgent)
.SetMethod("savePage", &WebContents::SavePage)
.SetMethod("openDevTools", &WebContents::OpenDevTools)
.SetMethod("closeDevTools", &WebContents::CloseDevTools)
.SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened)
.SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused)
.SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation)
.SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation)
.SetMethod("toggleDevTools", &WebContents::ToggleDevTools)
.SetMethod("inspectElement", &WebContents::InspectElement)
.SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts)
.SetMethod("setAudioMuted", &WebContents::SetAudioMuted)
.SetMethod("isAudioMuted", &WebContents::IsAudioMuted)
.SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible)
.SetMethod("undo", &WebContents::Undo)
.SetMethod("redo", &WebContents::Redo)
.SetMethod("cut", &WebContents::Cut)
.SetMethod("copy", &WebContents::Copy)
.SetMethod("centerSelection", &WebContents::CenterSelection)
.SetMethod("paste", &WebContents::Paste)
.SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle)
.SetMethod("delete", &WebContents::Delete)
.SetMethod("selectAll", &WebContents::SelectAll)
.SetMethod("unselect", &WebContents::Unselect)
.SetMethod("scrollToTop", &WebContents::ScrollToTopOfDocument)
.SetMethod("scrollToBottom", &WebContents::ScrollToBottomOfDocument)
.SetMethod("adjustSelection",
&WebContents::AdjustSelectionByCharacterOffset)
.SetMethod("replace", &WebContents::Replace)
.SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling)
.SetMethod("findInPage", &WebContents::FindInPage)
.SetMethod("stopFindInPage", &WebContents::StopFindInPage)
.SetMethod("focus", &WebContents::Focus)
.SetMethod("isFocused", &WebContents::IsFocused)
.SetMethod("sendInputEvent", &WebContents::SendInputEvent)
.SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription)
.SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription)
.SetMethod("startDrag", &WebContents::StartDrag)
.SetMethod("attachToIframe", &WebContents::AttachToIframe)
.SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame)
.SetMethod("isOffscreen", &WebContents::IsOffScreen)
.SetMethod("startPainting", &WebContents::StartPainting)
.SetMethod("stopPainting", &WebContents::StopPainting)
.SetMethod("isPainting", &WebContents::IsPainting)
.SetMethod("setFrameRate", &WebContents::SetFrameRate)
.SetMethod("getFrameRate", &WebContents::GetFrameRate)
.SetMethod("invalidate", &WebContents::Invalidate)
.SetMethod("setZoomLevel", &WebContents::SetZoomLevel)
.SetMethod("getZoomLevel", &WebContents::GetZoomLevel)
.SetMethod("setZoomFactor", &WebContents::SetZoomFactor)
.SetMethod("getZoomFactor", &WebContents::GetZoomFactor)
.SetMethod("getType", &WebContents::GetType)
.SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths)
.SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences)
.SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow)
.SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker)
.SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker)
.SetMethod("inspectSharedWorkerById",
&WebContents::InspectSharedWorkerById)
.SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers)
#if BUILDFLAG(ENABLE_PRINTING)
.SetMethod("_print", &WebContents::Print)
.SetMethod("_printToPDF", &WebContents::PrintToPDF)
#endif
.SetMethod("_setNextChildWebPreferences",
&WebContents::SetNextChildWebPreferences)
.SetMethod("addWorkSpace", &WebContents::AddWorkSpace)
.SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace)
.SetMethod("showDefinitionForSelection",
&WebContents::ShowDefinitionForSelection)
.SetMethod("copyImageAt", &WebContents::CopyImageAt)
.SetMethod("capturePage", &WebContents::CapturePage)
.SetMethod("setEmbedder", &WebContents::SetEmbedder)
.SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents)
.SetMethod("getNativeView", &WebContents::GetNativeView)
.SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured)
.SetMethod("setWebRTCIPHandlingPolicy",
&WebContents::SetWebRTCIPHandlingPolicy)
.SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID)
.SetMethod("getWebRTCIPHandlingPolicy",
&WebContents::GetWebRTCIPHandlingPolicy)
.SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot)
.SetMethod("setImageAnimationPolicy",
&WebContents::SetImageAnimationPolicy)
.SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo)
.SetProperty("id", &WebContents::ID)
.SetProperty("session", &WebContents::Session)
.SetProperty("hostWebContents", &WebContents::HostWebContents)
.SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents)
.SetProperty("debugger", &WebContents::Debugger)
.SetProperty("mainFrame", &WebContents::MainFrame)
.SetProperty("opener", &WebContents::Opener)
.Build();
}
const char* WebContents::GetTypeName() {
return "WebContents";
}
ElectronBrowserContext* WebContents::GetBrowserContext() const {
return static_cast<ElectronBrowserContext*>(
web_contents()->GetBrowserContext());
}
// static
gin::Handle<WebContents> WebContents::New(
v8::Isolate* isolate,
const gin_helper::Dictionary& options) {
gin::Handle<WebContents> handle =
gin::CreateHandle(isolate, new WebContents(isolate, options));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
gin::Handle<WebContents> WebContents::CreateAndTake(
v8::Isolate* isolate,
std::unique_ptr<content::WebContents> web_contents,
Type type) {
gin::Handle<WebContents> handle = gin::CreateHandle(
isolate, new WebContents(isolate, std::move(web_contents), type));
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, handle.get(), "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
return handle;
}
// static
WebContents* WebContents::From(content::WebContents* web_contents) {
if (!web_contents)
return nullptr;
auto* data = static_cast<UserDataLink*>(
web_contents->GetUserData(kElectronApiWebContentsKey));
return data ? data->web_contents.get() : nullptr;
}
// static
gin::Handle<WebContents> WebContents::FromOrCreate(
v8::Isolate* isolate,
content::WebContents* web_contents) {
WebContents* api_web_contents = From(web_contents);
if (!api_web_contents) {
api_web_contents = new WebContents(isolate, web_contents);
v8::TryCatch try_catch(isolate);
gin_helper::CallMethod(isolate, api_web_contents, "_init");
if (try_catch.HasCaught()) {
node::errors::TriggerUncaughtException(isolate, try_catch);
}
}
return gin::CreateHandle(isolate, api_web_contents);
}
// static
gin::Handle<WebContents> WebContents::CreateFromWebPreferences(
v8::Isolate* isolate,
const gin_helper::Dictionary& web_preferences) {
// Check if webPreferences has |webContents| option.
gin::Handle<WebContents> web_contents;
if (web_preferences.GetHidden("webContents", &web_contents) &&
!web_contents.IsEmpty()) {
// Set webPreferences from options if using an existing webContents.
// These preferences will be used when the webContent launches new
// render processes.
auto* existing_preferences =
WebContentsPreferences::From(web_contents->web_contents());
gin_helper::Dictionary web_preferences_dict;
if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(),
&web_preferences_dict)) {
existing_preferences->SetFromDictionary(web_preferences_dict);
absl::optional<SkColor> color =
existing_preferences->GetBackgroundColor();
web_contents->web_contents()->SetPageBaseBackgroundColor(color);
// Because web preferences don't recognize transparency,
// only set rwhv background color if a color exists
auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView();
if (rwhv && color.has_value())
SetBackgroundColor(rwhv, color.value());
}
} else {
// Create one if not.
web_contents = WebContents::New(isolate, web_preferences);
}
return web_contents;
}
// static
WebContents* WebContents::FromID(int32_t id) {
return GetAllWebContents().Lookup(id);
}
// static
gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin};
} // namespace electron::api
namespace {
using electron::api::GetAllWebContents;
using electron::api::WebContents;
using electron::api::WebFrameMain;
gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) {
WebContents* contents = WebContents::FromID(id);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromFrame(v8::Isolate* isolate,
WebFrameMain* web_frame) {
content::RenderFrameHost* rfh = web_frame->render_frame_host();
content::WebContents* source = content::WebContents::FromRenderFrameHost(rfh);
WebContents* contents = WebContents::From(source);
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
gin::Handle<WebContents> WebContentsFromDevToolsTargetID(
v8::Isolate* isolate,
std::string target_id) {
auto agent_host = content::DevToolsAgentHost::GetForId(target_id);
WebContents* contents =
agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr;
return contents ? gin::CreateHandle(isolate, contents)
: gin::Handle<WebContents>();
}
std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8(
v8::Isolate* isolate) {
std::vector<gin::Handle<WebContents>> list;
for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents());
!iter.IsAtEnd(); iter.Advance()) {
list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue()));
}
return list;
}
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
gin_helper::Dictionary dict(isolate, exports);
dict.Set("WebContents", WebContents::GetConstructor(context));
dict.SetMethod("fromId", &WebContentsFromID);
dict.SetMethod("fromFrame", &WebContentsFromFrame);
dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID);
dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8);
}
} // namespace
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
|
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,941 |
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.preventDefault().
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0 or higher
### What operating system are you using?
Windows
### Operating System Version
windows 11 22h2
### What arch are you using?
x64
### Last Known Working Electron version
21.4.4
### Expected Behavior
Not crash.
### Actual Behavior
Crash.
### Testcase Gist URL
https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52
### Additional Information
npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
|
https://github.com/electron/electron/issues/38941
|
https://github.com/electron/electron/pull/38996
|
5a77c75753f560bbc4fe6560441ba88433a561f8
|
c7a64ab994de826ed6e4c300cce75d9fd88efa20
| 2023-06-28T07:41:44Z |
c++
| 2023-07-06T08:20:34Z |
spec/fixtures/crash-cases/webview-remove-on-wc-close/index.html
| |
closed
|
electron/electron
|
https://github.com/electron/electron
| 38,941 |
[Bug]: Crash after removing the webview that fired will-prevent-unload and called event.preventDefault().
|
### Preflight Checklist
- [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project.
- [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to.
- [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success.
### Electron Version
22.0.0 or higher
### What operating system are you using?
Windows
### Operating System Version
windows 11 22h2
### What arch are you using?
x64
### Last Known Working Electron version
21.4.4
### Expected Behavior
Not crash.
### Actual Behavior
Crash.
### Testcase Gist URL
https://gist.github.com/asd281533890/aede872ca474bc546185053e2bad9a52
### Additional Information
npm run start. click the webview page text (to trigger will-prevent-unload), then click the close webview button. At this time, the close confirmation dialog will pop up, click to leave, and the app will crash.
|
https://github.com/electron/electron/issues/38941
|
https://github.com/electron/electron/pull/38996
|
5a77c75753f560bbc4fe6560441ba88433a561f8
|
c7a64ab994de826ed6e4c300cce75d9fd88efa20
| 2023-06-28T07:41:44Z |
c++
| 2023-07-06T08:20:34Z |
spec/fixtures/crash-cases/webview-remove-on-wc-close/index.js
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.