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_window_custom_bindings.h"
50 #include "extensions/renderer/binding_generating_native_handler.h"
51 #include "extensions/renderer/blob_native_handler.h"
52 #include "extensions/renderer/content_watcher.h"
53 #include "extensions/renderer/context_menus_custom_bindings.h"
54 #include "extensions/renderer/css_native_handler.h"
55 #include "extensions/renderer/dispatcher_delegate.h"
56 #include "extensions/renderer/document_custom_bindings.h"
57 #include "extensions/renderer/dom_activity_logger.h"
58 #include "extensions/renderer/event_bindings.h"
59 #include "extensions/renderer/extension_frame_helper.h"
60 #include "extensions/renderer/extension_helper.h"
61 #include "extensions/renderer/extensions_renderer_client.h"
62 #include "extensions/renderer/file_system_natives.h"
63 #include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
64 #include "extensions/renderer/i18n_custom_bindings.h"
65 #include "extensions/renderer/id_generator_custom_bindings.h"
66 #include "extensions/renderer/lazy_background_page_native_handler.h"
67 #include "extensions/renderer/logging_native_handler.h"
68 #include "extensions/renderer/messaging_bindings.h"
69 #include "extensions/renderer/module_system.h"
70 #include "extensions/renderer/print_native_handler.h"
71 #include "extensions/renderer/process_info_native_handler.h"
72 #include "extensions/renderer/render_frame_observer_natives.h"
73 #include "extensions/renderer/request_sender.h"
74 #include "extensions/renderer/runtime_custom_bindings.h"
75 #include "extensions/renderer/script_context.h"
76 #include "extensions/renderer/script_context_set.h"
77 #include "extensions/renderer/script_injection.h"
78 #include "extensions/renderer/script_injection_manager.h"
79 #include "extensions/renderer/send_request_natives.h"
80 #include "extensions/renderer/set_icon_natives.h"
81 #include "extensions/renderer/test_features_native_handler.h"
82 #include "extensions/renderer/user_gestures_native_handler.h"
83 #include "extensions/renderer/utils_native_handler.h"
84 #include "extensions/renderer/v8_context_native_handler.h"
85 #include "grit/extensions_renderer_resources.h"
86 #include "third_party/WebKit/public/platform/WebString.h"
87 #include "third_party/WebKit/public/platform/WebURLRequest.h"
88 #include "third_party/WebKit/public/web/WebCustomElement.h"
89 #include "third_party/WebKit/public/web/WebDataSource.h"
90 #include "third_party/WebKit/public/web/WebDocument.h"
91 #include "third_party/WebKit/public/web/WebFrame.h"
92 #include "third_party/WebKit/public/web/WebLocalFrame.h"
93 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
94 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
95 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
96 #include "third_party/WebKit/public/web/WebView.h"
97 #include "third_party/mojo/src/mojo/public/js/constants.h"
98 #include "ui/base/layout.h"
99 #include "ui/base/resource/resource_bundle.h"
100 #include "v8/include/v8.h"
102 using base::UserMetricsAction
;
103 using blink::WebDataSource
;
104 using blink::WebDocument
;
105 using blink::WebScopedUserGesture
;
106 using blink::WebSecurityPolicy
;
107 using blink::WebString
;
108 using blink::WebVector
;
109 using blink::WebView
;
110 using content::RenderThread
;
112 namespace extensions
{
116 static const int64 kInitialExtensionIdleHandlerDelayMs
= 5 * 1000;
117 static const int64 kMaxExtensionIdleHandlerDelayMs
= 5 * 60 * 1000;
118 static const char kEventDispatchFunction
[] = "dispatchEvent";
119 static const char kOnSuspendEvent
[] = "runtime.onSuspend";
120 static const char kOnSuspendCanceledEvent
[] = "runtime.onSuspendCanceled";
122 // Returns the global value for "chrome" from |context|. If one doesn't exist
123 // creates a new object for it.
125 // Note that this isn't necessarily an object, since webpages can write, for
126 // example, "window.chrome = true".
127 v8::Local
<v8::Value
> GetOrCreateChrome(ScriptContext
* context
) {
128 v8::Local
<v8::String
> chrome_string(
129 v8::String::NewFromUtf8(context
->isolate(), "chrome"));
130 v8::Local
<v8::Object
> global(context
->v8_context()->Global());
131 v8::Local
<v8::Value
> chrome(global
->Get(chrome_string
));
132 if (chrome
->IsUndefined()) {
133 chrome
= v8::Object::New(context
->isolate());
134 global
->Set(chrome_string
, chrome
);
139 // Returns |value| cast to an object if possible, else an empty handle.
140 v8::Local
<v8::Object
> AsObjectOrEmpty(v8::Local
<v8::Value
> value
) {
141 return value
->IsObject() ? value
.As
<v8::Object
>() : v8::Local
<v8::Object
>();
144 // Calls a method |method_name| in a module |module_name| belonging to the
145 // module system from |context|. Intended as a callback target from
146 // ScriptContextSet::ForEach.
147 void CallModuleMethod(const std::string
& module_name
,
148 const std::string
& method_name
,
149 const base::ListValue
* args
,
150 ScriptContext
* context
) {
151 v8::HandleScope
handle_scope(context
->isolate());
152 v8::Context::Scope
context_scope(context
->v8_context());
154 scoped_ptr
<content::V8ValueConverter
> converter(
155 content::V8ValueConverter::create());
157 std::vector
<v8::Local
<v8::Value
>> arguments
;
158 for (base::ListValue::const_iterator it
= args
->begin(); it
!= args
->end();
160 arguments
.push_back(converter
->ToV8Value(*it
, context
->v8_context()));
163 context
->module_system()->CallModuleMethod(
164 module_name
, method_name
, &arguments
);
167 // This handles the "chrome." root API object in script contexts.
168 class ChromeNativeHandler
: public ObjectBackedNativeHandler
{
170 explicit ChromeNativeHandler(ScriptContext
* context
)
171 : ObjectBackedNativeHandler(context
) {
174 base::Bind(&ChromeNativeHandler::GetChrome
, base::Unretained(this)));
177 void GetChrome(const v8::FunctionCallbackInfo
<v8::Value
>& args
) {
178 args
.GetReturnValue().Set(GetOrCreateChrome(context()));
184 Dispatcher::Dispatcher(DispatcherDelegate
* delegate
)
185 : delegate_(delegate
),
186 content_watcher_(new ContentWatcher()),
187 source_map_(&ResourceBundle::GetSharedInstance()),
188 v8_schema_registry_(new V8SchemaRegistry
),
189 is_webkit_initialized_(false),
190 user_script_set_manager_observer_(this),
191 webrequest_used_(false) {
192 const base::CommandLine
& command_line
=
193 *(base::CommandLine::ForCurrentProcess());
194 set_idle_notifications_
=
195 command_line
.HasSwitch(switches::kExtensionProcess
) ||
196 command_line
.HasSwitch(::switches::kSingleProcess
);
198 if (set_idle_notifications_
) {
199 RenderThread::Get()->SetIdleNotificationDelayInMs(
200 kInitialExtensionIdleHandlerDelayMs
);
203 script_context_set_
.reset(
204 new ScriptContextSet(&extensions_
, &active_extension_ids_
));
205 user_script_set_manager_
.reset(new UserScriptSetManager(&extensions_
));
206 script_injection_manager_
.reset(
207 new ScriptInjectionManager(&extensions_
, user_script_set_manager_
.get()));
208 user_script_set_manager_observer_
.Add(user_script_set_manager_
.get());
209 request_sender_
.reset(new RequestSender(this));
213 Dispatcher::~Dispatcher() {
216 void Dispatcher::OnRenderFrameCreated(content::RenderFrame
* render_frame
) {
217 script_injection_manager_
->OnRenderFrameCreated(render_frame
);
220 bool Dispatcher::IsExtensionActive(const std::string
& extension_id
) const {
222 active_extension_ids_
.find(extension_id
) != active_extension_ids_
.end();
224 CHECK(extensions_
.Contains(extension_id
));
228 void Dispatcher::DidCreateScriptContext(
229 blink::WebLocalFrame
* frame
,
230 const v8::Local
<v8::Context
>& v8_context
,
233 const base::TimeTicks start_time
= base::TimeTicks::Now();
235 ScriptContext
* context
= script_context_set_
->Register(
236 frame
, v8_context
, extension_group
, world_id
);
238 // Initialize origin permissions for content scripts, which can't be
239 // initialized in |OnActivateExtension|.
240 if (context
->context_type() == Feature::CONTENT_SCRIPT_CONTEXT
)
241 InitOriginPermissions(context
->extension());
244 scoped_ptr
<ModuleSystem
> module_system(
245 new ModuleSystem(context
, &source_map_
));
246 context
->set_module_system(module_system
.Pass());
248 ModuleSystem
* module_system
= context
->module_system();
250 // Enable natives in startup.
251 ModuleSystem::NativesEnabledScope
natives_enabled_scope(module_system
);
253 RegisterNativeHandlers(module_system
, context
);
255 // chrome.Event is part of the public API (although undocumented). Make it
256 // lazily evalulate to Event from event_bindings.js. For extensions only
257 // though, not all webpages!
258 if (context
->extension()) {
259 v8::Local
<v8::Object
> chrome
= AsObjectOrEmpty(GetOrCreateChrome(context
));
260 if (!chrome
.IsEmpty())
261 module_system
->SetLazyField(chrome
, "Event", kEventBindings
, "Event");
264 UpdateBindingsForContext(context
);
266 bool is_within_platform_app
= IsWithinPlatformApp();
267 // Inject custom JS into the platform app context.
268 if (is_within_platform_app
) {
269 module_system
->Require("platformApp");
272 RequireGuestViewModules(context
);
273 delegate_
->RequireAdditionalModules(context
, is_within_platform_app
);
275 const base::TimeDelta elapsed
= base::TimeTicks::Now() - start_time
;
276 switch (context
->context_type()) {
277 case Feature::UNSPECIFIED_CONTEXT
:
278 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
281 case Feature::BLESSED_EXTENSION_CONTEXT
:
282 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed
);
284 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
285 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
288 case Feature::CONTENT_SCRIPT_CONTEXT
:
289 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
292 case Feature::WEB_PAGE_CONTEXT
:
293 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed
);
295 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
296 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
299 case Feature::WEBUI_CONTEXT
:
300 UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed
);
304 VLOG(1) << "Num tracked contexts: " << script_context_set_
->size();
307 void Dispatcher::WillReleaseScriptContext(
308 blink::WebLocalFrame
* frame
,
309 const v8::Local
<v8::Context
>& v8_context
,
311 ScriptContext
* context
= script_context_set_
->GetByV8Context(v8_context
);
315 context
->DispatchOnUnloadEvent();
316 // TODO(kalman): Make |request_sender| use |context->AddInvalidationObserver|.
317 // In fact |request_sender_| should really be owned by ScriptContext.
318 request_sender_
->InvalidateSource(context
);
320 script_context_set_
->Remove(context
);
321 VLOG(1) << "Num tracked contexts: " << script_context_set_
->size();
324 void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame
* frame
) {
325 // Note: use GetEffectiveDocumentURL not just frame->document()->url()
326 // so that this also injects the stylesheet on about:blank frames that
327 // are hosted in the extension process.
328 GURL effective_document_url
= ScriptContext::GetEffectiveDocumentURL(
329 frame
, frame
->document().url(), true /* match_about_blank */);
331 const Extension
* extension
=
332 extensions_
.GetExtensionOrAppByURL(effective_document_url
);
335 (extension
->is_extension() || extension
->is_platform_app())) {
336 int resource_id
= extension
->is_platform_app() ? IDR_PLATFORM_APP_CSS
337 : IDR_EXTENSION_FONTS_CSS
;
338 std::string stylesheet
= ResourceBundle::GetSharedInstance()
339 .GetRawDataResource(resource_id
)
341 base::ReplaceFirstSubstringAfterOffset(
342 &stylesheet
, 0, "$FONTFAMILY", system_font_family_
);
343 base::ReplaceFirstSubstringAfterOffset(
344 &stylesheet
, 0, "$FONTSIZE", system_font_size_
);
346 // Blink doesn't let us define an additional user agent stylesheet, so
347 // we insert the default platform app or extension stylesheet into all
348 // documents that are loaded in each app or extension.
349 frame
->document().insertStyleSheet(WebString::fromUTF8(stylesheet
));
352 // If this is an extension options page, and the extension has opted into
353 // using Chrome styles, then insert the Chrome extension stylesheet.
354 if (extension
&& extension
->is_extension() &&
355 OptionsPageInfo::ShouldUseChromeStyle(extension
) &&
356 effective_document_url
== OptionsPageInfo::GetOptionsPage(extension
)) {
357 frame
->document().insertStyleSheet(
358 WebString::fromUTF8(ResourceBundle::GetSharedInstance()
359 .GetRawDataResource(IDR_EXTENSION_CSS
)
363 // In testing, the document lifetime events can happen after the render
364 // process shutdown event.
365 // See: http://crbug.com/21508 and http://crbug.com/500851
366 if (content_watcher_
) {
367 content_watcher_
->DidCreateDocumentElement(frame
);
371 void Dispatcher::OnExtensionResponse(int request_id
,
373 const base::ListValue
& response
,
374 const std::string
& error
) {
375 request_sender_
->HandleResponse(request_id
, success
, response
, error
);
378 void Dispatcher::DispatchEvent(const std::string
& extension_id
,
379 const std::string
& event_name
) const {
380 base::ListValue args
;
381 args
.Set(0, new base::StringValue(event_name
));
382 args
.Set(1, new base::ListValue());
384 // Needed for Windows compilation, since kEventBindings is declared extern.
385 const char* local_event_bindings
= kEventBindings
;
386 script_context_set_
->ForEach(
387 extension_id
, base::Bind(&CallModuleMethod
, local_event_bindings
,
388 kEventDispatchFunction
, &args
));
391 void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame
* render_frame
,
392 const std::string
& extension_id
,
393 const std::string
& module_name
,
394 const std::string
& function_name
,
395 const base::ListValue
& args
,
397 scoped_ptr
<WebScopedUserGesture
> web_user_gesture
;
399 web_user_gesture
.reset(new WebScopedUserGesture
);
401 script_context_set_
->ForEach(
402 extension_id
, render_frame
,
403 base::Bind(&CallModuleMethod
, module_name
, function_name
, &args
));
405 // Reset the idle handler each time there's any activity like event or message
406 // dispatch, for which Invoke is the chokepoint.
407 if (set_idle_notifications_
) {
408 RenderThread::Get()->ScheduleIdleHandler(
409 kInitialExtensionIdleHandlerDelayMs
);
412 // Tell the browser process when an event has been dispatched with a lazy
413 // background page active.
414 const Extension
* extension
= extensions_
.GetByID(extension_id
);
415 if (extension
&& BackgroundInfo::HasLazyBackgroundPage(extension
) &&
416 module_name
== kEventBindings
&&
417 function_name
== kEventDispatchFunction
) {
418 content::RenderFrame
* background_frame
=
419 ExtensionFrameHelper::GetBackgroundPageFrame(extension_id
);
420 if (background_frame
) {
422 args
.GetInteger(3, &message_id
);
423 background_frame
->Send(new ExtensionHostMsg_EventAck(
424 background_frame
->GetRoutingID(), message_id
));
429 void Dispatcher::ClearPortData(int port_id
) {
430 // Only the target port side has entries in |port_to_tab_id_map_|. If
431 // |port_id| is a source port, std::map::erase() will just silently fail
433 port_to_tab_id_map_
.erase(port_id
);
437 std::vector
<std::pair
<std::string
, int> > Dispatcher::GetJsResources() {
438 std::vector
<std::pair
<std::string
, int> > resources
;
441 resources
.push_back(std::make_pair("appView", IDR_APP_VIEW_JS
));
442 resources
.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER
));
443 resources
.push_back(std::make_pair(kEventBindings
, IDR_EVENT_BINDINGS_JS
));
444 resources
.push_back(std::make_pair("extensionOptions",
445 IDR_EXTENSION_OPTIONS_JS
));
446 resources
.push_back(std::make_pair("extensionOptionsAttributes",
447 IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS
));
448 resources
.push_back(std::make_pair("extensionOptionsConstants",
449 IDR_EXTENSION_OPTIONS_CONSTANTS_JS
));
450 resources
.push_back(std::make_pair("extensionOptionsEvents",
451 IDR_EXTENSION_OPTIONS_EVENTS_JS
));
452 resources
.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS
));
453 resources
.push_back(std::make_pair("extensionViewApiMethods",
454 IDR_EXTENSION_VIEW_API_METHODS_JS
));
455 resources
.push_back(std::make_pair("extensionViewAttributes",
456 IDR_EXTENSION_VIEW_ATTRIBUTES_JS
));
457 resources
.push_back(std::make_pair("extensionViewConstants",
458 IDR_EXTENSION_VIEW_CONSTANTS_JS
));
459 resources
.push_back(std::make_pair("extensionViewEvents",
460 IDR_EXTENSION_VIEW_EVENTS_JS
));
461 resources
.push_back(std::make_pair(
462 "extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
463 resources
.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS
));
464 resources
.push_back(std::make_pair("guestViewAttributes",
465 IDR_GUEST_VIEW_ATTRIBUTES_JS
));
466 resources
.push_back(std::make_pair("guestViewContainer",
467 IDR_GUEST_VIEW_CONTAINER_JS
));
468 resources
.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS
));
469 resources
.push_back(std::make_pair("guestViewEvents",
470 IDR_GUEST_VIEW_EVENTS_JS
));
472 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
473 resources
.push_back(std::make_pair("guestViewIframe",
474 IDR_GUEST_VIEW_IFRAME_JS
));
475 resources
.push_back(std::make_pair("guestViewIframeContainer",
476 IDR_GUEST_VIEW_IFRAME_CONTAINER_JS
));
479 resources
.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS
));
480 resources
.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS
));
481 resources
.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS
));
482 resources
.push_back(std::make_pair("messaging", IDR_MESSAGING_JS
));
483 resources
.push_back(std::make_pair("messaging_utils",
484 IDR_MESSAGING_UTILS_JS
));
485 resources
.push_back(std::make_pair(kSchemaUtils
, IDR_SCHEMA_UTILS_JS
));
486 resources
.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS
));
487 resources
.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS
));
488 resources
.push_back(std::make_pair("surfaceWorker", IDR_SURFACE_VIEW_JS
));
489 resources
.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS
));
491 std::make_pair("test_environment_specific_bindings",
492 IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS
));
493 resources
.push_back(std::make_pair("uncaught_exception_handler",
494 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS
));
495 resources
.push_back(std::make_pair("unload_event", IDR_UNLOAD_EVENT_JS
));
496 resources
.push_back(std::make_pair("utils", IDR_UTILS_JS
));
497 resources
.push_back(std::make_pair("webRequest",
498 IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS
));
500 std::make_pair("webRequestInternal",
501 IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS
));
502 // Note: webView not webview so that this doesn't interfere with the
503 // chrome.webview API bindings.
504 resources
.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS
));
505 resources
.push_back(std::make_pair("webViewActionRequests",
506 IDR_WEB_VIEW_ACTION_REQUESTS_JS
));
507 resources
.push_back(std::make_pair("webViewApiMethods",
508 IDR_WEB_VIEW_API_METHODS_JS
));
509 resources
.push_back(std::make_pair("webViewAttributes",
510 IDR_WEB_VIEW_ATTRIBUTES_JS
));
511 resources
.push_back(std::make_pair("webViewConstants",
512 IDR_WEB_VIEW_CONSTANTS_JS
));
513 resources
.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS
));
514 resources
.push_back(std::make_pair("webViewInternal",
515 IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS
));
516 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
517 resources
.push_back(std::make_pair("webViewIframe",
518 IDR_WEB_VIEW_IFRAME_JS
));
521 std::make_pair(mojo::kBindingsModuleName
, IDR_MOJO_BINDINGS_JS
));
523 std::make_pair(mojo::kBufferModuleName
, IDR_MOJO_BUFFER_JS
));
525 std::make_pair(mojo::kCodecModuleName
, IDR_MOJO_CODEC_JS
));
527 std::make_pair(mojo::kConnectionModuleName
, IDR_MOJO_CONNECTION_JS
));
529 std::make_pair(mojo::kConnectorModuleName
, IDR_MOJO_CONNECTOR_JS
));
531 std::make_pair(mojo::kRouterModuleName
, IDR_MOJO_ROUTER_JS
));
533 std::make_pair(mojo::kUnicodeModuleName
, IDR_MOJO_UNICODE_JS
));
535 std::make_pair(mojo::kValidatorModuleName
, IDR_MOJO_VALIDATOR_JS
));
536 resources
.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS
));
537 resources
.push_back(std::make_pair("data_receiver", IDR_DATA_RECEIVER_JS
));
538 resources
.push_back(std::make_pair("data_sender", IDR_DATA_SENDER_JS
));
539 resources
.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS
));
540 resources
.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
541 IDR_KEEP_ALIVE_MOJOM_JS
));
542 resources
.push_back(std::make_pair("device/serial/data_stream.mojom",
543 IDR_DATA_STREAM_MOJOM_JS
));
545 std::make_pair("device/serial/data_stream_serialization.mojom",
546 IDR_DATA_STREAM_SERIALIZATION_MOJOM_JS
));
547 resources
.push_back(std::make_pair("stash_client", IDR_STASH_CLIENT_JS
));
549 std::make_pair("extensions/common/mojo/stash.mojom", IDR_STASH_MOJOM_JS
));
553 std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS
));
555 std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS
));
557 std::make_pair("declarativeWebRequest",
558 IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS
));
560 std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS
));
562 std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS
));
564 std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS
));
565 resources
.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS
));
566 resources
.push_back(std::make_pair(
567 "mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS
));
568 resources
.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
569 IDR_MIME_HANDLER_MOJOM_JS
));
571 std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS
));
573 std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS
));
574 resources
.push_back(std::make_pair("printerProvider",
575 IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS
));
577 std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS
));
578 resources
.push_back(std::make_pair("windowControls", IDR_WINDOW_CONTROLS_JS
));
580 std::make_pair("webViewRequest",
581 IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS
));
582 resources
.push_back(std::make_pair("binding", IDR_BINDING_JS
));
584 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
585 switches::kEnableMojoSerialService
)) {
587 std::make_pair("serial", IDR_SERIAL_CUSTOM_BINDINGS_JS
));
589 resources
.push_back(std::make_pair("serial_service", IDR_SERIAL_SERVICE_JS
));
591 std::make_pair("device/serial/serial.mojom", IDR_SERIAL_MOJOM_JS
));
592 resources
.push_back(std::make_pair("device/serial/serial_serialization.mojom",
593 IDR_SERIAL_SERIALIZATION_MOJOM_JS
));
595 // Custom types sources.
596 resources
.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS
));
598 // Platform app sources that are not API-specific..
599 resources
.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS
));
601 #if defined(ENABLE_MEDIA_ROUTER)
603 std::make_pair("chrome/browser/media/router/media_router.mojom",
604 IDR_MEDIA_ROUTER_MOJOM_JS
));
606 std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS
));
607 #endif // defined(ENABLE_MEDIA_ROUTER)
612 // NOTE: please use the naming convention "foo_natives" for these.
614 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
615 ScriptContext
* context
,
616 Dispatcher
* dispatcher
,
617 RequestSender
* request_sender
,
618 V8SchemaRegistry
* v8_schema_registry
) {
619 module_system
->RegisterNativeHandler(
620 "chrome", scoped_ptr
<NativeHandler
>(new ChromeNativeHandler(context
)));
621 module_system
->RegisterNativeHandler(
622 "lazy_background_page",
623 scoped_ptr
<NativeHandler
>(new LazyBackgroundPageNativeHandler(context
)));
624 module_system
->RegisterNativeHandler(
625 "logging", scoped_ptr
<NativeHandler
>(new LoggingNativeHandler(context
)));
626 module_system
->RegisterNativeHandler("schema_registry",
627 v8_schema_registry
->AsNativeHandler());
628 module_system
->RegisterNativeHandler(
629 "print", scoped_ptr
<NativeHandler
>(new PrintNativeHandler(context
)));
630 module_system
->RegisterNativeHandler(
632 scoped_ptr
<NativeHandler
>(new TestFeaturesNativeHandler(context
)));
633 module_system
->RegisterNativeHandler(
635 scoped_ptr
<NativeHandler
>(new UserGesturesNativeHandler(context
)));
636 module_system
->RegisterNativeHandler(
637 "utils", scoped_ptr
<NativeHandler
>(new UtilsNativeHandler(context
)));
638 module_system
->RegisterNativeHandler(
640 scoped_ptr
<NativeHandler
>(
641 new V8ContextNativeHandler(context
, dispatcher
)));
642 module_system
->RegisterNativeHandler(
643 "event_natives", scoped_ptr
<NativeHandler
>(new EventBindings(context
)));
644 module_system
->RegisterNativeHandler(
646 scoped_ptr
<NativeHandler
>(MessagingBindings::Get(dispatcher
, context
)));
647 module_system
->RegisterNativeHandler(
649 scoped_ptr
<NativeHandler
>(
650 new ApiDefinitionsNatives(dispatcher
, context
)));
651 module_system
->RegisterNativeHandler(
653 scoped_ptr
<NativeHandler
>(
654 new SendRequestNatives(request_sender
, context
)));
655 module_system
->RegisterNativeHandler(
657 scoped_ptr
<NativeHandler
>(new SetIconNatives(context
)));
658 module_system
->RegisterNativeHandler(
660 scoped_ptr
<NativeHandler
>(new APIActivityLogger(context
)));
661 module_system
->RegisterNativeHandler(
662 "renderFrameObserverNatives",
663 scoped_ptr
<NativeHandler
>(new RenderFrameObserverNatives(context
)));
665 // Natives used by multiple APIs.
666 module_system
->RegisterNativeHandler(
667 "file_system_natives",
668 scoped_ptr
<NativeHandler
>(new FileSystemNatives(context
)));
671 // |dispatcher| is null in unit tests.
672 const ScriptContextSet
* script_context_set
= dispatcher
?
673 &dispatcher
->script_context_set() : nullptr;
674 module_system
->RegisterNativeHandler(
675 "app_window_natives",
676 scoped_ptr
<NativeHandler
>(new AppWindowCustomBindings(
677 script_context_set
, context
)));
678 module_system
->RegisterNativeHandler(
680 scoped_ptr
<NativeHandler
>(new BlobNativeHandler(context
)));
681 module_system
->RegisterNativeHandler(
683 scoped_ptr
<NativeHandler
>(new ContextMenusCustomBindings(context
)));
684 module_system
->RegisterNativeHandler(
685 "css_natives", scoped_ptr
<NativeHandler
>(new CssNativeHandler(context
)));
686 module_system
->RegisterNativeHandler(
688 scoped_ptr
<NativeHandler
>(new DocumentCustomBindings(context
)));
689 module_system
->RegisterNativeHandler(
690 "guest_view_internal",
691 scoped_ptr
<NativeHandler
>(
692 new GuestViewInternalCustomBindings(context
)));
693 module_system
->RegisterNativeHandler(
694 "i18n", scoped_ptr
<NativeHandler
>(new I18NCustomBindings(context
)));
695 module_system
->RegisterNativeHandler(
697 scoped_ptr
<NativeHandler
>(new IdGeneratorCustomBindings(context
)));
698 module_system
->RegisterNativeHandler(
699 "runtime", scoped_ptr
<NativeHandler
>(new RuntimeCustomBindings(context
)));
702 void Dispatcher::LoadExtensionForTest(const Extension
* extension
) {
703 CHECK(extensions_
.Insert(extension
));
706 bool Dispatcher::OnControlMessageReceived(const IPC::Message
& message
) {
708 IPC_BEGIN_MESSAGE_MAP(Dispatcher
, message
)
709 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension
, OnActivateExtension
)
710 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend
, OnCancelSuspend
)
711 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage
, OnDeliverMessage
)
712 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect
, OnDispatchOnConnect
)
713 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect
, OnDispatchOnDisconnect
)
714 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded
, OnLoaded
)
715 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke
, OnMessageInvoke
)
716 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel
, OnSetChannel
)
717 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames
, OnSetFunctionNames
)
718 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist
,
719 OnSetScriptingWhitelist
)
720 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont
, OnSetSystemFont
)
721 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend
, OnShouldSuspend
)
722 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend
, OnSuspend
)
723 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs
, OnTransferBlobs
)
724 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded
, OnUnloaded
)
725 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions
, OnUpdatePermissions
)
726 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions
,
727 OnUpdateTabSpecificPermissions
)
728 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions
,
729 OnClearTabSpecificPermissions
)
730 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI
, OnUsingWebRequestAPI
)
731 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages
,
732 content_watcher_
.get(),
733 ContentWatcher::OnWatchPages
)
734 IPC_MESSAGE_UNHANDLED(handled
= false)
735 IPC_END_MESSAGE_MAP()
740 void Dispatcher::WebKitInitialized() {
741 // For extensions, we want to ensure we call the IdleHandler every so often,
742 // even if the extension keeps up activity.
743 if (set_idle_notifications_
) {
744 forced_idle_timer_
.reset(new base::RepeatingTimer
<content::RenderThread
>);
745 forced_idle_timer_
->Start(
747 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs
),
749 &RenderThread::IdleHandler
);
752 // Initialize host permissions for any extensions that were activated before
753 // WebKit was initialized.
754 for (const std::string
& extension_id
: active_extension_ids_
) {
755 const Extension
* extension
= extensions_
.GetByID(extension_id
);
757 InitOriginPermissions(extension
);
760 EnableCustomElementWhiteList();
762 is_webkit_initialized_
= true;
765 void Dispatcher::IdleNotification() {
766 if (set_idle_notifications_
&& forced_idle_timer_
) {
767 // Dampen the forced delay as well if the extension stays idle for long
768 // periods of time. (forced_idle_timer_ can be NULL after
769 // OnRenderProcessShutdown has been called.)
770 int64 forced_delay_ms
=
771 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
772 kMaxExtensionIdleHandlerDelayMs
);
773 forced_idle_timer_
->Stop();
774 forced_idle_timer_
->Start(
776 base::TimeDelta::FromMilliseconds(forced_delay_ms
),
778 &RenderThread::IdleHandler
);
782 void Dispatcher::OnRenderProcessShutdown() {
783 v8_schema_registry_
.reset();
784 forced_idle_timer_
.reset();
785 content_watcher_
.reset();
788 void Dispatcher::OnActivateExtension(const std::string
& extension_id
) {
789 const Extension
* extension
= extensions_
.GetByID(extension_id
);
791 // Extension was activated but was never loaded. This probably means that
792 // the renderer failed to load it (or the browser failed to tell us when it
793 // did). Failures shouldn't happen, but instead of crashing there (which
794 // executes on all renderers) be conservative and only crash in the renderer
795 // of the extension which failed to load; this one.
796 std::string
& error
= extension_load_errors_
[extension_id
];
798 base::debug::Alias(&minidump
);
799 base::snprintf(minidump
,
801 "e::dispatcher:%s:%s",
802 extension_id
.c_str(),
804 LOG(FATAL
) << extension_id
<< " was never loaded: " << error
;
807 active_extension_ids_
.insert(extension_id
);
809 // This is called when starting a new extension page, so start the idle
811 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs
);
813 if (is_webkit_initialized_
) {
814 DOMActivityLogger::AttachToWorld(
815 DOMActivityLogger::kMainWorldId
, extension_id
);
817 InitOriginPermissions(extension
);
820 UpdateActiveExtensions();
823 void Dispatcher::OnCancelSuspend(const std::string
& extension_id
) {
824 DispatchEvent(extension_id
, kOnSuspendCanceledEvent
);
827 void Dispatcher::OnDeliverMessage(int target_port_id
, const Message
& message
) {
828 scoped_ptr
<RequestSender::ScopedTabID
> scoped_tab_id
;
829 std::map
<int, int>::const_iterator it
=
830 port_to_tab_id_map_
.find(target_port_id
);
831 if (it
!= port_to_tab_id_map_
.end()) {
833 new RequestSender::ScopedTabID(request_sender(), it
->second
));
836 MessagingBindings::DeliverMessage(*script_context_set_
, target_port_id
,
838 NULL
); // All render frames.
841 void Dispatcher::OnDispatchOnConnect(
843 const std::string
& channel_name
,
844 const ExtensionMsg_TabConnectionInfo
& source
,
845 const ExtensionMsg_ExternalConnectionInfo
& info
,
846 const std::string
& tls_channel_id
) {
847 DCHECK(!ContainsKey(port_to_tab_id_map_
, target_port_id
));
848 DCHECK_EQ(1, target_port_id
% 2); // target renderer ports have odd IDs.
849 int sender_tab_id
= -1;
850 source
.tab
.GetInteger("id", &sender_tab_id
);
851 port_to_tab_id_map_
[target_port_id
] = sender_tab_id
;
853 MessagingBindings::DispatchOnConnect(*script_context_set_
, target_port_id
,
854 channel_name
, source
, info
,
856 NULL
); // All render frames.
859 void Dispatcher::OnDispatchOnDisconnect(int port_id
,
860 const std::string
& error_message
) {
861 MessagingBindings::DispatchOnDisconnect(*script_context_set_
, port_id
,
863 NULL
); // All render frames.
866 void Dispatcher::OnLoaded(
867 const std::vector
<ExtensionMsg_Loaded_Params
>& loaded_extensions
) {
868 for (const auto& param
: loaded_extensions
) {
870 scoped_refptr
<const Extension
> extension
= param
.ConvertToExtension(&error
);
871 if (!extension
.get()) {
872 NOTREACHED() << error
;
873 // Note: in tests |param.id| has been observed to be empty (see comment
874 // just below) so this isn't all that reliable.
875 extension_load_errors_
[param
.id
] = error
;
879 // TODO(kalman): This test is deliberately not a CHECK (though I wish it
880 // could be) and uses extension->id() not params.id:
881 // 1. For some reason params.id can be empty. I've only seen it with
882 // the webstore extension, in tests, and I've spent some time trying to
883 // figure out why - but cost/benefit won.
884 // 2. The browser only sends this IPC to RenderProcessHosts once, but the
885 // Dispatcher is attached to a RenderThread. Presumably there is a
886 // mismatch there. In theory one would think it's possible for the
887 // browser to figure this out itself - but again, cost/benefit.
888 if (!extensions_
.Contains(extension
->id()))
889 extensions_
.Insert(extension
);
892 // Update the available bindings for all contexts. These may have changed if
893 // an externally_connectable extension was loaded that can connect to an
898 void Dispatcher::OnMessageInvoke(const std::string
& extension_id
,
899 const std::string
& module_name
,
900 const std::string
& function_name
,
901 const base::ListValue
& args
,
903 InvokeModuleSystemMethod(
904 NULL
, extension_id
, module_name
, function_name
, args
, user_gesture
);
907 void Dispatcher::OnSetChannel(int channel
) {
908 delegate_
->SetChannel(channel
);
909 AddChannelSpecificFeatures();
912 void Dispatcher::OnSetFunctionNames(const std::vector
<std::string
>& names
) {
913 function_names_
.clear();
914 for (size_t i
= 0; i
< names
.size(); ++i
)
915 function_names_
.insert(names
[i
]);
918 void Dispatcher::OnSetScriptingWhitelist(
919 const ExtensionsClient::ScriptingWhitelist
& extension_ids
) {
920 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids
);
923 void Dispatcher::OnSetSystemFont(const std::string
& font_family
,
924 const std::string
& font_size
) {
925 system_font_family_
= font_family
;
926 system_font_size_
= font_size
;
929 void Dispatcher::OnShouldSuspend(const std::string
& extension_id
,
930 uint64 sequence_id
) {
931 RenderThread::Get()->Send(
932 new ExtensionHostMsg_ShouldSuspendAck(extension_id
, sequence_id
));
935 void Dispatcher::OnSuspend(const std::string
& extension_id
) {
936 // Dispatch the suspend event. This doesn't go through the standard event
937 // dispatch machinery because it requires special handling. We need to let
938 // the browser know when we are starting and stopping the event dispatch, so
939 // that it still considers the extension idle despite any activity the suspend
941 DispatchEvent(extension_id
, kOnSuspendEvent
);
942 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id
));
945 void Dispatcher::OnTransferBlobs(const std::vector
<std::string
>& blob_uuids
) {
946 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids
));
949 void Dispatcher::OnUnloaded(const std::string
& id
) {
950 // See comment in OnLoaded for why it would be nice, but perhaps incorrect,
951 // to CHECK here rather than guarding.
952 if (!extensions_
.Remove(id
))
955 active_extension_ids_
.erase(id
);
957 script_injection_manager_
->OnExtensionUnloaded(id
);
959 // If the extension is later reloaded with a different set of permissions,
960 // we'd like it to get a new isolated world ID, so that it can pick up the
961 // changed origin whitelist.
962 ScriptInjection::RemoveIsolatedWorld(id
);
964 // Invalidate all of the contexts that were removed.
965 // TODO(kalman): add an invalidation observer interface to ScriptContext.
966 std::set
<ScriptContext
*> removed_contexts
=
967 script_context_set_
->OnExtensionUnloaded(id
);
968 for (ScriptContext
* context
: removed_contexts
) {
969 request_sender_
->InvalidateSource(context
);
972 // Update the available bindings for the remaining contexts. These may have
973 // changed if an externally_connectable extension is unloaded and a webpage
974 // is no longer accessible.
977 // Invalidates the messages map for the extension in case the extension is
978 // reloaded with a new messages map.
979 EraseL10nMessagesMap(id
);
981 // We don't do anything with existing platform-app stylesheets. They will
982 // stay resident, but the URL pattern corresponding to the unloaded
983 // extension's URL just won't match anything anymore.
986 void Dispatcher::OnUpdatePermissions(
987 const ExtensionMsg_UpdatePermissions_Params
& params
) {
988 const Extension
* extension
= extensions_
.GetByID(params
.extension_id
);
992 scoped_refptr
<const PermissionSet
> active
=
993 params
.active_permissions
.ToPermissionSet();
994 scoped_refptr
<const PermissionSet
> withheld
=
995 params
.withheld_permissions
.ToPermissionSet();
997 if (is_webkit_initialized_
) {
998 UpdateOriginPermissions(
1000 extension
->permissions_data()->GetEffectiveHostPermissions(),
1001 active
->effective_hosts());
1004 extension
->permissions_data()->SetPermissions(active
, withheld
);
1005 UpdateBindings(extension
->id());
1008 void Dispatcher::OnUpdateTabSpecificPermissions(const GURL
& visible_url
,
1009 const std::string
& extension_id
,
1010 const URLPatternSet
& new_hosts
,
1011 bool update_origin_whitelist
,
1013 const Extension
* extension
= extensions_
.GetByID(extension_id
);
1017 URLPatternSet old_effective
=
1018 extension
->permissions_data()->GetEffectiveHostPermissions();
1019 extension
->permissions_data()->UpdateTabSpecificPermissions(
1021 new extensions::PermissionSet(extensions::APIPermissionSet(),
1022 extensions::ManifestPermissionSet(),
1024 extensions::URLPatternSet()));
1026 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1027 UpdateOriginPermissions(
1030 extension
->permissions_data()->GetEffectiveHostPermissions());
1034 void Dispatcher::OnClearTabSpecificPermissions(
1035 const std::vector
<std::string
>& extension_ids
,
1036 bool update_origin_whitelist
,
1038 for (const std::string
& id
: extension_ids
) {
1039 const Extension
* extension
= extensions_
.GetByID(id
);
1041 URLPatternSet old_effective
=
1042 extension
->permissions_data()->GetEffectiveHostPermissions();
1043 extension
->permissions_data()->ClearTabSpecificPermissions(tab_id
);
1044 if (is_webkit_initialized_
&& update_origin_whitelist
) {
1045 UpdateOriginPermissions(
1048 extension
->permissions_data()->GetEffectiveHostPermissions());
1054 void Dispatcher::OnUsingWebRequestAPI(bool webrequest_used
) {
1055 webrequest_used_
= webrequest_used
;
1058 void Dispatcher::OnUserScriptsUpdated(const std::set
<HostID
>& changed_hosts
,
1059 const std::vector
<UserScript
*>& scripts
) {
1060 UpdateActiveExtensions();
1063 void Dispatcher::UpdateActiveExtensions() {
1064 std::set
<std::string
> active_extensions
= active_extension_ids_
;
1065 user_script_set_manager_
->GetAllActiveExtensionIds(&active_extensions
);
1066 delegate_
->OnActiveExtensionsUpdated(active_extensions
);
1069 void Dispatcher::InitOriginPermissions(const Extension
* extension
) {
1070 delegate_
->InitOriginPermissions(extension
,
1071 IsExtensionActive(extension
->id()));
1072 UpdateOriginPermissions(
1074 URLPatternSet(), // No old permissions.
1075 extension
->permissions_data()->GetEffectiveHostPermissions());
1078 void Dispatcher::UpdateOriginPermissions(const GURL
& extension_url
,
1079 const URLPatternSet
& old_patterns
,
1080 const URLPatternSet
& new_patterns
) {
1081 static const char* kSchemes
[] = {
1085 content::kChromeUIScheme
,
1087 #if defined(OS_CHROMEOS)
1088 content::kExternalFileScheme
,
1090 extensions::kExtensionScheme
,
1092 for (size_t i
= 0; i
< arraysize(kSchemes
); ++i
) {
1093 const char* scheme
= kSchemes
[i
];
1094 // Remove all old patterns...
1095 for (URLPatternSet::const_iterator pattern
= old_patterns
.begin();
1096 pattern
!= old_patterns
.end(); ++pattern
) {
1097 if (pattern
->MatchesScheme(scheme
)) {
1098 WebSecurityPolicy::removeOriginAccessWhitelistEntry(
1100 WebString::fromUTF8(scheme
),
1101 WebString::fromUTF8(pattern
->host()),
1102 pattern
->match_subdomains());
1105 // ...And add the new ones.
1106 for (URLPatternSet::const_iterator pattern
= new_patterns
.begin();
1107 pattern
!= new_patterns
.end(); ++pattern
) {
1108 if (pattern
->MatchesScheme(scheme
)) {
1109 WebSecurityPolicy::addOriginAccessWhitelistEntry(
1111 WebString::fromUTF8(scheme
),
1112 WebString::fromUTF8(pattern
->host()),
1113 pattern
->match_subdomains());
1119 void Dispatcher::EnableCustomElementWhiteList() {
1120 blink::WebCustomElement::addEmbedderCustomElementName("appview");
1121 blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
1122 blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
1123 blink::WebCustomElement::addEmbedderCustomElementName(
1124 "extensionoptionsbrowserplugin");
1125 blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
1126 blink::WebCustomElement::addEmbedderCustomElementName(
1127 "extensionviewbrowserplugin");
1128 blink::WebCustomElement::addEmbedderCustomElementName("webview");
1129 blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
1130 blink::WebCustomElement::addEmbedderCustomElementName("surfaceview");
1131 blink::WebCustomElement::addEmbedderCustomElementName(
1132 "surfaceviewbrowserplugin");
1135 void Dispatcher::UpdateBindings(const std::string
& extension_id
) {
1136 script_context_set().ForEach(extension_id
,
1137 base::Bind(&Dispatcher::UpdateBindingsForContext
,
1138 base::Unretained(this)));
1141 void Dispatcher::UpdateBindingsForContext(ScriptContext
* context
) {
1142 v8::HandleScope
handle_scope(context
->isolate());
1143 v8::Context::Scope
context_scope(context
->v8_context());
1145 // TODO(kalman): Make the bindings registration have zero overhead then run
1146 // the same code regardless of context type.
1147 switch (context
->context_type()) {
1148 case Feature::UNSPECIFIED_CONTEXT
:
1149 case Feature::WEB_PAGE_CONTEXT
:
1150 case Feature::BLESSED_WEB_PAGE_CONTEXT
:
1151 // Hard-code registration of any APIs that are exposed to webpage-like
1152 // contexts, because it's too expensive to run the full bindings code.
1153 // All of the same permission checks will still apply.
1154 if (context
->GetAvailability("app").is_available())
1155 RegisterBinding("app", context
);
1156 if (context
->GetAvailability("webstore").is_available())
1157 RegisterBinding("webstore", context
);
1158 if (context
->GetAvailability("dashboardPrivate").is_available())
1159 RegisterBinding("dashboardPrivate", context
);
1160 if (IsRuntimeAvailableToContext(context
))
1161 RegisterBinding("runtime", context
);
1162 UpdateContentCapabilities(context
);
1165 case Feature::BLESSED_EXTENSION_CONTEXT
:
1166 case Feature::UNBLESSED_EXTENSION_CONTEXT
:
1167 case Feature::CONTENT_SCRIPT_CONTEXT
:
1168 case Feature::WEBUI_CONTEXT
: {
1169 // Extension context; iterate through all the APIs and bind the available
1171 const FeatureProvider
* api_feature_provider
=
1172 FeatureProvider::GetAPIFeatures();
1173 const std::vector
<std::string
>& apis
=
1174 api_feature_provider
->GetAllFeatureNames();
1175 for (const std::string
& api_name
: apis
) {
1176 Feature
* feature
= api_feature_provider
->GetFeature(api_name
);
1179 // Internal APIs are included via require(api_name) from internal code
1180 // rather than chrome[api_name].
1181 if (feature
->IsInternal())
1184 // If this API has a parent feature (and isn't marked 'noparent'),
1185 // then this must be a function or event, so we should not register.
1186 if (api_feature_provider
->GetParent(feature
) != NULL
)
1189 // Skip chrome.test if this isn't a test.
1190 if (api_name
== "test" &&
1191 !base::CommandLine::ForCurrentProcess()->HasSwitch(
1192 ::switches::kTestType
)) {
1196 if (context
->IsAnyFeatureAvailableToContext(*feature
))
1197 RegisterBinding(api_name
, context
);
1204 void Dispatcher::RegisterBinding(const std::string
& api_name
,
1205 ScriptContext
* context
) {
1206 std::string bind_name
;
1207 v8::Local
<v8::Object
> bind_object
=
1208 GetOrCreateBindObjectIfAvailable(api_name
, &bind_name
, context
);
1210 // Empty if the bind object failed to be created, probably because the
1211 // extension overrode chrome with a non-object, e.g. window.chrome = true.
1212 if (bind_object
.IsEmpty())
1215 v8::Local
<v8::String
> v8_bind_name
=
1216 v8::String::NewFromUtf8(context
->isolate(), bind_name
.c_str());
1217 if (bind_object
->HasRealNamedProperty(v8_bind_name
)) {
1218 // The bind object may already have the property if the API has been
1219 // registered before (or if the extension has put something there already,
1222 // In the former case, we need to re-register the bindings for the APIs
1223 // which the extension now has permissions for (if any), but not touch any
1224 // others so that we don't destroy state such as event listeners.
1226 // TODO(kalman): Only register available APIs to make this all moot.
1227 if (bind_object
->HasRealNamedCallbackProperty(v8_bind_name
))
1228 return; // lazy binding still there, nothing to do
1229 if (bind_object
->Get(v8_bind_name
)->IsObject())
1230 return; // binding has already been fully installed
1233 ModuleSystem
* module_system
= context
->module_system();
1234 if (!source_map_
.Contains(api_name
)) {
1235 module_system
->RegisterNativeHandler(
1237 scoped_ptr
<NativeHandler
>(new BindingGeneratingNativeHandler(
1238 context
, api_name
, "binding")));
1239 module_system
->SetNativeLazyField(
1240 bind_object
, bind_name
, api_name
, "binding");
1242 module_system
->SetLazyField(bind_object
, bind_name
, api_name
, "binding");
1246 // NOTE: please use the naming convention "foo_natives" for these.
1247 void Dispatcher::RegisterNativeHandlers(ModuleSystem
* module_system
,
1248 ScriptContext
* context
) {
1249 RegisterNativeHandlers(module_system
,
1252 request_sender_
.get(),
1253 v8_schema_registry_
.get());
1254 const Extension
* extension
= context
->extension();
1255 int manifest_version
= extension
? extension
->manifest_version() : 1;
1256 bool is_component_extension
=
1257 extension
&& Manifest::IsComponentLocation(extension
->location());
1258 bool send_request_disabled
=
1259 (extension
&& Manifest::IsUnpackedLocation(extension
->location()) &&
1260 BackgroundInfo::HasLazyBackgroundPage(extension
));
1261 module_system
->RegisterNativeHandler(
1263 scoped_ptr
<NativeHandler
>(new ProcessInfoNativeHandler(
1265 context
->GetExtensionID(),
1266 context
->GetContextTypeDescription(),
1267 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1268 is_component_extension
,
1270 send_request_disabled
)));
1272 delegate_
->RegisterNativeHandlers(this, module_system
, context
);
1275 bool Dispatcher::IsRuntimeAvailableToContext(ScriptContext
* context
) {
1276 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1277 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1280 for (const auto& extension
: extensions_
) {
1281 ExternallyConnectableInfo
* info
= static_cast<ExternallyConnectableInfo
*>(
1282 extension
->GetManifestData(manifest_keys::kExternallyConnectable
));
1283 if (info
&& info
->matches
.MatchesURL(context
->GetURL()))
1289 void Dispatcher::UpdateContentCapabilities(ScriptContext
* context
) {
1290 APIPermissionSet permissions
;
1291 for (const auto& extension
: extensions_
) {
1292 const ContentCapabilitiesInfo
& info
=
1293 ContentCapabilitiesInfo::Get(extension
.get());
1294 if (info
.url_patterns
.MatchesURL(context
->GetURL())) {
1295 APIPermissionSet new_permissions
;
1296 APIPermissionSet::Union(permissions
, info
.permissions
, &new_permissions
);
1297 permissions
= new_permissions
;
1300 context
->SetContentCapabilities(permissions
);
1303 void Dispatcher::PopulateSourceMap() {
1304 const std::vector
<std::pair
<std::string
, int> > resources
= GetJsResources();
1305 for (std::vector
<std::pair
<std::string
, int> >::const_iterator resource
=
1307 resource
!= resources
.end();
1309 source_map_
.RegisterSource(resource
->first
, resource
->second
);
1311 delegate_
->PopulateSourceMap(&source_map_
);
1314 bool Dispatcher::IsWithinPlatformApp() {
1315 for (std::set
<std::string
>::iterator iter
= active_extension_ids_
.begin();
1316 iter
!= active_extension_ids_
.end();
1318 const Extension
* extension
= extensions_
.GetByID(*iter
);
1319 if (extension
&& extension
->is_platform_app())
1325 v8::Local
<v8::Object
> Dispatcher::GetOrCreateObject(
1326 const v8::Local
<v8::Object
>& object
,
1327 const std::string
& field
,
1328 v8::Isolate
* isolate
) {
1329 v8::Local
<v8::String
> key
= v8::String::NewFromUtf8(isolate
, field
.c_str());
1330 // If the object has a callback property, it is assumed it is an unavailable
1331 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1333 if (object
->HasRealNamedCallbackProperty(key
)) {
1334 object
->Delete(key
);
1335 } else if (object
->HasRealNamedProperty(key
)) {
1336 v8::Local
<v8::Value
> value
= object
->Get(key
);
1337 CHECK(value
->IsObject());
1338 return v8::Local
<v8::Object
>::Cast(value
);
1341 v8::Local
<v8::Object
> new_object
= v8::Object::New(isolate
);
1342 object
->Set(key
, new_object
);
1346 v8::Local
<v8::Object
> Dispatcher::GetOrCreateBindObjectIfAvailable(
1347 const std::string
& api_name
,
1348 std::string
* bind_name
,
1349 ScriptContext
* context
) {
1350 std::vector
<std::string
> split
= base::SplitString(
1351 api_name
, ".", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
1353 v8::Local
<v8::Object
> bind_object
;
1355 // Check if this API has an ancestor. If the API's ancestor is available and
1356 // the API is not available, don't install the bindings for this API. If
1357 // the API is available and its ancestor is not, delete the ancestor and
1358 // install the bindings for the API. This is to prevent loading the ancestor
1359 // API schema if it will not be needed.
1362 // If app is available and app.window is not, just install app.
1363 // If app.window is available and app is not, delete app and install
1364 // app.window on a new object so app does not have to be loaded.
1365 const FeatureProvider
* api_feature_provider
=
1366 FeatureProvider::GetAPIFeatures();
1367 std::string ancestor_name
;
1368 bool only_ancestor_available
= false;
1370 for (size_t i
= 0; i
< split
.size() - 1; ++i
) {
1371 ancestor_name
+= (i
? "." : "") + split
[i
];
1372 if (api_feature_provider
->GetFeature(ancestor_name
) &&
1373 context
->GetAvailability(ancestor_name
).is_available() &&
1374 !context
->GetAvailability(api_name
).is_available()) {
1375 only_ancestor_available
= true;
1379 if (bind_object
.IsEmpty()) {
1380 bind_object
= AsObjectOrEmpty(GetOrCreateChrome(context
));
1381 if (bind_object
.IsEmpty())
1382 return v8::Local
<v8::Object
>();
1384 bind_object
= GetOrCreateObject(bind_object
, split
[i
], context
->isolate());
1387 if (only_ancestor_available
)
1388 return v8::Local
<v8::Object
>();
1391 *bind_name
= split
.back();
1393 return bind_object
.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context
))
1397 void Dispatcher::RequireGuestViewModules(ScriptContext
* context
) {
1398 Feature::Context context_type
= context
->context_type();
1399 ModuleSystem
* module_system
= context
->module_system();
1402 if (context
->GetAvailability("appViewEmbedderInternal").is_available()) {
1403 module_system
->Require("appView");
1406 // Require ExtensionOptions.
1407 if (context
->GetAvailability("extensionOptionsInternal").is_available()) {
1408 module_system
->Require("extensionOptions");
1409 module_system
->Require("extensionOptionsAttributes");
1412 // Require ExtensionView.
1413 if (context
->GetAvailability("extensionViewInternal").is_available()) {
1414 module_system
->Require("extensionView");
1415 module_system
->Require("extensionViewApiMethods");
1416 module_system
->Require("extensionViewAttributes");
1419 // Require SurfaceView.
1420 if (extensions::FeatureSwitch::surface_worker()->IsEnabled() &&
1421 context
->GetAvailability("surfaceWorkerInternal").is_available()) {
1422 module_system
->Require("surfaceWorker");
1426 if (context
->GetAvailability("webViewInternal").is_available()) {
1427 module_system
->Require("webView");
1428 module_system
->Require("webViewApiMethods");
1429 module_system
->Require("webViewAttributes");
1431 if (content::BrowserPluginGuestMode::UseCrossProcessFramesForGuests()) {
1432 module_system
->Require("webViewIframe");
1436 // The "guestViewDeny" module must always be loaded last. It registers
1437 // error-providing custom elements for the GuestView types that are not
1438 // available, and thus all of those types must have been checked and loaded
1439 // (or not loaded) beforehand.
1440 if (context_type
== Feature::BLESSED_EXTENSION_CONTEXT
) {
1441 module_system
->Require("guestViewDeny");
1445 void Dispatcher::AddChannelSpecificFeatures() {
1446 // chrome-extension: resources should be allowed to register a Service Worker.
1447 if (FeatureProvider::GetBehaviorFeature(BehaviorFeature::kServiceWorker
)
1448 ->IsAvailableToEnvironment()
1450 WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
1451 WebString::fromUTF8(kExtensionScheme
));
1454 } // namespace extensions