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/script_context.h"
77 #include "extensions/renderer/script_context_set.h"
78 #include "extensions/renderer/script_injection.h"
79 #include "extensions/renderer/script_injection_manager.h"
80 #include "extensions/renderer/send_request_natives.h"
81 #include "extensions/renderer/set_icon_natives.h"
82 #include "extensions/renderer/test_features_native_handler.h"
83 #include "extensions/renderer/user_gestures_native_handler.h"
84 #include "extensions/renderer/utils_native_handler.h"
85 #include "extensions/renderer/v8_context_native_handler.h"
86 #include "grit/extensions_renderer_resources.h"
87 #include "third_party/WebKit/public/platform/WebString.h"
88 #include "third_party/WebKit/public/platform/WebURLRequest.h"
89 #include "third_party/WebKit/public/web/WebCustomElement.h"
90 #include "third_party/WebKit/public/web/WebDataSource.h"
91 #include "third_party/WebKit/public/web/WebDocument.h"
92 #include "third_party/WebKit/public/web/WebFrame.h"
93 #include "third_party/WebKit/public/web/WebLocalFrame.h"
94 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
95 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
96 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
97 #include "third_party/WebKit/public/web/WebView.h"
98 #include "third_party/mojo/src/mojo/public/js/constants.h"
99 #include "ui/base/layout.h"
100 #include "ui/base/resource/resource_bundle.h"
101 #include "v8/include/v8.h"
103 using base::UserMetricsAction
;
104 using blink::WebDataSource
;
105 using blink::WebDocument
;
106 using blink::WebScopedUserGesture
;
107 using blink::WebSecurityPolicy
;
108 using blink::WebString
;
109 using blink::WebVector
;
110 using blink::WebView
;
111 using content::RenderThread
;
113 namespace extensions
{
117 static const int64 kInitialExtensionIdleHandlerDelayMs
= 5 * 1000;
118 static const int64 kMaxExtensionIdleHandlerDelayMs
= 5 * 60 * 1000;
119 static const char kEventDispatchFunction
[] = "dispatchEvent";
120 static const char kOnSuspendEvent
[] = "runtime.onSuspend";
121 static const char kOnSuspendCanceledEvent
[] = "runtime.onSuspendCanceled";
123 // Returns the global value for "chrome" from |context|. If one doesn't exist
124 // creates a new object for it.
126 // Note that this isn't necessarily an object, since webpages can write, for
127 // example, "window.chrome = true".
128 v8::Local
<v8::Value
> GetOrCreateChrome(ScriptContext
* context
) {
129 v8::Local
<v8::String
> chrome_string(
130 v8::String::NewFromUtf8(context
->isolate(), "chrome"));
131 v8::Local
<v8::Object
> global(context
->v8_context()->Global());
132 v8::Local
<v8::Value
> chrome(global
->Get(chrome_string
));
133 if (chrome
->IsUndefined()) {
134 chrome
= v8::Object::New(context
->isolate());
135 global
->Set(chrome_string
, chrome
);
140 // Returns |value| cast to an object if possible, else an empty handle.
141 v8::Local
<v8::Object
> AsObjectOrEmpty(v8::Local
<v8::Value
> value
) {
142 return value
->IsObject() ? value
.As
<v8::Object
>() : v8::Local
<v8::Object
>();
145 // Calls a method |method_name| in a module |module_name| belonging to the
146 // module system from |context|. Intended as a callback target from
147 // ScriptContextSet::ForEach.
148 void CallModuleMethod(const std::string
& module_name
,
149 const std::string
& method_name
,
150 const base::ListValue
* args
,
151 ScriptContext
* context
) {
152 v8::HandleScope
handle_scope(context
->isolate());
153 v8::Context::Scope
context_scope(context
->v8_context());
155 scoped_ptr
<content::V8ValueConverter
> converter(
156 content::V8ValueConverter::create());
158 std::vector
<v8::Local
<v8::Value
>> arguments
;
159 for (base::ListValue::const_iterator it
= args
->begin(); it
!= args
->end();
161 arguments
.push_back(converter
->ToV8Value(*it
, context
->v8_context()));
164 context
->module_system()->CallModuleMethod(
165 module_name
, method_name
, &arguments
);
168 // This handles the "chrome." root API object in script contexts.
169 class ChromeNativeHandler
: public ObjectBackedNativeHandler
{
171 explicit ChromeNativeHandler(ScriptContext
* context
)
172 : ObjectBackedNativeHandler(context
) {
175 base::Bind(&ChromeNativeHandler::GetChrome
, base::Unretained(this)));
178 void GetChrome(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
179 args
.GetReturnValue().Set(GetOrCreateChrome(context()));
185 Dispatcher::Dispatcher(DispatcherDelegate
* delegate
)
186 : delegate_(delegate
),
187 content_watcher_(new ContentWatcher()),
188 source_map_(&ResourceBundle::GetSharedInstance()),
189 v8_schema_registry_(new V8SchemaRegistry
),
190 is_webkit_initialized_(false),
191 user_script_set_manager_observer_(this),
192 webrequest_used_(false) {
193 const base::CommandLine
& command_line
=
194 *(base::CommandLine::ForCurrentProcess());
195 set_idle_notifications_
=
196 command_line
.HasSwitch(switches::kExtensionProcess
) ||
197 command_line
.HasSwitch(::switches::kSingleProcess
);
199 if (set_idle_notifications_
) {
200 RenderThread::Get()->SetIdleNotificationDelayInMs(
201 kInitialExtensionIdleHandlerDelayMs
);
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::WebLocalFrame
* 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 // In testing, the document lifetime events can happen after the render
365 // process shutdown event.
366 // See: http://crbug.com/21508 and http://crbug.com/500851
367 if (content_watcher_
) {
368 content_watcher_
->DidCreateDocumentElement(frame
);
372 void Dispatcher::OnExtensionResponse(int request_id
,
374 const base::ListValue
& response
,
375 const std::string
& error
) {
376 request_sender_
->HandleResponse(request_id
, success
, response
, error
);
379 void Dispatcher::DispatchEvent(const std::string
& extension_id
,
380 const std::string
& event_name
) const {
381 base::ListValue args
;
382 args
.Set(0, new base::StringValue(event_name
));
383 args
.Set(1, new base::ListValue());
385 // Needed for Windows compilation, since kEventBindings is declared extern.
386 const char* local_event_bindings
= kEventBindings
;
387 script_context_set_
->ForEach(
388 extension_id
, base::Bind(&CallModuleMethod
, local_event_bindings
,
389 kEventDispatchFunction
, &args
));
392 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame
* render_frame
,
393 const std::string
& extension_id
,
394 const std::string
& module_name
,
395 const std::string
& function_name
,
396 const base::ListValue
& args
,
398 scoped_ptr
<WebScopedUserGesture
> web_user_gesture
;
400 web_user_gesture
.reset(new WebScopedUserGesture
);
402 script_context_set_
->ForEach(
403 extension_id
, render_frame
,
404 base::Bind(&CallModuleMethod
, module_name
, function_name
, &args
));
406 // Reset the idle handler each time there's any activity like event or message
407 // dispatch, for which Invoke is the chokepoint.
408 if (set_idle_notifications_
) {
409 RenderThread::Get()->ScheduleIdleHandler(
410 kInitialExtensionIdleHandlerDelayMs
);
413 // Tell the browser process when an event has been dispatched with a lazy
414 // background page active.
415 const Extension
* extension
= extensions_
.GetByID(extension_id
);
416 if (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
417 module_name
== kEventBindings
&&
418 function_name
== kEventDispatchFunction
) {
419 content::RenderFrame
* background_frame
=
420 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id
);
421 if (background_frame
) {
423 args
.GetInteger(3, &message_id
);
424 background_frame
->Send(new ExtensionHostMsg_EventAck(
425 background_frame
->GetRoutingID(), message_id
));
430 void Dispatcher::ClearPortData(int port_id
) {
431 // Only the target port side has entries in |port_to_tab_id_map_|. If
432 // |port_id| is a source port, std::map::erase() will just silently fail
434 port_to_tab_id_map_
.erase(port_id
);
438 std::vector
<std::pair
<std::string
, int> > Dispatcher::GetJsResources() {
439 std::vector
<std::pair
<std::string
, int> > resources
;
442 resources
.push_back(std::make_pair("appView", IDR_APP_VIEW_JS
));
443 resources
.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER
));
444 resources
.push_back(std::make_pair(kEventBindings
, IDR_EVENT_BINDINGS_JS
));
445 resources
.push_back(std::make_pair("extensionOptions",
446 IDR_EXTENSION_OPTIONS_JS
));
447 resources
.push_back(std::make_pair("extensionOptionsAttributes",
448 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS
));
449 resources
.push_back(std::make_pair("extensionOptionsConstants",
450 IDR_EXTENSION_OPTIONS_CONSTANTS_JS
));
451 resources
.push_back(std::make_pair("extensionOptionsEvents",
452 IDR_EXTENSION_OPTIONS_EVENTS_JS
));
453 resources
.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS
));
454 resources
.push_back(std::make_pair("extensionViewApiMethods",
455 IDR_EXTENSION_VIEW_API_METHODS_JS
));
456 resources
.push_back(std::make_pair("extensionViewAttributes",
457 IDR_EXTENSION_VIEW_ATTRIBUTES_JS
));
458 resources
.push_back(std::make_pair("extensionViewConstants",
459 IDR_EXTENSION_VIEW_CONSTANTS_JS
));
460 resources
.push_back(std::make_pair("extensionViewEvents",
461 IDR_EXTENSION_VIEW_EVENTS_JS
));
462 resources
.push_back(std::make_pair(
463 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
464 resources
.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS
));
465 resources
.push_back(std::make_pair("guestViewAttributes",
466 IDR_GUEST_VIEW_ATTRIBUTES_JS
));
467 resources
.push_back(std::make_pair("guestViewContainer",
468 IDR_GUEST_VIEW_CONTAINER_JS
));
469 resources
.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS
));
470 resources
.push_back(std::make_pair("guestViewEvents",
471 IDR_GUEST_VIEW_EVENTS_JS
));
473 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
474 resources
.push_back(std::make_pair("guestViewIframe",
475 IDR_GUEST_VIEW_IFRAME_JS
));
476 resources
.push_back(std::make_pair("guestViewIframeContainer",
477 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS
));
480 resources
.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS
));
481 resources
.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS
));
482 resources
.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS
));
483 resources
.push_back(std::make_pair("messaging", IDR_MESSAGING_JS
));
484 resources
.push_back(std::make_pair("messaging_utils",
485 IDR_MESSAGING_UTILS_JS
));
486 resources
.push_back(std::make_pair(kSchemaUtils
, IDR_SCHEMA_UTILS_JS
));
487 resources
.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS
));
488 resources
.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS
));
489 resources
.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS
));
490 resources
.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS
));
492 std::make_pair("test_environment_specific_bindings",
493 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS
));
494 resources
.push_back(std::make_pair("uncaught_exception_handler",
495 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS
));
496 resources
.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS
));
497 resources
.push_back(std::make_pair("utils", IDR_UTILS_JS
));
498 resources
.push_back(std::make_pair("webRequest",
499 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS
));
501 std::make_pair("webRequestInternal",
502 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS
));
503 // Note: webView not webview so that this doesn't interfere with the
504 // chrome.webview API bindings.
505 resources
.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS
));
506 resources
.push_back(std::make_pair("webViewActionRequests",
507 IDR_WEB_VIEW_ACTION_REQUESTS_JS
));
508 resources
.push_back(std::make_pair("webViewApiMethods",
509 IDR_WEB_VIEW_API_METHODS_JS
));
510 resources
.push_back(std::make_pair("webViewAttributes",
511 IDR_WEB_VIEW_ATTRIBUTES_JS
));
512 resources
.push_back(std::make_pair("webViewConstants",
513 IDR_WEB_VIEW_CONSTANTS_JS
));
514 resources
.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS
));
515 resources
.push_back(std::make_pair("webViewInternal",
516 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
517 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
518 resources
.push_back(std::make_pair("webViewIframe",
519 IDR_WEB_VIEW_IFRAME_JS
));
522 std::make_pair(mojo::kBindingsModuleName
, IDR_MOJO_BINDINGS_JS
));
524 std::make_pair(mojo::kBufferModuleName
, IDR_MOJO_BUFFER_JS
));
526 std::make_pair(mojo::kCodecModuleName
, IDR_MOJO_CODEC_JS
));
528 std::make_pair(mojo::kConnectionModuleName
, IDR_MOJO_CONNECTION_JS
));
530 std::make_pair(mojo::kConnectorModuleName
, IDR_MOJO_CONNECTOR_JS
));
532 std::make_pair(mojo::kRouterModuleName
, IDR_MOJO_ROUTER_JS
));
534 std::make_pair(mojo::kUnicodeModuleName
, IDR_MOJO_UNICODE_JS
));
536 std::make_pair(mojo::kValidatorModuleName
, IDR_MOJO_VALIDATOR_JS
));
537 resources
.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS
));
538 resources
.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS
));
539 resources
.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS
));
540 resources
.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS
));
541 resources
.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
542 IDR_KEEP_ALIVE_MOJOM_JS
));
543 resources
.push_back(std::make_pair("device/serial/data_stream.mojom",
544 IDR_DATA_STREAM_MOJOM_JS
));
546 std::make_pair("device/serial/data_stream_serialization.mojom",
547 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS
));
548 resources
.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS
));
550 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS
));
554 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS
));
556 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS
));
558 std::make_pair("declarativeWebRequest",
559 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS
));
561 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS
));
563 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS
));
565 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS
));
566 resources
.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS
));
567 resources
.push_back(std::make_pair(
568 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS
));
569 resources
.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
570 IDR_MIME_HANDLER_MOJOM_JS
));
572 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS
));
574 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS
));
575 resources
.push_back(std::make_pair("printerProvider",
576 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS
));
578 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS
));
579 resources
.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS
));
581 std::make_pair("webViewRequest",
582 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS
));
583 resources
.push_back(std::make_pair("binding", IDR_BINDING_JS
));
585 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
586 switches::kEnableMojoSerialService
)) {
588 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS
));
590 resources
.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS
));
592 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS
));
593 resources
.push_back(std::make_pair("device/serial/serial_serialization.mojom",
594 IDR_SERIAL_SERIALIZATION_MOJOM_JS
));
596 // Custom types sources.
597 resources
.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS
));
599 // Platform app sources that are not API-specific..
600 resources
.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS
));
602 #if defined(ENABLE_MEDIA_ROUTER)
604 std::make_pair("chrome/browser/media/router/media_router.mojom",
605 IDR_MEDIA_ROUTER_MOJOM_JS
));
607 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS
));
608 #endif // defined(ENABLE_MEDIA_ROUTER)
613 // NOTE: please use the naming convention "foo_natives" for these.
615 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
616 ScriptContext
* context
,
617 Dispatcher
* dispatcher
,
618 RequestSender
* request_sender
,
619 V8SchemaRegistry
* v8_schema_registry
) {
620 module_system
->RegisterNativeHandler(
621 "chrome", scoped_ptr
<NativeHandler
>(new ChromeNativeHandler(context
)));
622 module_system
->RegisterNativeHandler(
623 "lazy_background_page",
624 scoped_ptr
<NativeHandler
>(new LazyBackgroundPageNativeHandler(context
)));
625 module_system
->RegisterNativeHandler(
626 "logging", scoped_ptr
<NativeHandler
>(new LoggingNativeHandler(context
)));
627 module_system
->RegisterNativeHandler("schema_registry",
628 v8_schema_registry
->AsNativeHandler());
629 module_system
->RegisterNativeHandler(
630 "print", scoped_ptr
<NativeHandler
>(new PrintNativeHandler(context
)));
631 module_system
->RegisterNativeHandler(
633 scoped_ptr
<NativeHandler
>(new TestFeaturesNativeHandler(context
)));
634 module_system
->RegisterNativeHandler(
636 scoped_ptr
<NativeHandler
>(new UserGesturesNativeHandler(context
)));
637 module_system
->RegisterNativeHandler(
638 "utils", scoped_ptr
<NativeHandler
>(new UtilsNativeHandler(context
)));
639 module_system
->RegisterNativeHandler(
641 scoped_ptr
<NativeHandler
>(
642 new V8ContextNativeHandler(context
, dispatcher
)));
643 module_system
->RegisterNativeHandler(
644 "event_natives", scoped_ptr
<NativeHandler
>(new EventBindings(context
)));
645 module_system
->RegisterNativeHandler(
647 scoped_ptr
<NativeHandler
>(MessagingBindings::Get(dispatcher
, context
)));
648 module_system
->RegisterNativeHandler(
650 scoped_ptr
<NativeHandler
>(
651 new ApiDefinitionsNatives(dispatcher
, context
)));
652 module_system
->RegisterNativeHandler(
654 scoped_ptr
<NativeHandler
>(
655 new SendRequestNatives(request_sender
, context
)));
656 module_system
->RegisterNativeHandler(
658 scoped_ptr
<NativeHandler
>(new SetIconNatives(context
)));
659 module_system
->RegisterNativeHandler(
661 scoped_ptr
<NativeHandler
>(new APIActivityLogger(context
)));
662 module_system
->RegisterNativeHandler(
663 "renderFrameObserverNatives",
664 scoped_ptr
<NativeHandler
>(new RenderFrameObserverNatives(context
)));
666 // Natives used by multiple APIs.
667 module_system
->RegisterNativeHandler(
668 "file_system_natives",
669 scoped_ptr
<NativeHandler
>(new FileSystemNatives(context
)));
672 module_system
->RegisterNativeHandler(
674 scoped_ptr
<NativeHandler
>(new AppRuntimeCustomBindings(context
)));
675 // |dispatcher| is null in unit tests.
676 const ScriptContextSet
* script_context_set
= dispatcher
?
677 &dispatcher
->script_context_set() : nullptr;
678 module_system
->RegisterNativeHandler(
679 "app_window_natives",
680 scoped_ptr
<NativeHandler
>(new AppWindowCustomBindings(
681 script_context_set
, context
)));
682 module_system
->RegisterNativeHandler(
684 scoped_ptr
<NativeHandler
>(new BlobNativeHandler(context
)));
685 module_system
->RegisterNativeHandler(
687 scoped_ptr
<NativeHandler
>(new ContextMenusCustomBindings(context
)));
688 module_system
->RegisterNativeHandler(
689 "css_natives", scoped_ptr
<NativeHandler
>(new CssNativeHandler(context
)));
690 module_system
->RegisterNativeHandler(
692 scoped_ptr
<NativeHandler
>(new DocumentCustomBindings(context
)));
693 module_system
->RegisterNativeHandler(
694 "guest_view_internal",
695 scoped_ptr
<NativeHandler
>(
696 new GuestViewInternalCustomBindings(context
)));
697 module_system
->RegisterNativeHandler(
698 "i18n", scoped_ptr
<NativeHandler
>(new I18NCustomBindings(context
)));
699 module_system
->RegisterNativeHandler(
701 scoped_ptr
<NativeHandler
>(new IdGeneratorCustomBindings(context
)));
702 module_system
->RegisterNativeHandler(
703 "runtime", scoped_ptr
<NativeHandler
>(new RuntimeCustomBindings(context
)));
706 void Dispatcher::LoadExtensionForTest(const Extension
* extension
) {
707 CHECK(extensions_
.Insert(extension
));
710 bool Dispatcher::OnControlMessageReceived(const IPC::Message
& message
) {
712 IPC_BEGIN_MESSAGE_MAP(Dispatcher
, message
)
713 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension
, OnActivateExtension
)
714 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend
, OnCancelSuspend
)
715 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage
, OnDeliverMessage
)
716 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect
, OnDispatchOnConnect
)
717 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect
, OnDispatchOnDisconnect
)
718 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded
, OnLoaded
)
719 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke
, OnMessageInvoke
)
720 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel
, OnSetChannel
)
721 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames
, OnSetFunctionNames
)
722 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist
,
723 OnSetScriptingWhitelist
)
724 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont
, OnSetSystemFont
)
725 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend
, OnShouldSuspend
)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend
, OnSuspend
)
727 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs
, OnTransferBlobs
)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded
, OnUnloaded
)
729 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions
, OnUpdatePermissions
)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions
,
731 OnUpdateTabSpecificPermissions
)
732 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions
,
733 OnClearTabSpecificPermissions
)
734 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI
, OnUsingWebRequestAPI
)
735 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages
,
736 content_watcher_
.get(),
737 ContentWatcher::OnWatchPages
)
738 IPC_MESSAGE_UNHANDLED(handled
= false)
739 IPC_END_MESSAGE_MAP()
744 void Dispatcher::WebKitInitialized() {
745 // For extensions, we want to ensure we call the IdleHandler every so often,
746 // even if the extension keeps up activity.
747 if (set_idle_notifications_
) {
748 forced_idle_timer_
.reset(new base::RepeatingTimer
<content::RenderThread
>);
749 forced_idle_timer_
->Start(
751 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs
),
753 &RenderThread::IdleHandler
);
756 // Initialize host permissions for any extensions that were activated before
757 // WebKit was initialized.
758 for (const std::string
& extension_id
: active_extension_ids_
) {
759 const Extension
* extension
= extensions_
.GetByID(extension_id
);
761 InitOriginPermissions(extension
);
764 EnableCustomElementWhiteList();
766 is_webkit_initialized_
= true;
769 void Dispatcher::IdleNotification() {
770 if (set_idle_notifications_
&& forced_idle_timer_
) {
771 // Dampen the forced delay as well if the extension stays idle for long
772 // periods of time. (forced_idle_timer_ can be NULL after
773 // OnRenderProcessShutdown has been called.)
774 int64 forced_delay_ms
=
775 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
776 kMaxExtensionIdleHandlerDelayMs
);
777 forced_idle_timer_
->Stop();
778 forced_idle_timer_
->Start(
780 base::TimeDelta::FromMilliseconds(forced_delay_ms
),
782 &RenderThread::IdleHandler
);
786 void Dispatcher::OnRenderProcessShutdown() {
787 v8_schema_registry_
.reset();
788 forced_idle_timer_
.reset();
789 content_watcher_
.reset();
792 void Dispatcher::OnActivateExtension(const std::string
& extension_id
) {
793 const Extension
* extension
= extensions_
.GetByID(extension_id
);
795 // Extension was activated but was never loaded. This probably means that
796 // the renderer failed to load it (or the browser failed to tell us when it
797 // did). Failures shouldn't happen, but instead of crashing there (which
798 // executes on all renderers) be conservative and only crash in the renderer
799 // of the extension which failed to load; this one.
800 std::string
& error
= extension_load_errors_
[extension_id
];
802 base::debug::Alias(&minidump
);
803 base::snprintf(minidump
,
805 "e::dispatcher:%s:%s",
806 extension_id
.c_str(),
808 LOG(FATAL
) << extension_id
<< " was never loaded: " << error
;
811 active_extension_ids_
.insert(extension_id
);
813 // This is called when starting a new extension page, so start the idle
815 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs
);
817 if (is_webkit_initialized_
) {
818 DOMActivityLogger::AttachToWorld(
819 DOMActivityLogger::kMainWorldId
, extension_id
);
821 InitOriginPermissions(extension
);
824 UpdateActiveExtensions();
827 void Dispatcher::OnCancelSuspend(const std::string
& extension_id
) {
828 DispatchEvent(extension_id
, kOnSuspendCanceledEvent
);
831 void Dispatcher::OnDeliverMessage(int target_port_id
, const Message
& message
) {
832 scoped_ptr
<RequestSender::ScopedTabID
> scoped_tab_id
;
833 std::map
<int, int>::const_iterator it
=
834 port_to_tab_id_map_
.find(target_port_id
);
835 if (it
!= port_to_tab_id_map_
.end()) {
837 new RequestSender::ScopedTabID(request_sender(), it
->second
));
840 MessagingBindings::DeliverMessage(*script_context_set_
, target_port_id
,
842 NULL
); // All render frames.
845 void Dispatcher::OnDispatchOnConnect(
847 const std::string
& channel_name
,
848 const ExtensionMsg_TabConnectionInfo
& source
,
849 const ExtensionMsg_ExternalConnectionInfo
& info
,
850 const std::string
& tls_channel_id
) {
851 DCHECK(!ContainsKey(port_to_tab_id_map_
, target_port_id
));
852 DCHECK_EQ(1, target_port_id
% 2); // target renderer ports have odd IDs.
853 int sender_tab_id
= -1;
854 source
.tab
.GetInteger("id", &sender_tab_id
);
855 port_to_tab_id_map_
[target_port_id
] = sender_tab_id
;
857 MessagingBindings::DispatchOnConnect(*script_context_set_
, target_port_id
,
858 channel_name
, source
, info
,
860 NULL
); // All render frames.
863 void Dispatcher::OnDispatchOnDisconnect(int port_id
,
864 const std::string
& error_message
) {
865 MessagingBindings::DispatchOnDisconnect(*script_context_set_
, port_id
,
867 NULL
); // All render frames.
870 void Dispatcher::OnLoaded(
871 const std::vector
<ExtensionMsg_Loaded_Params
>& loaded_extensions
) {
872 for (const auto& param
: loaded_extensions
) {
874 scoped_refptr
<const Extension
> extension
= param
.ConvertToExtension(&error
);
875 if (!extension
.get()) {
876 NOTREACHED() << error
;
877 // Note: in tests |param.id| has been observed to be empty (see comment
878 // just below) so this isn't all that reliable.
879 extension_load_errors_
[param
.id
] = error
;
883 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
884 // could be) and uses extension->id() not params.id:
885 // 1. For some reason params.id can be empty. I've only seen it with
886 // the webstore extension, in tests, and I've spent some time trying to
887 // figure out why - but cost/benefit won.
888 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
889 // Dispatcher is attached to a RenderThread. Presumably there is a
890 // mismatch there. In theory one would think it's possible for the
891 // browser to figure this out itself - but again, cost/benefit.
892 if (!extensions_
.Contains(extension
->id()))
893 extensions_
.Insert(extension
);
896 // Update the available bindings for all contexts. These may have changed if
897 // an externally_connectable extension was loaded that can connect to an
902 void Dispatcher::OnMessageInvoke(const std::string
& extension_id
,
903 const std::string
& module_name
,
904 const std::string
& function_name
,
905 const base::ListValue
& args
,
907 InvokeModuleSystemMethod(
908 NULL
, extension_id
, module_name
, function_name
, args
, user_gesture
);
911 void Dispatcher::OnSetChannel(int channel
) {
912 delegate_
->SetChannel(channel
);
913 AddChannelSpecificFeatures();
916 void Dispatcher::OnSetFunctionNames(const std::vector
<std::string
>& names
) {
917 function_names_
.clear();
918 for (size_t i
= 0; i
< names
.size(); ++i
)
919 function_names_
.insert(names
[i
]);
922 void Dispatcher::OnSetScriptingWhitelist(
923 const ExtensionsClient::ScriptingWhitelist
& extension_ids
) {
924 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids
);
927 void Dispatcher::OnSetSystemFont(const std::string
& font_family
,
928 const std::string
& font_size
) {
929 system_font_family_
= font_family
;
930 system_font_size_
= font_size
;
933 void Dispatcher::OnShouldSuspend(const std::string
& extension_id
,
934 uint64 sequence_id
) {
935 RenderThread::Get()->Send(
936 new ExtensionHostMsg_ShouldSuspendAck(extension_id
, sequence_id
));
939 void Dispatcher::OnSuspend(const std::string
& extension_id
) {
940 // Dispatch the suspend event. This doesn't go through the standard event
941 // dispatch machinery because it requires special handling. We need to let
942 // the browser know when we are starting and stopping the event dispatch, so
943 // that it still considers the extension idle despite any activity the suspend
945 DispatchEvent(extension_id
, kOnSuspendEvent
);
946 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id
));
949 void Dispatcher::OnTransferBlobs(const std::vector
<std::string
>& blob_uuids
) {
950 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids
));
953 void Dispatcher::OnUnloaded(const std::string
& id
) {
954 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
955 // to CHECK here rather than guarding.
956 if (!extensions_
.Remove(id
))
959 active_extension_ids_
.erase(id
);
961 script_injection_manager_
->OnExtensionUnloaded(id
);
963 // If the extension is later reloaded with a different set of permissions,
964 // we'd like it to get a new isolated world ID, so that it can pick up the
965 // changed origin whitelist.
966 ScriptInjection::RemoveIsolatedWorld(id
);
968 // Invalidate all of the contexts that were removed.
969 // TODO(kalman): add an invalidation observer interface to ScriptContext.
970 std::set
<ScriptContext
*> removed_contexts
=
971 script_context_set_
->OnExtensionUnloaded(id
);
972 for (ScriptContext
* context
: removed_contexts
) {
973 request_sender_
->InvalidateSource(context
);
976 // Update the available bindings for the remaining contexts. These may have
977 // changed if an externally_connectable extension is unloaded and a webpage
978 // is no longer accessible.
981 // Invalidates the messages map for the extension in case the extension is
982 // reloaded with a new messages map.
983 EraseL10nMessagesMap(id
);
985 // We don't do anything with existing platform-app stylesheets. They will
986 // stay resident, but the URL pattern corresponding to the unloaded
987 // extension's URL just won't match anything anymore.
990 void Dispatcher::OnUpdatePermissions(
991 const ExtensionMsg_UpdatePermissions_Params
& params
) {
992 const Extension
* extension
= extensions_
.GetByID(params
.extension_id
);
996 scoped_refptr
<const PermissionSet
> active
=
997 params
.active_permissions
.ToPermissionSet();
998 scoped_refptr
<const PermissionSet
> withheld
=
999 params
.withheld_permissions
.ToPermissionSet();
1001 if (is_webkit_initialized_
) {
1002 UpdateOriginPermissions(
1004 extension
->permissions_data()->GetEffectiveHostPermissions(),
1005 active
->effective_hosts());
1008 extension
->permissions_data()->SetPermissions(active
, withheld
);
1009 UpdateBindings(extension
->id());
1012 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL
& visible_url
,
1013 const std::string
& extension_id
,
1014 const URLPatternSet
& new_hosts
,
1015 bool update_origin_whitelist
,
1017 const Extension
* extension
= extensions_
.GetByID(extension_id
);
1021 URLPatternSet old_effective
=
1022 extension
->permissions_data()->GetEffectiveHostPermissions();
1023 extension
->permissions_data()->UpdateTabSpecificPermissions(
1025 new extensions::PermissionSet(extensions::APIPermissionSet(),
1026 extensions::ManifestPermissionSet(),
1028 extensions::URLPatternSet()));
1030 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1031 UpdateOriginPermissions(
1034 extension
->permissions_data()->GetEffectiveHostPermissions());
1038 void Dispatcher::OnClearTabSpecificPermissions(
1039 const std::vector
<std::string
>& extension_ids
,
1040 bool update_origin_whitelist
,
1042 for (const std::string
& id
: extension_ids
) {
1043 const Extension
* extension
= extensions_
.GetByID(id
);
1045 URLPatternSet old_effective
=
1046 extension
->permissions_data()->GetEffectiveHostPermissions();
1047 extension
->permissions_data()->ClearTabSpecificPermissions(tab_id
);
1048 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1049 UpdateOriginPermissions(
1052 extension
->permissions_data()->GetEffectiveHostPermissions());
1058 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used
) {
1059 webrequest_used_
= webrequest_used
;
1062 void Dispatcher::OnUserScriptsUpdated(const std::set
<HostID
>& changed_hosts
,
1063 const std::vector
<UserScript
*>& scripts
) {
1064 UpdateActiveExtensions();
1067 void Dispatcher::UpdateActiveExtensions() {
1068 std::set
<std::string
> active_extensions
= active_extension_ids_
;
1069 user_script_set_manager_
->GetAllActiveExtensionIds(&active_extensions
);
1070 delegate_
->OnActiveExtensionsUpdated(active_extensions
);
1073 void Dispatcher::InitOriginPermissions(const Extension
* extension
) {
1074 delegate_
->InitOriginPermissions(extension
,
1075 IsExtensionActive(extension
->id()));
1076 UpdateOriginPermissions(
1078 URLPatternSet(), // No old permissions.
1079 extension
->permissions_data()->GetEffectiveHostPermissions());
1082 void Dispatcher::UpdateOriginPermissions(const GURL
& extension_url
,
1083 const URLPatternSet
& old_patterns
,
1084 const URLPatternSet
& new_patterns
) {
1085 static const char* kSchemes
[] = {
1089 content::kChromeUIScheme
,
1091 #if defined(OS_CHROMEOS)
1092 content::kExternalFileScheme
,
1094 extensions::kExtensionScheme
,
1096 for (size_t i
= 0; i
< arraysize(kSchemes
); ++i
) {
1097 const char* scheme
= kSchemes
[i
];
1098 // Remove all old patterns...
1099 for (URLPatternSet::const_iterator pattern
= old_patterns
.begin();
1100 pattern
!= old_patterns
.end(); ++pattern
) {
1101 if (pattern
->MatchesScheme(scheme
)) {
1102 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1104 WebString::fromUTF8(scheme
),
1105 WebString::fromUTF8(pattern
->host()),
1106 pattern
->match_subdomains());
1109 // ...And add the new ones.
1110 for (URLPatternSet::const_iterator pattern
= new_patterns
.begin();
1111 pattern
!= new_patterns
.end(); ++pattern
) {
1112 if (pattern
->MatchesScheme(scheme
)) {
1113 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1115 WebString::fromUTF8(scheme
),
1116 WebString::fromUTF8(pattern
->host()),
1117 pattern
->match_subdomains());
1123 void Dispatcher::EnableCustomElementWhiteList() {
1124 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1125 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1126 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1127 blink::WebCustomElement::addEmbedderCustomElementName(
1128 "extensionoptionsbrowserplugin");
1129 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1130 blink::WebCustomElement::addEmbedderCustomElementName(
1131 "extensionviewbrowserplugin");
1132 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1133 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1134 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1135 blink::WebCustomElement::addEmbedderCustomElementName(
1136 "surfaceviewbrowserplugin");
1139 void Dispatcher::UpdateBindings(const std::string
& extension_id
) {
1140 script_context_set().ForEach(extension_id
,
1141 base::Bind(&Dispatcher::UpdateBindingsForContext
,
1142 base::Unretained(this)));
1145 void Dispatcher::UpdateBindingsForContext(ScriptContext
* context
) {
1146 v8::HandleScope
handle_scope(context
->isolate());
1147 v8::Context::Scope
context_scope(context
->v8_context());
1149 // TODO(kalman): Make the bindings registration have zero overhead then run
1150 // the same code regardless of context type.
1151 switch (context
->context_type()) {
1152 case Feature::UNSPECIFIED_CONTEXT
:
1153 case Feature::WEB_PAGE_CONTEXT
:
1154 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
1155 // Hard-code registration of any APIs that are exposed to webpage-like
1156 // contexts, because it's too expensive to run the full bindings code.
1157 // All of the same permission checks will still apply.
1158 if (context
->GetAvailability("app").is_available())
1159 RegisterBinding("app", context
);
1160 if (context
->GetAvailability("webstore").is_available())
1161 RegisterBinding("webstore", context
);
1162 if (context
->GetAvailability("dashboardPrivate").is_available())
1163 RegisterBinding("dashboardPrivate", context
);
1164 if (IsRuntimeAvailableToContext(context
))
1165 RegisterBinding("runtime", context
);
1166 UpdateContentCapabilities(context
);
1169 case Feature::BLESSED_EXTENSION_CONTEXT
:
1170 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
1171 case Feature::CONTENT_SCRIPT_CONTEXT
:
1172 case Feature::WEBUI_CONTEXT
: {
1173 // Extension context; iterate through all the APIs and bind the available
1175 const FeatureProvider
* api_feature_provider
=
1176 FeatureProvider::GetAPIFeatures();
1177 const std::vector
<std::string
>& apis
=
1178 api_feature_provider
->GetAllFeatureNames();
1179 for (const std::string
& api_name
: apis
) {
1180 Feature
* feature
= api_feature_provider
->GetFeature(api_name
);
1183 // Internal APIs are included via require(api_name) from internal code
1184 // rather than chrome[api_name].
1185 if (feature
->IsInternal())
1188 // If this API has a parent feature (and isn't marked 'noparent'),
1189 // then this must be a function or event, so we should not register.
1190 if (api_feature_provider
->GetParent(feature
) != NULL
)
1193 // Skip chrome.test if this isn't a test.
1194 if (api_name
== "test" &&
1195 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1196 ::switches::kTestType
)) {
1200 if (context
->IsAnyFeatureAvailableToContext(*feature
))
1201 RegisterBinding(api_name
, context
);
1208 void Dispatcher::RegisterBinding(const std::string
& api_name
,
1209 ScriptContext
* context
) {
1210 std::string bind_name
;
1211 v8::Local
<v8::Object
> bind_object
=
1212 GetOrCreateBindObjectIfAvailable(api_name
, &bind_name
, context
);
1214 // Empty if the bind object failed to be created, probably because the
1215 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1216 if (bind_object
.IsEmpty())
1219 v8::Local
<v8::String
> v8_bind_name
=
1220 v8::String::NewFromUtf8(context
->isolate(), bind_name
.c_str());
1221 if (bind_object
->HasRealNamedProperty(v8_bind_name
)) {
1222 // The bind object may already have the property if the API has been
1223 // registered before (or if the extension has put something there already,
1226 // In the former case, we need to re-register the bindings for the APIs
1227 // which the extension now has permissions for (if any), but not touch any
1228 // others so that we don't destroy state such as event listeners.
1230 // TODO(kalman): Only register available APIs to make this all moot.
1231 if (bind_object
->HasRealNamedCallbackProperty(v8_bind_name
))
1232 return; // lazy binding still there, nothing to do
1233 if (bind_object
->Get(v8_bind_name
)->IsObject())
1234 return; // binding has already been fully installed
1237 ModuleSystem
* module_system
= context
->module_system();
1238 if (!source_map_
.Contains(api_name
)) {
1239 module_system
->RegisterNativeHandler(
1241 scoped_ptr
<NativeHandler
>(new BindingGeneratingNativeHandler(
1242 context
, api_name
, "binding")));
1243 module_system
->SetNativeLazyField(
1244 bind_object
, bind_name
, api_name
, "binding");
1246 module_system
->SetLazyField(bind_object
, bind_name
, api_name
, "binding");
1250 // NOTE: please use the naming convention "foo_natives" for these.
1251 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
1252 ScriptContext
* context
) {
1253 RegisterNativeHandlers(module_system
,
1256 request_sender_
.get(),
1257 v8_schema_registry_
.get());
1258 const Extension
* extension
= context
->extension();
1259 int manifest_version
= extension
? extension
->manifest_version() : 1;
1260 bool is_component_extension
=
1261 extension
&& Manifest::IsComponentLocation(extension
->location());
1262 bool send_request_disabled
=
1263 (extension
&& Manifest::IsUnpackedLocation(extension
->location()) &&
1264 BackgroundInfo::HasLazyBackgroundPage(extension
));
1265 module_system
->RegisterNativeHandler(
1267 scoped_ptr
<NativeHandler
>(new ProcessInfoNativeHandler(
1269 context
->GetExtensionID(),
1270 context
->GetContextTypeDescription(),
1271 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1272 is_component_extension
,
1274 send_request_disabled
)));
1276 delegate_
->RegisterNativeHandlers(this, module_system
, context
);
1279 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext
* context
) {
1280 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1281 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1284 for (const auto& extension
: extensions_
) {
1285 ExternallyConnectableInfo
* info
= static_cast<ExternallyConnectableInfo
*>(
1286 extension
->GetManifestData(manifest_keys::kExternallyConnectable
));
1287 if (info
&& info
->matches
.MatchesURL(context
->GetURL()))
1293 void Dispatcher::UpdateContentCapabilities(ScriptContext
* context
) {
1294 APIPermissionSet permissions
;
1295 for (const auto& extension
: extensions_
) {
1296 const ContentCapabilitiesInfo
& info
=
1297 ContentCapabilitiesInfo::Get(extension
.get());
1298 if (info
.url_patterns
.MatchesURL(context
->GetURL())) {
1299 APIPermissionSet new_permissions
;
1300 APIPermissionSet::Union(permissions
, info
.permissions
, &new_permissions
);
1301 permissions
= new_permissions
;
1304 context
->SetContentCapabilities(permissions
);
1307 void Dispatcher::PopulateSourceMap() {
1308 const std::vector
<std::pair
<std::string
, int> > resources
= GetJsResources();
1309 for (std::vector
<std::pair
<std::string
, int> >::const_iterator resource
=
1311 resource
!= resources
.end();
1313 source_map_
.RegisterSource(resource
->first
, resource
->second
);
1315 delegate_
->PopulateSourceMap(&source_map_
);
1318 bool Dispatcher::IsWithinPlatformApp() {
1319 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
1320 iter
!= active_extension_ids_
.end();
1322 const Extension
* extension
= extensions_
.GetByID(*iter
);
1323 if (extension
&& extension
->is_platform_app())
1329 v8::Local
<v8::Object
> Dispatcher::GetOrCreateObject(
1330 const v8::Local
<v8::Object
>& object
,
1331 const std::string
& field
,
1332 v8::Isolate
* isolate
) {
1333 v8::Local
<v8::String
> key
= v8::String::NewFromUtf8(isolate
, field
.c_str());
1334 // If the object has a callback property, it is assumed it is an unavailable
1335 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1337 if (object
->HasRealNamedCallbackProperty(key
)) {
1338 object
->Delete(key
);
1339 } else if (object
->HasRealNamedProperty(key
)) {
1340 v8::Local
<v8::Value
> value
= object
->Get(key
);
1341 CHECK(value
->IsObject());
1342 return v8::Local
<v8::Object
>::Cast(value
);
1345 v8::Local
<v8::Object
> new_object
= v8::Object::New(isolate
);
1346 object
->Set(key
, new_object
);
1350 v8::Local
<v8::Object
> Dispatcher::GetOrCreateBindObjectIfAvailable(
1351 const std::string
& api_name
,
1352 std::string
* bind_name
,
1353 ScriptContext
* context
) {
1354 std::vector
<std::string
> split
;
1355 base::SplitString(api_name
, '.', &split
);
1357 v8::Local
<v8::Object
> bind_object
;
1359 // Check if this API has an ancestor. If the API's ancestor is available and
1360 // the API is not available, don't install the bindings for this API. If
1361 // the API is available and its ancestor is not, delete the ancestor and
1362 // install the bindings for the API. This is to prevent loading the ancestor
1363 // API schema if it will not be needed.
1366 // If app is available and app.window is not, just install app.
1367 // If app.window is available and app is not, delete app and install
1368 // app.window on a new object so app does not have to be loaded.
1369 const FeatureProvider
* api_feature_provider
=
1370 FeatureProvider::GetAPIFeatures();
1371 std::string ancestor_name
;
1372 bool only_ancestor_available
= false;
1374 for (size_t i
= 0; i
< split
.size() - 1; ++i
) {
1375 ancestor_name
+= (i
? "." : "") + split
[i
];
1376 if (api_feature_provider
->GetFeature(ancestor_name
) &&
1377 context
->GetAvailability(ancestor_name
).is_available() &&
1378 !context
->GetAvailability(api_name
).is_available()) {
1379 only_ancestor_available
= true;
1383 if (bind_object
.IsEmpty()) {
1384 bind_object
= AsObjectOrEmpty(GetOrCreateChrome(context
));
1385 if (bind_object
.IsEmpty())
1386 return v8::Local
<v8::Object
>();
1388 bind_object
= GetOrCreateObject(bind_object
, split
[i
], context
->isolate());
1391 if (only_ancestor_available
)
1392 return v8::Local
<v8::Object
>();
1395 *bind_name
= split
.back();
1397 return bind_object
.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context
))
1401 void Dispatcher::RequireGuestViewModules(ScriptContext
* context
) {
1402 Feature::Context context_type
= context
->context_type();
1403 ModuleSystem
* module_system
= context
->module_system();
1406 if (context
->GetAvailability("appViewEmbedderInternal").is_available()) {
1407 module_system
->Require("appView");
1410 // Require ExtensionOptions.
1411 if (context
->GetAvailability("extensionOptionsInternal").is_available()) {
1412 module_system
->Require("extensionOptions");
1413 module_system
->Require("extensionOptionsAttributes");
1416 // Require ExtensionView.
1417 if (context
->GetAvailability("extensionViewInternal").is_available()) {
1418 module_system
->Require("extensionView");
1419 module_system
->Require("extensionViewApiMethods");
1420 module_system
->Require("extensionViewAttributes");
1423 // Require SurfaceView.
1424 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1425 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1426 module_system
->Require("surfaceWorker");
1430 if (context
->GetAvailability("webViewInternal").is_available()) {
1431 module_system
->Require("webView");
1432 module_system
->Require("webViewApiMethods");
1433 module_system
->Require("webViewAttributes");
1435 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1436 module_system
->Require("webViewIframe");
1440 // The "guestViewDeny" module must always be loaded last. It registers
1441 // error-providing custom elements for the GuestView types that are not
1442 // available, and thus all of those types must have been checked and loaded
1443 // (or not loaded) beforehand.
1444 if (context_type
== Feature::BLESSED_EXTENSION_CONTEXT
) {
1445 module_system
->Require("guestViewDeny");
1449 void Dispatcher::AddChannelSpecificFeatures() {
1450 // chrome-extension: resources should be allowed to register a Service Worker.
1451 if (FeatureProvider::GetBehaviorFeature(BehaviorFeature::kServiceWorker
)
1452 ->IsAvailableToEnvironment()
1454 WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
1455 WebString::fromUTF8(kExtensionScheme
));
1458 } // namespace extensions