electron_renderer_client.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 <algorithm>
  6. #include "base/command_line.h"
  7. #include "base/containers/contains.h"
  8. #include "base/debug/stack_trace.h"
  9. #include "content/public/renderer/render_frame.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_{NodeBindings::Create(
  27. 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. v8::Context::Scope context_scope(env->context());
  44. gin_helper::EmitEvent(env->isolate(), env->process_object(),
  45. "document-start");
  46. }
  47. }
  48. void ElectronRendererClient::RunScriptsAtDocumentEnd(
  49. content::RenderFrame* render_frame) {
  50. RendererClientBase::RunScriptsAtDocumentEnd(render_frame);
  51. // Inform the document end phase.
  52. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  53. node::Environment* env = GetEnvironment(render_frame);
  54. if (env) {
  55. v8::Context::Scope context_scope(env->context());
  56. gin_helper::EmitEvent(env->isolate(), env->process_object(),
  57. "document-end");
  58. }
  59. }
  60. void ElectronRendererClient::UndeferLoad(content::RenderFrame* render_frame) {
  61. render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
  62. blink::LoaderFreezeMode::kNone);
  63. }
  64. void ElectronRendererClient::DidCreateScriptContext(
  65. v8::Local<v8::Context> renderer_context,
  66. content::RenderFrame* render_frame) {
  67. // TODO(zcbenz): Do not create Node environment if node integration is not
  68. // enabled.
  69. // Only load Node.js if we are a main frame or a devtools extension
  70. // unless Node.js support has been explicitly enabled for subframes.
  71. if (!ShouldLoadPreload(renderer_context, render_frame))
  72. return;
  73. injected_frames_.insert(render_frame);
  74. if (!node_integration_initialized_) {
  75. node_integration_initialized_ = true;
  76. node_bindings_->Initialize(renderer_context);
  77. node_bindings_->PrepareEmbedThread();
  78. }
  79. // Setup node tracing controller.
  80. if (!node::tracing::TraceEventHelper::GetAgent()) {
  81. auto* tracing_agent = new node::tracing::Agent();
  82. node::tracing::TraceEventHelper::SetAgent(tracing_agent);
  83. }
  84. // Setup node environment for each window.
  85. v8::Maybe<bool> initialized = node::InitializeContext(renderer_context);
  86. CHECK(!initialized.IsNothing() && initialized.FromJust());
  87. // Before we load the node environment, let's tell blink to hold off on
  88. // loading the body of this frame. We will undefer the load once the preload
  89. // script has finished. This allows our preload script to run async (E.g.
  90. // with ESM) without the preload being in a race
  91. render_frame->GetWebFrame()->GetDocumentLoader()->SetDefersLoading(
  92. blink::LoaderFreezeMode::kStrict);
  93. std::shared_ptr<node::Environment> env = node_bindings_->CreateEnvironment(
  94. renderer_context, nullptr, 0,
  95. base::BindRepeating(&ElectronRendererClient::UndeferLoad,
  96. base::Unretained(this), render_frame));
  97. // We need to use the Blink implementation of fetch in the renderer process
  98. // Node.js deletes the global fetch function when their fetch implementation
  99. // is disabled, so we need to save and re-add it after the Node.js environment
  100. // is loaded. See corresponding change in node/init.ts.
  101. v8::Isolate* isolate = env->isolate();
  102. v8::Local<v8::Object> global = renderer_context->Global();
  103. std::vector<std::string> keys = {"fetch", "Response", "FormData",
  104. "Request", "Headers", "EventSource"};
  105. for (const auto& key : keys) {
  106. v8::MaybeLocal<v8::Value> value =
  107. global->Get(renderer_context, gin::StringToV8(isolate, key));
  108. if (!value.IsEmpty()) {
  109. std::string blink_key = "blink" + key;
  110. global
  111. ->Set(renderer_context, gin::StringToV8(isolate, blink_key),
  112. value.ToLocalChecked())
  113. .Check();
  114. }
  115. }
  116. // If we have disabled the site instance overrides we should prevent loading
  117. // any non-context aware native module.
  118. env->options()->force_context_aware = true;
  119. // We do not want to crash the renderer process on unhandled rejections.
  120. env->options()->unhandled_rejections = "warn-with-error-code";
  121. environments_.insert(env);
  122. // Add Electron extended APIs.
  123. electron_bindings_->BindTo(env->isolate(), env->process_object());
  124. gin_helper::Dictionary process_dict(env->isolate(), env->process_object());
  125. BindProcess(env->isolate(), &process_dict, render_frame);
  126. // Load everything.
  127. node_bindings_->LoadEnvironment(env.get());
  128. if (node_bindings_->uv_env() == nullptr) {
  129. // Make uv loop being wrapped by window context.
  130. node_bindings_->set_uv_env(env.get());
  131. // Give the node loop a run to make sure everything is ready.
  132. node_bindings_->StartPolling();
  133. }
  134. }
  135. void ElectronRendererClient::WillReleaseScriptContext(
  136. v8::Local<v8::Context> context,
  137. content::RenderFrame* render_frame) {
  138. if (injected_frames_.erase(render_frame) == 0)
  139. return;
  140. node::Environment* env = node::Environment::GetCurrent(context);
  141. const auto iter = std::ranges::find_if(
  142. environments_, [env](auto& item) { return env == item.get(); });
  143. if (iter == environments_.end())
  144. return;
  145. gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit");
  146. // The main frame may be replaced.
  147. if (env == node_bindings_->uv_env())
  148. node_bindings_->set_uv_env(nullptr);
  149. // Destroying the node environment will also run the uv loop,
  150. // Node.js expects `kExplicit` microtasks policy and will run microtasks
  151. // checkpoints after every call into JavaScript. Since we use a different
  152. // policy in the renderer - switch to `kExplicit` and then drop back to the
  153. // previous policy value.
  154. v8::MicrotaskQueue* microtask_queue = context->GetMicrotaskQueue();
  155. auto old_policy = microtask_queue->microtasks_policy();
  156. DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0);
  157. microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit);
  158. environments_.erase(iter);
  159. microtask_queue->set_microtasks_policy(old_policy);
  160. // ElectronBindings is tracking node environments.
  161. electron_bindings_->EnvironmentDestroyed(env);
  162. }
  163. void ElectronRendererClient::WorkerScriptReadyForEvaluationOnWorkerThread(
  164. v8::Local<v8::Context> context) {
  165. // We do not create a Node.js environment in service or shared workers
  166. // owing to an inability to customize sandbox policies in these workers
  167. // given that they're run out-of-process.
  168. // Also avoid creating a Node.js environment for worklet global scope
  169. // created on the main thread.
  170. auto* ec = blink::ExecutionContext::From(context);
  171. if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope() ||
  172. ec->IsMainThreadWorkletGlobalScope())
  173. return;
  174. // This won't be correct for in-process child windows with webPreferences
  175. // that have a different value for nodeIntegrationInWorker
  176. if (base::CommandLine::ForCurrentProcess()->HasSwitch(
  177. switches::kNodeIntegrationInWorker)) {
  178. auto* current = WebWorkerObserver::GetCurrent();
  179. if (current)
  180. return;
  181. WebWorkerObserver::Create()->WorkerScriptReadyForEvaluation(context);
  182. }
  183. }
  184. void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread(
  185. v8::Local<v8::Context> context) {
  186. auto* ec = blink::ExecutionContext::From(context);
  187. if (ec->IsServiceWorkerGlobalScope() || ec->IsSharedWorkerGlobalScope() ||
  188. ec->IsMainThreadWorkletGlobalScope())
  189. return;
  190. // TODO(loc): Note that this will not be correct for in-process child windows
  191. // with webPreferences that have a different value for nodeIntegrationInWorker
  192. if (base::CommandLine::ForCurrentProcess()->HasSwitch(
  193. switches::kNodeIntegrationInWorker)) {
  194. auto* current = WebWorkerObserver::GetCurrent();
  195. if (current)
  196. current->ContextWillDestroy(context);
  197. }
  198. }
  199. node::Environment* ElectronRendererClient::GetEnvironment(
  200. content::RenderFrame* render_frame) const {
  201. if (!injected_frames_.contains(render_frame))
  202. return nullptr;
  203. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  204. auto context =
  205. GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent());
  206. node::Environment* env = node::Environment::GetCurrent(context);
  207. return base::Contains(environments_, env,
  208. [](auto const& item) { return item.get(); })
  209. ? env
  210. : nullptr;
  211. }
  212. } // namespace electron