1 // Copyright (c) 2012 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 "chrome/browser/extensions/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/histogram.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/extensions/error_console/error_console.h"
19 #include "chrome/browser/extensions/extension_service.h"
20 #include "chrome/browser/extensions/extension_system.h"
21 #include "chrome/browser/extensions/extension_tab_util.h"
22 #include "chrome/browser/extensions/extension_web_contents_observer.h"
23 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
24 #include "chrome/common/chrome_constants.h"
25 #include "chrome/common/extensions/extension_constants.h"
26 #include "chrome/common/extensions/extension_messages.h"
27 #include "chrome/common/render_messages.h"
28 #include "chrome/common/url_constants.h"
29 #include "content/public/browser/browser_context.h"
30 #include "content/public/browser/content_browser_client.h"
31 #include "content/public/browser/native_web_keyboard_event.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_source.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/render_process_host.h"
36 #include "content/public/browser/render_view_host.h"
37 #include "content/public/browser/render_widget_host_view.h"
38 #include "content/public/browser/site_instance.h"
39 #include "content/public/browser/web_contents.h"
40 #include "extensions/browser/event_router.h"
41 #include "extensions/browser/extension_error.h"
42 #include "extensions/browser/extensions_browser_client.h"
43 #include "extensions/browser/process_manager.h"
44 #include "extensions/browser/view_type_utils.h"
45 #include "extensions/common/extension.h"
46 #include "extensions/common/extension_urls.h"
47 #include "extensions/common/feature_switch.h"
48 #include "extensions/common/manifest_handlers/background_info.h"
49 #include "ui/base/l10n/l10n_util.h"
50 #include "ui/base/window_open_disposition.h"
52 using content::BrowserContext
;
53 using content::OpenURLParams
;
54 using content::RenderProcessHost
;
55 using content::RenderViewHost
;
56 using content::SiteInstance
;
57 using content::WebContents
;
59 namespace extensions
{
61 // Helper class that rate-limits the creation of renderer processes for
62 // ExtensionHosts, to avoid blocking the UI.
63 class ExtensionHost::ProcessCreationQueue
{
65 static ProcessCreationQueue
* GetInstance() {
66 return Singleton
<ProcessCreationQueue
>::get();
69 // Add a host to the queue for RenderView creation.
70 void CreateSoon(ExtensionHost
* host
) {
71 queue_
.push_back(host
);
75 // Remove a host from the queue (in case it's being deleted).
76 void Remove(ExtensionHost
* host
) {
77 Queue::iterator it
= std::find(queue_
.begin(), queue_
.end(), host
);
78 if (it
!= queue_
.end())
83 friend class Singleton
<ProcessCreationQueue
>;
84 friend struct DefaultSingletonTraits
<ProcessCreationQueue
>;
85 ProcessCreationQueue()
86 : pending_create_(false),
89 // Queue up a delayed task to process the next ExtensionHost in the queue.
91 if (!pending_create_
) {
92 base::MessageLoop::current()->PostTask(FROM_HERE
,
93 base::Bind(&ProcessCreationQueue::ProcessOneHost
,
94 ptr_factory_
.GetWeakPtr()));
95 pending_create_
= true;
99 // Create the RenderView for the next host in the queue.
100 void ProcessOneHost() {
101 pending_create_
= false;
103 return; // can happen on shutdown
105 queue_
.front()->CreateRenderViewNow();
112 typedef std::list
<ExtensionHost
*> Queue
;
114 bool pending_create_
;
115 base::WeakPtrFactory
<ProcessCreationQueue
> ptr_factory_
;
121 ExtensionHost::ExtensionHost(const Extension
* extension
,
122 SiteInstance
* site_instance
,
125 : extension_(extension
),
126 extension_id_(extension
->id()),
127 browser_context_(site_instance
->GetBrowserContext()),
128 render_view_host_(NULL
),
129 did_stop_loading_(false),
130 document_element_available_(false),
132 extension_function_dispatcher_(browser_context_
, this),
133 extension_host_type_(host_type
) {
134 // Not used for panels, see PanelHost.
135 DCHECK(host_type
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
||
136 host_type
== VIEW_TYPE_EXTENSION_DIALOG
||
137 host_type
== VIEW_TYPE_EXTENSION_INFOBAR
||
138 host_type
== VIEW_TYPE_EXTENSION_POPUP
);
139 host_contents_
.reset(WebContents::Create(
140 WebContents::CreateParams(browser_context_
, site_instance
))),
141 content::WebContentsObserver::Observe(host_contents_
.get());
142 host_contents_
->SetDelegate(this);
143 SetViewType(host_contents_
.get(), host_type
);
145 ExtensionWebContentsObserver::CreateForWebContents(host_contents());
147 render_view_host_
= host_contents_
->GetRenderViewHost();
149 // Listen for when an extension is unloaded from the same profile, as it may
150 // be the same extension that this points to.
151 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED
,
152 content::Source
<BrowserContext
>(browser_context_
));
154 ExtensionsBrowserClient::Get()->OnExtensionHostCreated(host_contents());
157 ExtensionHost::~ExtensionHost() {
158 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
&&
159 extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
)) {
160 UMA_HISTOGRAM_LONG_TIMES("Extensions.EventPageActiveTime",
161 since_created_
.Elapsed());
163 content::NotificationService::current()->Notify(
164 chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED
,
165 content::Source
<BrowserContext
>(browser_context_
),
166 content::Details
<ExtensionHost
>(this));
167 ProcessCreationQueue::GetInstance()->Remove(this);
170 content::RenderProcessHost
* ExtensionHost::render_process_host() const {
171 return render_view_host()->GetProcess();
174 RenderViewHost
* ExtensionHost::render_view_host() const {
175 // TODO(mpcomplete): This can be NULL. How do we handle that?
176 return render_view_host_
;
179 bool ExtensionHost::IsRenderViewLive() const {
180 return render_view_host()->IsRenderViewLive();
183 void ExtensionHost::CreateRenderViewSoon() {
184 if ((render_process_host() && render_process_host()->HasConnection())) {
185 // If the process is already started, go ahead and initialize the RenderView
186 // synchronously. The process creation is the real meaty part that we want
188 CreateRenderViewNow();
190 ProcessCreationQueue::GetInstance()->CreateSoon(this);
194 void ExtensionHost::CreateRenderViewNow() {
196 if (!IsBackgroundPage()) {
197 DCHECK(IsRenderViewLive());
198 ExtensionService
* service
= GetExtensionService();
200 service
->DidCreateRenderViewForBackgroundPage(this);
204 ExtensionService
* ExtensionHost::GetExtensionService() {
205 return ExtensionSystem::GetForBrowserContext(browser_context_
)
206 ->extension_service();
209 const GURL
& ExtensionHost::GetURL() const {
210 return host_contents()->GetURL();
213 void ExtensionHost::LoadInitialURL() {
214 host_contents_
->GetController().LoadURL(
215 initial_url_
, content::Referrer(), content::PAGE_TRANSITION_LINK
,
219 bool ExtensionHost::IsBackgroundPage() const {
220 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
224 void ExtensionHost::Close() {
225 content::NotificationService::current()->Notify(
226 chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE
,
227 content::Source
<BrowserContext
>(browser_context_
),
228 content::Details
<ExtensionHost
>(this));
231 void ExtensionHost::Observe(int type
,
232 const content::NotificationSource
& source
,
233 const content::NotificationDetails
& details
) {
235 case chrome::NOTIFICATION_EXTENSION_UNLOADED
:
236 // The extension object will be deleted after this notification has been
237 // sent. NULL it out so that dirty pointer issues don't arise in cases
238 // when multiple ExtensionHost objects pointing to the same Extension are
240 if (extension_
== content::Details
<UnloadedExtensionInfo
>(details
)->
246 NOTREACHED() << "Unexpected notification sent.";
251 void ExtensionHost::RenderProcessGone(base::TerminationStatus status
) {
252 // During browser shutdown, we may use sudden termination on an extension
253 // process, so it is expected to lose our connection to the render view.
255 RenderProcessHost
* process_host
= host_contents_
->GetRenderProcessHost();
256 if (process_host
&& process_host
->FastShutdownStarted())
259 // In certain cases, multiple ExtensionHost objects may have pointed to
260 // the same Extension at some point (one with a background page and a
261 // popup, for example). When the first ExtensionHost goes away, the extension
262 // is unloaded, and any other host that pointed to that extension will have
263 // its pointer to it NULLed out so that any attempt to unload a dirty pointer
268 // TODO(aa): This is suspicious. There can be multiple views in an extension,
269 // and they aren't all going to use ExtensionHost. This should be in someplace
270 // more central, like EPM maybe.
271 content::NotificationService::current()->Notify(
272 chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
273 content::Source
<BrowserContext
>(browser_context_
),
274 content::Details
<ExtensionHost
>(this));
277 void ExtensionHost::DidStopLoading(content::RenderViewHost
* render_view_host
) {
278 bool notify
= !did_stop_loading_
;
279 did_stop_loading_
= true;
282 if (extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
) {
283 if (extension_
&& BackgroundInfo::HasLazyBackgroundPage(extension_
)) {
284 UMA_HISTOGRAM_TIMES("Extensions.EventPageLoadTime",
285 since_created_
.Elapsed());
287 UMA_HISTOGRAM_TIMES("Extensions.BackgroundPageLoadTime",
288 since_created_
.Elapsed());
290 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_DIALOG
) {
291 UMA_HISTOGRAM_TIMES("Extensions.DialogLoadTime",
292 since_created_
.Elapsed());
293 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_POPUP
) {
294 UMA_HISTOGRAM_TIMES("Extensions.PopupLoadTime",
295 since_created_
.Elapsed());
296 } else if (extension_host_type_
== VIEW_TYPE_EXTENSION_INFOBAR
) {
297 UMA_HISTOGRAM_TIMES("Extensions.InfobarLoadTime",
298 since_created_
.Elapsed());
301 // Send the notification last, because it might result in this being
303 content::NotificationService::current()->Notify(
304 chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING
,
305 content::Source
<BrowserContext
>(browser_context_
),
306 content::Details
<ExtensionHost
>(this));
310 void ExtensionHost::OnDidStopLoading() {
311 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
312 // Nothing to do for background pages.
315 void ExtensionHost::DocumentAvailableInMainFrame() {
316 // If the document has already been marked as available for this host, then
317 // bail. No need for the redundant setup. http://crbug.com/31170
318 if (document_element_available_
)
320 document_element_available_
= true;
321 OnDocumentAvailable();
324 void ExtensionHost::OnDocumentAvailable() {
325 DCHECK(extension_host_type_
== VIEW_TYPE_EXTENSION_BACKGROUND_PAGE
);
326 ExtensionService
* service
= GetExtensionService();
328 service
->SetBackgroundPageReady(extension_
);
329 content::NotificationService::current()->Notify(
330 chrome::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY
,
331 content::Source
<const Extension
>(extension_
),
332 content::NotificationService::NoDetails());
335 void ExtensionHost::CloseContents(WebContents
* contents
) {
339 bool ExtensionHost::OnMessageReceived(const IPC::Message
& message
) {
341 IPC_BEGIN_MESSAGE_MAP(ExtensionHost
, message
)
342 IPC_MESSAGE_HANDLER(ExtensionHostMsg_Request
, OnRequest
)
343 IPC_MESSAGE_HANDLER(ExtensionHostMsg_EventAck
, OnEventAck
)
344 IPC_MESSAGE_HANDLER(ExtensionHostMsg_IncrementLazyKeepaliveCount
,
345 OnIncrementLazyKeepaliveCount
)
346 IPC_MESSAGE_HANDLER(ExtensionHostMsg_DecrementLazyKeepaliveCount
,
347 OnDecrementLazyKeepaliveCount
)
348 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DetailedConsoleMessageAdded
,
349 OnDetailedConsoleMessageAdded
)
350 IPC_MESSAGE_UNHANDLED(handled
= false)
351 IPC_END_MESSAGE_MAP()
355 void ExtensionHost::OnRequest(const ExtensionHostMsg_Request_Params
& params
) {
356 extension_function_dispatcher_
.Dispatch(params
, render_view_host());
359 void ExtensionHost::OnEventAck() {
360 EventRouter
* router
=
361 ExtensionSystem::GetForBrowserContext(browser_context_
)->event_router();
363 router
->OnEventAck(browser_context_
, extension_id());
366 void ExtensionHost::OnIncrementLazyKeepaliveCount() {
367 ProcessManager
* pm
= ExtensionSystem::GetForBrowserContext(
368 browser_context_
)->process_manager();
370 pm
->IncrementLazyKeepaliveCount(extension());
373 void ExtensionHost::OnDecrementLazyKeepaliveCount() {
374 ProcessManager
* pm
= ExtensionSystem::GetForBrowserContext(
375 browser_context_
)->process_manager();
377 pm
->DecrementLazyKeepaliveCount(extension());
380 void ExtensionHost::OnDetailedConsoleMessageAdded(
381 const base::string16
& message
,
382 const base::string16
& source
,
383 const StackTrace
& stack_trace
,
384 int32 severity_level
) {
385 if (!IsSourceFromAnExtension(source
))
389 WebContents
* associated_contents
= GetAssociatedWebContents();
390 if (associated_contents
)
391 context_url
= associated_contents
->GetLastCommittedURL();
392 else if (host_contents_
.get())
393 context_url
= host_contents_
->GetLastCommittedURL();
395 ErrorConsole
* console
=
396 ExtensionSystem::GetForBrowserContext(browser_context_
)->error_console();
400 console
->ReportError(
401 scoped_ptr
<ExtensionError
>(new RuntimeError(
403 browser_context_
->IsOffTheRecord(),
408 static_cast<logging::LogSeverity
>(severity_level
),
409 render_view_host_
->GetRoutingID(),
410 render_view_host_
->GetProcess()->GetID())));
413 // content::WebContentsObserver
415 void ExtensionHost::RenderViewCreated(RenderViewHost
* render_view_host
) {
416 render_view_host_
= render_view_host
;
419 void ExtensionHost::RenderViewDeleted(RenderViewHost
* render_view_host
) {
420 // If our RenderViewHost is deleted, fall back to the host_contents' current
421 // RVH. There is sometimes a small gap between the pending RVH being deleted
422 // and RenderViewCreated being called, so we update it here.
423 if (render_view_host
== render_view_host_
)
424 render_view_host_
= host_contents_
->GetRenderViewHost();
427 content::JavaScriptDialogManager
* ExtensionHost::GetJavaScriptDialogManager() {
428 return ExtensionsBrowserClient::Get()->GetJavaScriptDialogManager();
431 void ExtensionHost::AddNewContents(WebContents
* source
,
432 WebContents
* new_contents
,
433 WindowOpenDisposition disposition
,
434 const gfx::Rect
& initial_pos
,
437 // First, if the creating extension view was associated with a tab contents,
438 // use that tab content's delegate. We must be careful here that the
439 // associated tab contents has the same profile as the new tab contents. In
440 // the case of extensions in 'spanning' incognito mode, they can mismatch.
441 // We don't want to end up putting a normal tab into an incognito window, or
443 // Note that we don't do this for popup windows, because we need to associate
444 // those with their extension_app_id.
445 if (disposition
!= NEW_POPUP
) {
446 WebContents
* associated_contents
= GetAssociatedWebContents();
447 if (associated_contents
&&
448 associated_contents
->GetBrowserContext() ==
449 new_contents
->GetBrowserContext()) {
450 WebContentsDelegate
* delegate
= associated_contents
->GetDelegate();
452 delegate
->AddNewContents(
453 associated_contents
, new_contents
, disposition
, initial_pos
,
454 user_gesture
, was_blocked
);
460 ExtensionTabUtil::CreateTab(new_contents
, extension_id_
, disposition
,
461 initial_pos
, user_gesture
);
464 void ExtensionHost::RenderViewReady() {
465 content::NotificationService::current()->Notify(
466 chrome::NOTIFICATION_EXTENSION_HOST_CREATED
,
467 content::Source
<BrowserContext
>(browser_context_
),
468 content::Details
<ExtensionHost
>(this));
471 void ExtensionHost::RequestMediaAccessPermission(
472 content::WebContents
* web_contents
,
473 const content::MediaStreamRequest
& request
,
474 const content::MediaResponseCallback
& callback
) {
475 MediaCaptureDevicesDispatcher::GetInstance()->ProcessMediaAccessRequest(
476 web_contents
, request
, callback
, extension());
479 } // namespace extensions