atom_renderer_client.cc 9.9 KB

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