electron_renderer_client.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // Copyright (c) 2013 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/renderer/electron_renderer_client.h"
  5. #include "base/command_line.h"
  6. #include "base/containers/contains.h"
  7. #include "base/debug/stack_trace.h"
  8. #include "content/public/renderer/render_frame.h"
  9. #include "electron/buildflags/buildflags.h"
  10. #include "net/http/http_request_headers.h"
  11. #include "shell/common/api/electron_bindings.h"
  12. #include "shell/common/gin_helper/dictionary.h"
  13. #include "shell/common/gin_helper/event_emitter_caller.h"
  14. #include "shell/common/node_bindings.h"
  15. #include "shell/common/node_includes.h"
  16. #include "shell/common/options_switches.h"
  17. #include "shell/renderer/electron_render_frame_observer.h"
  18. #include "shell/renderer/web_worker_observer.h"
  19. #include "third_party/blink/public/common/web_preferences/web_preferences.h"
  20. #include "third_party/blink/public/web/web_document.h"
  21. #include "third_party/blink/public/web/web_local_frame.h"
  22. #include "third_party/blink/renderer/core/execution_context/execution_context.h" // nogncheck
  23. #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" // nogncheck
  24. namespace electron {
  25. ElectronRendererClient::ElectronRendererClient()
  26. : node_bindings_(
  27. NodeBindings::Create(NodeBindings::BrowserEnvironment::kRenderer)),
  28. electron_bindings_(
  29. std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {}
  30. ElectronRendererClient::~ElectronRendererClient() = default;
  31. void ElectronRendererClient::RenderFrameCreated(
  32. content::RenderFrame* render_frame) {
  33. new ElectronRenderFrameObserver(render_frame, this);
  34. RendererClientBase::RenderFrameCreated(render_frame);
  35. }
  36. void ElectronRendererClient::RunScriptsAtDocumentStart(
  37. content::RenderFrame* render_frame) {
  38. RendererClientBase::RunScriptsAtDocumentStart(render_frame);
  39. // Inform the document start phase.
  40. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  41. node::Environment* env = GetEnvironment(render_frame);
  42. if (env)
  43. gin_helper::EmitEvent(env->isolate(), env->process_object(),
  44. "document-start");
  45. }
  46. void ElectronRendererClient::RunScriptsAtDocumentEnd(
  47. content::RenderFrame* render_frame) {
  48. RendererClientBase::RunScriptsAtDocumentEnd(render_frame);
  49. // Inform the document end phase.
  50. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  51. node::Environment* env = GetEnvironment(render_frame);
  52. if (env)
  53. gin_helper::EmitEvent(env->isolate(), env->process_object(),
  54. "document-end");
  55. }
  56. void ElectronRendererClient::UndeferLoad(content::RenderFrame* render_frame) {
  57. render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
  58. blink::LoaderFreezeMode::kNone);
  59. }
  60. void ElectronRendererClient::DidCreateScriptContext(
  61. v8::Handle<v8::Context> renderer_context,
  62. content::RenderFrame* render_frame) {
  63. // TODO(zcbenz): Do not create Node environment if node integration is not
  64. // enabled.
  65. // Only load Node.js if we are a main frame or a devtools extension
  66. // unless Node.js support has been explicitly enabled for subframes.
  67. if (!ShouldLoadPreload(renderer_context, render_frame))
  68. return;
  69. injected_frames_.insert(render_frame);
  70. if (!node_integration_initialized_) {
  71. node_integration_initialized_ = true;
  72. node_bindings_->Initialize(renderer_context);
  73. node_bindings_->PrepareEmbedThread();
  74. }
  75. // Setup node tracing controller.
  76. if (!node::tracing::TraceEventHelper::GetAgent())
  77. node::tracing::TraceEventHelper::SetAgent(node::CreateAgent());
  78. // Setup node environment for each window.
  79. v8::Maybe<bool> initialized = node::InitializeContext(renderer_context);
  80. CHECK(!initialized.IsNothing() && initialized.FromJust());
  81. // Before we load the node environment, let's tell blink to hold off on
  82. // loading the body of this frame. We will undefer the load once the preload
  83. // script has finished. This allows our preload script to run async (E.g.
  84. // with ESM) without the preload being in a race
  85. render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
  86. blink::LoaderFreezeMode::kStrict);
  87. std::shared_ptr<node::Environment> env = node_bindings_->CreateEnvironment(
  88. renderer_context, nullptr,
  89. base::BindRepeating(&ElectronRendererClient::UndeferLoad,
  90. base::Unretained(this), render_frame));
  91. // If we have disabled the site instance overrides we should prevent loading
  92. // any non-context aware native module.
  93. env->options()->force_context_aware = true;
  94. // We do not want to crash the renderer process on unhandled rejections.
  95. env->options()->unhandled_rejections = "warn-with-error-code";
  96. environments_.insert(env);
  97. // Add Electron extended APIs.
  98. electron_bindings_->BindTo(env->isolate(), env->process_object());
  99. gin_helper::Dictionary process_dict(env->isolate(), env->process_object());
  100. BindProcess(env->isolate(), &process_dict, render_frame);
  101. // Load everything.
  102. node_bindings_->LoadEnvironment(env.get());
  103. if (node_bindings_->uv_env() == nullptr) {
  104. // Make uv loop being wrapped by window context.
  105. node_bindings_->set_uv_env(env.get());
  106. // Give the node loop a run to make sure everything is ready.
  107. node_bindings_->StartPolling();
  108. }
  109. }
  110. void ElectronRendererClient::WillReleaseScriptContext(
  111. v8::Handle<v8::Context> context,
  112. content::RenderFrame* render_frame) {
  113. if (injected_frames_.erase(render_frame) == 0)
  114. return;
  115. node::Environment* env = node::Environment::GetCurrent(context);
  116. const auto iter = base::ranges::find_if(
  117. environments_, [env](auto& item) { return env == item.get(); });
  118. if (iter == environments_.end())
  119. return;
  120. gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit");
  121. // The main frame may be replaced.
  122. if (env == node_bindings_->uv_env())
  123. node_bindings_->set_uv_env(nullptr);
  124. // Destroying the node environment will also run the uv loop,
  125. // Node.js expects `kExplicit` microtasks policy and will run microtasks
  126. // checkpoints after every call into JavaScript. Since we use a different
  127. // policy in the renderer - switch to `kExplicit` and then drop back to the
  128. // previous policy value.
  129. v8::MicrotaskQueue* microtask_queue = context->GetMicrotaskQueue();
  130. auto old_policy = microtask_queue->microtasks_policy();
  131. DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0);
  132. microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit);
  133. environments_.erase(iter);
  134. microtask_queue->set_microtasks_policy(old_policy);
  135. // ElectronBindings is tracking node environments.
  136. electron_bindings_->EnvironmentDestroyed(env);
  137. }
  138. void ElectronRendererClient::WorkerScriptReadyForEvaluationOnWorkerThread(
  139. v8::Local<v8::Context> context) {
  140. // We do not create a Node.js environment in service or shared workers
  141. // owing to an inability to customize sandbox policies in these workers
  142. // given that they're run out-of-process.
  143. // Also avoid creating a Node.js environment for worklet global scope
  144. // created on the main thread.
  145. auto* ec = blink::ExecutionContext::From(context);
  146. if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope() ||
  147. ec->IsMainThreadWorkletGlobalScope())
  148. return;
  149. // This won't be correct for in-process child windows with webPreferences
  150. // that have a different value for nodeIntegrationInWorker
  151. if (base::CommandLine::ForCurrentProcess()->HasSwitch(
  152. switches::kNodeIntegrationInWorker)) {
  153. auto* current = WebWorkerObserver::GetCurrent();
  154. if (current)
  155. return;
  156. WebWorkerObserver::Create()->WorkerScriptReadyForEvaluation(context);
  157. }
  158. }
  159. void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread(
  160. v8::Local<v8::Context> context) {
  161. auto* ec = blink::ExecutionContext::From(context);
  162. if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope() ||
  163. ec->IsMainThreadWorkletGlobalScope())
  164. return;
  165. // TODO(loc): Note that this will not be correct for in-process child windows
  166. // with webPreferences that have a different value for nodeIntegrationInWorker
  167. if (base::CommandLine::ForCurrentProcess()->HasSwitch(
  168. switches::kNodeIntegrationInWorker)) {
  169. auto* current = WebWorkerObserver::GetCurrent();
  170. if (current)
  171. current->ContextWillDestroy(context);
  172. }
  173. }
  174. node::Environment* ElectronRendererClient::GetEnvironment(
  175. content::RenderFrame* render_frame) const {
  176. if (!base::Contains(injected_frames_, render_frame))
  177. return nullptr;
  178. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  179. auto context =
  180. GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent());
  181. node::Environment* env = node::Environment::GetCurrent(context);
  182. return base::Contains(environments_, env,
  183. [](auto const& item) { return item.get(); })
  184. ? env
  185. : nullptr;
  186. }
  187. } // namespace electron