1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/renderer/dispatcher.h"
8 #include "base/callback.h"
9 #include "base/command_line.h"
10 #include "base/debug/alias.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/user_metrics_action.h"
14 #include "base/strings/string_piece.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/time/time.h"
18 #include "base/values.h"
19 #include "content/grit/content_resources.h"
20 #include "content/public/child/v8_value_converter.h"
21 #include "content/public/common/content_switches.h"
22 #include "content/public/common/url_constants.h"
23 #include "content/public/renderer/render_frame.h"
24 #include "content/public/renderer/render_thread.h"
25 #include "extensions/common/api/messaging/message.h"
26 #include "extensions/common/constants.h"
27 #include "extensions/common/extension_api.h"
28 #include "extensions/common/extension_messages.h"
29 #include "extensions/common/extension_urls.h"
30 #include "extensions/common/feature_switch.h"
31 #include "extensions/common/features/feature.h"
32 #include "extensions/common/features/feature_provider.h"
33 #include "extensions/common/manifest.h"
34 #include "extensions/common/manifest_constants.h"
35 #include "extensions/common/manifest_handlers/background_info.h"
36 #include "extensions/common/manifest_handlers/content_capabilities_handler.h"
37 #include "extensions/common/manifest_handlers/externally_connectable.h"
38 #include "extensions/common/manifest_handlers/options_page_info.h"
39 #include "extensions/common/message_bundle.h"
40 #include "extensions/common/permissions/permission_set.h"
41 #include "extensions/common/permissions/permissions_data.h"
42 #include "extensions/common/switches.h"
43 #include "extensions/common/view_type.h"
44 #include "extensions/renderer/api_activity_logger.h"
45 #include "extensions/renderer/api_definitions_natives.h"
46 #include "extensions/renderer/app_runtime_custom_bindings.h"
47 #include "extensions/renderer/app_window_custom_bindings.h"
48 #include "extensions/renderer/binding_generating_native_handler.h"
49 #include "extensions/renderer/blob_native_handler.h"
50 #include "extensions/renderer/content_watcher.h"
51 #include "extensions/renderer/context_menus_custom_bindings.h"
52 #include "extensions/renderer/css_native_handler.h"
53 #include "extensions/renderer/dispatcher_delegate.h"
54 #include "extensions/renderer/document_custom_bindings.h"
55 #include "extensions/renderer/dom_activity_logger.h"
56 #include "extensions/renderer/event_bindings.h"
57 #include "extensions/renderer/extension_frame_helper.h"
58 #include "extensions/renderer/extension_helper.h"
59 #include "extensions/renderer/extensions_renderer_client.h"
60 #include "extensions/renderer/file_system_natives.h"
61 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
62 #include "extensions/renderer/i18n_custom_bindings.h"
63 #include "extensions/renderer/id_generator_custom_bindings.h"
64 #include "extensions/renderer/lazy_background_page_native_handler.h"
65 #include "extensions/renderer/logging_native_handler.h"
66 #include "extensions/renderer/messaging_bindings.h"
67 #include "extensions/renderer/module_system.h"
68 #include "extensions/renderer/print_native_handler.h"
69 #include "extensions/renderer/process_info_native_handler.h"
70 #include "extensions/renderer/render_view_observer_natives.h"
71 #include "extensions/renderer/request_sender.h"
72 #include "extensions/renderer/runtime_custom_bindings.h"
73 #include "extensions/renderer/safe_builtins.h"
74 #include "extensions/renderer/script_context.h"
75 #include "extensions/renderer/script_context_set.h"
76 #include "extensions/renderer/script_injection.h"
77 #include "extensions/renderer/script_injection_manager.h"
78 #include "extensions/renderer/send_request_natives.h"
79 #include "extensions/renderer/set_icon_natives.h"
80 #include "extensions/renderer/test_features_native_handler.h"
81 #include "extensions/renderer/user_gestures_native_handler.h"
82 #include "extensions/renderer/utils_native_handler.h"
83 #include "extensions/renderer/v8_context_native_handler.h"
84 #include "grit/extensions_renderer_resources.h"
85 #include "third_party/WebKit/public/platform/WebString.h"
86 #include "third_party/WebKit/public/platform/WebURLRequest.h"
87 #include "third_party/WebKit/public/web/WebCustomElement.h"
88 #include "third_party/WebKit/public/web/WebDataSource.h"
89 #include "third_party/WebKit/public/web/WebDocument.h"
90 #include "third_party/WebKit/public/web/WebFrame.h"
91 #include "third_party/WebKit/public/web/WebLocalFrame.h"
92 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
93 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
94 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
95 #include "third_party/WebKit/public/web/WebView.h"
96 #include "third_party/mojo/src/mojo/public/js/constants.h"
97 #include "ui/base/layout.h"
98 #include "ui/base/resource/resource_bundle.h"
99 #include "v8/include/v8.h"
101 using base::UserMetricsAction
;
102 using blink::WebDataSource
;
103 using blink::WebDocument
;
104 using blink::WebScopedUserGesture
;
105 using blink::WebSecurityPolicy
;
106 using blink::WebString
;
107 using blink::WebVector
;
108 using blink::WebView
;
109 using content::RenderThread
;
111 namespace extensions
{
115 static const int64 kInitialExtensionIdleHandlerDelayMs
= 5 * 1000;
116 static const int64 kMaxExtensionIdleHandlerDelayMs
= 5 * 60 * 1000;
117 static const char kEventDispatchFunction
[] = "dispatchEvent";
118 static const char kOnSuspendEvent
[] = "runtime.onSuspend";
119 static const char kOnSuspendCanceledEvent
[] = "runtime.onSuspendCanceled";
121 // Returns the global value for "chrome" from |context|. If one doesn't exist
122 // creates a new object for it.
124 // Note that this isn't necessarily an object, since webpages can write, for
125 // example, "window.chrome = true".
126 v8::Local
<v8::Value
> GetOrCreateChrome(ScriptContext
* context
) {
127 v8::Local
<v8::String
> chrome_string(
128 v8::String::NewFromUtf8(context
->isolate(), "chrome"));
129 v8::Local
<v8::Object
> global(context
->v8_context()->Global());
130 v8::Local
<v8::Value
> chrome(global
->Get(chrome_string
));
131 if (chrome
->IsUndefined()) {
132 chrome
= v8::Object::New(context
->isolate());
133 global
->Set(chrome_string
, chrome
);
138 // Returns |value| cast to an object if possible, else an empty handle.
139 v8::Local
<v8::Object
> AsObjectOrEmpty(v8::Local
<v8::Value
> value
) {
140 return value
->IsObject() ? value
.As
<v8::Object
>() : v8::Local
<v8::Object
>();
143 // Calls a method |method_name| in a module |module_name| belonging to the
144 // module system from |context|. Intended as a callback target from
145 // ScriptContextSet::ForEach.
146 void CallModuleMethod(const std::string
& module_name
,
147 const std::string
& method_name
,
148 const base::ListValue
* args
,
149 ScriptContext
* context
) {
150 v8::HandleScope
handle_scope(context
->isolate());
151 v8::Context::Scope
context_scope(context
->v8_context());
153 scoped_ptr
<content::V8ValueConverter
> converter(
154 content::V8ValueConverter::create());
156 std::vector
<v8::Local
<v8::Value
>> arguments
;
157 for (base::ListValue::const_iterator it
= args
->begin(); it
!= args
->end();
159 arguments
.push_back(converter
->ToV8Value(*it
, context
->v8_context()));
162 context
->module_system()->CallModuleMethod(
163 module_name
, method_name
, &arguments
);
166 // This handles the "chrome." root API object in script contexts.
167 class ChromeNativeHandler
: public ObjectBackedNativeHandler
{
169 explicit ChromeNativeHandler(ScriptContext
* context
)
170 : ObjectBackedNativeHandler(context
) {
173 base::Bind(&ChromeNativeHandler::GetChrome
, base::Unretained(this)));
176 void GetChrome(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
177 args
.GetReturnValue().Set(GetOrCreateChrome(context()));
183 Dispatcher::Dispatcher(DispatcherDelegate
* delegate
)
184 : delegate_(delegate
),
185 content_watcher_(new ContentWatcher()),
186 source_map_(&ResourceBundle::GetSharedInstance()),
187 v8_schema_registry_(new V8SchemaRegistry
),
188 is_webkit_initialized_(false),
189 user_script_set_manager_observer_(this),
190 webrequest_used_(false) {
191 const base::CommandLine
& command_line
=
192 *(base::CommandLine::ForCurrentProcess());
193 set_idle_notifications_
=
194 command_line
.HasSwitch(switches::kExtensionProcess
) ||
195 command_line
.HasSwitch(::switches::kSingleProcess
);
197 if (set_idle_notifications_
) {
198 RenderThread::Get()->SetIdleNotificationDelayInMs(
199 kInitialExtensionIdleHandlerDelayMs
);
202 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
204 script_context_set_
.reset(
205 new ScriptContextSet(&extensions_
, &active_extension_ids_
));
206 user_script_set_manager_
.reset(new UserScriptSetManager(&extensions_
));
207 script_injection_manager_
.reset(
208 new ScriptInjectionManager(&extensions_
, user_script_set_manager_
.get()));
209 user_script_set_manager_observer_
.Add(user_script_set_manager_
.get());
210 request_sender_
.reset(new RequestSender(this));
214 Dispatcher::~Dispatcher() {
217 void Dispatcher::OnRenderFrameCreated(content::RenderFrame
* render_frame
) {
218 script_injection_manager_
->OnRenderFrameCreated(render_frame
);
221 bool Dispatcher::IsExtensionActive(const std::string
& extension_id
) const {
223 active_extension_ids_
.find(extension_id
) != active_extension_ids_
.end();
225 CHECK(extensions_
.Contains(extension_id
));
229 void Dispatcher::DidCreateScriptContext(
230 blink::WebLocalFrame
* frame
,
231 const v8::Local
<v8::Context
>& v8_context
,
234 const base::TimeTicks start_time
= base::TimeTicks::Now();
236 ScriptContext
* context
= script_context_set_
->Register(
237 frame
, v8_context
, extension_group
, world_id
);
239 // Initialize origin permissions for content scripts, which can't be
240 // initialized in |OnActivateExtension|.
241 if (context
->context_type() == Feature::CONTENT_SCRIPT_CONTEXT
)
242 InitOriginPermissions(context
->extension());
245 scoped_ptr
<ModuleSystem
> module_system(
246 new ModuleSystem(context
, &source_map_
));
247 context
->set_module_system(module_system
.Pass());
249 ModuleSystem
* module_system
= context
->module_system();
251 // Enable natives in startup.
252 ModuleSystem::NativesEnabledScope
natives_enabled_scope(module_system
);
254 RegisterNativeHandlers(module_system
, context
);
256 // chrome.Event is part of the public API (although undocumented). Make it
257 // lazily evalulate to Event from event_bindings.js. For extensions only
258 // though, not all webpages!
259 if (context
->extension()) {
260 v8::Local
<v8::Object
> chrome
= AsObjectOrEmpty(GetOrCreateChrome(context
));
261 if (!chrome
.IsEmpty())
262 module_system
->SetLazyField(chrome
, "Event", kEventBindings
, "Event");
265 UpdateBindingsForContext(context
);
267 bool is_within_platform_app
= IsWithinPlatformApp();
268 // Inject custom JS into the platform app context.
269 if (is_within_platform_app
) {
270 module_system
->Require("platformApp");
273 RequireGuestViewModules(context
);
274 delegate_
->RequireAdditionalModules(context
, is_within_platform_app
);
276 const base::TimeDelta elapsed
= base::TimeTicks::Now() - start_time
;
277 switch (context
->context_type()) {
278 case Feature::UNSPECIFIED_CONTEXT
:
279 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
282 case Feature::BLESSED_EXTENSION_CONTEXT
:
283 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed
);
285 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
286 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
289 case Feature::CONTENT_SCRIPT_CONTEXT
:
290 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
293 case Feature::WEB_PAGE_CONTEXT
:
294 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed
);
296 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
297 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
300 case Feature::WEBUI_CONTEXT
:
301 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed
);
305 VLOG(1) << "Num tracked contexts: " << script_context_set_
->size();
308 void Dispatcher::WillReleaseScriptContext(
309 blink::WebLocalFrame
* frame
,
310 const v8::Local
<v8::Context
>& v8_context
,
312 ScriptContext
* context
= script_context_set_
->GetByV8Context(v8_context
);
316 context
->DispatchOnUnloadEvent();
317 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
318 // In fact |request_sender_| should really be owned by ScriptContext.
319 request_sender_
->InvalidateSource(context
);
321 script_context_set_
->Remove(context
);
322 VLOG(1) << "Num tracked contexts: " << script_context_set_
->size();
325 void Dispatcher::DidCreateDocumentElement(blink::WebFrame
* frame
) {
326 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
327 // so that this also injects the stylesheet on about:blank frames that
328 // are hosted in the extension process.
329 GURL effective_document_url
= ScriptContext::GetEffectiveDocumentURL(
330 frame
, frame
->document().url(), true /* match_about_blank */);
332 const Extension
* extension
=
333 extensions_
.GetExtensionOrAppByURL(effective_document_url
);
336 (extension
->is_extension() || extension
->is_platform_app())) {
337 int resource_id
= extension
->is_platform_app() ? IDR_PLATFORM_APP_CSS
338 : IDR_EXTENSION_FONTS_CSS
;
339 std::string stylesheet
= ResourceBundle::GetSharedInstance()
340 .GetRawDataResource(resource_id
)
342 base::ReplaceFirstSubstringAfterOffset(
343 &stylesheet
, 0, "$FONTFAMILY", system_font_family_
);
344 base::ReplaceFirstSubstringAfterOffset(
345 &stylesheet
, 0, "$FONTSIZE", system_font_size_
);
347 // Blink doesn't let us define an additional user agent stylesheet, so
348 // we insert the default platform app or extension stylesheet into all
349 // documents that are loaded in each app or extension.
350 frame
->document().insertStyleSheet(WebString::fromUTF8(stylesheet
));
353 // If this is an extension options page, and the extension has opted into
354 // using Chrome styles, then insert the Chrome extension stylesheet.
355 if (extension
&& extension
->is_extension() &&
356 OptionsPageInfo::ShouldUseChromeStyle(extension
) &&
357 effective_document_url
== OptionsPageInfo::GetOptionsPage(extension
)) {
358 frame
->document().insertStyleSheet(
359 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
360 .GetRawDataResource(IDR_EXTENSION_CSS
)
364 content_watcher_
->DidCreateDocumentElement(frame
);
367 void Dispatcher::DidMatchCSS(
368 blink::WebFrame
* frame
,
369 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
370 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
371 content_watcher_
->DidMatchCSS(
372 frame
, newly_matching_selectors
, stopped_matching_selectors
);
375 void Dispatcher::OnExtensionResponse(int request_id
,
377 const base::ListValue
& response
,
378 const std::string
& error
) {
379 request_sender_
->HandleResponse(request_id
, success
, response
, error
);
382 void Dispatcher::DispatchEvent(const std::string
& extension_id
,
383 const std::string
& event_name
) const {
384 base::ListValue args
;
385 args
.Set(0, new base::StringValue(event_name
));
386 args
.Set(1, new base::ListValue());
388 // Needed for Windows compilation, since kEventBindings is declared extern.
389 const char* local_event_bindings
= kEventBindings
;
390 script_context_set_
->ForEach(
391 extension_id
, base::Bind(&CallModuleMethod
, local_event_bindings
,
392 kEventDispatchFunction
, &args
));
395 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame
* render_frame
,
396 const std::string
& extension_id
,
397 const std::string
& module_name
,
398 const std::string
& function_name
,
399 const base::ListValue
& args
,
401 scoped_ptr
<WebScopedUserGesture
> web_user_gesture
;
403 web_user_gesture
.reset(new WebScopedUserGesture
);
405 script_context_set_
->ForEach(
406 extension_id
, render_frame
,
407 base::Bind(&CallModuleMethod
, module_name
, function_name
, &args
));
409 // Reset the idle handler each time there's any activity like event or message
410 // dispatch, for which Invoke is the chokepoint.
411 if (set_idle_notifications_
) {
412 RenderThread::Get()->ScheduleIdleHandler(
413 kInitialExtensionIdleHandlerDelayMs
);
416 // Tell the browser process when an event has been dispatched with a lazy
417 // background page active.
418 const Extension
* extension
= extensions_
.GetByID(extension_id
);
419 if (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
420 module_name
== kEventBindings
&&
421 function_name
== kEventDispatchFunction
) {
422 content::RenderFrame
* background_frame
=
423 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id
);
424 if (background_frame
) {
426 args
.GetInteger(3, &message_id
);
427 background_frame
->Send(new ExtensionHostMsg_EventAck(
428 background_frame
->GetRoutingID(), message_id
));
433 void Dispatcher::ClearPortData(int port_id
) {
434 // Only the target port side has entries in |port_to_tab_id_map_|. If
435 // |port_id| is a source port, std::map::erase() will just silently fail
437 port_to_tab_id_map_
.erase(port_id
);
441 std::vector
<std::pair
<std::string
, int> > Dispatcher::GetJsResources() {
442 std::vector
<std::pair
<std::string
, int> > resources
;
445 resources
.push_back(std::make_pair("appView", IDR_APP_VIEW_JS
));
446 resources
.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER
));
447 resources
.push_back(std::make_pair(kEventBindings
, IDR_EVENT_BINDINGS_JS
));
448 resources
.push_back(std::make_pair("extensionOptions",
449 IDR_EXTENSION_OPTIONS_JS
));
450 resources
.push_back(std::make_pair("extensionOptionsAttributes",
451 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS
));
452 resources
.push_back(std::make_pair("extensionOptionsConstants",
453 IDR_EXTENSION_OPTIONS_CONSTANTS_JS
));
454 resources
.push_back(std::make_pair("extensionOptionsEvents",
455 IDR_EXTENSION_OPTIONS_EVENTS_JS
));
456 resources
.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS
));
457 resources
.push_back(std::make_pair("extensionViewApiMethods",
458 IDR_EXTENSION_VIEW_API_METHODS_JS
));
459 resources
.push_back(std::make_pair("extensionViewAttributes",
460 IDR_EXTENSION_VIEW_ATTRIBUTES_JS
));
461 resources
.push_back(std::make_pair("extensionViewConstants",
462 IDR_EXTENSION_VIEW_CONSTANTS_JS
));
463 resources
.push_back(std::make_pair("extensionViewEvents",
464 IDR_EXTENSION_VIEW_EVENTS_JS
));
465 resources
.push_back(std::make_pair(
466 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
467 resources
.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS
));
468 resources
.push_back(std::make_pair("guestViewAttributes",
469 IDR_GUEST_VIEW_ATTRIBUTES_JS
));
470 resources
.push_back(std::make_pair("guestViewContainer",
471 IDR_GUEST_VIEW_CONTAINER_JS
));
472 resources
.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS
));
473 resources
.push_back(std::make_pair("guestViewEvents",
474 IDR_GUEST_VIEW_EVENTS_JS
));
476 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
477 ::switches::kSitePerProcess
)) {
478 resources
.push_back(std::make_pair("guestViewIframe",
479 IDR_GUEST_VIEW_IFRAME_JS
));
480 resources
.push_back(std::make_pair("guestViewIframeContainer",
481 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS
));
484 resources
.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS
));
485 resources
.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS
));
486 resources
.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS
));
487 resources
.push_back(std::make_pair("messaging", IDR_MESSAGING_JS
));
488 resources
.push_back(std::make_pair("messaging_utils",
489 IDR_MESSAGING_UTILS_JS
));
490 resources
.push_back(std::make_pair(kSchemaUtils
, IDR_SCHEMA_UTILS_JS
));
491 resources
.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS
));
492 resources
.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS
));
493 resources
.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS
));
494 resources
.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS
));
496 std::make_pair("test_environment_specific_bindings",
497 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS
));
498 resources
.push_back(std::make_pair("uncaught_exception_handler",
499 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS
));
500 resources
.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS
));
501 resources
.push_back(std::make_pair("utils", IDR_UTILS_JS
));
502 resources
.push_back(std::make_pair("webRequest",
503 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS
));
505 std::make_pair("webRequestInternal",
506 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS
));
507 // Note: webView not webview so that this doesn't interfere with the
508 // chrome.webview API bindings.
509 resources
.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS
));
510 resources
.push_back(std::make_pair("webViewActionRequests",
511 IDR_WEB_VIEW_ACTION_REQUESTS_JS
));
512 resources
.push_back(std::make_pair("webViewApiMethods",
513 IDR_WEB_VIEW_API_METHODS_JS
));
514 resources
.push_back(std::make_pair("webViewAttributes",
515 IDR_WEB_VIEW_ATTRIBUTES_JS
));
516 resources
.push_back(std::make_pair("webViewConstants",
517 IDR_WEB_VIEW_CONSTANTS_JS
));
518 resources
.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS
));
519 resources
.push_back(std::make_pair("webViewInternal",
520 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
521 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
522 ::switches::kSitePerProcess
)) {
523 resources
.push_back(std::make_pair("webViewIframe",
524 IDR_WEB_VIEW_IFRAME_JS
));
527 std::make_pair(mojo::kBindingsModuleName
, IDR_MOJO_BINDINGS_JS
));
529 std::make_pair(mojo::kBufferModuleName
, IDR_MOJO_BUFFER_JS
));
531 std::make_pair(mojo::kCodecModuleName
, IDR_MOJO_CODEC_JS
));
533 std::make_pair(mojo::kConnectionModuleName
, IDR_MOJO_CONNECTION_JS
));
535 std::make_pair(mojo::kConnectorModuleName
, IDR_MOJO_CONNECTOR_JS
));
537 std::make_pair(mojo::kRouterModuleName
, IDR_MOJO_ROUTER_JS
));
539 std::make_pair(mojo::kUnicodeModuleName
, IDR_MOJO_UNICODE_JS
));
541 std::make_pair(mojo::kValidatorModuleName
, IDR_MOJO_VALIDATOR_JS
));
542 resources
.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS
));
543 resources
.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS
));
544 resources
.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS
));
545 resources
.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS
));
546 resources
.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
547 IDR_KEEP_ALIVE_MOJOM_JS
));
548 resources
.push_back(std::make_pair("device/serial/data_stream.mojom",
549 IDR_DATA_STREAM_MOJOM_JS
));
551 std::make_pair("device/serial/data_stream_serialization.mojom",
552 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS
));
553 resources
.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS
));
555 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS
));
559 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS
));
561 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS
));
563 std::make_pair("declarativeWebRequest",
564 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS
));
566 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS
));
568 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS
));
570 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS
));
571 resources
.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS
));
572 resources
.push_back(std::make_pair(
573 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS
));
574 resources
.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
575 IDR_MIME_HANDLER_MOJOM_JS
));
577 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS
));
579 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS
));
580 resources
.push_back(std::make_pair("printerProvider",
581 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS
));
583 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS
));
584 resources
.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS
));
586 std::make_pair("webViewRequest",
587 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS
));
588 resources
.push_back(std::make_pair("binding", IDR_BINDING_JS
));
590 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
591 switches::kEnableMojoSerialService
)) {
593 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS
));
595 resources
.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS
));
597 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS
));
598 resources
.push_back(std::make_pair("device/serial/serial_serialization.mojom",
599 IDR_SERIAL_SERIALIZATION_MOJOM_JS
));
601 // Custom types sources.
602 resources
.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS
));
604 // Platform app sources that are not API-specific..
605 resources
.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS
));
607 #if defined(ENABLE_MEDIA_ROUTER)
609 std::make_pair("chrome/browser/media/router/media_router.mojom",
610 IDR_MEDIA_ROUTER_MOJOM_JS
));
612 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS
));
613 #endif // defined(ENABLE_MEDIA_ROUTER)
618 // NOTE: please use the naming convention "foo_natives" for these.
620 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
621 ScriptContext
* context
,
622 Dispatcher
* dispatcher
,
623 RequestSender
* request_sender
,
624 V8SchemaRegistry
* v8_schema_registry
) {
625 module_system
->RegisterNativeHandler(
626 "chrome", scoped_ptr
<NativeHandler
>(new ChromeNativeHandler(context
)));
627 module_system
->RegisterNativeHandler(
628 "lazy_background_page",
629 scoped_ptr
<NativeHandler
>(new LazyBackgroundPageNativeHandler(context
)));
630 module_system
->RegisterNativeHandler(
631 "logging", scoped_ptr
<NativeHandler
>(new LoggingNativeHandler(context
)));
632 module_system
->RegisterNativeHandler("schema_registry",
633 v8_schema_registry
->AsNativeHandler());
634 module_system
->RegisterNativeHandler(
635 "print", scoped_ptr
<NativeHandler
>(new PrintNativeHandler(context
)));
636 module_system
->RegisterNativeHandler(
638 scoped_ptr
<NativeHandler
>(new TestFeaturesNativeHandler(context
)));
639 module_system
->RegisterNativeHandler(
641 scoped_ptr
<NativeHandler
>(new UserGesturesNativeHandler(context
)));
642 module_system
->RegisterNativeHandler(
643 "utils", scoped_ptr
<NativeHandler
>(new UtilsNativeHandler(context
)));
644 module_system
->RegisterNativeHandler(
646 scoped_ptr
<NativeHandler
>(
647 new V8ContextNativeHandler(context
, dispatcher
)));
648 module_system
->RegisterNativeHandler(
649 "event_natives", scoped_ptr
<NativeHandler
>(new EventBindings(context
)));
650 module_system
->RegisterNativeHandler(
652 scoped_ptr
<NativeHandler
>(MessagingBindings::Get(dispatcher
, context
)));
653 module_system
->RegisterNativeHandler(
655 scoped_ptr
<NativeHandler
>(
656 new ApiDefinitionsNatives(dispatcher
, context
)));
657 module_system
->RegisterNativeHandler(
659 scoped_ptr
<NativeHandler
>(
660 new SendRequestNatives(request_sender
, context
)));
661 module_system
->RegisterNativeHandler(
663 scoped_ptr
<NativeHandler
>(new SetIconNatives(context
)));
664 module_system
->RegisterNativeHandler(
666 scoped_ptr
<NativeHandler
>(new APIActivityLogger(context
)));
667 module_system
->RegisterNativeHandler(
668 "renderViewObserverNatives",
669 scoped_ptr
<NativeHandler
>(new RenderViewObserverNatives(context
)));
671 // Natives used by multiple APIs.
672 module_system
->RegisterNativeHandler(
673 "file_system_natives",
674 scoped_ptr
<NativeHandler
>(new FileSystemNatives(context
)));
677 module_system
->RegisterNativeHandler(
679 scoped_ptr
<NativeHandler
>(new AppRuntimeCustomBindings(context
)));
680 module_system
->RegisterNativeHandler(
681 "app_window_natives",
682 scoped_ptr
<NativeHandler
>(
683 new AppWindowCustomBindings(dispatcher
, context
)));
684 module_system
->RegisterNativeHandler(
686 scoped_ptr
<NativeHandler
>(new BlobNativeHandler(context
)));
687 module_system
->RegisterNativeHandler(
689 scoped_ptr
<NativeHandler
>(new ContextMenusCustomBindings(context
)));
690 module_system
->RegisterNativeHandler(
691 "css_natives", scoped_ptr
<NativeHandler
>(new CssNativeHandler(context
)));
692 module_system
->RegisterNativeHandler(
694 scoped_ptr
<NativeHandler
>(new DocumentCustomBindings(context
)));
695 module_system
->RegisterNativeHandler(
696 "guest_view_internal",
697 scoped_ptr
<NativeHandler
>(
698 new GuestViewInternalCustomBindings(context
)));
699 module_system
->RegisterNativeHandler(
700 "i18n", scoped_ptr
<NativeHandler
>(new I18NCustomBindings(context
)));
701 module_system
->RegisterNativeHandler(
703 scoped_ptr
<NativeHandler
>(new IdGeneratorCustomBindings(context
)));
704 module_system
->RegisterNativeHandler(
705 "runtime", scoped_ptr
<NativeHandler
>(new RuntimeCustomBindings(context
)));
708 void Dispatcher::LoadExtensionForTest(const Extension
* extension
) {
709 CHECK(extensions_
.Insert(extension
));
712 bool Dispatcher::OnControlMessageReceived(const IPC::Message
& message
) {
714 IPC_BEGIN_MESSAGE_MAP(Dispatcher
, message
)
715 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension
, OnActivateExtension
)
716 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend
, OnCancelSuspend
)
717 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage
, OnDeliverMessage
)
718 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect
, OnDispatchOnConnect
)
719 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect
, OnDispatchOnDisconnect
)
720 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded
, OnLoaded
)
721 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke
, OnMessageInvoke
)
722 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel
, OnSetChannel
)
723 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames
, OnSetFunctionNames
)
724 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist
,
725 OnSetScriptingWhitelist
)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont
, OnSetSystemFont
)
727 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend
, OnShouldSuspend
)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend
, OnSuspend
)
729 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs
, OnTransferBlobs
)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded
, OnUnloaded
)
731 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions
, OnUpdatePermissions
)
732 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions
,
733 OnUpdateTabSpecificPermissions
)
734 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions
,
735 OnClearTabSpecificPermissions
)
736 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI
, OnUsingWebRequestAPI
)
737 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages
,
738 content_watcher_
.get(),
739 ContentWatcher::OnWatchPages
)
740 IPC_MESSAGE_UNHANDLED(handled
= false)
741 IPC_END_MESSAGE_MAP()
746 void Dispatcher::WebKitInitialized() {
747 // For extensions, we want to ensure we call the IdleHandler every so often,
748 // even if the extension keeps up activity.
749 if (set_idle_notifications_
) {
750 forced_idle_timer_
.reset(new base::RepeatingTimer
<content::RenderThread
>);
751 forced_idle_timer_
->Start(
753 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs
),
755 &RenderThread::IdleHandler
);
758 // Initialize host permissions for any extensions that were activated before
759 // WebKit was initialized.
760 for (const std::string
& extension_id
: active_extension_ids_
) {
761 const Extension
* extension
= extensions_
.GetByID(extension_id
);
763 InitOriginPermissions(extension
);
766 EnableCustomElementWhiteList();
768 is_webkit_initialized_
= true;
771 void Dispatcher::IdleNotification() {
772 if (set_idle_notifications_
&& forced_idle_timer_
) {
773 // Dampen the forced delay as well if the extension stays idle for long
774 // periods of time. (forced_idle_timer_ can be NULL after
775 // OnRenderProcessShutdown has been called.)
776 int64 forced_delay_ms
=
777 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
778 kMaxExtensionIdleHandlerDelayMs
);
779 forced_idle_timer_
->Stop();
780 forced_idle_timer_
->Start(
782 base::TimeDelta::FromMilliseconds(forced_delay_ms
),
784 &RenderThread::IdleHandler
);
788 void Dispatcher::OnRenderProcessShutdown() {
789 v8_schema_registry_
.reset();
790 forced_idle_timer_
.reset();
791 content_watcher_
.reset();
794 void Dispatcher::OnActivateExtension(const std::string
& extension_id
) {
795 const Extension
* extension
= extensions_
.GetByID(extension_id
);
797 // Extension was activated but was never loaded. This probably means that
798 // the renderer failed to load it (or the browser failed to tell us when it
799 // did). Failures shouldn't happen, but instead of crashing there (which
800 // executes on all renderers) be conservative and only crash in the renderer
801 // of the extension which failed to load; this one.
802 std::string
& error
= extension_load_errors_
[extension_id
];
804 base::debug::Alias(&minidump
);
805 base::snprintf(minidump
,
807 "e::dispatcher:%s:%s",
808 extension_id
.c_str(),
810 LOG(FATAL
) << extension_id
<< " was never loaded: " << error
;
813 active_extension_ids_
.insert(extension_id
);
815 // This is called when starting a new extension page, so start the idle
817 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs
);
819 if (is_webkit_initialized_
) {
820 DOMActivityLogger::AttachToWorld(
821 DOMActivityLogger::kMainWorldId
, extension_id
);
823 InitOriginPermissions(extension
);
826 UpdateActiveExtensions();
829 void Dispatcher::OnCancelSuspend(const std::string
& extension_id
) {
830 DispatchEvent(extension_id
, kOnSuspendCanceledEvent
);
833 void Dispatcher::OnDeliverMessage(int target_port_id
, const Message
& message
) {
834 scoped_ptr
<RequestSender::ScopedTabID
> scoped_tab_id
;
835 std::map
<int, int>::const_iterator it
=
836 port_to_tab_id_map_
.find(target_port_id
);
837 if (it
!= port_to_tab_id_map_
.end()) {
839 new RequestSender::ScopedTabID(request_sender(), it
->second
));
842 MessagingBindings::DeliverMessage(*script_context_set_
, target_port_id
,
844 NULL
); // All render frames.
847 void Dispatcher::OnDispatchOnConnect(
849 const std::string
& channel_name
,
850 const ExtensionMsg_TabConnectionInfo
& source
,
851 const ExtensionMsg_ExternalConnectionInfo
& info
,
852 const std::string
& tls_channel_id
) {
853 DCHECK(!ContainsKey(port_to_tab_id_map_
, target_port_id
));
854 DCHECK_EQ(1, target_port_id
% 2); // target renderer ports have odd IDs.
855 int sender_tab_id
= -1;
856 source
.tab
.GetInteger("id", &sender_tab_id
);
857 port_to_tab_id_map_
[target_port_id
] = sender_tab_id
;
859 MessagingBindings::DispatchOnConnect(*script_context_set_
, target_port_id
,
860 channel_name
, source
, info
,
862 NULL
); // All render frames.
865 void Dispatcher::OnDispatchOnDisconnect(int port_id
,
866 const std::string
& error_message
) {
867 MessagingBindings::DispatchOnDisconnect(*script_context_set_
, port_id
,
869 NULL
); // All render frames.
872 void Dispatcher::OnLoaded(
873 const std::vector
<ExtensionMsg_Loaded_Params
>& loaded_extensions
) {
874 for (const auto& param
: loaded_extensions
) {
876 scoped_refptr
<const Extension
> extension
= param
.ConvertToExtension(&error
);
877 if (!extension
.get()) {
878 NOTREACHED() << error
;
879 // Note: in tests |param.id| has been observed to be empty (see comment
880 // just below) so this isn't all that reliable.
881 extension_load_errors_
[param
.id
] = error
;
885 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
886 // could be) and uses extension->id() not params.id:
887 // 1. For some reason params.id can be empty. I've only seen it with
888 // the webstore extension, in tests, and I've spent some time trying to
889 // figure out why - but cost/benefit won.
890 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
891 // Dispatcher is attached to a RenderThread. Presumably there is a
892 // mismatch there. In theory one would think it's possible for the
893 // browser to figure this out itself - but again, cost/benefit.
894 if (!extensions_
.Contains(extension
->id()))
895 extensions_
.Insert(extension
);
898 // Update the available bindings for all contexts. These may have changed if
899 // an externally_connectable extension was loaded that can connect to an
904 void Dispatcher::OnMessageInvoke(const std::string
& extension_id
,
905 const std::string
& module_name
,
906 const std::string
& function_name
,
907 const base::ListValue
& args
,
909 InvokeModuleSystemMethod(
910 NULL
, extension_id
, module_name
, function_name
, args
, user_gesture
);
913 void Dispatcher::OnSetChannel(int channel
) {
914 delegate_
->SetChannel(channel
);
917 void Dispatcher::OnSetFunctionNames(const std::vector
<std::string
>& names
) {
918 function_names_
.clear();
919 for (size_t i
= 0; i
< names
.size(); ++i
)
920 function_names_
.insert(names
[i
]);
923 void Dispatcher::OnSetScriptingWhitelist(
924 const ExtensionsClient::ScriptingWhitelist
& extension_ids
) {
925 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids
);
928 void Dispatcher::OnSetSystemFont(const std::string
& font_family
,
929 const std::string
& font_size
) {
930 system_font_family_
= font_family
;
931 system_font_size_
= font_size
;
934 void Dispatcher::OnShouldSuspend(const std::string
& extension_id
,
935 uint64 sequence_id
) {
936 RenderThread::Get()->Send(
937 new ExtensionHostMsg_ShouldSuspendAck(extension_id
, sequence_id
));
940 void Dispatcher::OnSuspend(const std::string
& extension_id
) {
941 // Dispatch the suspend event. This doesn't go through the standard event
942 // dispatch machinery because it requires special handling. We need to let
943 // the browser know when we are starting and stopping the event dispatch, so
944 // that it still considers the extension idle despite any activity the suspend
946 DispatchEvent(extension_id
, kOnSuspendEvent
);
947 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id
));
950 void Dispatcher::OnTransferBlobs(const std::vector
<std::string
>& blob_uuids
) {
951 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids
));
954 void Dispatcher::OnUnloaded(const std::string
& id
) {
955 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
956 // to CHECK here rather than guarding.
957 if (!extensions_
.Remove(id
))
960 active_extension_ids_
.erase(id
);
962 script_injection_manager_
->OnExtensionUnloaded(id
);
964 // If the extension is later reloaded with a different set of permissions,
965 // we'd like it to get a new isolated world ID, so that it can pick up the
966 // changed origin whitelist.
967 ScriptInjection::RemoveIsolatedWorld(id
);
969 // Invalidate all of the contexts that were removed.
970 // TODO(kalman): add an invalidation observer interface to ScriptContext.
971 std::set
<ScriptContext
*> removed_contexts
=
972 script_context_set_
->OnExtensionUnloaded(id
);
973 for (ScriptContext
* context
: removed_contexts
) {
974 request_sender_
->InvalidateSource(context
);
977 // Update the available bindings for the remaining contexts. These may have
978 // changed if an externally_connectable extension is unloaded and a webpage
979 // is no longer accessible.
982 // Invalidates the messages map for the extension in case the extension is
983 // reloaded with a new messages map.
984 EraseL10nMessagesMap(id
);
986 // We don't do anything with existing platform-app stylesheets. They will
987 // stay resident, but the URL pattern corresponding to the unloaded
988 // extension's URL just won't match anything anymore.
991 void Dispatcher::OnUpdatePermissions(
992 const ExtensionMsg_UpdatePermissions_Params
& params
) {
993 const Extension
* extension
= extensions_
.GetByID(params
.extension_id
);
997 scoped_refptr
<const PermissionSet
> active
=
998 params
.active_permissions
.ToPermissionSet();
999 scoped_refptr
<const PermissionSet
> withheld
=
1000 params
.withheld_permissions
.ToPermissionSet();
1002 if (is_webkit_initialized_
) {
1003 UpdateOriginPermissions(
1005 extension
->permissions_data()->GetEffectiveHostPermissions(),
1006 active
->effective_hosts());
1009 extension
->permissions_data()->SetPermissions(active
, withheld
);
1010 UpdateBindings(extension
->id());
1013 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL
& visible_url
,
1014 const std::string
& extension_id
,
1015 const URLPatternSet
& new_hosts
,
1016 bool update_origin_whitelist
,
1018 const Extension
* extension
= extensions_
.GetByID(extension_id
);
1022 URLPatternSet old_effective
=
1023 extension
->permissions_data()->GetEffectiveHostPermissions();
1024 extension
->permissions_data()->UpdateTabSpecificPermissions(
1026 new extensions::PermissionSet(extensions::APIPermissionSet(),
1027 extensions::ManifestPermissionSet(),
1029 extensions::URLPatternSet()));
1031 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1032 UpdateOriginPermissions(
1035 extension
->permissions_data()->GetEffectiveHostPermissions());
1039 void Dispatcher::OnClearTabSpecificPermissions(
1040 const std::vector
<std::string
>& extension_ids
,
1041 bool update_origin_whitelist
,
1043 for (const std::string
& id
: extension_ids
) {
1044 const Extension
* extension
= extensions_
.GetByID(id
);
1046 URLPatternSet old_effective
=
1047 extension
->permissions_data()->GetEffectiveHostPermissions();
1048 extension
->permissions_data()->ClearTabSpecificPermissions(tab_id
);
1049 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1050 UpdateOriginPermissions(
1053 extension
->permissions_data()->GetEffectiveHostPermissions());
1059 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used
) {
1060 webrequest_used_
= webrequest_used
;
1063 void Dispatcher::OnUserScriptsUpdated(const std::set
<HostID
>& changed_hosts
,
1064 const std::vector
<UserScript
*>& scripts
) {
1065 UpdateActiveExtensions();
1068 void Dispatcher::UpdateActiveExtensions() {
1069 std::set
<std::string
> active_extensions
= active_extension_ids_
;
1070 user_script_set_manager_
->GetAllActiveExtensionIds(&active_extensions
);
1071 delegate_
->OnActiveExtensionsUpdated(active_extensions
);
1074 void Dispatcher::InitOriginPermissions(const Extension
* extension
) {
1075 delegate_
->InitOriginPermissions(extension
,
1076 IsExtensionActive(extension
->id()));
1077 UpdateOriginPermissions(
1079 URLPatternSet(), // No old permissions.
1080 extension
->permissions_data()->GetEffectiveHostPermissions());
1083 void Dispatcher::UpdateOriginPermissions(const GURL
& extension_url
,
1084 const URLPatternSet
& old_patterns
,
1085 const URLPatternSet
& new_patterns
) {
1086 static const char* kSchemes
[] = {
1090 content::kChromeUIScheme
,
1092 #if defined(OS_CHROMEOS)
1093 content::kExternalFileScheme
,
1095 extensions::kExtensionScheme
,
1097 for (size_t i
= 0; i
< arraysize(kSchemes
); ++i
) {
1098 const char* scheme
= kSchemes
[i
];
1099 // Remove all old patterns...
1100 for (URLPatternSet::const_iterator pattern
= old_patterns
.begin();
1101 pattern
!= old_patterns
.end(); ++pattern
) {
1102 if (pattern
->MatchesScheme(scheme
)) {
1103 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1105 WebString::fromUTF8(scheme
),
1106 WebString::fromUTF8(pattern
->host()),
1107 pattern
->match_subdomains());
1110 // ...And add the new ones.
1111 for (URLPatternSet::const_iterator pattern
= new_patterns
.begin();
1112 pattern
!= new_patterns
.end(); ++pattern
) {
1113 if (pattern
->MatchesScheme(scheme
)) {
1114 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1116 WebString::fromUTF8(scheme
),
1117 WebString::fromUTF8(pattern
->host()),
1118 pattern
->match_subdomains());
1124 void Dispatcher::EnableCustomElementWhiteList() {
1125 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1126 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1127 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1128 blink::WebCustomElement::addEmbedderCustomElementName(
1129 "extensionoptionsbrowserplugin");
1130 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1131 blink::WebCustomElement::addEmbedderCustomElementName(
1132 "extensionviewbrowserplugin");
1133 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1134 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1135 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1136 blink::WebCustomElement::addEmbedderCustomElementName(
1137 "surfaceviewbrowserplugin");
1140 void Dispatcher::UpdateBindings(const std::string
& extension_id
) {
1141 script_context_set().ForEach(extension_id
,
1142 base::Bind(&Dispatcher::UpdateBindingsForContext
,
1143 base::Unretained(this)));
1146 void Dispatcher::UpdateBindingsForContext(ScriptContext
* context
) {
1147 v8::HandleScope
handle_scope(context
->isolate());
1148 v8::Context::Scope
context_scope(context
->v8_context());
1150 // TODO(kalman): Make the bindings registration have zero overhead then run
1151 // the same code regardless of context type.
1152 switch (context
->context_type()) {
1153 case Feature::UNSPECIFIED_CONTEXT
:
1154 case Feature::WEB_PAGE_CONTEXT
:
1155 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
1156 // Web page context; it's too expensive to run the full bindings code.
1157 // Hard-code that the app and webstore APIs are available...
1158 if (context
->GetAvailability("app").is_available())
1159 RegisterBinding("app", context
);
1160 if (context
->GetAvailability("webstore").is_available())
1161 RegisterBinding("webstore", context
);
1162 if (IsRuntimeAvailableToContext(context
))
1163 RegisterBinding("runtime", context
);
1164 UpdateContentCapabilities(context
);
1167 case Feature::BLESSED_EXTENSION_CONTEXT
:
1168 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
1169 case Feature::CONTENT_SCRIPT_CONTEXT
:
1170 case Feature::WEBUI_CONTEXT
: {
1171 // Extension context; iterate through all the APIs and bind the available
1173 const FeatureProvider
* api_feature_provider
=
1174 FeatureProvider::GetAPIFeatures();
1175 const std::vector
<std::string
>& apis
=
1176 api_feature_provider
->GetAllFeatureNames();
1177 for (std::vector
<std::string
>::const_iterator it
= apis
.begin();
1180 const std::string
& api_name
= *it
;
1181 Feature
* feature
= api_feature_provider
->GetFeature(api_name
);
1184 // Internal APIs are included via require(api_name) from internal code
1185 // rather than chrome[api_name].
1186 if (feature
->IsInternal())
1189 // If this API has a parent feature (and isn't marked 'noparent'),
1190 // then this must be a function or event, so we should not register.
1191 if (api_feature_provider
->GetParent(feature
) != NULL
)
1194 // Skip chrome.test if this isn't a test.
1195 if (api_name
== "test" &&
1196 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1197 ::switches::kTestType
)) {
1201 if (context
->IsAnyFeatureAvailableToContext(*feature
))
1202 RegisterBinding(api_name
, context
);
1209 void Dispatcher::RegisterBinding(const std::string
& api_name
,
1210 ScriptContext
* context
) {
1211 std::string bind_name
;
1212 v8::Local
<v8::Object
> bind_object
=
1213 GetOrCreateBindObjectIfAvailable(api_name
, &bind_name
, context
);
1215 // Empty if the bind object failed to be created, probably because the
1216 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1217 if (bind_object
.IsEmpty())
1220 v8::Local
<v8::String
> v8_bind_name
=
1221 v8::String::NewFromUtf8(context
->isolate(), bind_name
.c_str());
1222 if (bind_object
->HasRealNamedProperty(v8_bind_name
)) {
1223 // The bind object may already have the property if the API has been
1224 // registered before (or if the extension has put something there already,
1227 // In the former case, we need to re-register the bindings for the APIs
1228 // which the extension now has permissions for (if any), but not touch any
1229 // others so that we don't destroy state such as event listeners.
1231 // TODO(kalman): Only register available APIs to make this all moot.
1232 if (bind_object
->HasRealNamedCallbackProperty(v8_bind_name
))
1233 return; // lazy binding still there, nothing to do
1234 if (bind_object
->Get(v8_bind_name
)->IsObject())
1235 return; // binding has already been fully installed
1238 ModuleSystem
* module_system
= context
->module_system();
1239 if (!source_map_
.Contains(api_name
)) {
1240 module_system
->RegisterNativeHandler(
1242 scoped_ptr
<NativeHandler
>(new BindingGeneratingNativeHandler(
1243 context
, api_name
, "binding")));
1244 module_system
->SetNativeLazyField(
1245 bind_object
, bind_name
, api_name
, "binding");
1247 module_system
->SetLazyField(bind_object
, bind_name
, api_name
, "binding");
1251 // NOTE: please use the naming convention "foo_natives" for these.
1252 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
1253 ScriptContext
* context
) {
1254 RegisterNativeHandlers(module_system
,
1257 request_sender_
.get(),
1258 v8_schema_registry_
.get());
1259 const Extension
* extension
= context
->extension();
1260 int manifest_version
= extension
? extension
->manifest_version() : 1;
1261 bool is_component_extension
=
1262 extension
&& Manifest::IsComponentLocation(extension
->location());
1263 bool send_request_disabled
=
1264 (extension
&& Manifest::IsUnpackedLocation(extension
->location()) &&
1265 BackgroundInfo::HasLazyBackgroundPage(extension
));
1266 module_system
->RegisterNativeHandler(
1268 scoped_ptr
<NativeHandler
>(new ProcessInfoNativeHandler(
1270 context
->GetExtensionID(),
1271 context
->GetContextTypeDescription(),
1272 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1273 is_component_extension
,
1275 send_request_disabled
)));
1277 delegate_
->RegisterNativeHandlers(this, module_system
, context
);
1280 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext
* context
) {
1281 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1282 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1285 for (const auto& extension
: extensions_
) {
1286 ExternallyConnectableInfo
* info
= static_cast<ExternallyConnectableInfo
*>(
1287 extension
->GetManifestData(manifest_keys::kExternallyConnectable
));
1288 if (info
&& info
->matches
.MatchesURL(context
->GetURL()))
1294 void Dispatcher::UpdateContentCapabilities(ScriptContext
* context
) {
1295 APIPermissionSet permissions
;
1296 for (const auto& extension
: extensions_
) {
1297 const ContentCapabilitiesInfo
& info
=
1298 ContentCapabilitiesInfo::Get(extension
.get());
1299 if (info
.url_patterns
.MatchesURL(context
->GetURL())) {
1300 APIPermissionSet new_permissions
;
1301 APIPermissionSet::Union(permissions
, info
.permissions
, &new_permissions
);
1302 permissions
= new_permissions
;
1305 context
->SetContentCapabilities(permissions
);
1308 void Dispatcher::PopulateSourceMap() {
1309 const std::vector
<std::pair
<std::string
, int> > resources
= GetJsResources();
1310 for (std::vector
<std::pair
<std::string
, int> >::const_iterator resource
=
1312 resource
!= resources
.end();
1314 source_map_
.RegisterSource(resource
->first
, resource
->second
);
1316 delegate_
->PopulateSourceMap(&source_map_
);
1319 bool Dispatcher::IsWithinPlatformApp() {
1320 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
1321 iter
!= active_extension_ids_
.end();
1323 const Extension
* extension
= extensions_
.GetByID(*iter
);
1324 if (extension
&& extension
->is_platform_app())
1330 v8::Local
<v8::Object
> Dispatcher::GetOrCreateObject(
1331 const v8::Local
<v8::Object
>& object
,
1332 const std::string
& field
,
1333 v8::Isolate
* isolate
) {
1334 v8::Local
<v8::String
> key
= v8::String::NewFromUtf8(isolate
, field
.c_str());
1335 // If the object has a callback property, it is assumed it is an unavailable
1336 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1338 if (object
->HasRealNamedCallbackProperty(key
)) {
1339 object
->Delete(key
);
1340 } else if (object
->HasRealNamedProperty(key
)) {
1341 v8::Local
<v8::Value
> value
= object
->Get(key
);
1342 CHECK(value
->IsObject());
1343 return v8::Local
<v8::Object
>::Cast(value
);
1346 v8::Local
<v8::Object
> new_object
= v8::Object::New(isolate
);
1347 object
->Set(key
, new_object
);
1351 v8::Local
<v8::Object
> Dispatcher::GetOrCreateBindObjectIfAvailable(
1352 const std::string
& api_name
,
1353 std::string
* bind_name
,
1354 ScriptContext
* context
) {
1355 std::vector
<std::string
> split
;
1356 base::SplitString(api_name
, '.', &split
);
1358 v8::Local
<v8::Object
> bind_object
;
1360 // Check if this API has an ancestor. If the API's ancestor is available and
1361 // the API is not available, don't install the bindings for this API. If
1362 // the API is available and its ancestor is not, delete the ancestor and
1363 // install the bindings for the API. This is to prevent loading the ancestor
1364 // API schema if it will not be needed.
1367 // If app is available and app.window is not, just install app.
1368 // If app.window is available and app is not, delete app and install
1369 // app.window on a new object so app does not have to be loaded.
1370 const FeatureProvider
* api_feature_provider
=
1371 FeatureProvider::GetAPIFeatures();
1372 std::string ancestor_name
;
1373 bool only_ancestor_available
= false;
1375 for (size_t i
= 0; i
< split
.size() - 1; ++i
) {
1376 ancestor_name
+= (i
? "." : "") + split
[i
];
1377 if (api_feature_provider
->GetFeature(ancestor_name
) &&
1378 context
->GetAvailability(ancestor_name
).is_available() &&
1379 !context
->GetAvailability(api_name
).is_available()) {
1380 only_ancestor_available
= true;
1384 if (bind_object
.IsEmpty()) {
1385 bind_object
= AsObjectOrEmpty(GetOrCreateChrome(context
));
1386 if (bind_object
.IsEmpty())
1387 return v8::Local
<v8::Object
>();
1389 bind_object
= GetOrCreateObject(bind_object
, split
[i
], context
->isolate());
1392 if (only_ancestor_available
)
1393 return v8::Local
<v8::Object
>();
1396 *bind_name
= split
.back();
1398 return bind_object
.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context
))
1402 void Dispatcher::RequireGuestViewModules(ScriptContext
* context
) {
1403 Feature::Context context_type
= context
->context_type();
1404 ModuleSystem
* module_system
= context
->module_system();
1407 if (context
->GetAvailability("appViewEmbedderInternal").is_available()) {
1408 module_system
->Require("appView");
1411 // Require ExtensionOptions.
1412 if (context
->GetAvailability("extensionOptionsInternal").is_available()) {
1413 module_system
->Require("extensionOptions");
1414 module_system
->Require("extensionOptionsAttributes");
1417 // Require ExtensionView.
1418 if (context
->GetAvailability("extensionViewInternal").is_available()) {
1419 module_system
->Require("extensionView");
1420 module_system
->Require("extensionViewApiMethods");
1421 module_system
->Require("extensionViewAttributes");
1424 // Require SurfaceView.
1425 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1426 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1427 module_system
->Require("surfaceWorker");
1431 if (context
->GetAvailability("webViewInternal").is_available()) {
1432 module_system
->Require("webView");
1433 module_system
->Require("webViewApiMethods");
1434 module_system
->Require("webViewAttributes");
1436 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1437 ::switches::kSitePerProcess
)) {
1438 module_system
->Require("webViewIframe");
1442 // The "guestViewDeny" module must always be loaded last. It registers
1443 // error-providing custom elements for the GuestView types that are not
1444 // available, and thus all of those types must have been checked and loaded
1445 // (or not loaded) beforehand.
1446 if (context_type
== Feature::BLESSED_EXTENSION_CONTEXT
) {
1447 module_system
->Require("guestViewDeny");
1451 } // namespace extensions