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/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "base/values.h"
20 #include "content/grit/content_resources.h"
21 #include "content/public/child/v8_value_converter.h"
22 #include "content/public/common/browser_plugin_guest_mode.h"
23 #include "content/public/common/content_switches.h"
24 #include "content/public/common/url_constants.h"
25 #include "content/public/renderer/render_frame.h"
26 #include "content/public/renderer/render_thread.h"
27 #include "extensions/common/api/messaging/message.h"
28 #include "extensions/common/constants.h"
29 #include "extensions/common/extension_api.h"
30 #include "extensions/common/extension_messages.h"
31 #include "extensions/common/extension_urls.h"
32 #include "extensions/common/feature_switch.h"
33 #include "extensions/common/features/behavior_feature.h"
34 #include "extensions/common/features/feature.h"
35 #include "extensions/common/features/feature_provider.h"
36 #include "extensions/common/manifest.h"
37 #include "extensions/common/manifest_constants.h"
38 #include "extensions/common/manifest_handlers/background_info.h"
39 #include "extensions/common/manifest_handlers/content_capabilities_handler.h"
40 #include "extensions/common/manifest_handlers/externally_connectable.h"
41 #include "extensions/common/manifest_handlers/options_page_info.h"
42 #include "extensions/common/message_bundle.h"
43 #include "extensions/common/permissions/permission_set.h"
44 #include "extensions/common/permissions/permissions_data.h"
45 #include "extensions/common/switches.h"
46 #include "extensions/common/view_type.h"
47 #include "extensions/renderer/api_activity_logger.h"
48 #include "extensions/renderer/api_definitions_natives.h"
49 #include "extensions/renderer/app_runtime_custom_bindings.h"
50 #include "extensions/renderer/app_window_custom_bindings.h"
51 #include "extensions/renderer/binding_generating_native_handler.h"
52 #include "extensions/renderer/blob_native_handler.h"
53 #include "extensions/renderer/content_watcher.h"
54 #include "extensions/renderer/context_menus_custom_bindings.h"
55 #include "extensions/renderer/css_native_handler.h"
56 #include "extensions/renderer/dispatcher_delegate.h"
57 #include "extensions/renderer/document_custom_bindings.h"
58 #include "extensions/renderer/dom_activity_logger.h"
59 #include "extensions/renderer/event_bindings.h"
60 #include "extensions/renderer/extension_frame_helper.h"
61 #include "extensions/renderer/extension_helper.h"
62 #include "extensions/renderer/extensions_renderer_client.h"
63 #include "extensions/renderer/file_system_natives.h"
64 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
65 #include "extensions/renderer/i18n_custom_bindings.h"
66 #include "extensions/renderer/id_generator_custom_bindings.h"
67 #include "extensions/renderer/lazy_background_page_native_handler.h"
68 #include "extensions/renderer/logging_native_handler.h"
69 #include "extensions/renderer/messaging_bindings.h"
70 #include "extensions/renderer/module_system.h"
71 #include "extensions/renderer/print_native_handler.h"
72 #include "extensions/renderer/process_info_native_handler.h"
73 #include "extensions/renderer/render_frame_observer_natives.h"
74 #include "extensions/renderer/request_sender.h"
75 #include "extensions/renderer/runtime_custom_bindings.h"
76 #include "extensions/renderer/safe_builtins.h"
77 #include "extensions/renderer/script_context.h"
78 #include "extensions/renderer/script_context_set.h"
79 #include "extensions/renderer/script_injection.h"
80 #include "extensions/renderer/script_injection_manager.h"
81 #include "extensions/renderer/send_request_natives.h"
82 #include "extensions/renderer/set_icon_natives.h"
83 #include "extensions/renderer/test_features_native_handler.h"
84 #include "extensions/renderer/user_gestures_native_handler.h"
85 #include "extensions/renderer/utils_native_handler.h"
86 #include "extensions/renderer/v8_context_native_handler.h"
87 #include "grit/extensions_renderer_resources.h"
88 #include "third_party/WebKit/public/platform/WebString.h"
89 #include "third_party/WebKit/public/platform/WebURLRequest.h"
90 #include "third_party/WebKit/public/web/WebCustomElement.h"
91 #include "third_party/WebKit/public/web/WebDataSource.h"
92 #include "third_party/WebKit/public/web/WebDocument.h"
93 #include "third_party/WebKit/public/web/WebFrame.h"
94 #include "third_party/WebKit/public/web/WebLocalFrame.h"
95 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
96 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
97 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
98 #include "third_party/WebKit/public/web/WebView.h"
99 #include "third_party/mojo/src/mojo/public/js/constants.h"
100 #include "ui/base/layout.h"
101 #include "ui/base/resource/resource_bundle.h"
102 #include "v8/include/v8.h"
104 using base::UserMetricsAction
;
105 using blink::WebDataSource
;
106 using blink::WebDocument
;
107 using blink::WebScopedUserGesture
;
108 using blink::WebSecurityPolicy
;
109 using blink::WebString
;
110 using blink::WebVector
;
111 using blink::WebView
;
112 using content::RenderThread
;
114 namespace extensions
{
118 static const int64 kInitialExtensionIdleHandlerDelayMs
= 5 * 1000;
119 static const int64 kMaxExtensionIdleHandlerDelayMs
= 5 * 60 * 1000;
120 static const char kEventDispatchFunction
[] = "dispatchEvent";
121 static const char kOnSuspendEvent
[] = "runtime.onSuspend";
122 static const char kOnSuspendCanceledEvent
[] = "runtime.onSuspendCanceled";
124 // Returns the global value for "chrome" from |context|. If one doesn't exist
125 // creates a new object for it.
127 // Note that this isn't necessarily an object, since webpages can write, for
128 // example, "window.chrome = true".
129 v8::Local
<v8::Value
> GetOrCreateChrome(ScriptContext
* context
) {
130 v8::Local
<v8::String
> chrome_string(
131 v8::String::NewFromUtf8(context
->isolate(), "chrome"));
132 v8::Local
<v8::Object
> global(context
->v8_context()->Global());
133 v8::Local
<v8::Value
> chrome(global
->Get(chrome_string
));
134 if (chrome
->IsUndefined()) {
135 chrome
= v8::Object::New(context
->isolate());
136 global
->Set(chrome_string
, chrome
);
141 // Returns |value| cast to an object if possible, else an empty handle.
142 v8::Local
<v8::Object
> AsObjectOrEmpty(v8::Local
<v8::Value
> value
) {
143 return value
->IsObject() ? value
.As
<v8::Object
>() : v8::Local
<v8::Object
>();
146 // Calls a method |method_name| in a module |module_name| belonging to the
147 // module system from |context|. Intended as a callback target from
148 // ScriptContextSet::ForEach.
149 void CallModuleMethod(const std::string
& module_name
,
150 const std::string
& method_name
,
151 const base::ListValue
* args
,
152 ScriptContext
* context
) {
153 v8::HandleScope
handle_scope(context
->isolate());
154 v8::Context::Scope
context_scope(context
->v8_context());
156 scoped_ptr
<content::V8ValueConverter
> converter(
157 content::V8ValueConverter::create());
159 std::vector
<v8::Local
<v8::Value
>> arguments
;
160 for (base::ListValue::const_iterator it
= args
->begin(); it
!= args
->end();
162 arguments
.push_back(converter
->ToV8Value(*it
, context
->v8_context()));
165 context
->module_system()->CallModuleMethod(
166 module_name
, method_name
, &arguments
);
169 // This handles the "chrome." root API object in script contexts.
170 class ChromeNativeHandler
: public ObjectBackedNativeHandler
{
172 explicit ChromeNativeHandler(ScriptContext
* context
)
173 : ObjectBackedNativeHandler(context
) {
176 base::Bind(&ChromeNativeHandler::GetChrome
, base::Unretained(this)));
179 void GetChrome(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
180 args
.GetReturnValue().Set(GetOrCreateChrome(context()));
186 Dispatcher::Dispatcher(DispatcherDelegate
* delegate
)
187 : delegate_(delegate
),
188 content_watcher_(new ContentWatcher()),
189 source_map_(&ResourceBundle::GetSharedInstance()),
190 v8_schema_registry_(new V8SchemaRegistry
),
191 is_webkit_initialized_(false),
192 user_script_set_manager_observer_(this),
193 webrequest_used_(false) {
194 const base::CommandLine
& command_line
=
195 *(base::CommandLine::ForCurrentProcess());
196 set_idle_notifications_
=
197 command_line
.HasSwitch(switches::kExtensionProcess
) ||
198 command_line
.HasSwitch(::switches::kSingleProcess
);
200 if (set_idle_notifications_
) {
201 RenderThread::Get()->SetIdleNotificationDelayInMs(
202 kInitialExtensionIdleHandlerDelayMs
);
205 script_context_set_
.reset(
206 new ScriptContextSet(&extensions_
, &active_extension_ids_
));
207 user_script_set_manager_
.reset(new UserScriptSetManager(&extensions_
));
208 script_injection_manager_
.reset(
209 new ScriptInjectionManager(&extensions_
, user_script_set_manager_
.get()));
210 user_script_set_manager_observer_
.Add(user_script_set_manager_
.get());
211 request_sender_
.reset(new RequestSender(this));
215 Dispatcher::~Dispatcher() {
218 void Dispatcher::OnRenderFrameCreated(content::RenderFrame
* render_frame
) {
219 script_injection_manager_
->OnRenderFrameCreated(render_frame
);
222 bool Dispatcher::IsExtensionActive(const std::string
& extension_id
) const {
224 active_extension_ids_
.find(extension_id
) != active_extension_ids_
.end();
226 CHECK(extensions_
.Contains(extension_id
));
230 void Dispatcher::DidCreateScriptContext(
231 blink::WebLocalFrame
* frame
,
232 const v8::Local
<v8::Context
>& v8_context
,
235 const base::TimeTicks start_time
= base::TimeTicks::Now();
237 ScriptContext
* context
= script_context_set_
->Register(
238 frame
, v8_context
, extension_group
, world_id
);
240 // Initialize origin permissions for content scripts, which can't be
241 // initialized in |OnActivateExtension|.
242 if (context
->context_type() == Feature::CONTENT_SCRIPT_CONTEXT
)
243 InitOriginPermissions(context
->extension());
246 scoped_ptr
<ModuleSystem
> module_system(
247 new ModuleSystem(context
, &source_map_
));
248 context
->set_module_system(module_system
.Pass());
250 ModuleSystem
* module_system
= context
->module_system();
252 // Enable natives in startup.
253 ModuleSystem::NativesEnabledScope
natives_enabled_scope(module_system
);
255 RegisterNativeHandlers(module_system
, context
);
257 // chrome.Event is part of the public API (although undocumented). Make it
258 // lazily evalulate to Event from event_bindings.js. For extensions only
259 // though, not all webpages!
260 if (context
->extension()) {
261 v8::Local
<v8::Object
> chrome
= AsObjectOrEmpty(GetOrCreateChrome(context
));
262 if (!chrome
.IsEmpty())
263 module_system
->SetLazyField(chrome
, "Event", kEventBindings
, "Event");
266 UpdateBindingsForContext(context
);
268 bool is_within_platform_app
= IsWithinPlatformApp();
269 // Inject custom JS into the platform app context.
270 if (is_within_platform_app
) {
271 module_system
->Require("platformApp");
274 RequireGuestViewModules(context
);
275 delegate_
->RequireAdditionalModules(context
, is_within_platform_app
);
277 const base::TimeDelta elapsed
= base::TimeTicks::Now() - start_time
;
278 switch (context
->context_type()) {
279 case Feature::UNSPECIFIED_CONTEXT
:
280 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
283 case Feature::BLESSED_EXTENSION_CONTEXT
:
284 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed
);
286 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
287 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
290 case Feature::CONTENT_SCRIPT_CONTEXT
:
291 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
294 case Feature::WEB_PAGE_CONTEXT
:
295 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed
);
297 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
298 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
301 case Feature::WEBUI_CONTEXT
:
302 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed
);
306 VLOG(1) << "Num tracked contexts: " << script_context_set_
->size();
309 void Dispatcher::WillReleaseScriptContext(
310 blink::WebLocalFrame
* frame
,
311 const v8::Local
<v8::Context
>& v8_context
,
313 ScriptContext
* context
= script_context_set_
->GetByV8Context(v8_context
);
317 context
->DispatchOnUnloadEvent();
318 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
319 // In fact |request_sender_| should really be owned by ScriptContext.
320 request_sender_
->InvalidateSource(context
);
322 script_context_set_
->Remove(context
);
323 VLOG(1) << "Num tracked contexts: " << script_context_set_
->size();
326 void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame
* frame
) {
327 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
328 // so that this also injects the stylesheet on about:blank frames that
329 // are hosted in the extension process.
330 GURL effective_document_url
= ScriptContext::GetEffectiveDocumentURL(
331 frame
, frame
->document().url(), true /* match_about_blank */);
333 const Extension
* extension
=
334 extensions_
.GetExtensionOrAppByURL(effective_document_url
);
337 (extension
->is_extension() || extension
->is_platform_app())) {
338 int resource_id
= extension
->is_platform_app() ? IDR_PLATFORM_APP_CSS
339 : IDR_EXTENSION_FONTS_CSS
;
340 std::string stylesheet
= ResourceBundle::GetSharedInstance()
341 .GetRawDataResource(resource_id
)
343 base::ReplaceFirstSubstringAfterOffset(
344 &stylesheet
, 0, "$FONTFAMILY", system_font_family_
);
345 base::ReplaceFirstSubstringAfterOffset(
346 &stylesheet
, 0, "$FONTSIZE", system_font_size_
);
348 // Blink doesn't let us define an additional user agent stylesheet, so
349 // we insert the default platform app or extension stylesheet into all
350 // documents that are loaded in each app or extension.
351 frame
->document().insertStyleSheet(WebString::fromUTF8(stylesheet
));
354 // If this is an extension options page, and the extension has opted into
355 // using Chrome styles, then insert the Chrome extension stylesheet.
356 if (extension
&& extension
->is_extension() &&
357 OptionsPageInfo::ShouldUseChromeStyle(extension
) &&
358 effective_document_url
== OptionsPageInfo::GetOptionsPage(extension
)) {
359 frame
->document().insertStyleSheet(
360 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
361 .GetRawDataResource(IDR_EXTENSION_CSS
)
365 // In testing, the document lifetime events can happen after the render
366 // process shutdown event.
367 // See: http://crbug.com/21508 and http://crbug.com/500851
368 if (content_watcher_
) {
369 content_watcher_
->DidCreateDocumentElement(frame
);
373 void Dispatcher::OnExtensionResponse(int request_id
,
375 const base::ListValue
& response
,
376 const std::string
& error
) {
377 request_sender_
->HandleResponse(request_id
, success
, response
, error
);
380 void Dispatcher::DispatchEvent(const std::string
& extension_id
,
381 const std::string
& event_name
) const {
382 base::ListValue args
;
383 args
.Set(0, new base::StringValue(event_name
));
384 args
.Set(1, new base::ListValue());
386 // Needed for Windows compilation, since kEventBindings is declared extern.
387 const char* local_event_bindings
= kEventBindings
;
388 script_context_set_
->ForEach(
389 extension_id
, base::Bind(&CallModuleMethod
, local_event_bindings
,
390 kEventDispatchFunction
, &args
));
393 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame
* render_frame
,
394 const std::string
& extension_id
,
395 const std::string
& module_name
,
396 const std::string
& function_name
,
397 const base::ListValue
& args
,
399 scoped_ptr
<WebScopedUserGesture
> web_user_gesture
;
401 web_user_gesture
.reset(new WebScopedUserGesture
);
403 script_context_set_
->ForEach(
404 extension_id
, render_frame
,
405 base::Bind(&CallModuleMethod
, module_name
, function_name
, &args
));
407 // Reset the idle handler each time there's any activity like event or message
408 // dispatch, for which Invoke is the chokepoint.
409 if (set_idle_notifications_
) {
410 RenderThread::Get()->ScheduleIdleHandler(
411 kInitialExtensionIdleHandlerDelayMs
);
414 // Tell the browser process when an event has been dispatched with a lazy
415 // background page active.
416 const Extension
* extension
= extensions_
.GetByID(extension_id
);
417 if (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
418 module_name
== kEventBindings
&&
419 function_name
== kEventDispatchFunction
) {
420 content::RenderFrame
* background_frame
=
421 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id
);
422 if (background_frame
) {
424 args
.GetInteger(3, &message_id
);
425 background_frame
->Send(new ExtensionHostMsg_EventAck(
426 background_frame
->GetRoutingID(), message_id
));
431 void Dispatcher::ClearPortData(int port_id
) {
432 // Only the target port side has entries in |port_to_tab_id_map_|. If
433 // |port_id| is a source port, std::map::erase() will just silently fail
435 port_to_tab_id_map_
.erase(port_id
);
439 std::vector
<std::pair
<std::string
, int> > Dispatcher::GetJsResources() {
440 std::vector
<std::pair
<std::string
, int> > resources
;
443 resources
.push_back(std::make_pair("appView", IDR_APP_VIEW_JS
));
444 resources
.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER
));
445 resources
.push_back(std::make_pair(kEventBindings
, IDR_EVENT_BINDINGS_JS
));
446 resources
.push_back(std::make_pair("extensionOptions",
447 IDR_EXTENSION_OPTIONS_JS
));
448 resources
.push_back(std::make_pair("extensionOptionsAttributes",
449 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS
));
450 resources
.push_back(std::make_pair("extensionOptionsConstants",
451 IDR_EXTENSION_OPTIONS_CONSTANTS_JS
));
452 resources
.push_back(std::make_pair("extensionOptionsEvents",
453 IDR_EXTENSION_OPTIONS_EVENTS_JS
));
454 resources
.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS
));
455 resources
.push_back(std::make_pair("extensionViewApiMethods",
456 IDR_EXTENSION_VIEW_API_METHODS_JS
));
457 resources
.push_back(std::make_pair("extensionViewAttributes",
458 IDR_EXTENSION_VIEW_ATTRIBUTES_JS
));
459 resources
.push_back(std::make_pair("extensionViewConstants",
460 IDR_EXTENSION_VIEW_CONSTANTS_JS
));
461 resources
.push_back(std::make_pair("extensionViewEvents",
462 IDR_EXTENSION_VIEW_EVENTS_JS
));
463 resources
.push_back(std::make_pair(
464 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
465 resources
.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS
));
466 resources
.push_back(std::make_pair("guestViewAttributes",
467 IDR_GUEST_VIEW_ATTRIBUTES_JS
));
468 resources
.push_back(std::make_pair("guestViewContainer",
469 IDR_GUEST_VIEW_CONTAINER_JS
));
470 resources
.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS
));
471 resources
.push_back(std::make_pair("guestViewEvents",
472 IDR_GUEST_VIEW_EVENTS_JS
));
474 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
475 resources
.push_back(std::make_pair("guestViewIframe",
476 IDR_GUEST_VIEW_IFRAME_JS
));
477 resources
.push_back(std::make_pair("guestViewIframeContainer",
478 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS
));
481 resources
.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS
));
482 resources
.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS
));
483 resources
.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS
));
484 resources
.push_back(std::make_pair("messaging", IDR_MESSAGING_JS
));
485 resources
.push_back(std::make_pair("messaging_utils",
486 IDR_MESSAGING_UTILS_JS
));
487 resources
.push_back(std::make_pair(kSchemaUtils
, IDR_SCHEMA_UTILS_JS
));
488 resources
.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS
));
489 resources
.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS
));
490 resources
.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS
));
491 resources
.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS
));
493 std::make_pair("test_environment_specific_bindings",
494 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS
));
495 resources
.push_back(std::make_pair("uncaught_exception_handler",
496 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS
));
497 resources
.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS
));
498 resources
.push_back(std::make_pair("utils", IDR_UTILS_JS
));
499 resources
.push_back(std::make_pair("webRequest",
500 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS
));
502 std::make_pair("webRequestInternal",
503 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS
));
504 // Note: webView not webview so that this doesn't interfere with the
505 // chrome.webview API bindings.
506 resources
.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS
));
507 resources
.push_back(std::make_pair("webViewActionRequests",
508 IDR_WEB_VIEW_ACTION_REQUESTS_JS
));
509 resources
.push_back(std::make_pair("webViewApiMethods",
510 IDR_WEB_VIEW_API_METHODS_JS
));
511 resources
.push_back(std::make_pair("webViewAttributes",
512 IDR_WEB_VIEW_ATTRIBUTES_JS
));
513 resources
.push_back(std::make_pair("webViewConstants",
514 IDR_WEB_VIEW_CONSTANTS_JS
));
515 resources
.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS
));
516 resources
.push_back(std::make_pair("webViewInternal",
517 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
518 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
519 resources
.push_back(std::make_pair("webViewIframe",
520 IDR_WEB_VIEW_IFRAME_JS
));
523 std::make_pair(mojo::kBindingsModuleName
, IDR_MOJO_BINDINGS_JS
));
525 std::make_pair(mojo::kBufferModuleName
, IDR_MOJO_BUFFER_JS
));
527 std::make_pair(mojo::kCodecModuleName
, IDR_MOJO_CODEC_JS
));
529 std::make_pair(mojo::kConnectionModuleName
, IDR_MOJO_CONNECTION_JS
));
531 std::make_pair(mojo::kConnectorModuleName
, IDR_MOJO_CONNECTOR_JS
));
533 std::make_pair(mojo::kRouterModuleName
, IDR_MOJO_ROUTER_JS
));
535 std::make_pair(mojo::kUnicodeModuleName
, IDR_MOJO_UNICODE_JS
));
537 std::make_pair(mojo::kValidatorModuleName
, IDR_MOJO_VALIDATOR_JS
));
538 resources
.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS
));
539 resources
.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS
));
540 resources
.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS
));
541 resources
.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS
));
542 resources
.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
543 IDR_KEEP_ALIVE_MOJOM_JS
));
544 resources
.push_back(std::make_pair("device/serial/data_stream.mojom",
545 IDR_DATA_STREAM_MOJOM_JS
));
547 std::make_pair("device/serial/data_stream_serialization.mojom",
548 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS
));
549 resources
.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS
));
551 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS
));
555 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS
));
557 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS
));
559 std::make_pair("declarativeWebRequest",
560 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS
));
562 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS
));
564 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS
));
566 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS
));
567 resources
.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS
));
568 resources
.push_back(std::make_pair(
569 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS
));
570 resources
.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
571 IDR_MIME_HANDLER_MOJOM_JS
));
573 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS
));
575 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS
));
576 resources
.push_back(std::make_pair("printerProvider",
577 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS
));
579 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS
));
580 resources
.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS
));
582 std::make_pair("webViewRequest",
583 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS
));
584 resources
.push_back(std::make_pair("binding", IDR_BINDING_JS
));
586 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
587 switches::kEnableMojoSerialService
)) {
589 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS
));
591 resources
.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS
));
593 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS
));
594 resources
.push_back(std::make_pair("device/serial/serial_serialization.mojom",
595 IDR_SERIAL_SERIALIZATION_MOJOM_JS
));
597 // Custom types sources.
598 resources
.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS
));
600 // Platform app sources that are not API-specific..
601 resources
.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS
));
603 #if defined(ENABLE_MEDIA_ROUTER)
605 std::make_pair("chrome/browser/media/router/media_router.mojom",
606 IDR_MEDIA_ROUTER_MOJOM_JS
));
608 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS
));
609 #endif // defined(ENABLE_MEDIA_ROUTER)
614 // NOTE: please use the naming convention "foo_natives" for these.
616 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
617 ScriptContext
* context
,
618 Dispatcher
* dispatcher
,
619 RequestSender
* request_sender
,
620 V8SchemaRegistry
* v8_schema_registry
) {
621 module_system
->RegisterNativeHandler(
622 "chrome", scoped_ptr
<NativeHandler
>(new ChromeNativeHandler(context
)));
623 module_system
->RegisterNativeHandler(
624 "lazy_background_page",
625 scoped_ptr
<NativeHandler
>(new LazyBackgroundPageNativeHandler(context
)));
626 module_system
->RegisterNativeHandler(
627 "logging", scoped_ptr
<NativeHandler
>(new LoggingNativeHandler(context
)));
628 module_system
->RegisterNativeHandler("schema_registry",
629 v8_schema_registry
->AsNativeHandler());
630 module_system
->RegisterNativeHandler(
631 "print", scoped_ptr
<NativeHandler
>(new PrintNativeHandler(context
)));
632 module_system
->RegisterNativeHandler(
634 scoped_ptr
<NativeHandler
>(new TestFeaturesNativeHandler(context
)));
635 module_system
->RegisterNativeHandler(
637 scoped_ptr
<NativeHandler
>(new UserGesturesNativeHandler(context
)));
638 module_system
->RegisterNativeHandler(
639 "utils", scoped_ptr
<NativeHandler
>(new UtilsNativeHandler(context
)));
640 module_system
->RegisterNativeHandler(
642 scoped_ptr
<NativeHandler
>(
643 new V8ContextNativeHandler(context
, dispatcher
)));
644 module_system
->RegisterNativeHandler(
645 "event_natives", scoped_ptr
<NativeHandler
>(new EventBindings(context
)));
646 module_system
->RegisterNativeHandler(
648 scoped_ptr
<NativeHandler
>(MessagingBindings::Get(dispatcher
, context
)));
649 module_system
->RegisterNativeHandler(
651 scoped_ptr
<NativeHandler
>(
652 new ApiDefinitionsNatives(dispatcher
, context
)));
653 module_system
->RegisterNativeHandler(
655 scoped_ptr
<NativeHandler
>(
656 new SendRequestNatives(request_sender
, context
)));
657 module_system
->RegisterNativeHandler(
659 scoped_ptr
<NativeHandler
>(new SetIconNatives(context
)));
660 module_system
->RegisterNativeHandler(
662 scoped_ptr
<NativeHandler
>(new APIActivityLogger(context
)));
663 module_system
->RegisterNativeHandler(
664 "renderFrameObserverNatives",
665 scoped_ptr
<NativeHandler
>(new RenderFrameObserverNatives(context
)));
667 // Natives used by multiple APIs.
668 module_system
->RegisterNativeHandler(
669 "file_system_natives",
670 scoped_ptr
<NativeHandler
>(new FileSystemNatives(context
)));
673 module_system
->RegisterNativeHandler(
675 scoped_ptr
<NativeHandler
>(new AppRuntimeCustomBindings(context
)));
676 // |dispatcher| is null in unit tests.
677 const ScriptContextSet
* script_context_set
= dispatcher
?
678 &dispatcher
->script_context_set() : nullptr;
679 module_system
->RegisterNativeHandler(
680 "app_window_natives",
681 scoped_ptr
<NativeHandler
>(new AppWindowCustomBindings(
682 script_context_set
, context
)));
683 module_system
->RegisterNativeHandler(
685 scoped_ptr
<NativeHandler
>(new BlobNativeHandler(context
)));
686 module_system
->RegisterNativeHandler(
688 scoped_ptr
<NativeHandler
>(new ContextMenusCustomBindings(context
)));
689 module_system
->RegisterNativeHandler(
690 "css_natives", scoped_ptr
<NativeHandler
>(new CssNativeHandler(context
)));
691 module_system
->RegisterNativeHandler(
693 scoped_ptr
<NativeHandler
>(new DocumentCustomBindings(context
)));
694 module_system
->RegisterNativeHandler(
695 "guest_view_internal",
696 scoped_ptr
<NativeHandler
>(
697 new GuestViewInternalCustomBindings(context
)));
698 module_system
->RegisterNativeHandler(
699 "i18n", scoped_ptr
<NativeHandler
>(new I18NCustomBindings(context
)));
700 module_system
->RegisterNativeHandler(
702 scoped_ptr
<NativeHandler
>(new IdGeneratorCustomBindings(context
)));
703 module_system
->RegisterNativeHandler(
704 "runtime", scoped_ptr
<NativeHandler
>(new RuntimeCustomBindings(context
)));
707 void Dispatcher::LoadExtensionForTest(const Extension
* extension
) {
708 CHECK(extensions_
.Insert(extension
));
711 bool Dispatcher::OnControlMessageReceived(const IPC::Message
& message
) {
713 IPC_BEGIN_MESSAGE_MAP(Dispatcher
, message
)
714 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension
, OnActivateExtension
)
715 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend
, OnCancelSuspend
)
716 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage
, OnDeliverMessage
)
717 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect
, OnDispatchOnConnect
)
718 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect
, OnDispatchOnDisconnect
)
719 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded
, OnLoaded
)
720 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke
, OnMessageInvoke
)
721 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel
, OnSetChannel
)
722 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames
, OnSetFunctionNames
)
723 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist
,
724 OnSetScriptingWhitelist
)
725 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont
, OnSetSystemFont
)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend
, OnShouldSuspend
)
727 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend
, OnSuspend
)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs
, OnTransferBlobs
)
729 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded
, OnUnloaded
)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions
, OnUpdatePermissions
)
731 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions
,
732 OnUpdateTabSpecificPermissions
)
733 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions
,
734 OnClearTabSpecificPermissions
)
735 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI
, OnUsingWebRequestAPI
)
736 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages
,
737 content_watcher_
.get(),
738 ContentWatcher::OnWatchPages
)
739 IPC_MESSAGE_UNHANDLED(handled
= false)
740 IPC_END_MESSAGE_MAP()
745 void Dispatcher::WebKitInitialized() {
746 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
748 // For extensions, we want to ensure we call the IdleHandler every so often,
749 // even if the extension keeps up activity.
750 if (set_idle_notifications_
) {
751 forced_idle_timer_
.reset(new base::RepeatingTimer
<content::RenderThread
>);
752 forced_idle_timer_
->Start(
754 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs
),
756 &RenderThread::IdleHandler
);
759 // Initialize host permissions for any extensions that were activated before
760 // WebKit was initialized.
761 for (const std::string
& extension_id
: active_extension_ids_
) {
762 const Extension
* extension
= extensions_
.GetByID(extension_id
);
764 InitOriginPermissions(extension
);
767 EnableCustomElementWhiteList();
769 is_webkit_initialized_
= true;
772 void Dispatcher::IdleNotification() {
773 if (set_idle_notifications_
&& forced_idle_timer_
) {
774 // Dampen the forced delay as well if the extension stays idle for long
775 // periods of time. (forced_idle_timer_ can be NULL after
776 // OnRenderProcessShutdown has been called.)
777 int64 forced_delay_ms
=
778 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
779 kMaxExtensionIdleHandlerDelayMs
);
780 forced_idle_timer_
->Stop();
781 forced_idle_timer_
->Start(
783 base::TimeDelta::FromMilliseconds(forced_delay_ms
),
785 &RenderThread::IdleHandler
);
789 void Dispatcher::OnRenderProcessShutdown() {
790 v8_schema_registry_
.reset();
791 forced_idle_timer_
.reset();
792 content_watcher_
.reset();
795 void Dispatcher::OnActivateExtension(const std::string
& extension_id
) {
796 const Extension
* extension
= extensions_
.GetByID(extension_id
);
798 // Extension was activated but was never loaded. This probably means that
799 // the renderer failed to load it (or the browser failed to tell us when it
800 // did). Failures shouldn't happen, but instead of crashing there (which
801 // executes on all renderers) be conservative and only crash in the renderer
802 // of the extension which failed to load; this one.
803 std::string
& error
= extension_load_errors_
[extension_id
];
805 base::debug::Alias(&minidump
);
806 base::snprintf(minidump
,
808 "e::dispatcher:%s:%s",
809 extension_id
.c_str(),
811 LOG(FATAL
) << extension_id
<< " was never loaded: " << error
;
814 active_extension_ids_
.insert(extension_id
);
816 // This is called when starting a new extension page, so start the idle
818 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs
);
820 if (is_webkit_initialized_
) {
821 DOMActivityLogger::AttachToWorld(
822 DOMActivityLogger::kMainWorldId
, extension_id
);
824 InitOriginPermissions(extension
);
827 UpdateActiveExtensions();
830 void Dispatcher::OnCancelSuspend(const std::string
& extension_id
) {
831 DispatchEvent(extension_id
, kOnSuspendCanceledEvent
);
834 void Dispatcher::OnDeliverMessage(int target_port_id
, const Message
& message
) {
835 scoped_ptr
<RequestSender::ScopedTabID
> scoped_tab_id
;
836 std::map
<int, int>::const_iterator it
=
837 port_to_tab_id_map_
.find(target_port_id
);
838 if (it
!= port_to_tab_id_map_
.end()) {
840 new RequestSender::ScopedTabID(request_sender(), it
->second
));
843 MessagingBindings::DeliverMessage(*script_context_set_
, target_port_id
,
845 NULL
); // All render frames.
848 void Dispatcher::OnDispatchOnConnect(
850 const std::string
& channel_name
,
851 const ExtensionMsg_TabConnectionInfo
& source
,
852 const ExtensionMsg_ExternalConnectionInfo
& info
,
853 const std::string
& tls_channel_id
) {
854 DCHECK(!ContainsKey(port_to_tab_id_map_
, target_port_id
));
855 DCHECK_EQ(1, target_port_id
% 2); // target renderer ports have odd IDs.
856 int sender_tab_id
= -1;
857 source
.tab
.GetInteger("id", &sender_tab_id
);
858 port_to_tab_id_map_
[target_port_id
] = sender_tab_id
;
860 MessagingBindings::DispatchOnConnect(*script_context_set_
, target_port_id
,
861 channel_name
, source
, info
,
863 NULL
); // All render frames.
866 void Dispatcher::OnDispatchOnDisconnect(int port_id
,
867 const std::string
& error_message
) {
868 MessagingBindings::DispatchOnDisconnect(*script_context_set_
, port_id
,
870 NULL
); // All render frames.
873 void Dispatcher::OnLoaded(
874 const std::vector
<ExtensionMsg_Loaded_Params
>& loaded_extensions
) {
875 for (const auto& param
: loaded_extensions
) {
877 scoped_refptr
<const Extension
> extension
= param
.ConvertToExtension(&error
);
878 if (!extension
.get()) {
879 NOTREACHED() << error
;
880 // Note: in tests |param.id| has been observed to be empty (see comment
881 // just below) so this isn't all that reliable.
882 extension_load_errors_
[param
.id
] = error
;
886 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
887 // could be) and uses extension->id() not params.id:
888 // 1. For some reason params.id can be empty. I've only seen it with
889 // the webstore extension, in tests, and I've spent some time trying to
890 // figure out why - but cost/benefit won.
891 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
892 // Dispatcher is attached to a RenderThread. Presumably there is a
893 // mismatch there. In theory one would think it's possible for the
894 // browser to figure this out itself - but again, cost/benefit.
895 if (!extensions_
.Contains(extension
->id()))
896 extensions_
.Insert(extension
);
899 // Update the available bindings for all contexts. These may have changed if
900 // an externally_connectable extension was loaded that can connect to an
905 void Dispatcher::OnMessageInvoke(const std::string
& extension_id
,
906 const std::string
& module_name
,
907 const std::string
& function_name
,
908 const base::ListValue
& args
,
910 InvokeModuleSystemMethod(
911 NULL
, extension_id
, module_name
, function_name
, args
, user_gesture
);
914 void Dispatcher::OnSetChannel(int channel
) {
915 delegate_
->SetChannel(channel
);
916 AddChannelSpecificFeatures();
919 void Dispatcher::OnSetFunctionNames(const std::vector
<std::string
>& names
) {
920 function_names_
.clear();
921 for (size_t i
= 0; i
< names
.size(); ++i
)
922 function_names_
.insert(names
[i
]);
925 void Dispatcher::OnSetScriptingWhitelist(
926 const ExtensionsClient::ScriptingWhitelist
& extension_ids
) {
927 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids
);
930 void Dispatcher::OnSetSystemFont(const std::string
& font_family
,
931 const std::string
& font_size
) {
932 system_font_family_
= font_family
;
933 system_font_size_
= font_size
;
936 void Dispatcher::OnShouldSuspend(const std::string
& extension_id
,
937 uint64 sequence_id
) {
938 RenderThread::Get()->Send(
939 new ExtensionHostMsg_ShouldSuspendAck(extension_id
, sequence_id
));
942 void Dispatcher::OnSuspend(const std::string
& extension_id
) {
943 // Dispatch the suspend event. This doesn't go through the standard event
944 // dispatch machinery because it requires special handling. We need to let
945 // the browser know when we are starting and stopping the event dispatch, so
946 // that it still considers the extension idle despite any activity the suspend
948 DispatchEvent(extension_id
, kOnSuspendEvent
);
949 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id
));
952 void Dispatcher::OnTransferBlobs(const std::vector
<std::string
>& blob_uuids
) {
953 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids
));
956 void Dispatcher::OnUnloaded(const std::string
& id
) {
957 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
958 // to CHECK here rather than guarding.
959 if (!extensions_
.Remove(id
))
962 active_extension_ids_
.erase(id
);
964 script_injection_manager_
->OnExtensionUnloaded(id
);
966 // If the extension is later reloaded with a different set of permissions,
967 // we'd like it to get a new isolated world ID, so that it can pick up the
968 // changed origin whitelist.
969 ScriptInjection::RemoveIsolatedWorld(id
);
971 // Invalidate all of the contexts that were removed.
972 // TODO(kalman): add an invalidation observer interface to ScriptContext.
973 std::set
<ScriptContext
*> removed_contexts
=
974 script_context_set_
->OnExtensionUnloaded(id
);
975 for (ScriptContext
* context
: removed_contexts
) {
976 request_sender_
->InvalidateSource(context
);
979 // Update the available bindings for the remaining contexts. These may have
980 // changed if an externally_connectable extension is unloaded and a webpage
981 // is no longer accessible.
984 // Invalidates the messages map for the extension in case the extension is
985 // reloaded with a new messages map.
986 EraseL10nMessagesMap(id
);
988 // We don't do anything with existing platform-app stylesheets. They will
989 // stay resident, but the URL pattern corresponding to the unloaded
990 // extension's URL just won't match anything anymore.
993 void Dispatcher::OnUpdatePermissions(
994 const ExtensionMsg_UpdatePermissions_Params
& params
) {
995 const Extension
* extension
= extensions_
.GetByID(params
.extension_id
);
999 scoped_refptr
<const PermissionSet
> active
=
1000 params
.active_permissions
.ToPermissionSet();
1001 scoped_refptr
<const PermissionSet
> withheld
=
1002 params
.withheld_permissions
.ToPermissionSet();
1004 if (is_webkit_initialized_
) {
1005 UpdateOriginPermissions(
1007 extension
->permissions_data()->GetEffectiveHostPermissions(),
1008 active
->effective_hosts());
1011 extension
->permissions_data()->SetPermissions(active
, withheld
);
1012 UpdateBindings(extension
->id());
1015 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL
& visible_url
,
1016 const std::string
& extension_id
,
1017 const URLPatternSet
& new_hosts
,
1018 bool update_origin_whitelist
,
1020 const Extension
* extension
= extensions_
.GetByID(extension_id
);
1024 URLPatternSet old_effective
=
1025 extension
->permissions_data()->GetEffectiveHostPermissions();
1026 extension
->permissions_data()->UpdateTabSpecificPermissions(
1028 new extensions::PermissionSet(extensions::APIPermissionSet(),
1029 extensions::ManifestPermissionSet(),
1031 extensions::URLPatternSet()));
1033 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1034 UpdateOriginPermissions(
1037 extension
->permissions_data()->GetEffectiveHostPermissions());
1041 void Dispatcher::OnClearTabSpecificPermissions(
1042 const std::vector
<std::string
>& extension_ids
,
1043 bool update_origin_whitelist
,
1045 for (const std::string
& id
: extension_ids
) {
1046 const Extension
* extension
= extensions_
.GetByID(id
);
1048 URLPatternSet old_effective
=
1049 extension
->permissions_data()->GetEffectiveHostPermissions();
1050 extension
->permissions_data()->ClearTabSpecificPermissions(tab_id
);
1051 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1052 UpdateOriginPermissions(
1055 extension
->permissions_data()->GetEffectiveHostPermissions());
1061 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used
) {
1062 webrequest_used_
= webrequest_used
;
1065 void Dispatcher::OnUserScriptsUpdated(const std::set
<HostID
>& changed_hosts
,
1066 const std::vector
<UserScript
*>& scripts
) {
1067 UpdateActiveExtensions();
1070 void Dispatcher::UpdateActiveExtensions() {
1071 std::set
<std::string
> active_extensions
= active_extension_ids_
;
1072 user_script_set_manager_
->GetAllActiveExtensionIds(&active_extensions
);
1073 delegate_
->OnActiveExtensionsUpdated(active_extensions
);
1076 void Dispatcher::InitOriginPermissions(const Extension
* extension
) {
1077 delegate_
->InitOriginPermissions(extension
,
1078 IsExtensionActive(extension
->id()));
1079 UpdateOriginPermissions(
1081 URLPatternSet(), // No old permissions.
1082 extension
->permissions_data()->GetEffectiveHostPermissions());
1085 void Dispatcher::UpdateOriginPermissions(const GURL
& extension_url
,
1086 const URLPatternSet
& old_patterns
,
1087 const URLPatternSet
& new_patterns
) {
1088 static const char* kSchemes
[] = {
1092 content::kChromeUIScheme
,
1094 #if defined(OS_CHROMEOS)
1095 content::kExternalFileScheme
,
1097 extensions::kExtensionScheme
,
1099 for (size_t i
= 0; i
< arraysize(kSchemes
); ++i
) {
1100 const char* scheme
= kSchemes
[i
];
1101 // Remove all old patterns...
1102 for (URLPatternSet::const_iterator pattern
= old_patterns
.begin();
1103 pattern
!= old_patterns
.end(); ++pattern
) {
1104 if (pattern
->MatchesScheme(scheme
)) {
1105 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1107 WebString::fromUTF8(scheme
),
1108 WebString::fromUTF8(pattern
->host()),
1109 pattern
->match_subdomains());
1112 // ...And add the new ones.
1113 for (URLPatternSet::const_iterator pattern
= new_patterns
.begin();
1114 pattern
!= new_patterns
.end(); ++pattern
) {
1115 if (pattern
->MatchesScheme(scheme
)) {
1116 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1118 WebString::fromUTF8(scheme
),
1119 WebString::fromUTF8(pattern
->host()),
1120 pattern
->match_subdomains());
1126 void Dispatcher::EnableCustomElementWhiteList() {
1127 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1128 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1129 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1130 blink::WebCustomElement::addEmbedderCustomElementName(
1131 "extensionoptionsbrowserplugin");
1132 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1133 blink::WebCustomElement::addEmbedderCustomElementName(
1134 "extensionviewbrowserplugin");
1135 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1136 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1137 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1138 blink::WebCustomElement::addEmbedderCustomElementName(
1139 "surfaceviewbrowserplugin");
1142 void Dispatcher::UpdateBindings(const std::string
& extension_id
) {
1143 script_context_set().ForEach(extension_id
,
1144 base::Bind(&Dispatcher::UpdateBindingsForContext
,
1145 base::Unretained(this)));
1148 void Dispatcher::UpdateBindingsForContext(ScriptContext
* context
) {
1149 v8::HandleScope
handle_scope(context
->isolate());
1150 v8::Context::Scope
context_scope(context
->v8_context());
1152 // TODO(kalman): Make the bindings registration have zero overhead then run
1153 // the same code regardless of context type.
1154 switch (context
->context_type()) {
1155 case Feature::UNSPECIFIED_CONTEXT
:
1156 case Feature::WEB_PAGE_CONTEXT
:
1157 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
1158 // Hard-code registration of any APIs that are exposed to webpage-like
1159 // contexts, because it's too expensive to run the full bindings code.
1160 // All of the same permission checks will still apply.
1161 if (context
->GetAvailability("app").is_available())
1162 RegisterBinding("app", context
);
1163 if (context
->GetAvailability("webstore").is_available())
1164 RegisterBinding("webstore", context
);
1165 if (context
->GetAvailability("dashboardPrivate").is_available())
1166 RegisterBinding("dashboardPrivate", context
);
1167 if (IsRuntimeAvailableToContext(context
))
1168 RegisterBinding("runtime", context
);
1169 UpdateContentCapabilities(context
);
1172 case Feature::BLESSED_EXTENSION_CONTEXT
:
1173 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
1174 case Feature::CONTENT_SCRIPT_CONTEXT
:
1175 case Feature::WEBUI_CONTEXT
: {
1176 // Extension context; iterate through all the APIs and bind the available
1178 const FeatureProvider
* api_feature_provider
=
1179 FeatureProvider::GetAPIFeatures();
1180 const std::vector
<std::string
>& apis
=
1181 api_feature_provider
->GetAllFeatureNames();
1182 for (const std::string
& api_name
: apis
) {
1183 Feature
* feature
= api_feature_provider
->GetFeature(api_name
);
1186 // Internal APIs are included via require(api_name) from internal code
1187 // rather than chrome[api_name].
1188 if (feature
->IsInternal())
1191 // If this API has a parent feature (and isn't marked 'noparent'),
1192 // then this must be a function or event, so we should not register.
1193 if (api_feature_provider
->GetParent(feature
) != NULL
)
1196 // Skip chrome.test if this isn't a test.
1197 if (api_name
== "test" &&
1198 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1199 ::switches::kTestType
)) {
1203 if (context
->IsAnyFeatureAvailableToContext(*feature
))
1204 RegisterBinding(api_name
, context
);
1211 void Dispatcher::RegisterBinding(const std::string
& api_name
,
1212 ScriptContext
* context
) {
1213 std::string bind_name
;
1214 v8::Local
<v8::Object
> bind_object
=
1215 GetOrCreateBindObjectIfAvailable(api_name
, &bind_name
, context
);
1217 // Empty if the bind object failed to be created, probably because the
1218 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1219 if (bind_object
.IsEmpty())
1222 v8::Local
<v8::String
> v8_bind_name
=
1223 v8::String::NewFromUtf8(context
->isolate(), bind_name
.c_str());
1224 if (bind_object
->HasRealNamedProperty(v8_bind_name
)) {
1225 // The bind object may already have the property if the API has been
1226 // registered before (or if the extension has put something there already,
1229 // In the former case, we need to re-register the bindings for the APIs
1230 // which the extension now has permissions for (if any), but not touch any
1231 // others so that we don't destroy state such as event listeners.
1233 // TODO(kalman): Only register available APIs to make this all moot.
1234 if (bind_object
->HasRealNamedCallbackProperty(v8_bind_name
))
1235 return; // lazy binding still there, nothing to do
1236 if (bind_object
->Get(v8_bind_name
)->IsObject())
1237 return; // binding has already been fully installed
1240 ModuleSystem
* module_system
= context
->module_system();
1241 if (!source_map_
.Contains(api_name
)) {
1242 module_system
->RegisterNativeHandler(
1244 scoped_ptr
<NativeHandler
>(new BindingGeneratingNativeHandler(
1245 context
, api_name
, "binding")));
1246 module_system
->SetNativeLazyField(
1247 bind_object
, bind_name
, api_name
, "binding");
1249 module_system
->SetLazyField(bind_object
, bind_name
, api_name
, "binding");
1253 // NOTE: please use the naming convention "foo_natives" for these.
1254 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
1255 ScriptContext
* context
) {
1256 RegisterNativeHandlers(module_system
,
1259 request_sender_
.get(),
1260 v8_schema_registry_
.get());
1261 const Extension
* extension
= context
->extension();
1262 int manifest_version
= extension
? extension
->manifest_version() : 1;
1263 bool is_component_extension
=
1264 extension
&& Manifest::IsComponentLocation(extension
->location());
1265 bool send_request_disabled
=
1266 (extension
&& Manifest::IsUnpackedLocation(extension
->location()) &&
1267 BackgroundInfo::HasLazyBackgroundPage(extension
));
1268 module_system
->RegisterNativeHandler(
1270 scoped_ptr
<NativeHandler
>(new ProcessInfoNativeHandler(
1272 context
->GetExtensionID(),
1273 context
->GetContextTypeDescription(),
1274 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1275 is_component_extension
,
1277 send_request_disabled
)));
1279 delegate_
->RegisterNativeHandlers(this, module_system
, context
);
1282 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext
* context
) {
1283 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1284 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1287 for (const auto& extension
: extensions_
) {
1288 ExternallyConnectableInfo
* info
= static_cast<ExternallyConnectableInfo
*>(
1289 extension
->GetManifestData(manifest_keys::kExternallyConnectable
));
1290 if (info
&& info
->matches
.MatchesURL(context
->GetURL()))
1296 void Dispatcher::UpdateContentCapabilities(ScriptContext
* context
) {
1297 APIPermissionSet permissions
;
1298 for (const auto& extension
: extensions_
) {
1299 const ContentCapabilitiesInfo
& info
=
1300 ContentCapabilitiesInfo::Get(extension
.get());
1301 if (info
.url_patterns
.MatchesURL(context
->GetURL())) {
1302 APIPermissionSet new_permissions
;
1303 APIPermissionSet::Union(permissions
, info
.permissions
, &new_permissions
);
1304 permissions
= new_permissions
;
1307 context
->SetContentCapabilities(permissions
);
1310 void Dispatcher::PopulateSourceMap() {
1311 const std::vector
<std::pair
<std::string
, int> > resources
= GetJsResources();
1312 for (std::vector
<std::pair
<std::string
, int> >::const_iterator resource
=
1314 resource
!= resources
.end();
1316 source_map_
.RegisterSource(resource
->first
, resource
->second
);
1318 delegate_
->PopulateSourceMap(&source_map_
);
1321 bool Dispatcher::IsWithinPlatformApp() {
1322 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
1323 iter
!= active_extension_ids_
.end();
1325 const Extension
* extension
= extensions_
.GetByID(*iter
);
1326 if (extension
&& extension
->is_platform_app())
1332 v8::Local
<v8::Object
> Dispatcher::GetOrCreateObject(
1333 const v8::Local
<v8::Object
>& object
,
1334 const std::string
& field
,
1335 v8::Isolate
* isolate
) {
1336 v8::Local
<v8::String
> key
= v8::String::NewFromUtf8(isolate
, field
.c_str());
1337 // If the object has a callback property, it is assumed it is an unavailable
1338 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1340 if (object
->HasRealNamedCallbackProperty(key
)) {
1341 object
->Delete(key
);
1342 } else if (object
->HasRealNamedProperty(key
)) {
1343 v8::Local
<v8::Value
> value
= object
->Get(key
);
1344 CHECK(value
->IsObject());
1345 return v8::Local
<v8::Object
>::Cast(value
);
1348 v8::Local
<v8::Object
> new_object
= v8::Object::New(isolate
);
1349 object
->Set(key
, new_object
);
1353 v8::Local
<v8::Object
> Dispatcher::GetOrCreateBindObjectIfAvailable(
1354 const std::string
& api_name
,
1355 std::string
* bind_name
,
1356 ScriptContext
* context
) {
1357 std::vector
<std::string
> split
;
1358 base::SplitString(api_name
, '.', &split
);
1360 v8::Local
<v8::Object
> bind_object
;
1362 // Check if this API has an ancestor. If the API's ancestor is available and
1363 // the API is not available, don't install the bindings for this API. If
1364 // the API is available and its ancestor is not, delete the ancestor and
1365 // install the bindings for the API. This is to prevent loading the ancestor
1366 // API schema if it will not be needed.
1369 // If app is available and app.window is not, just install app.
1370 // If app.window is available and app is not, delete app and install
1371 // app.window on a new object so app does not have to be loaded.
1372 const FeatureProvider
* api_feature_provider
=
1373 FeatureProvider::GetAPIFeatures();
1374 std::string ancestor_name
;
1375 bool only_ancestor_available
= false;
1377 for (size_t i
= 0; i
< split
.size() - 1; ++i
) {
1378 ancestor_name
+= (i
? "." : "") + split
[i
];
1379 if (api_feature_provider
->GetFeature(ancestor_name
) &&
1380 context
->GetAvailability(ancestor_name
).is_available() &&
1381 !context
->GetAvailability(api_name
).is_available()) {
1382 only_ancestor_available
= true;
1386 if (bind_object
.IsEmpty()) {
1387 bind_object
= AsObjectOrEmpty(GetOrCreateChrome(context
));
1388 if (bind_object
.IsEmpty())
1389 return v8::Local
<v8::Object
>();
1391 bind_object
= GetOrCreateObject(bind_object
, split
[i
], context
->isolate());
1394 if (only_ancestor_available
)
1395 return v8::Local
<v8::Object
>();
1398 *bind_name
= split
.back();
1400 return bind_object
.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context
))
1404 void Dispatcher::RequireGuestViewModules(ScriptContext
* context
) {
1405 Feature::Context context_type
= context
->context_type();
1406 ModuleSystem
* module_system
= context
->module_system();
1409 if (context
->GetAvailability("appViewEmbedderInternal").is_available()) {
1410 module_system
->Require("appView");
1413 // Require ExtensionOptions.
1414 if (context
->GetAvailability("extensionOptionsInternal").is_available()) {
1415 module_system
->Require("extensionOptions");
1416 module_system
->Require("extensionOptionsAttributes");
1419 // Require ExtensionView.
1420 if (context
->GetAvailability("extensionViewInternal").is_available()) {
1421 module_system
->Require("extensionView");
1422 module_system
->Require("extensionViewApiMethods");
1423 module_system
->Require("extensionViewAttributes");
1426 // Require SurfaceView.
1427 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1428 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1429 module_system
->Require("surfaceWorker");
1433 if (context
->GetAvailability("webViewInternal").is_available()) {
1434 module_system
->Require("webView");
1435 module_system
->Require("webViewApiMethods");
1436 module_system
->Require("webViewAttributes");
1438 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1439 module_system
->Require("webViewIframe");
1443 // The "guestViewDeny" module must always be loaded last. It registers
1444 // error-providing custom elements for the GuestView types that are not
1445 // available, and thus all of those types must have been checked and loaded
1446 // (or not loaded) beforehand.
1447 if (context_type
== Feature::BLESSED_EXTENSION_CONTEXT
) {
1448 module_system
->Require("guestViewDeny");
1452 void Dispatcher::AddChannelSpecificFeatures() {
1453 // chrome-extension: resources should be allowed to register a Service Worker.
1454 if (FeatureProvider::GetBehaviorFeature(BehaviorFeature::kServiceWorker
)
1455 ->IsAvailableToEnvironment()
1457 WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
1458 WebString::fromUTF8(kExtensionScheme
));
1461 } // namespace extensions