Remove adview
[chromium-blink-merge.git] / extensions / renderer / dispatcher.cc
blob12beada9957dde24f4f03f5b8191cda670afdda3
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"
7 #include "base/callback.h"
8 #include "base/command_line.h"
9 #include "base/debug/alias.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/metrics/user_metrics_action.h"
12 #include "base/strings/string_piece.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/values.h"
16 #include "content/public/common/content_switches.h"
17 #include "content/public/common/url_constants.h"
18 #include "content/public/renderer/render_thread.h"
19 #include "content/public/renderer/render_view.h"
20 #include "content/public/renderer/v8_value_converter.h"
21 #include "extensions/common/api/messaging/message.h"
22 #include "extensions/common/constants.h"
23 #include "extensions/common/extension.h"
24 #include "extensions/common/extension_api.h"
25 #include "extensions/common/extension_messages.h"
26 #include "extensions/common/extension_urls.h"
27 #include "extensions/common/features/feature.h"
28 #include "extensions/common/features/feature_provider.h"
29 #include "extensions/common/manifest.h"
30 #include "extensions/common/manifest_constants.h"
31 #include "extensions/common/manifest_handlers/background_info.h"
32 #include "extensions/common/manifest_handlers/externally_connectable.h"
33 #include "extensions/common/manifest_handlers/sandboxed_page_info.h"
34 #include "extensions/common/message_bundle.h"
35 #include "extensions/common/permissions/permission_set.h"
36 #include "extensions/common/permissions/permissions_data.h"
37 #include "extensions/common/switches.h"
38 #include "extensions/common/view_type.h"
39 #include "extensions/renderer/api_activity_logger.h"
40 #include "extensions/renderer/api_definitions_natives.h"
41 #include "extensions/renderer/app_runtime_custom_bindings.h"
42 #include "extensions/renderer/binding_generating_native_handler.h"
43 #include "extensions/renderer/blob_native_handler.h"
44 #include "extensions/renderer/content_watcher.h"
45 #include "extensions/renderer/context_menus_custom_bindings.h"
46 #include "extensions/renderer/css_native_handler.h"
47 #include "extensions/renderer/dispatcher_delegate.h"
48 #include "extensions/renderer/document_custom_bindings.h"
49 #include "extensions/renderer/dom_activity_logger.h"
50 #include "extensions/renderer/event_bindings.h"
51 #include "extensions/renderer/extension_groups.h"
52 #include "extensions/renderer/extension_helper.h"
53 #include "extensions/renderer/extensions_renderer_client.h"
54 #include "extensions/renderer/file_system_natives.h"
55 #include "extensions/renderer/i18n_custom_bindings.h"
56 #include "extensions/renderer/id_generator_custom_bindings.h"
57 #include "extensions/renderer/lazy_background_page_native_handler.h"
58 #include "extensions/renderer/logging_native_handler.h"
59 #include "extensions/renderer/messaging_bindings.h"
60 #include "extensions/renderer/module_system.h"
61 #include "extensions/renderer/print_native_handler.h"
62 #include "extensions/renderer/process_info_native_handler.h"
63 #include "extensions/renderer/render_view_observer_natives.h"
64 #include "extensions/renderer/request_sender.h"
65 #include "extensions/renderer/runtime_custom_bindings.h"
66 #include "extensions/renderer/safe_builtins.h"
67 #include "extensions/renderer/script_context.h"
68 #include "extensions/renderer/script_context_set.h"
69 #include "extensions/renderer/send_request_natives.h"
70 #include "extensions/renderer/set_icon_natives.h"
71 #include "extensions/renderer/test_features_native_handler.h"
72 #include "extensions/renderer/user_gestures_native_handler.h"
73 #include "extensions/renderer/user_script_slave.h"
74 #include "extensions/renderer/utils_native_handler.h"
75 #include "extensions/renderer/v8_context_native_handler.h"
76 #include "grit/extensions_renderer_resources.h"
77 #include "third_party/WebKit/public/platform/WebString.h"
78 #include "third_party/WebKit/public/platform/WebURLRequest.h"
79 #include "third_party/WebKit/public/web/WebCustomElement.h"
80 #include "third_party/WebKit/public/web/WebDataSource.h"
81 #include "third_party/WebKit/public/web/WebDocument.h"
82 #include "third_party/WebKit/public/web/WebFrame.h"
83 #include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
84 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
85 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
86 #include "third_party/WebKit/public/web/WebView.h"
87 #include "ui/base/layout.h"
88 #include "ui/base/resource/resource_bundle.h"
89 #include "v8/include/v8.h"
91 using base::UserMetricsAction;
92 using blink::WebDataSource;
93 using blink::WebDocument;
94 using blink::WebFrame;
95 using blink::WebScopedUserGesture;
96 using blink::WebSecurityPolicy;
97 using blink::WebString;
98 using blink::WebVector;
99 using blink::WebView;
100 using content::RenderThread;
101 using content::RenderView;
103 namespace extensions {
105 namespace {
107 static const int64 kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
108 static const int64 kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
109 static const char kEventDispatchFunction[] = "dispatchEvent";
110 static const char kOnSuspendEvent[] = "runtime.onSuspend";
111 static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
113 // Returns the global value for "chrome" from |context|. If one doesn't exist
114 // creates a new object for it.
116 // Note that this isn't necessarily an object, since webpages can write, for
117 // example, "window.chrome = true".
118 v8::Handle<v8::Value> GetOrCreateChrome(ScriptContext* context) {
119 v8::Handle<v8::String> chrome_string(
120 v8::String::NewFromUtf8(context->isolate(), "chrome"));
121 v8::Handle<v8::Object> global(context->v8_context()->Global());
122 v8::Handle<v8::Value> chrome(global->Get(chrome_string));
123 if (chrome->IsUndefined()) {
124 chrome = v8::Object::New(context->isolate());
125 global->Set(chrome_string, chrome);
127 return chrome;
130 // Returns |value| cast to an object if possible, else an empty handle.
131 v8::Handle<v8::Object> AsObjectOrEmpty(v8::Handle<v8::Value> value) {
132 return value->IsObject() ? value.As<v8::Object>() : v8::Handle<v8::Object>();
135 // Calls a method |method_name| in a module |module_name| belonging to the
136 // module system from |context|. Intended as a callback target from
137 // ScriptContextSet::ForEach.
138 void CallModuleMethod(const std::string& module_name,
139 const std::string& method_name,
140 const base::ListValue* args,
141 ScriptContext* context) {
142 v8::HandleScope handle_scope(context->isolate());
143 v8::Context::Scope context_scope(context->v8_context());
145 scoped_ptr<content::V8ValueConverter> converter(
146 content::V8ValueConverter::create());
148 std::vector<v8::Handle<v8::Value> > arguments;
149 for (base::ListValue::const_iterator it = args->begin(); it != args->end();
150 ++it) {
151 arguments.push_back(converter->ToV8Value(*it, context->v8_context()));
154 context->module_system()->CallModuleMethod(
155 module_name, method_name, &arguments);
158 // This handles the "chrome." root API object in script contexts.
159 class ChromeNativeHandler : public ObjectBackedNativeHandler {
160 public:
161 explicit ChromeNativeHandler(ScriptContext* context)
162 : ObjectBackedNativeHandler(context) {
163 RouteFunction(
164 "GetChrome",
165 base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
168 void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
169 args.GetReturnValue().Set(GetOrCreateChrome(context()));
173 } // namespace
175 Dispatcher::Dispatcher(DispatcherDelegate* delegate)
176 : delegate_(delegate),
177 content_watcher_(new ContentWatcher()),
178 source_map_(&ResourceBundle::GetSharedInstance()),
179 v8_schema_registry_(new V8SchemaRegistry),
180 is_webkit_initialized_(false) {
181 const CommandLine& command_line = *(CommandLine::ForCurrentProcess());
182 is_extension_process_ =
183 command_line.HasSwitch(extensions::switches::kExtensionProcess) ||
184 command_line.HasSwitch(::switches::kSingleProcess);
186 if (is_extension_process_) {
187 RenderThread::Get()->SetIdleNotificationDelayInMs(
188 kInitialExtensionIdleHandlerDelayMs);
191 RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
193 user_script_slave_.reset(new UserScriptSlave(&extensions_));
194 request_sender_.reset(new RequestSender(this));
195 PopulateSourceMap();
198 Dispatcher::~Dispatcher() {
201 bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
202 bool is_active =
203 active_extension_ids_.find(extension_id) != active_extension_ids_.end();
204 if (is_active)
205 CHECK(extensions_.Contains(extension_id));
206 return is_active;
209 std::string Dispatcher::GetExtensionID(const WebFrame* frame, int world_id) {
210 if (world_id != 0) {
211 // Isolated worlds (content script).
212 return user_script_slave_->GetExtensionIdForIsolatedWorld(world_id);
215 // TODO(kalman): Delete this check.
216 if (frame->document().securityOrigin().isUnique())
217 return std::string();
219 // Extension pages (chrome-extension:// URLs).
220 GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame);
221 return extensions_.GetExtensionOrAppIDByURL(frame_url);
224 void Dispatcher::DidCreateScriptContext(
225 WebFrame* frame,
226 const v8::Handle<v8::Context>& v8_context,
227 int extension_group,
228 int world_id) {
229 #if !defined(ENABLE_EXTENSIONS)
230 return;
231 #endif
233 std::string extension_id = GetExtensionID(frame, world_id);
235 const Extension* extension = extensions_.GetByID(extension_id);
236 if (!extension && !extension_id.empty()) {
237 // There are conditions where despite a context being associated with an
238 // extension, no extension actually gets found. Ignore "invalid" because
239 // CSP blocks extension page loading by switching the extension ID to
240 // "invalid". This isn't interesting.
241 if (extension_id != "invalid") {
242 LOG(ERROR) << "Extension \"" << extension_id << "\" not found";
243 RenderThread::Get()->RecordAction(
244 UserMetricsAction("ExtensionNotFound_ED"));
247 extension_id = "";
250 Feature::Context context_type =
251 ClassifyJavaScriptContext(extension,
252 extension_group,
253 ScriptContext::GetDataSourceURLForFrame(frame),
254 frame->document().securityOrigin());
256 ScriptContext* context =
257 delegate_->CreateScriptContext(v8_context, frame, extension, context_type)
258 .release();
259 script_context_set_.Add(context);
261 // Initialize origin permissions for content scripts, which can't be
262 // initialized in |OnActivateExtension|.
263 if (context_type == Feature::CONTENT_SCRIPT_CONTEXT)
264 InitOriginPermissions(extension);
267 scoped_ptr<ModuleSystem> module_system(
268 new ModuleSystem(context, &source_map_));
269 context->set_module_system(module_system.Pass());
271 ModuleSystem* module_system = context->module_system();
273 // Enable natives in startup.
274 ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
276 RegisterNativeHandlers(module_system, context);
278 // chrome.Event is part of the public API (although undocumented). Make it
279 // lazily evalulate to Event from event_bindings.js. For extensions only
280 // though, not all webpages!
281 if (context->extension()) {
282 v8::Handle<v8::Object> chrome = AsObjectOrEmpty(GetOrCreateChrome(context));
283 if (!chrome.IsEmpty())
284 module_system->SetLazyField(chrome, "Event", kEventBindings, "Event");
287 UpdateBindingsForContext(context);
289 bool is_within_platform_app = IsWithinPlatformApp();
290 // Inject custom JS into the platform app context.
291 if (is_within_platform_app) {
292 module_system->Require("platformApp");
295 delegate_->RequireAdditionalModules(
296 module_system, extension, context_type, is_within_platform_app);
298 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
301 void Dispatcher::WillReleaseScriptContext(
302 WebFrame* frame,
303 const v8::Handle<v8::Context>& v8_context,
304 int world_id) {
305 ScriptContext* context = script_context_set_.GetByV8Context(v8_context);
306 if (!context)
307 return;
309 context->DispatchOnUnloadEvent();
310 // TODO(kalman): add an invalidation observer interface to ScriptContext.
311 request_sender_->InvalidateSource(context);
313 script_context_set_.Remove(context);
314 VLOG(1) << "Num tracked contexts: " << script_context_set_.size();
317 void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) {
318 if (IsWithinPlatformApp()) {
319 // WebKit doesn't let us define an additional user agent stylesheet, so we
320 // insert the default platform app stylesheet into all documents that are
321 // loaded in each app.
322 std::string stylesheet = ResourceBundle::GetSharedInstance()
323 .GetRawDataResource(IDR_PLATFORM_APP_CSS)
324 .as_string();
325 ReplaceFirstSubstringAfterOffset(
326 &stylesheet, 0, "$FONTFAMILY", system_font_family_);
327 ReplaceFirstSubstringAfterOffset(
328 &stylesheet, 0, "$FONTSIZE", system_font_size_);
329 frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
332 content_watcher_->DidCreateDocumentElement(frame);
335 void Dispatcher::DidMatchCSS(
336 blink::WebFrame* frame,
337 const blink::WebVector<blink::WebString>& newly_matching_selectors,
338 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
339 content_watcher_->DidMatchCSS(
340 frame, newly_matching_selectors, stopped_matching_selectors);
343 void Dispatcher::OnExtensionResponse(int request_id,
344 bool success,
345 const base::ListValue& response,
346 const std::string& error) {
347 request_sender_->HandleResponse(request_id, success, response, error);
350 bool Dispatcher::CheckContextAccessToExtensionAPI(
351 const std::string& function_name,
352 ScriptContext* context) const {
353 if (!context) {
354 DLOG(ERROR) << "Not in a v8::Context";
355 return false;
358 if (!context->extension()) {
359 context->isolate()->ThrowException(v8::Exception::Error(
360 v8::String::NewFromUtf8(context->isolate(), "Not in an extension.")));
361 return false;
364 // Theoretically we could end up with bindings being injected into sandboxed
365 // frames, for example content scripts. Don't let them execute API functions.
366 blink::WebFrame* frame = context->web_frame();
367 if (IsSandboxedPage(ScriptContext::GetDataSourceURLForFrame(frame))) {
368 static const char kMessage[] =
369 "%s cannot be used within a sandboxed frame.";
370 std::string error_msg = base::StringPrintf(kMessage, function_name.c_str());
371 context->isolate()->ThrowException(v8::Exception::Error(
372 v8::String::NewFromUtf8(context->isolate(), error_msg.c_str())));
373 return false;
376 Feature::Availability availability = context->GetAvailability(function_name);
377 if (!availability.is_available()) {
378 context->isolate()->ThrowException(
379 v8::Exception::Error(v8::String::NewFromUtf8(
380 context->isolate(), availability.message().c_str())));
383 return availability.is_available();
386 void Dispatcher::DispatchEvent(const std::string& extension_id,
387 const std::string& event_name) const {
388 base::ListValue args;
389 args.Set(0, new base::StringValue(event_name));
390 args.Set(1, new base::ListValue());
392 // Needed for Windows compilation, since kEventBindings is declared extern.
393 const char* local_event_bindings = kEventBindings;
394 script_context_set_.ForEach(extension_id,
395 base::Bind(&CallModuleMethod,
396 local_event_bindings,
397 kEventDispatchFunction,
398 &args));
401 void Dispatcher::InvokeModuleSystemMethod(content::RenderView* render_view,
402 const std::string& extension_id,
403 const std::string& module_name,
404 const std::string& function_name,
405 const base::ListValue& args,
406 bool user_gesture) {
407 scoped_ptr<WebScopedUserGesture> web_user_gesture;
408 if (user_gesture)
409 web_user_gesture.reset(new WebScopedUserGesture);
411 script_context_set_.ForEach(
412 extension_id,
413 render_view,
414 base::Bind(&CallModuleMethod, module_name, function_name, &args));
416 // Reset the idle handler each time there's any activity like event or message
417 // dispatch, for which Invoke is the chokepoint.
418 if (is_extension_process_) {
419 RenderThread::Get()->ScheduleIdleHandler(
420 kInitialExtensionIdleHandlerDelayMs);
423 // Tell the browser process when an event has been dispatched with a lazy
424 // background page active.
425 const Extension* extension = extensions_.GetByID(extension_id);
426 if (extension && BackgroundInfo::HasLazyBackgroundPage(extension) &&
427 module_name == kEventBindings &&
428 function_name == kEventDispatchFunction) {
429 RenderView* background_view =
430 ExtensionHelper::GetBackgroundPage(extension_id);
431 if (background_view) {
432 background_view->Send(
433 new ExtensionHostMsg_EventAck(background_view->GetRoutingID()));
438 void Dispatcher::ClearPortData(int port_id) {
439 // Only the target port side has entries in |port_to_tab_id_map_|. If
440 // |port_id| is a source port, std::map::erase() will just silently fail
441 // here as a no-op.
442 port_to_tab_id_map_.erase(port_id);
445 bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
446 bool handled = true;
447 IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
448 IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
449 IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
450 IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
451 OnClearTabSpecificPermissions)
452 IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
453 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
454 IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
455 IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
456 IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
457 IPC_MESSAGE_HANDLER(ExtensionMsg_SetChannel, OnSetChannel)
458 IPC_MESSAGE_HANDLER(ExtensionMsg_SetFunctionNames, OnSetFunctionNames)
459 IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
460 OnSetScriptingWhitelist)
461 IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
462 IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
463 IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
464 IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
465 IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
466 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
467 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
468 OnUpdateTabSpecificPermissions)
469 IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateUserScripts, OnUpdateUserScripts)
470 IPC_MESSAGE_HANDLER(ExtensionMsg_UsingWebRequestAPI, OnUsingWebRequestAPI)
471 IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
472 content_watcher_.get(),
473 ContentWatcher::OnWatchPages)
474 IPC_MESSAGE_UNHANDLED(handled = false)
475 IPC_END_MESSAGE_MAP()
477 return handled;
480 void Dispatcher::WebKitInitialized() {
481 // For extensions, we want to ensure we call the IdleHandler every so often,
482 // even if the extension keeps up activity.
483 if (is_extension_process_) {
484 forced_idle_timer_.reset(new base::RepeatingTimer<content::RenderThread>);
485 forced_idle_timer_->Start(
486 FROM_HERE,
487 base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
488 RenderThread::Get(),
489 &RenderThread::IdleHandler);
492 // Initialize host permissions for any extensions that were activated before
493 // WebKit was initialized.
494 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
495 iter != active_extension_ids_.end();
496 ++iter) {
497 const Extension* extension = extensions_.GetByID(*iter);
498 CHECK(extension);
500 InitOriginPermissions(extension);
503 EnableCustomElementWhiteList();
505 is_webkit_initialized_ = true;
508 void Dispatcher::IdleNotification() {
509 if (is_extension_process_) {
510 // Dampen the forced delay as well if the extension stays idle for long
511 // periods of time.
512 int64 forced_delay_ms =
513 std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
514 kMaxExtensionIdleHandlerDelayMs);
515 forced_idle_timer_->Stop();
516 forced_idle_timer_->Start(
517 FROM_HERE,
518 base::TimeDelta::FromMilliseconds(forced_delay_ms),
519 RenderThread::Get(),
520 &RenderThread::IdleHandler);
524 void Dispatcher::OnRenderProcessShutdown() {
525 v8_schema_registry_.reset();
526 forced_idle_timer_.reset();
529 void Dispatcher::OnActivateExtension(const std::string& extension_id) {
530 const Extension* extension = extensions_.GetByID(extension_id);
531 if (!extension) {
532 // Extension was activated but was never loaded. This probably means that
533 // the renderer failed to load it (or the browser failed to tell us when it
534 // did). Failures shouldn't happen, but instead of crashing there (which
535 // executes on all renderers) be conservative and only crash in the renderer
536 // of the extension which failed to load; this one.
537 std::string& error = extension_load_errors_[extension_id];
538 char minidump[256];
539 base::debug::Alias(&minidump);
540 base::snprintf(minidump,
541 arraysize(minidump),
542 "e::dispatcher:%s:%s",
543 extension_id.c_str(),
544 error.c_str());
545 CHECK(extension) << extension_id << " was never loaded: " << error;
548 active_extension_ids_.insert(extension_id);
550 // This is called when starting a new extension page, so start the idle
551 // handler ticking.
552 RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
554 if (is_webkit_initialized_) {
555 extensions::DOMActivityLogger::AttachToWorld(
556 extensions::DOMActivityLogger::kMainWorldId, extension_id);
558 InitOriginPermissions(extension);
561 UpdateActiveExtensions();
564 void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
565 DispatchEvent(extension_id, kOnSuspendCanceledEvent);
568 void Dispatcher::OnClearTabSpecificPermissions(
569 int tab_id,
570 const std::vector<std::string>& extension_ids) {
571 delegate_->ClearTabSpecificPermissions(this, tab_id, extension_ids);
574 void Dispatcher::OnDeliverMessage(int target_port_id, const Message& message) {
575 scoped_ptr<RequestSender::ScopedTabID> scoped_tab_id;
576 std::map<int, int>::const_iterator it =
577 port_to_tab_id_map_.find(target_port_id);
578 if (it != port_to_tab_id_map_.end()) {
579 scoped_tab_id.reset(
580 new RequestSender::ScopedTabID(request_sender(), it->second));
583 MessagingBindings::DeliverMessage(script_context_set_,
584 target_port_id,
585 message,
586 NULL); // All render views.
589 void Dispatcher::OnDispatchOnConnect(
590 int target_port_id,
591 const std::string& channel_name,
592 const base::DictionaryValue& source_tab,
593 const ExtensionMsg_ExternalConnectionInfo& info,
594 const std::string& tls_channel_id) {
595 DCHECK(!ContainsKey(port_to_tab_id_map_, target_port_id));
596 DCHECK_EQ(1, target_port_id % 2); // target renderer ports have odd IDs.
597 int sender_tab_id = -1;
598 source_tab.GetInteger("id", &sender_tab_id);
599 port_to_tab_id_map_[target_port_id] = sender_tab_id;
601 MessagingBindings::DispatchOnConnect(script_context_set_,
602 target_port_id,
603 channel_name,
604 source_tab,
605 info,
606 tls_channel_id,
607 NULL); // All render views.
610 void Dispatcher::OnDispatchOnDisconnect(int port_id,
611 const std::string& error_message) {
612 MessagingBindings::DispatchOnDisconnect(script_context_set_,
613 port_id,
614 error_message,
615 NULL); // All render views.
618 void Dispatcher::OnLoaded(
619 const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
620 std::vector<ExtensionMsg_Loaded_Params>::const_iterator i;
621 for (i = loaded_extensions.begin(); i != loaded_extensions.end(); ++i) {
622 std::string error;
623 scoped_refptr<const Extension> extension = i->ConvertToExtension(&error);
624 if (!extension.get()) {
625 extension_load_errors_[i->id] = error;
626 continue;
628 OnLoadedInternal(extension);
630 // Update the available bindings for all contexts. These may have changed if
631 // an externally_connectable extension was loaded that can connect to an
632 // open webpage.
633 UpdateBindings("");
636 void Dispatcher::OnLoadedInternal(scoped_refptr<const Extension> extension) {
637 extensions_.Insert(extension);
640 void Dispatcher::OnMessageInvoke(const std::string& extension_id,
641 const std::string& module_name,
642 const std::string& function_name,
643 const base::ListValue& args,
644 bool user_gesture) {
645 InvokeModuleSystemMethod(
646 NULL, extension_id, module_name, function_name, args, user_gesture);
649 void Dispatcher::OnSetChannel(int channel) {
650 delegate_->SetChannel(channel);
653 void Dispatcher::OnSetFunctionNames(const std::vector<std::string>& names) {
654 function_names_.clear();
655 for (size_t i = 0; i < names.size(); ++i)
656 function_names_.insert(names[i]);
659 void Dispatcher::OnSetScriptingWhitelist(
660 const ExtensionsClient::ScriptingWhitelist& extension_ids) {
661 ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
664 void Dispatcher::OnSetSystemFont(const std::string& font_family,
665 const std::string& font_size) {
666 system_font_family_ = font_family;
667 system_font_size_ = font_size;
670 void Dispatcher::OnShouldSuspend(const std::string& extension_id,
671 int sequence_id) {
672 RenderThread::Get()->Send(
673 new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
676 void Dispatcher::OnSuspend(const std::string& extension_id) {
677 // Dispatch the suspend event. This doesn't go through the standard event
678 // dispatch machinery because it requires special handling. We need to let
679 // the browser know when we are starting and stopping the event dispatch, so
680 // that it still considers the extension idle despite any activity the suspend
681 // event creates.
682 DispatchEvent(extension_id, kOnSuspendEvent);
683 RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
686 void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
687 RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
690 void Dispatcher::OnUnloaded(const std::string& id) {
691 extensions_.Remove(id);
692 active_extension_ids_.erase(id);
694 // If the extension is later reloaded with a different set of permissions,
695 // we'd like it to get a new isolated world ID, so that it can pick up the
696 // changed origin whitelist.
697 user_script_slave_->RemoveIsolatedWorld(id);
699 // Invalidate all of the contexts that were removed.
700 // TODO(kalman): add an invalidation observer interface to ScriptContext.
701 ScriptContextSet::ContextSet removed_contexts =
702 script_context_set_.OnExtensionUnloaded(id);
703 for (ScriptContextSet::ContextSet::iterator it = removed_contexts.begin();
704 it != removed_contexts.end();
705 ++it) {
706 request_sender_->InvalidateSource(*it);
709 // Update the available bindings for the remaining contexts. These may have
710 // changed if an externally_connectable extension is unloaded and a webpage
711 // is no longer accessible.
712 UpdateBindings("");
714 // Invalidates the messages map for the extension in case the extension is
715 // reloaded with a new messages map.
716 EraseL10nMessagesMap(id);
718 // We don't do anything with existing platform-app stylesheets. They will
719 // stay resident, but the URL pattern corresponding to the unloaded
720 // extension's URL just won't match anything anymore.
723 void Dispatcher::OnUpdatePermissions(
724 const ExtensionMsg_UpdatePermissions_Params& params) {
725 int reason_id = params.reason_id;
726 const std::string& extension_id = params.extension_id;
727 const APIPermissionSet& apis = params.apis;
728 const ManifestPermissionSet& manifest_permissions =
729 params.manifest_permissions;
730 const URLPatternSet& explicit_hosts = params.explicit_hosts;
731 const URLPatternSet& scriptable_hosts = params.scriptable_hosts;
733 const Extension* extension = extensions_.GetByID(extension_id);
734 if (!extension)
735 return;
737 scoped_refptr<const PermissionSet> delta = new PermissionSet(
738 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
739 scoped_refptr<const PermissionSet> old_active =
740 extension->permissions_data()->active_permissions();
741 UpdatedExtensionPermissionsInfo::Reason reason =
742 static_cast<UpdatedExtensionPermissionsInfo::Reason>(reason_id);
744 const PermissionSet* new_active = NULL;
745 switch (reason) {
746 case UpdatedExtensionPermissionsInfo::ADDED:
747 new_active = PermissionSet::CreateUnion(old_active.get(), delta.get());
748 break;
749 case UpdatedExtensionPermissionsInfo::REMOVED:
750 new_active =
751 PermissionSet::CreateDifference(old_active.get(), delta.get());
752 break;
755 extension->permissions_data()->SetActivePermissions(new_active);
756 UpdateOriginPermissions(reason, extension, explicit_hosts);
757 UpdateBindings(extension->id());
760 void Dispatcher::OnUpdateTabSpecificPermissions(
761 int page_id,
762 int tab_id,
763 const std::string& extension_id,
764 const URLPatternSet& origin_set) {
765 delegate_->UpdateTabSpecificPermissions(
766 this, page_id, tab_id, extension_id, origin_set);
769 void Dispatcher::OnUpdateUserScripts(
770 base::SharedMemoryHandle scripts,
771 const std::set<std::string>& extension_ids) {
772 if (!base::SharedMemory::IsHandleValid(scripts)) {
773 NOTREACHED() << "Bad scripts handle";
774 return;
777 for (std::set<std::string>::const_iterator iter = extension_ids.begin();
778 iter != extension_ids.end();
779 ++iter) {
780 if (!Extension::IdIsValid(*iter)) {
781 NOTREACHED() << "Invalid extension id: " << *iter;
782 return;
786 user_script_slave_->UpdateScripts(scripts, extension_ids);
787 UpdateActiveExtensions();
790 void Dispatcher::OnUsingWebRequestAPI(bool adblock,
791 bool adblock_plus,
792 bool other_webrequest) {
793 delegate_->HandleWebRequestAPIUsage(adblock, adblock_plus, other_webrequest);
796 void Dispatcher::UpdateActiveExtensions() {
797 std::set<std::string> active_extensions = active_extension_ids_;
798 user_script_slave_->GetActiveExtensions(&active_extensions);
799 delegate_->OnActiveExtensionsUpdated(active_extensions);
802 void Dispatcher::InitOriginPermissions(const Extension* extension) {
803 delegate_->InitOriginPermissions(extension,
804 IsExtensionActive(extension->id()));
805 UpdateOriginPermissions(
806 UpdatedExtensionPermissionsInfo::ADDED,
807 extension,
808 extension->permissions_data()->GetEffectiveHostPermissions());
811 void Dispatcher::UpdateOriginPermissions(
812 UpdatedExtensionPermissionsInfo::Reason reason,
813 const Extension* extension,
814 const URLPatternSet& origins) {
815 for (URLPatternSet::const_iterator i = origins.begin(); i != origins.end();
816 ++i) {
817 const char* schemes[] = {
818 url::kHttpScheme,
819 url::kHttpsScheme,
820 url::kFileScheme,
821 content::kChromeUIScheme,
822 url::kFtpScheme,
824 for (size_t j = 0; j < arraysize(schemes); ++j) {
825 if (i->MatchesScheme(schemes[j])) {
826 ((reason == UpdatedExtensionPermissionsInfo::REMOVED)
827 ? WebSecurityPolicy::removeOriginAccessWhitelistEntry
828 : WebSecurityPolicy::addOriginAccessWhitelistEntry)(
829 extension->url(),
830 WebString::fromUTF8(schemes[j]),
831 WebString::fromUTF8(i->host()),
832 i->match_subdomains());
838 void Dispatcher::EnableCustomElementWhiteList() {
839 blink::WebCustomElement::addEmbedderCustomElementName("webview");
840 blink::WebCustomElement::addEmbedderCustomElementName("browser-plugin");
843 void Dispatcher::UpdateBindings(const std::string& extension_id) {
844 script_context_set().ForEach(extension_id,
845 base::Bind(&Dispatcher::UpdateBindingsForContext,
846 base::Unretained(this)));
849 void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
850 v8::HandleScope handle_scope(context->isolate());
851 v8::Context::Scope context_scope(context->v8_context());
853 // TODO(kalman): Make the bindings registration have zero overhead then run
854 // the same code regardless of context type.
855 switch (context->context_type()) {
856 case Feature::UNSPECIFIED_CONTEXT:
857 case Feature::WEB_PAGE_CONTEXT:
858 case Feature::BLESSED_WEB_PAGE_CONTEXT: {
859 // Web page context; it's too expensive to run the full bindings code.
860 // Hard-code that the app and webstore APIs are available...
861 RegisterBinding("app", context);
862 RegisterBinding("webstore", context);
864 // ... and that the runtime API might be available if any extension can
865 // connect to it.
866 bool runtime_is_available = false;
867 for (ExtensionSet::const_iterator it = extensions_.begin();
868 it != extensions_.end();
869 ++it) {
870 ExternallyConnectableInfo* info =
871 static_cast<ExternallyConnectableInfo*>(
872 (*it)->GetManifestData(manifest_keys::kExternallyConnectable));
873 if (info && info->matches.MatchesURL(context->GetURL())) {
874 runtime_is_available = true;
875 break;
878 if (runtime_is_available)
879 RegisterBinding("runtime", context);
880 break;
883 case Feature::BLESSED_EXTENSION_CONTEXT:
884 case Feature::UNBLESSED_EXTENSION_CONTEXT:
885 case Feature::CONTENT_SCRIPT_CONTEXT: {
886 // Extension context; iterate through all the APIs and bind the available
887 // ones.
888 const FeatureProvider* api_feature_provider =
889 FeatureProvider::GetAPIFeatures();
890 const std::vector<std::string>& apis =
891 api_feature_provider->GetAllFeatureNames();
892 for (std::vector<std::string>::const_iterator it = apis.begin();
893 it != apis.end();
894 ++it) {
895 const std::string& api_name = *it;
896 Feature* feature = api_feature_provider->GetFeature(api_name);
897 DCHECK(feature);
899 // Internal APIs are included via require(api_name) from internal code
900 // rather than chrome[api_name].
901 if (feature->IsInternal())
902 continue;
904 // If this API has a parent feature (and isn't marked 'noparent'),
905 // then this must be a function or event, so we should not register.
906 if (api_feature_provider->GetParent(feature) != NULL)
907 continue;
909 if (context->IsAnyFeatureAvailableToContext(*feature))
910 RegisterBinding(api_name, context);
912 if (CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestType)) {
913 RegisterBinding("test", context);
915 break;
920 void Dispatcher::RegisterBinding(const std::string& api_name,
921 ScriptContext* context) {
922 std::string bind_name;
923 v8::Handle<v8::Object> bind_object =
924 GetOrCreateBindObjectIfAvailable(api_name, &bind_name, context);
926 // Empty if the bind object failed to be created, probably because the
927 // extension overrode chrome with a non-object, e.g. window.chrome = true.
928 if (bind_object.IsEmpty())
929 return;
931 v8::Local<v8::String> v8_api_name =
932 v8::String::NewFromUtf8(context->isolate(), api_name.c_str());
933 if (bind_object->HasRealNamedProperty(v8_api_name)) {
934 // The bind object may already have the property if the API has been
935 // registered before (or if the extension has put something there already,
936 // but, whatevs).
938 // In the former case, we need to re-register the bindings for the APIs
939 // which the extension now has permissions for (if any), but not touch any
940 // others so that we don't destroy state such as event listeners.
942 // TODO(kalman): Only register available APIs to make this all moot.
943 if (bind_object->HasRealNamedCallbackProperty(v8_api_name))
944 return; // lazy binding still there, nothing to do
945 if (bind_object->Get(v8_api_name)->IsObject())
946 return; // binding has already been fully installed
949 ModuleSystem* module_system = context->module_system();
950 if (!source_map_.Contains(api_name)) {
951 module_system->RegisterNativeHandler(
952 api_name,
953 scoped_ptr<NativeHandler>(new BindingGeneratingNativeHandler(
954 module_system, api_name, "binding")));
955 module_system->SetNativeLazyField(
956 bind_object, bind_name, api_name, "binding");
957 } else {
958 module_system->SetLazyField(bind_object, bind_name, api_name, "binding");
962 // NOTE: please use the naming convention "foo_natives" for these.
963 void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
964 ScriptContext* context) {
965 module_system->RegisterNativeHandler(
966 "chrome", scoped_ptr<NativeHandler>(new ChromeNativeHandler(context)));
967 module_system->RegisterNativeHandler(
968 "lazy_background_page",
969 scoped_ptr<NativeHandler>(new LazyBackgroundPageNativeHandler(context)));
970 module_system->RegisterNativeHandler(
971 "logging", scoped_ptr<NativeHandler>(new LoggingNativeHandler(context)));
972 module_system->RegisterNativeHandler("schema_registry",
973 v8_schema_registry_->AsNativeHandler());
974 module_system->RegisterNativeHandler(
975 "print", scoped_ptr<NativeHandler>(new PrintNativeHandler(context)));
976 module_system->RegisterNativeHandler(
977 "test_features",
978 scoped_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
979 module_system->RegisterNativeHandler(
980 "user_gestures",
981 scoped_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
982 module_system->RegisterNativeHandler(
983 "utils", scoped_ptr<NativeHandler>(new UtilsNativeHandler(context)));
984 module_system->RegisterNativeHandler(
985 "v8_context",
986 scoped_ptr<NativeHandler>(new V8ContextNativeHandler(context, this)));
988 const Extension* extension = context->extension();
989 int manifest_version = extension ? extension->manifest_version() : 1;
990 bool send_request_disabled =
991 (extension && Manifest::IsUnpackedLocation(extension->location()) &&
992 BackgroundInfo::HasLazyBackgroundPage(extension));
993 module_system->RegisterNativeHandler(
994 "process",
995 scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler(
996 context,
997 context->GetExtensionID(),
998 context->GetContextTypeDescription(),
999 ExtensionsRendererClient::Get()->IsIncognitoProcess(),
1000 manifest_version,
1001 send_request_disabled)));
1003 module_system->RegisterNativeHandler(
1004 "event_natives",
1005 scoped_ptr<NativeHandler>(new EventBindings(this, context)));
1006 module_system->RegisterNativeHandler(
1007 "messaging_natives",
1008 scoped_ptr<NativeHandler>(MessagingBindings::Get(this, context)));
1009 module_system->RegisterNativeHandler(
1010 "apiDefinitions",
1011 scoped_ptr<NativeHandler>(new ApiDefinitionsNatives(this, context)));
1012 module_system->RegisterNativeHandler(
1013 "sendRequest",
1014 scoped_ptr<NativeHandler>(
1015 new SendRequestNatives(request_sender_.get(), context)));
1016 module_system->RegisterNativeHandler(
1017 "setIcon",
1018 scoped_ptr<NativeHandler>(
1019 new SetIconNatives(request_sender_.get(), context)));
1020 module_system->RegisterNativeHandler(
1021 "activityLogger",
1022 scoped_ptr<NativeHandler>(new APIActivityLogger(context)));
1023 module_system->RegisterNativeHandler(
1024 "renderViewObserverNatives",
1025 scoped_ptr<NativeHandler>(new RenderViewObserverNatives(context)));
1027 // Natives used by multiple APIs.
1028 module_system->RegisterNativeHandler(
1029 "file_system_natives",
1030 scoped_ptr<NativeHandler>(new FileSystemNatives(context)));
1032 // Custom bindings.
1033 module_system->RegisterNativeHandler(
1034 "app_runtime",
1035 scoped_ptr<NativeHandler>(new AppRuntimeCustomBindings(context)));
1036 module_system->RegisterNativeHandler(
1037 "blob_natives",
1038 scoped_ptr<NativeHandler>(new BlobNativeHandler(context)));
1039 module_system->RegisterNativeHandler(
1040 "context_menus",
1041 scoped_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
1042 module_system->RegisterNativeHandler(
1043 "css_natives", scoped_ptr<NativeHandler>(new CssNativeHandler(context)));
1044 module_system->RegisterNativeHandler(
1045 "document_natives",
1046 scoped_ptr<NativeHandler>(new DocumentCustomBindings(context)));
1047 module_system->RegisterNativeHandler(
1048 "i18n", scoped_ptr<NativeHandler>(new I18NCustomBindings(context)));
1049 module_system->RegisterNativeHandler(
1050 "id_generator",
1051 scoped_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
1052 module_system->RegisterNativeHandler(
1053 "runtime", scoped_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
1055 delegate_->RegisterNativeHandlers(this, module_system, context);
1058 void Dispatcher::PopulateSourceMap() {
1059 // Libraries.
1060 source_map_.RegisterSource("entryIdManager", IDR_ENTRY_ID_MANAGER);
1061 source_map_.RegisterSource(kEventBindings, IDR_EVENT_BINDINGS_JS);
1062 source_map_.RegisterSource("imageUtil", IDR_IMAGE_UTIL_JS);
1063 source_map_.RegisterSource("json_schema", IDR_JSON_SCHEMA_JS);
1064 source_map_.RegisterSource("lastError", IDR_LAST_ERROR_JS);
1065 source_map_.RegisterSource("messaging", IDR_MESSAGING_JS);
1066 source_map_.RegisterSource("messaging_utils", IDR_MESSAGING_UTILS_JS);
1067 source_map_.RegisterSource(kSchemaUtils, IDR_SCHEMA_UTILS_JS);
1068 source_map_.RegisterSource("sendRequest", IDR_SEND_REQUEST_JS);
1069 source_map_.RegisterSource("setIcon", IDR_SET_ICON_JS);
1070 source_map_.RegisterSource("test", IDR_TEST_CUSTOM_BINDINGS_JS);
1071 source_map_.RegisterSource("uncaught_exception_handler",
1072 IDR_UNCAUGHT_EXCEPTION_HANDLER_JS);
1073 source_map_.RegisterSource("unload_event", IDR_UNLOAD_EVENT_JS);
1074 source_map_.RegisterSource("utils", IDR_UTILS_JS);
1076 // Custom bindings.
1077 source_map_.RegisterSource("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS);
1078 source_map_.RegisterSource("contextMenus",
1079 IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS);
1080 source_map_.RegisterSource("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS);
1081 source_map_.RegisterSource("i18n", IDR_I18N_CUSTOM_BINDINGS_JS);
1082 source_map_.RegisterSource("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS);
1083 source_map_.RegisterSource("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS);
1084 source_map_.RegisterSource("binding", IDR_BINDING_JS);
1086 // Custom types sources.
1087 source_map_.RegisterSource("StorageArea", IDR_STORAGE_AREA_JS);
1089 // Platform app sources that are not API-specific..
1090 source_map_.RegisterSource("platformApp", IDR_PLATFORM_APP_JS);
1092 delegate_->PopulateSourceMap(&source_map_);
1095 bool Dispatcher::IsWithinPlatformApp() {
1096 for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
1097 iter != active_extension_ids_.end();
1098 ++iter) {
1099 const Extension* extension = extensions_.GetByID(*iter);
1100 if (extension && extension->is_platform_app())
1101 return true;
1103 return false;
1106 // TODO(kalman): This is checking for the wrong thing, it should be checking if
1107 // the frame's security origin is unique. The extension sandbox directive is
1108 // checked for in extensions/common/manifest_handlers/csp_info.cc.
1109 bool Dispatcher::IsSandboxedPage(const GURL& url) const {
1110 if (url.SchemeIs(kExtensionScheme)) {
1111 const Extension* extension = extensions_.GetByID(url.host());
1112 if (extension) {
1113 return SandboxedPageInfo::IsSandboxedPage(extension, url.path());
1116 return false;
1119 Feature::Context Dispatcher::ClassifyJavaScriptContext(
1120 const Extension* extension,
1121 int extension_group,
1122 const GURL& url,
1123 const blink::WebSecurityOrigin& origin) {
1124 DCHECK_GE(extension_group, 0);
1125 if (extension_group == EXTENSION_GROUP_CONTENT_SCRIPTS) {
1126 return extension ? // TODO(kalman): when does this happen?
1127 Feature::CONTENT_SCRIPT_CONTEXT
1128 : Feature::UNSPECIFIED_CONTEXT;
1131 // We have an explicit check for sandboxed pages before checking whether the
1132 // extension is active in this process because:
1133 // 1. Sandboxed pages run in the same process as regular extension pages, so
1134 // the extension is considered active.
1135 // 2. ScriptContext creation (which triggers bindings injection) happens
1136 // before the SecurityContext is updated with the sandbox flags (after
1137 // reading the CSP header), so the caller can't check if the context's
1138 // security origin is unique yet.
1139 if (IsSandboxedPage(url))
1140 return Feature::WEB_PAGE_CONTEXT;
1142 if (extension && IsExtensionActive(extension->id())) {
1143 // |extension| is active in this process, but it could be either a true
1144 // extension process or within the extent of a hosted app. In the latter
1145 // case this would usually be considered a (blessed) web page context,
1146 // unless the extension in question is a component extension, in which case
1147 // we cheat and call it blessed.
1148 return (extension->is_hosted_app() &&
1149 extension->location() != Manifest::COMPONENT)
1150 ? Feature::BLESSED_WEB_PAGE_CONTEXT
1151 : Feature::BLESSED_EXTENSION_CONTEXT;
1154 // TODO(kalman): This isUnique() check is wrong, it should be performed as
1155 // part of IsSandboxedPage().
1156 if (!origin.isUnique() && extensions_.ExtensionBindingsAllowed(url)) {
1157 if (!extension) // TODO(kalman): when does this happen?
1158 return Feature::UNSPECIFIED_CONTEXT;
1159 return extension->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT
1160 : Feature::UNBLESSED_EXTENSION_CONTEXT;
1163 if (url.is_valid())
1164 return Feature::WEB_PAGE_CONTEXT;
1166 return Feature::UNSPECIFIED_CONTEXT;
1169 v8::Handle<v8::Object> Dispatcher::GetOrCreateObject(
1170 const v8::Handle<v8::Object>& object,
1171 const std::string& field,
1172 v8::Isolate* isolate) {
1173 v8::Handle<v8::String> key = v8::String::NewFromUtf8(isolate, field.c_str());
1174 // If the object has a callback property, it is assumed it is an unavailable
1175 // API, so it is safe to delete. This is checked before GetOrCreateObject is
1176 // called.
1177 if (object->HasRealNamedCallbackProperty(key)) {
1178 object->Delete(key);
1179 } else if (object->HasRealNamedProperty(key)) {
1180 v8::Handle<v8::Value> value = object->Get(key);
1181 CHECK(value->IsObject());
1182 return v8::Handle<v8::Object>::Cast(value);
1185 v8::Handle<v8::Object> new_object = v8::Object::New(isolate);
1186 object->Set(key, new_object);
1187 return new_object;
1190 v8::Handle<v8::Object> Dispatcher::GetOrCreateBindObjectIfAvailable(
1191 const std::string& api_name,
1192 std::string* bind_name,
1193 ScriptContext* context) {
1194 std::vector<std::string> split;
1195 base::SplitString(api_name, '.', &split);
1197 v8::Handle<v8::Object> bind_object;
1199 // Check if this API has an ancestor. If the API's ancestor is available and
1200 // the API is not available, don't install the bindings for this API. If
1201 // the API is available and its ancestor is not, delete the ancestor and
1202 // install the bindings for the API. This is to prevent loading the ancestor
1203 // API schema if it will not be needed.
1205 // For example:
1206 // If app is available and app.window is not, just install app.
1207 // If app.window is available and app is not, delete app and install
1208 // app.window on a new object so app does not have to be loaded.
1209 const FeatureProvider* api_feature_provider =
1210 FeatureProvider::GetAPIFeatures();
1211 std::string ancestor_name;
1212 bool only_ancestor_available = false;
1214 for (size_t i = 0; i < split.size() - 1; ++i) {
1215 ancestor_name += (i ? "." : "") + split[i];
1216 if (api_feature_provider->GetFeature(ancestor_name) &&
1217 context->GetAvailability(ancestor_name).is_available() &&
1218 !context->GetAvailability(api_name).is_available()) {
1219 only_ancestor_available = true;
1220 break;
1223 if (bind_object.IsEmpty()) {
1224 bind_object = AsObjectOrEmpty(GetOrCreateChrome(context));
1225 if (bind_object.IsEmpty())
1226 return v8::Handle<v8::Object>();
1228 bind_object = GetOrCreateObject(bind_object, split[i], context->isolate());
1231 if (only_ancestor_available)
1232 return v8::Handle<v8::Object>();
1234 if (bind_name)
1235 *bind_name = split.back();
1237 return bind_object.IsEmpty() ? AsObjectOrEmpty(GetOrCreateChrome(context))
1238 : bind_object;
1241 } // namespace extensions