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/browser/extension_host.h"
10 #include "base/logging.h"
11 #include "base/memory/singleton.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/metrics/histogram.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "content/public/browser/browser_context.h"
19 #include "content/public/browser/content_browser_client.h"
20 #include "content/public/browser/native_web_keyboard_event.h"
21 #include "content/public/browser/notification_service.h"
22 #include "content/public/browser/notification_source.h"
23 #include "content/public/browser/notification_types.h"
24 #include "content/public/browser/render_process_host.h"
25 #include "content/public/browser/render_view_host.h"
26 #include "content/public/browser/render_widget_host_view.h"
27 #include "content/public/browser/site_instance.h"
28 #include "content/public/browser/web_contents.h"
29 #include "extensions/browser/event_router.h"
30 #include "extensions/browser/extension_error.h"
31 #include "extensions/browser/extension_host_delegate.h"
32 #include "extensions/browser/extension_system.h"
33 #include "extensions/browser/extensions_browser_client.h"
34 #include "extensions/browser/notification_types.h"
35 #include "extensions/browser/process_manager.h"
36 #include "extensions/browser/runtime_data.h"
37 #include "extensions/browser/view_type_utils.h"
38 #include "extensions/common/extension.h"
39 #include "extensions/common/extension_messages.h"
40 #include "extensions/common/extension_urls.h"
41 #include "extensions/common/feature_switch.h"
42 #include "extensions/common/manifest_handlers/background_info.h"
43 #include "ui/base/l10n/l10n_util.h"
44 #include "ui/base/window_open_disposition.h"
46 using content::BrowserContext
;
47 using content::OpenURLParams
;
48 using content::RenderProcessHost
;
49 using content::RenderViewHost
;
50 using content::SiteInstance
;
51 using content::WebContents
;
53 namespace extensions
{
55 // Helper class that rate-limits the creation of renderer processes for
56 // ExtensionHosts, to avoid blocking the UI.
57 class ExtensionHost::ProcessCreationQueue
{
59 static ProcessCreationQueue
* GetInstance() {
60 return Singleton
<ProcessCreationQueue
>::get();
63 // Add a host to the queue for RenderView creation.
64 void CreateSoon(ExtensionHost
* host
) {
65 queue_
.push_back(host
);
69 // Remove a host from the queue (in case it's being deleted).
70 void Remove(ExtensionHost
* host
) {
71 Queue::iterator it
= std::find(queue_
.begin(), queue_
.end(), host
);
72 if (it
!= queue_
.end())
77 friend class Singleton
<ProcessCreationQueue
>;
78 friend struct DefaultSingletonTraits
<ProcessCreationQueue
>;
79 ProcessCreationQueue()
80 : pending_create_(false),
83 // Queue up a delayed task to process the next ExtensionHost in the queue.
85 if (!pending_create_
) {
86 base::MessageLoop::current()->PostTask(FROM_HERE
,
87 base::Bind(&ProcessCreationQueue::ProcessOneHost
,
88 ptr_factory_
.GetWeakPtr()));
89 pending_create_
= true;
93 // Create the RenderView for the next host in the queue.
94 void ProcessOneHost() {
95 pending_create_
= false;
97 return; // can happen on shutdown
99 queue_
.front()->CreateRenderViewNow();
106 typedef std::list
<ExtensionHost
*> Queue
;
108 bool pending_create_
;
109 base::WeakPtrFactory
<ProcessCreationQueue
> ptr_factory_
;
115 ExtensionHost::ExtensionHost(const Extension
* extension
,
116 SiteInstance
* site_instance
,
119 : delegate_(ExtensionsBrowserClient::Get()->CreateExtensionHostDelegate()),
120 extension_(extension
),
121 extension_id_(extension
->id()),
122 browser_context_(site_instance
->GetBrowserContext()),
123 render_view_host_(NULL
),
124 did_stop_loading_(false),
125 document_element_available_(false),
127 extension_function_dispatcher_(browser_context_
, this),
128 extension_host_type_(host_type
) {
129 // Not used for panels, see PanelHost.
130 DCHECK(host_type
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
||
131 host_type
== VIEW_TYPE_EXTENSION_DIALOG
||
132 host_type
== VIEW_TYPE_EXTENSION_INFOBAR
||
133 host_type
== VIEW_TYPE_EXTENSION_POPUP
);
134 host_contents_
.reset(WebContents::Create(
135 WebContents::CreateParams(browser_context_
, site_instance
))),
136 content::WebContentsObserver::Observe(host_contents_
.get());
137 host_contents_
->SetDelegate(this);
138 SetViewType(host_contents_
.get(), host_type
);
140 render_view_host_
= host_contents_
->GetRenderViewHost();
142 // Listen for when an extension is unloaded from the same profile, as it may
143 // be the same extension that this points to.
145 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
146 content::Source
<BrowserContext
>(browser_context_
));
148 // Set up web contents observers and pref observers.
149 delegate_
->OnExtensionHostCreated(host_contents());
152 ExtensionHost::~ExtensionHost() {
153 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
&&
154 extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
)) {
155 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime",
156 since_created_
.Elapsed());
158 content::NotificationService::current()->Notify(
159 extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED
,
160 content::Source
<BrowserContext
>(browser_context_
),
161 content::Details
<ExtensionHost
>(this));
162 ProcessCreationQueue::GetInstance()->Remove(this);
165 content::RenderProcessHost
* ExtensionHost::render_process_host() const {
166 return render_view_host()->GetProcess();
169 RenderViewHost
* ExtensionHost::render_view_host() const {
170 // TODO(mpcomplete): This can be NULL. How do we handle that?
171 return render_view_host_
;
174 bool ExtensionHost::IsRenderViewLive() const {
175 return render_view_host()->IsRenderViewLive();
178 void ExtensionHost::CreateRenderViewSoon() {
179 if ((render_process_host() && render_process_host()->HasConnection())) {
180 // If the process is already started, go ahead and initialize the RenderView
181 // synchronously. The process creation is the real meaty part that we want
183 CreateRenderViewNow();
185 ProcessCreationQueue::GetInstance()->CreateSoon(this);
189 void ExtensionHost::CreateRenderViewNow() {
191 if (IsBackgroundPage()) {
192 DCHECK(IsRenderViewLive());
194 std::string group_name
= base::FieldTrialList::FindFullName(
195 "ThrottleExtensionBackgroundPages");
196 if ((group_name
== "ThrottlePersistent" &&
197 extensions::BackgroundInfo::HasPersistentBackgroundPage(
199 group_name
== "ThrottleAll") {
200 host_contents_
->WasHidden();
203 // Connect orphaned dev-tools instances.
204 delegate_
->OnRenderViewCreatedForBackgroundPage(this);
208 const GURL
& ExtensionHost::GetURL() const {
209 return host_contents()->GetURL();
212 void ExtensionHost::LoadInitialURL() {
213 host_contents_
->GetController().LoadURL(
214 initial_url_
, content::Referrer(), ui::PAGE_TRANSITION_LINK
,
218 bool ExtensionHost::IsBackgroundPage() const {
219 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
223 void ExtensionHost::Close() {
224 content::NotificationService::current()->Notify(
225 extensions::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE
,
226 content::Source
<BrowserContext
>(browser_context_
),
227 content::Details
<ExtensionHost
>(this));
230 void ExtensionHost::Observe(int type
,
231 const content::NotificationSource
& source
,
232 const content::NotificationDetails
& details
) {
234 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
:
235 // The extension object will be deleted after this notification has been
236 // sent. NULL it out so that dirty pointer issues don't arise in cases
237 // when multiple ExtensionHost objects pointing to the same Extension are
239 if (extension_
== content::Details
<UnloadedExtensionInfo
>(details
)->
245 NOTREACHED() << "Unexpected notification sent.";
250 void ExtensionHost::RenderProcessGone(base::TerminationStatus status
) {
251 // During browser shutdown, we may use sudden termination on an extension
252 // process, so it is expected to lose our connection to the render view.
254 RenderProcessHost
* process_host
= host_contents_
->GetRenderProcessHost();
255 if (process_host
&& process_host
->FastShutdownStarted())
258 // In certain cases, multiple ExtensionHost objects may have pointed to
259 // the same Extension at some point (one with a background page and a
260 // popup, for example). When the first ExtensionHost goes away, the extension
261 // is unloaded, and any other host that pointed to that extension will have
262 // its pointer to it NULLed out so that any attempt to unload a dirty pointer
267 // TODO(aa): This is suspicious. There can be multiple views in an extension,
268 // and they aren't all going to use ExtensionHost. This should be in someplace
269 // more central, like EPM maybe.
270 content::NotificationService::current()->Notify(
271 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
272 content::Source
<BrowserContext
>(browser_context_
),
273 content::Details
<ExtensionHost
>(this));
276 void ExtensionHost::DidStopLoading(content::RenderViewHost
* render_view_host
) {
277 bool notify
= !did_stop_loading_
;
278 did_stop_loading_
= true;
281 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
) {
282 if (extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
)) {
283 UMA_HISTOGRAM_TIMES("Extensions.EventPageLoadTime",
284 since_created_
.Elapsed());
286 UMA_HISTOGRAM_TIMES("Extensions.BackgroundPageLoadTime",
287 since_created_
.Elapsed());
289 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_DIALOG
) {
290 UMA_HISTOGRAM_TIMES("Extensions.DialogLoadTime",
291 since_created_
.Elapsed());
292 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_POPUP
) {
293 UMA_HISTOGRAM_TIMES("Extensions.PopupLoadTime",
294 since_created_
.Elapsed());
295 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_INFOBAR
) {
296 UMA_HISTOGRAM_TIMES("Extensions.InfobarLoadTime",
297 since_created_
.Elapsed());
300 // Send the notification last, because it might result in this being
302 content::NotificationService::current()->Notify(
303 extensions::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING
,
304 content::Source
<BrowserContext
>(browser_context_
),
305 content::Details
<ExtensionHost
>(this));
309 void ExtensionHost::OnDidStopLoading() {
310 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
311 // Nothing to do for background pages.
314 void ExtensionHost::DocumentAvailableInMainFrame() {
315 // If the document has already been marked as available for this host, then
316 // bail. No need for the redundant setup. http://crbug.com/31170
317 if (document_element_available_
)
319 document_element_available_
= true;
320 OnDocumentAvailable();
323 void ExtensionHost::OnDocumentAvailable() {
324 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
325 ExtensionSystem::Get(browser_context_
)
327 ->SetBackgroundPageReady(extension_
->id(), true);
328 content::NotificationService::current()->Notify(
329 extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY
,
330 content::Source
<const Extension
>(extension_
),
331 content::NotificationService::NoDetails());
334 void ExtensionHost::CloseContents(WebContents
* contents
) {
338 bool ExtensionHost::OnMessageReceived(const IPC::Message
& message
) {
340 IPC_BEGIN_MESSAGE_MAP(ExtensionHost
, message
)
341 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request
, OnRequest
)
342 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck
, OnEventAck
)
343 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount
,
344 OnIncrementLazyKeepaliveCount
)
345 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount
,
346 OnDecrementLazyKeepaliveCount
)
347 IPC_MESSAGE_UNHANDLED(handled
= false)
348 IPC_END_MESSAGE_MAP()
352 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params
& params
) {
353 extension_function_dispatcher_
.Dispatch(params
, render_view_host());
356 void ExtensionHost::OnEventAck() {
357 EventRouter
* router
= EventRouter::Get(browser_context_
);
359 router
->OnEventAck(browser_context_
, extension_id());
362 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
363 ProcessManager::Get(browser_context_
)
364 ->IncrementLazyKeepaliveCount(extension());
367 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
368 ProcessManager::Get(browser_context_
)
369 ->DecrementLazyKeepaliveCount(extension());
372 // content::WebContentsObserver
374 void ExtensionHost::RenderViewCreated(RenderViewHost
* render_view_host
) {
375 render_view_host_
= render_view_host
;
378 void ExtensionHost::RenderViewDeleted(RenderViewHost
* render_view_host
) {
379 // If our RenderViewHost is deleted, fall back to the host_contents' current
380 // RVH. There is sometimes a small gap between the pending RVH being deleted
381 // and RenderViewCreated being called, so we update it here.
382 if (render_view_host
== render_view_host_
)
383 render_view_host_
= host_contents_
->GetRenderViewHost();
386 content::JavaScriptDialogManager
* ExtensionHost::GetJavaScriptDialogManager(
387 WebContents
* source
) {
388 return delegate_
->GetJavaScriptDialogManager();
391 void ExtensionHost::AddNewContents(WebContents
* source
,
392 WebContents
* new_contents
,
393 WindowOpenDisposition disposition
,
394 const gfx::Rect
& initial_pos
,
397 // First, if the creating extension view was associated with a tab contents,
398 // use that tab content's delegate. We must be careful here that the
399 // associated tab contents has the same profile as the new tab contents. In
400 // the case of extensions in 'spanning' incognito mode, they can mismatch.
401 // We don't want to end up putting a normal tab into an incognito window, or
403 // Note that we don't do this for popup windows, because we need to associate
404 // those with their extension_app_id.
405 if (disposition
!= NEW_POPUP
) {
406 WebContents
* associated_contents
= GetAssociatedWebContents();
407 if (associated_contents
&&
408 associated_contents
->GetBrowserContext() ==
409 new_contents
->GetBrowserContext()) {
410 WebContentsDelegate
* delegate
= associated_contents
->GetDelegate();
412 delegate
->AddNewContents(
413 associated_contents
, new_contents
, disposition
, initial_pos
,
414 user_gesture
, was_blocked
);
420 delegate_
->CreateTab(
421 new_contents
, extension_id_
, disposition
, initial_pos
, user_gesture
);
424 void ExtensionHost::RenderViewReady() {
425 content::NotificationService::current()->Notify(
426 extensions::NOTIFICATION_EXTENSION_HOST_CREATED
,
427 content::Source
<BrowserContext
>(browser_context_
),
428 content::Details
<ExtensionHost
>(this));
431 void ExtensionHost::RequestMediaAccessPermission(
432 content::WebContents
* web_contents
,
433 const content::MediaStreamRequest
& request
,
434 const content::MediaResponseCallback
& callback
) {
435 delegate_
->ProcessMediaAccessRequest(
436 web_contents
, request
, callback
, extension());
439 bool ExtensionHost::CheckMediaAccessPermission(
440 content::WebContents
* web_contents
,
441 const GURL
& security_origin
,
442 content::MediaStreamType type
) {
443 return delegate_
->CheckMediaAccessPermission(
444 web_contents
, security_origin
, type
, extension());
447 bool ExtensionHost::IsNeverVisible(content::WebContents
* web_contents
) {
448 ViewType view_type
= extensions::GetViewType(web_contents
);
449 return view_type
== extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
;
452 } // namespace extensions