web_contents_preferences.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // Copyright (c) 2015 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/web_contents_preferences.h"
  5. #include <algorithm>
  6. #include <string>
  7. #include <string_view>
  8. #include <utility>
  9. #include <vector>
  10. #include "base/command_line.h"
  11. #include "base/containers/fixed_flat_map.h"
  12. #include "base/memory/ptr_util.h"
  13. #include "cc/base/switches.h"
  14. #include "content/public/browser/render_process_host.h"
  15. #include "content/public/browser/web_contents_user_data.h"
  16. #include "content/public/common/content_switches.h"
  17. #include "net/base/filename_util.h"
  18. #include "sandbox/policy/switches.h"
  19. #include "shell/browser/api/electron_api_web_contents.h"
  20. #include "shell/browser/native_window.h"
  21. #include "shell/browser/session_preferences.h"
  22. #include "shell/common/color_util.h"
  23. #include "shell/common/gin_converters/value_converter.h"
  24. #include "shell/common/gin_helper/dictionary.h"
  25. #include "shell/common/options_switches.h"
  26. #include "shell/common/process_util.h"
  27. #include "third_party/blink/public/common/web_preferences/web_preferences.h"
  28. #include "third_party/blink/public/mojom/v8_cache_options.mojom.h"
  29. #include "third_party/blink/public/mojom/webpreferences/web_preferences.mojom.h"
  30. #if BUILDFLAG(IS_WIN)
  31. #include "ui/gfx/switches.h"
  32. #endif
  33. namespace gin {
  34. template <>
  35. struct Converter<blink::mojom::AutoplayPolicy> {
  36. static bool FromV8(v8::Isolate* isolate,
  37. v8::Local<v8::Value> val,
  38. blink::mojom::AutoplayPolicy* out) {
  39. using Val = blink::mojom::AutoplayPolicy;
  40. static constexpr auto Lookup =
  41. base::MakeFixedFlatMap<std::string_view, Val>({
  42. {"document-user-activation-required",
  43. Val::kDocumentUserActivationRequired},
  44. {"no-user-gesture-required", Val::kNoUserGestureRequired},
  45. {"user-gesture-required", Val::kUserGestureRequired},
  46. });
  47. return FromV8WithLookup(isolate, val, Lookup, out);
  48. }
  49. };
  50. template <>
  51. struct Converter<blink::mojom::V8CacheOptions> {
  52. static bool FromV8(v8::Isolate* isolate,
  53. v8::Local<v8::Value> val,
  54. blink::mojom::V8CacheOptions* out) {
  55. using Val = blink::mojom::V8CacheOptions;
  56. static constexpr auto Lookup =
  57. base::MakeFixedFlatMap<std::string_view, Val>({
  58. {"bypassHeatCheck", Val::kCodeWithoutHeatCheck},
  59. {"bypassHeatCheckAndEagerCompile", Val::kFullCodeWithoutHeatCheck},
  60. {"code", Val::kCode},
  61. {"none", Val::kNone},
  62. });
  63. return FromV8WithLookup(isolate, val, Lookup, out);
  64. }
  65. };
  66. } // namespace gin
  67. namespace electron {
  68. namespace {
  69. std::vector<WebContentsPreferences*>& Instances() {
  70. static base::NoDestructor<std::vector<WebContentsPreferences*>> g_instances;
  71. return *g_instances;
  72. }
  73. } // namespace
  74. WebContentsPreferences::WebContentsPreferences(
  75. content::WebContents* web_contents,
  76. const gin_helper::Dictionary& web_preferences)
  77. : content::WebContentsUserData<WebContentsPreferences>(*web_contents),
  78. web_contents_(web_contents) {
  79. web_contents->SetUserData(UserDataKey(), base::WrapUnique(this));
  80. Instances().push_back(this);
  81. SetFromDictionary(web_preferences);
  82. // If this is a <webview> tag, and the embedder is offscreen-rendered, then
  83. // this WebContents is also offscreen-rendered.
  84. if (auto* api_web_contents = api::WebContents::From(web_contents_)) {
  85. if (electron::api::WebContents* embedder = api_web_contents->embedder()) {
  86. auto* embedder_preferences =
  87. WebContentsPreferences::From(embedder->web_contents());
  88. if (embedder_preferences && embedder_preferences->IsOffscreen()) {
  89. offscreen_ = true;
  90. }
  91. }
  92. }
  93. }
  94. WebContentsPreferences::~WebContentsPreferences() {
  95. std::erase(Instances(), this);
  96. }
  97. void WebContentsPreferences::Clear() {
  98. plugins_ = false;
  99. experimental_features_ = false;
  100. node_integration_ = false;
  101. node_integration_in_sub_frames_ = false;
  102. node_integration_in_worker_ = false;
  103. disable_html_fullscreen_window_resize_ = false;
  104. webview_tag_ = false;
  105. sandbox_ = std::nullopt;
  106. context_isolation_ = true;
  107. javascript_ = true;
  108. images_ = true;
  109. text_areas_are_resizable_ = true;
  110. webgl_ = true;
  111. enable_preferred_size_mode_ = false;
  112. web_security_ = true;
  113. allow_running_insecure_content_ = false;
  114. offscreen_ = false;
  115. navigate_on_drag_drop_ = false;
  116. autoplay_policy_ = blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
  117. default_font_family_.clear();
  118. default_font_size_ = std::nullopt;
  119. default_monospace_font_size_ = std::nullopt;
  120. minimum_font_size_ = std::nullopt;
  121. default_encoding_ = std::nullopt;
  122. is_webview_ = false;
  123. custom_args_.clear();
  124. custom_switches_.clear();
  125. enable_blink_features_ = std::nullopt;
  126. disable_blink_features_ = std::nullopt;
  127. disable_popups_ = false;
  128. disable_dialogs_ = false;
  129. safe_dialogs_ = false;
  130. safe_dialogs_message_ = std::nullopt;
  131. ignore_menu_shortcuts_ = false;
  132. background_color_ = std::nullopt;
  133. image_animation_policy_ =
  134. blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
  135. preload_path_ = std::nullopt;
  136. v8_cache_options_ = blink::mojom::V8CacheOptions::kDefault;
  137. deprecated_paste_enabled_ = false;
  138. #if BUILDFLAG(IS_MAC)
  139. scroll_bounce_ = false;
  140. #endif
  141. #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
  142. spellcheck_ = true;
  143. #endif
  144. }
  145. void WebContentsPreferences::SetFromDictionary(
  146. const gin_helper::Dictionary& web_preferences) {
  147. Clear();
  148. web_preferences.Get(options::kPlugins, &plugins_);
  149. web_preferences.Get(options::kExperimentalFeatures, &experimental_features_);
  150. web_preferences.Get(options::kNodeIntegration, &node_integration_);
  151. web_preferences.Get(options::kNodeIntegrationInSubFrames,
  152. &node_integration_in_sub_frames_);
  153. web_preferences.Get(options::kNodeIntegrationInWorker,
  154. &node_integration_in_worker_);
  155. web_preferences.Get(options::kDisableHtmlFullscreenWindowResize,
  156. &disable_html_fullscreen_window_resize_);
  157. web_preferences.Get(options::kWebviewTag, &webview_tag_);
  158. bool sandbox;
  159. if (web_preferences.Get(options::kSandbox, &sandbox))
  160. sandbox_ = sandbox;
  161. web_preferences.Get(options::kContextIsolation, &context_isolation_);
  162. web_preferences.Get(options::kJavaScript, &javascript_);
  163. web_preferences.Get(options::kImages, &images_);
  164. web_preferences.Get(options::kTextAreasAreResizable,
  165. &text_areas_are_resizable_);
  166. web_preferences.Get(options::kWebGL, &webgl_);
  167. web_preferences.Get(options::kEnablePreferredSizeMode,
  168. &enable_preferred_size_mode_);
  169. web_preferences.Get(options::kWebSecurity, &web_security_);
  170. if (!web_preferences.Get(options::kAllowRunningInsecureContent,
  171. &allow_running_insecure_content_) &&
  172. !web_security_)
  173. allow_running_insecure_content_ = true;
  174. web_preferences.Get(options::kOffscreen, &offscreen_);
  175. web_preferences.Get(options::kNavigateOnDragDrop, &navigate_on_drag_drop_);
  176. web_preferences.Get("autoplayPolicy", &autoplay_policy_);
  177. web_preferences.Get("defaultFontFamily", &default_font_family_);
  178. int size;
  179. if (web_preferences.Get("defaultFontSize", &size))
  180. default_font_size_ = size;
  181. if (web_preferences.Get("defaultMonospaceFontSize", &size))
  182. default_monospace_font_size_ = size;
  183. if (web_preferences.Get("minimumFontSize", &size))
  184. minimum_font_size_ = size;
  185. std::string encoding;
  186. if (web_preferences.Get("defaultEncoding", &encoding))
  187. default_encoding_ = encoding;
  188. web_preferences.Get(options::kCustomArgs, &custom_args_);
  189. web_preferences.Get("commandLineSwitches", &custom_switches_);
  190. web_preferences.Get("disablePopups", &disable_popups_);
  191. web_preferences.Get("disableDialogs", &disable_dialogs_);
  192. web_preferences.Get("safeDialogs", &safe_dialogs_);
  193. // preferences don't save a transparency option,
  194. // apply any existing transparency setting to background_color_
  195. bool transparent;
  196. if (web_preferences.Get(options::kTransparent, &transparent) && transparent) {
  197. background_color_ = SK_ColorTRANSPARENT;
  198. }
  199. std::string background_color;
  200. if (web_preferences.GetHidden(options::kBackgroundColor, &background_color))
  201. background_color_ = ParseCSSColor(background_color);
  202. std::string safe_dialogs_message;
  203. if (web_preferences.Get("safeDialogsMessage", &safe_dialogs_message))
  204. safe_dialogs_message_ = safe_dialogs_message;
  205. web_preferences.Get("ignoreMenuShortcuts", &ignore_menu_shortcuts_);
  206. std::string enable_blink_features;
  207. if (web_preferences.Get(options::kEnableBlinkFeatures,
  208. &enable_blink_features))
  209. enable_blink_features_ = enable_blink_features;
  210. std::string disable_blink_features;
  211. if (web_preferences.Get(options::kDisableBlinkFeatures,
  212. &disable_blink_features))
  213. disable_blink_features_ = disable_blink_features;
  214. base::FilePath::StringType preload_path;
  215. if (web_preferences.Get(options::kPreloadScript, &preload_path)) {
  216. base::FilePath preload(preload_path);
  217. if (preload.IsAbsolute()) {
  218. preload_path_ = preload;
  219. } else {
  220. LOG(ERROR) << "preload script must have absolute path.";
  221. }
  222. }
  223. std::string type;
  224. if (web_preferences.Get(options::kType, &type)) {
  225. is_webview_ = type == "webview";
  226. }
  227. web_preferences.Get("v8CacheOptions", &v8_cache_options_);
  228. web_preferences.Get(options::kEnableDeprecatedPaste,
  229. &deprecated_paste_enabled_);
  230. #if BUILDFLAG(IS_MAC)
  231. web_preferences.Get(options::kScrollBounce, &scroll_bounce_);
  232. #endif
  233. #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
  234. web_preferences.Get(options::kSpellcheck, &spellcheck_);
  235. #endif
  236. SaveLastPreferences();
  237. }
  238. bool WebContentsPreferences::SetImageAnimationPolicy(std::string policy) {
  239. if (policy == "animate") {
  240. image_animation_policy_ =
  241. blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
  242. return true;
  243. } else if (policy == "animateOnce") {
  244. image_animation_policy_ =
  245. blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAnimateOnce;
  246. return true;
  247. } else if (policy == "noAnimation") {
  248. image_animation_policy_ =
  249. blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyNoAnimation;
  250. return true;
  251. }
  252. return false;
  253. }
  254. bool WebContentsPreferences::IsSandboxed() const {
  255. if (sandbox_)
  256. return *sandbox_;
  257. bool sandbox_disabled_by_default =
  258. node_integration_ || node_integration_in_worker_;
  259. return !sandbox_disabled_by_default;
  260. }
  261. // static
  262. content::WebContents* WebContentsPreferences::GetWebContentsFromProcessID(
  263. content::ChildProcessId process_id) {
  264. for (WebContentsPreferences* preferences : Instances()) {
  265. content::WebContents* web_contents = preferences->web_contents_;
  266. if (web_contents->GetPrimaryMainFrame()->GetProcess()->GetID() ==
  267. process_id)
  268. return web_contents;
  269. }
  270. return nullptr;
  271. }
  272. // static
  273. WebContentsPreferences* WebContentsPreferences::From(
  274. content::WebContents* web_contents) {
  275. if (!web_contents)
  276. return nullptr;
  277. return FromWebContents(web_contents);
  278. }
  279. void WebContentsPreferences::AppendCommandLineSwitches(
  280. base::CommandLine* command_line,
  281. bool is_subframe) {
  282. // Experimental flags.
  283. if (experimental_features_)
  284. command_line->AppendSwitch(
  285. ::switches::kEnableExperimentalWebPlatformFeatures);
  286. // Sandbox can be enabled for renderer processes hosting cross-origin frames
  287. // unless nodeIntegrationInSubFrames is enabled
  288. bool can_sandbox_frame = is_subframe && !node_integration_in_sub_frames_;
  289. if (IsSandboxed() || can_sandbox_frame) {
  290. command_line->AppendSwitch(switches::kEnableSandbox);
  291. } else if (!command_line->HasSwitch(switches::kEnableSandbox)) {
  292. command_line->AppendSwitch(sandbox::policy::switches::kNoSandbox);
  293. command_line->AppendSwitch(::switches::kNoZygote);
  294. }
  295. #if BUILDFLAG(IS_MAC)
  296. // Enable scroll bounce.
  297. if (scroll_bounce_)
  298. command_line->AppendSwitch(switches::kScrollBounce);
  299. #endif
  300. // Custom args for renderer process
  301. for (const auto& arg : custom_args_)
  302. if (!arg.empty())
  303. command_line->AppendArg(arg);
  304. // Custom command line switches.
  305. for (const auto& arg : custom_switches_)
  306. if (!arg.empty())
  307. command_line->AppendSwitch(arg);
  308. if (enable_blink_features_)
  309. command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures,
  310. *enable_blink_features_);
  311. if (disable_blink_features_)
  312. command_line->AppendSwitchASCII(::switches::kDisableBlinkFeatures,
  313. *disable_blink_features_);
  314. if (node_integration_in_worker_)
  315. command_line->AppendSwitch(switches::kNodeIntegrationInWorker);
  316. // We are appending args to a webContents so let's save the current state
  317. // of our preferences object so that during the lifetime of the WebContents
  318. // we can fetch the options used to initially configure the WebContents
  319. // last_preference_ = preference_.Clone();
  320. SaveLastPreferences();
  321. }
  322. void WebContentsPreferences::SaveLastPreferences() {
  323. base::Value::Dict dict;
  324. dict.Set(options::kNodeIntegration, node_integration_);
  325. dict.Set(options::kNodeIntegrationInSubFrames,
  326. node_integration_in_sub_frames_);
  327. dict.Set(options::kSandbox, IsSandboxed());
  328. dict.Set(options::kContextIsolation, context_isolation_);
  329. dict.Set(options::kJavaScript, javascript_);
  330. dict.Set(options::kWebviewTag, webview_tag_);
  331. dict.Set("disablePopups", disable_popups_);
  332. dict.Set(options::kWebSecurity, web_security_);
  333. dict.Set(options::kAllowRunningInsecureContent,
  334. allow_running_insecure_content_);
  335. dict.Set(options::kExperimentalFeatures, experimental_features_);
  336. dict.Set(options::kEnableBlinkFeatures, enable_blink_features_.value_or(""));
  337. dict.Set("disableDialogs", disable_dialogs_);
  338. dict.Set("safeDialogs", safe_dialogs_);
  339. dict.Set("safeDialogsMessage", safe_dialogs_message_.value_or(""));
  340. last_web_preferences_ = base::Value(std::move(dict));
  341. }
  342. void WebContentsPreferences::OverrideWebkitPrefs(
  343. blink::web_pref::WebPreferences* prefs,
  344. blink::RendererPreferences* renderer_prefs) {
  345. prefs->javascript_enabled = javascript_;
  346. prefs->images_enabled = images_;
  347. prefs->animation_policy = image_animation_policy_;
  348. prefs->text_areas_are_resizable = text_areas_are_resizable_;
  349. prefs->autoplay_policy = autoplay_policy_;
  350. // TODO: navigate_on_drag_drop was removed from web prefs in favor of the
  351. // equivalent option in renderer prefs. this option should be deprecated from
  352. // our API and then removed here.
  353. renderer_prefs->can_accept_load_drops = navigate_on_drag_drop_;
  354. // Check if webgl should be enabled.
  355. prefs->webgl1_enabled = webgl_;
  356. prefs->webgl2_enabled = webgl_;
  357. // Check if web security should be enabled.
  358. prefs->web_security_enabled = web_security_;
  359. prefs->allow_running_insecure_content = allow_running_insecure_content_;
  360. if (!default_font_family_.empty()) {
  361. if (auto iter = default_font_family_.find("standard");
  362. iter != default_font_family_.end())
  363. prefs->standard_font_family_map[blink::web_pref::kCommonScript] =
  364. iter->second;
  365. if (auto iter = default_font_family_.find("serif");
  366. iter != default_font_family_.end())
  367. prefs->serif_font_family_map[blink::web_pref::kCommonScript] =
  368. iter->second;
  369. if (auto iter = default_font_family_.find("sansSerif");
  370. iter != default_font_family_.end())
  371. prefs->sans_serif_font_family_map[blink::web_pref::kCommonScript] =
  372. iter->second;
  373. if (auto iter = default_font_family_.find("monospace");
  374. iter != default_font_family_.end())
  375. prefs->fixed_font_family_map[blink::web_pref::kCommonScript] =
  376. iter->second;
  377. if (auto iter = default_font_family_.find("cursive");
  378. iter != default_font_family_.end())
  379. prefs->cursive_font_family_map[blink::web_pref::kCommonScript] =
  380. iter->second;
  381. if (auto iter = default_font_family_.find("fantasy");
  382. iter != default_font_family_.end())
  383. prefs->fantasy_font_family_map[blink::web_pref::kCommonScript] =
  384. iter->second;
  385. if (auto iter = default_font_family_.find("math");
  386. iter != default_font_family_.end())
  387. prefs->math_font_family_map[blink::web_pref::kCommonScript] =
  388. iter->second;
  389. }
  390. if (default_font_size_)
  391. prefs->default_font_size = *default_font_size_;
  392. if (default_monospace_font_size_)
  393. prefs->default_fixed_font_size = *default_monospace_font_size_;
  394. if (minimum_font_size_)
  395. prefs->minimum_font_size = *minimum_font_size_;
  396. if (default_encoding_)
  397. prefs->default_encoding = *default_encoding_;
  398. // Run Electron APIs and preload script in isolated world
  399. prefs->context_isolation = context_isolation_;
  400. prefs->is_webview = is_webview_;
  401. prefs->hidden_page = false;
  402. // Webview `document.visibilityState` tracks window visibility so we need
  403. // to let it know if the window happens to be hidden right now.
  404. if (auto* api_web_contents = api::WebContents::From(web_contents_)) {
  405. if (electron::api::WebContents* embedder = api_web_contents->embedder()) {
  406. if (auto* relay =
  407. NativeWindowRelay::FromWebContents(embedder->web_contents())) {
  408. if (auto* window = relay->GetNativeWindow()) {
  409. const bool visible = window->IsVisible() && !window->IsMinimized();
  410. if (!visible) {
  411. prefs->hidden_page = true;
  412. }
  413. }
  414. }
  415. }
  416. }
  417. prefs->offscreen = offscreen_;
  418. prefs->node_integration = node_integration_;
  419. prefs->node_integration_in_worker = node_integration_in_worker_;
  420. prefs->node_integration_in_sub_frames = node_integration_in_sub_frames_;
  421. #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
  422. prefs->enable_spellcheck = spellcheck_;
  423. #endif
  424. prefs->enable_plugins = plugins_;
  425. prefs->webview_tag = webview_tag_;
  426. prefs->v8_cache_options = v8_cache_options_;
  427. prefs->dom_paste_enabled = deprecated_paste_enabled_;
  428. }
  429. WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsPreferences);
  430. } // namespace electron