atom_renderer_client.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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/atom_renderer_client.h"
  5. #include <string>
  6. #include <vector>
  7. #include "base/command_line.h"
  8. #include "content/public/renderer/render_frame.h"
  9. #include "native_mate/dictionary.h"
  10. #include "shell/common/api/electron_bindings.h"
  11. #include "shell/common/api/event_emitter_caller.h"
  12. #include "shell/common/asar/asar_util.h"
  13. #include "shell/common/node_bindings.h"
  14. #include "shell/common/node_includes.h"
  15. #include "shell/common/options_switches.h"
  16. #include "shell/renderer/atom_render_frame_observer.h"
  17. #include "shell/renderer/web_worker_observer.h"
  18. #include "third_party/blink/public/web/web_document.h"
  19. #include "third_party/blink/public/web/web_local_frame.h"
  20. #include "third_party/electron_node/src/node_native_module_env.h"
  21. namespace electron {
  22. namespace {
  23. bool IsDevToolsExtension(content::RenderFrame* render_frame) {
  24. return static_cast<GURL>(render_frame->GetWebFrame()->GetDocument().Url())
  25. .SchemeIs("chrome-extension");
  26. }
  27. } // namespace
  28. AtomRendererClient::AtomRendererClient()
  29. : node_bindings_(
  30. NodeBindings::Create(NodeBindings::BrowserEnvironment::RENDERER)),
  31. electron_bindings_(new ElectronBindings(uv_default_loop())) {}
  32. AtomRendererClient::~AtomRendererClient() {
  33. asar::ClearArchives();
  34. }
  35. void AtomRendererClient::RenderFrameCreated(
  36. content::RenderFrame* render_frame) {
  37. new AtomRenderFrameObserver(render_frame, this);
  38. RendererClientBase::RenderFrameCreated(render_frame);
  39. }
  40. void AtomRendererClient::RunScriptsAtDocumentStart(
  41. content::RenderFrame* render_frame) {
  42. RendererClientBase::RunScriptsAtDocumentStart(render_frame);
  43. // Inform the document start pharse.
  44. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  45. node::Environment* env = GetEnvironment(render_frame);
  46. if (env)
  47. mate::EmitEvent(env->isolate(), env->process_object(), "document-start");
  48. }
  49. void AtomRendererClient::RunScriptsAtDocumentEnd(
  50. content::RenderFrame* render_frame) {
  51. RendererClientBase::RunScriptsAtDocumentEnd(render_frame);
  52. // Inform the document end pharse.
  53. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  54. node::Environment* env = GetEnvironment(render_frame);
  55. if (env)
  56. mate::EmitEvent(env->isolate(), env->process_object(), "document-end");
  57. }
  58. void AtomRendererClient::DidCreateScriptContext(
  59. v8::Handle<v8::Context> renderer_context,
  60. content::RenderFrame* render_frame) {
  61. RendererClientBase::DidCreateScriptContext(renderer_context, render_frame);
  62. // TODO(zcbenz): Do not create Node environment if node integration is not
  63. // enabled.
  64. auto* command_line = base::CommandLine::ForCurrentProcess();
  65. // Only load node if we are a main frame or a devtools extension
  66. // unless node support has been explicitly enabled for sub frames
  67. bool reuse_renderer_processes_enabled =
  68. command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides);
  69. // Consider the window not "opened" if it does not have an Opener, or if a
  70. // user has manually opted in to leaking node in the renderer
  71. bool is_not_opened =
  72. !render_frame->GetWebFrame()->Opener() ||
  73. command_line->HasSwitch(switches::kEnableNodeLeakageInRenderers);
  74. // Consider this the main frame if it is both a Main Frame and it wasn't
  75. // opened. We allow an opened main frame to have node if renderer process
  76. // reuse is enabled as that will correctly free node environments prevent a
  77. // leak in child windows.
  78. bool is_main_frame = render_frame->IsMainFrame() &&
  79. (is_not_opened || reuse_renderer_processes_enabled);
  80. bool is_devtools = IsDevToolsExtension(render_frame);
  81. bool allow_node_in_subframes =
  82. command_line->HasSwitch(switches::kNodeIntegrationInSubFrames);
  83. bool should_load_node =
  84. (is_main_frame || is_devtools || allow_node_in_subframes) &&
  85. !IsWebViewFrame(renderer_context, render_frame);
  86. if (!should_load_node) {
  87. return;
  88. }
  89. injected_frames_.insert(render_frame);
  90. // If this is the first environment we are creating, prepare the node
  91. // bindings.
  92. if (!node_integration_initialized_) {
  93. node_integration_initialized_ = true;
  94. node_bindings_->Initialize();
  95. node_bindings_->PrepareMessageLoop();
  96. }
  97. // Setup node tracing controller.
  98. if (!node::tracing::TraceEventHelper::GetAgent())
  99. node::tracing::TraceEventHelper::SetAgent(node::CreateAgent());
  100. // Setup node environment for each window.
  101. v8::Local<v8::Context> context =
  102. node::MaybeInitializeContext(renderer_context);
  103. DCHECK(!context.IsEmpty());
  104. node::Environment* env =
  105. node_bindings_->CreateEnvironment(context, nullptr, true);
  106. // If we have disabled the site instance overrides we should prevent loading
  107. // any non-context aware native module
  108. if (command_line->HasSwitch(switches::kDisableElectronSiteInstanceOverrides))
  109. env->ForceOnlyContextAwareNativeModules();
  110. env->WarnNonContextAwareNativeModules();
  111. environments_.insert(env);
  112. // Add Electron extended APIs.
  113. electron_bindings_->BindTo(env->isolate(), env->process_object());
  114. AddRenderBindings(env->isolate(), env->process_object());
  115. mate::Dictionary process_dict(env->isolate(), env->process_object());
  116. process_dict.SetReadOnly("isMainFrame", render_frame->IsMainFrame());
  117. // Load everything.
  118. node_bindings_->LoadEnvironment(env);
  119. if (node_bindings_->uv_env() == nullptr) {
  120. // Make uv loop being wrapped by window context.
  121. node_bindings_->set_uv_env(env);
  122. // Give the node loop a run to make sure everything is ready.
  123. node_bindings_->RunMessageLoop();
  124. }
  125. }
  126. void AtomRendererClient::WillReleaseScriptContext(
  127. v8::Handle<v8::Context> context,
  128. content::RenderFrame* render_frame) {
  129. if (injected_frames_.find(render_frame) == injected_frames_.end())
  130. return;
  131. injected_frames_.erase(render_frame);
  132. node::Environment* env = node::Environment::GetCurrent(context);
  133. if (environments_.find(env) == environments_.end())
  134. return;
  135. environments_.erase(env);
  136. mate::EmitEvent(env->isolate(), env->process_object(), "exit");
  137. // The main frame may be replaced.
  138. if (env == node_bindings_->uv_env())
  139. node_bindings_->set_uv_env(nullptr);
  140. // Destroy the node environment. We only do this if node support has been
  141. // enabled for sub-frames to avoid a change-of-behavior / introduce crashes
  142. // for existing users.
  143. // We also do this if we have disable electron site instance overrides to
  144. // avoid memory leaks
  145. auto* command_line = base::CommandLine::ForCurrentProcess();
  146. if (command_line->HasSwitch(switches::kNodeIntegrationInSubFrames) ||
  147. command_line->HasSwitch(
  148. switches::kDisableElectronSiteInstanceOverrides)) {
  149. node::RunAtExit(env);
  150. node::FreeEnvironment(env);
  151. }
  152. // ElectronBindings is tracking node environments.
  153. electron_bindings_->EnvironmentDestroyed(env);
  154. }
  155. bool AtomRendererClient::ShouldFork(blink::WebLocalFrame* frame,
  156. const GURL& url,
  157. const std::string& http_method,
  158. bool is_initial_navigation,
  159. bool is_server_redirect) {
  160. // Handle all the navigations and reloads in browser.
  161. // FIXME We only support GET here because http method will be ignored when
  162. // the OpenURLFromTab is triggered, which means form posting would not work,
  163. // we should solve this by patching Chromium in future.
  164. return http_method == "GET";
  165. }
  166. void AtomRendererClient::DidInitializeWorkerContextOnWorkerThread(
  167. v8::Local<v8::Context> context) {
  168. if (base::CommandLine::ForCurrentProcess()->HasSwitch(
  169. switches::kNodeIntegrationInWorker)) {
  170. WebWorkerObserver::GetCurrent()->ContextCreated(context);
  171. }
  172. }
  173. void AtomRendererClient::WillDestroyWorkerContextOnWorkerThread(
  174. v8::Local<v8::Context> context) {
  175. if (base::CommandLine::ForCurrentProcess()->HasSwitch(
  176. switches::kNodeIntegrationInWorker)) {
  177. WebWorkerObserver::GetCurrent()->ContextWillDestroy(context);
  178. }
  179. }
  180. void AtomRendererClient::SetupMainWorldOverrides(
  181. v8::Handle<v8::Context> context,
  182. content::RenderFrame* render_frame) {
  183. // We only need to run the isolated bundle if webview is enabled
  184. if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kWebviewTag))
  185. return;
  186. // Setup window overrides in the main world context
  187. // Wrap the bundle into a function that receives the isolatedWorld as
  188. // an argument.
  189. auto* isolate = context->GetIsolate();
  190. std::vector<v8::Local<v8::String>> isolated_bundle_params = {
  191. node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
  192. node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld")};
  193. auto* env = GetEnvironment(render_frame);
  194. DCHECK(env);
  195. std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
  196. env->process_object(),
  197. GetContext(render_frame->GetWebFrame(), isolate)->Global()};
  198. node::native_module::NativeModuleEnv::CompileAndCall(
  199. context, "electron/js2c/isolated_bundle", &isolated_bundle_params,
  200. &isolated_bundle_args, nullptr);
  201. }
  202. void AtomRendererClient::SetupExtensionWorldOverrides(
  203. v8::Handle<v8::Context> context,
  204. content::RenderFrame* render_frame,
  205. int world_id) {
  206. auto* isolate = context->GetIsolate();
  207. std::vector<v8::Local<v8::String>> isolated_bundle_params = {
  208. node::FIXED_ONE_BYTE_STRING(isolate, "nodeProcess"),
  209. node::FIXED_ONE_BYTE_STRING(isolate, "isolatedWorld"),
  210. node::FIXED_ONE_BYTE_STRING(isolate, "worldId")};
  211. auto* env = GetEnvironment(render_frame);
  212. if (!env)
  213. return;
  214. std::vector<v8::Local<v8::Value>> isolated_bundle_args = {
  215. env->process_object(),
  216. GetContext(render_frame->GetWebFrame(), isolate)->Global(),
  217. v8::Integer::New(isolate, world_id)};
  218. node::native_module::NativeModuleEnv::CompileAndCall(
  219. context, "electron/js2c/content_script_bundle", &isolated_bundle_params,
  220. &isolated_bundle_args, nullptr);
  221. }
  222. node::Environment* AtomRendererClient::GetEnvironment(
  223. content::RenderFrame* render_frame) const {
  224. if (injected_frames_.find(render_frame) == injected_frames_.end())
  225. return nullptr;
  226. v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
  227. auto context =
  228. GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent());
  229. node::Environment* env = node::Environment::GetCurrent(context);
  230. if (environments_.find(env) == environments_.end())
  231. return nullptr;
  232. return env;
  233. }
  234. } // namespace electron