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 "content/browser/web_contents/web_contents_impl.h"
9 #include "base/command_line.h"
10 #include "base/lazy_instance.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram.h"
13 #include "base/process/process.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/strings/string16.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/time/time.h"
20 #include "base/trace_event/trace_event.h"
21 #include "components/mime_util/mime_util.h"
22 #include "content/browser/accessibility/accessibility_mode_helper.h"
23 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
24 #include "content/browser/bad_message.h"
25 #include "content/browser/browser_plugin/browser_plugin_embedder.h"
26 #include "content/browser/browser_plugin/browser_plugin_guest.h"
27 #include "content/browser/child_process_security_policy_impl.h"
28 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
29 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
30 #include "content/browser/download/download_stats.h"
31 #include "content/browser/download/mhtml_generation_manager.h"
32 #include "content/browser/download/save_package.h"
33 #include "content/browser/frame_host/cross_process_frame_connector.h"
34 #include "content/browser/frame_host/interstitial_page_impl.h"
35 #include "content/browser/frame_host/navigation_entry_impl.h"
36 #include "content/browser/frame_host/navigator_impl.h"
37 #include "content/browser/frame_host/render_frame_host_impl.h"
38 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
39 #include "content/browser/geolocation/geolocation_service_context.h"
40 #include "content/browser/host_zoom_map_impl.h"
41 #include "content/browser/loader/resource_dispatcher_host_impl.h"
42 #include "content/browser/manifest/manifest_manager_host.h"
43 #include "content/browser/media/audio_stream_monitor.h"
44 #include "content/browser/media/capture/web_contents_audio_muter.h"
45 #include "content/browser/message_port_message_filter.h"
46 #include "content/browser/plugin_content_origin_whitelist.h"
47 #include "content/browser/power_save_blocker_impl.h"
48 #include "content/browser/renderer_host/render_process_host_impl.h"
49 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
50 #include "content/browser/renderer_host/render_view_host_impl.h"
51 #include "content/browser/renderer_host/render_widget_host_impl.h"
52 #include "content/browser/renderer_host/render_widget_host_view_base.h"
53 #include "content/browser/screen_orientation/screen_orientation_dispatcher_host_impl.h"
54 #include "content/browser/site_instance_impl.h"
55 #include "content/browser/web_contents/web_contents_view_guest.h"
56 #include "content/browser/webui/generic_handler.h"
57 #include "content/browser/webui/web_ui_controller_factory_registry.h"
58 #include "content/browser/webui/web_ui_impl.h"
59 #include "content/common/browser_plugin/browser_plugin_constants.h"
60 #include "content/common/browser_plugin/browser_plugin_messages.h"
61 #include "content/common/frame_messages.h"
62 #include "content/common/image_messages.h"
63 #include "content/common/input_messages.h"
64 #include "content/common/ssl_status_serialization.h"
65 #include "content/common/view_messages.h"
66 #include "content/public/browser/ax_event_notification_details.h"
67 #include "content/public/browser/browser_context.h"
68 #include "content/public/browser/browser_plugin_guest_manager.h"
69 #include "content/public/browser/content_browser_client.h"
70 #include "content/public/browser/devtools_agent_host.h"
71 #include "content/public/browser/download_manager.h"
72 #include "content/public/browser/download_url_parameters.h"
73 #include "content/public/browser/invalidate_type.h"
74 #include "content/public/browser/javascript_dialog_manager.h"
75 #include "content/public/browser/load_from_memory_cache_details.h"
76 #include "content/public/browser/load_notification_details.h"
77 #include "content/public/browser/navigation_details.h"
78 #include "content/public/browser/notification_details.h"
79 #include "content/public/browser/notification_service.h"
80 #include "content/public/browser/render_widget_host_iterator.h"
81 #include "content/public/browser/resource_request_details.h"
82 #include "content/public/browser/screen_orientation_dispatcher_host.h"
83 #include "content/public/browser/storage_partition.h"
84 #include "content/public/browser/user_metrics.h"
85 #include "content/public/browser/web_contents_delegate.h"
86 #include "content/public/browser/web_contents_observer.h"
87 #include "content/public/common/bindings_policy.h"
88 #include "content/public/common/content_constants.h"
89 #include "content/public/common/content_switches.h"
90 #include "content/public/common/page_zoom.h"
91 #include "content/public/common/result_codes.h"
92 #include "content/public/common/url_constants.h"
93 #include "content/public/common/url_utils.h"
94 #include "content/public/common/web_preferences.h"
95 #include "net/base/net_util.h"
96 #include "net/http/http_cache.h"
97 #include "net/http/http_transaction_factory.h"
98 #include "net/url_request/url_request_context.h"
99 #include "net/url_request/url_request_context_getter.h"
100 #include "ui/base/layout.h"
101 #include "ui/gfx/display.h"
102 #include "ui/gfx/screen.h"
103 #include "ui/gl/gl_switches.h"
105 #if defined(ENABLE_BROWSER_CDMS)
106 #include "content/browser/media/media_web_contents_observer.h"
109 #if defined(OS_ANDROID)
110 #include "content/browser/android/content_video_view.h"
111 #include "content/browser/android/date_time_chooser_android.h"
112 #include "content/browser/android/media_players_observer.h"
113 #include "content/browser/media/android/browser_media_player_manager.h"
114 #include "content/browser/web_contents/web_contents_android.h"
117 #if defined(OS_MACOSX)
118 #include "base/mac/foundation_util.h"
124 const int kMinimumDelayBetweenLoadingUpdatesMS
= 100;
125 const char kDotGoogleDotCom
[] = ".google.com";
127 #if defined(OS_ANDROID)
128 const char kWebContentsAndroidKey
[] = "web_contents_android";
131 base::LazyInstance
<std::vector
<WebContentsImpl::CreatedCallback
> >
132 g_created_callbacks
= LAZY_INSTANCE_INITIALIZER
;
134 static int StartDownload(RenderFrameHost
* rfh
,
137 uint32_t max_bitmap_size
,
139 static int g_next_image_download_id
= 0;
140 rfh
->Send(new ImageMsg_DownloadImage(rfh
->GetRoutingID(),
141 ++g_next_image_download_id
,
146 return g_next_image_download_id
;
149 void NotifyCacheOnIO(
150 scoped_refptr
<net::URLRequestContextGetter
> request_context
,
152 const std::string
& http_method
) {
153 net::HttpCache
* cache
= request_context
->GetURLRequestContext()->
154 http_transaction_factory()->GetCache();
156 cache
->OnExternalCacheHit(url
, http_method
);
159 // Helper function for retrieving all the sites in a frame tree.
160 bool CollectSites(BrowserContext
* context
,
161 std::set
<GURL
>* sites
,
162 FrameTreeNode
* node
) {
163 sites
->insert(SiteInstance::GetSiteForURL(context
, node
->current_url()));
167 bool ForEachFrameInternal(
168 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
169 FrameTreeNode
* node
) {
170 on_frame
.Run(node
->current_frame_host());
174 bool ForEachPendingFrameInternal(
175 const base::Callback
<void(RenderFrameHost
*)>& on_frame
,
176 FrameTreeNode
* node
) {
177 RenderFrameHost
* pending_frame_host
=
178 node
->render_manager()->pending_frame_host();
179 if (pending_frame_host
)
180 on_frame
.Run(pending_frame_host
);
184 void SendToAllFramesInternal(IPC::Message
* message
, RenderFrameHost
* rfh
) {
185 IPC::Message
* message_copy
= new IPC::Message(*message
);
186 message_copy
->set_routing_id(rfh
->GetRoutingID());
187 rfh
->Send(message_copy
);
190 void AddRenderWidgetHostViewToSet(std::set
<RenderWidgetHostView
*>* set
,
191 RenderFrameHost
* rfh
) {
192 RenderWidgetHostView
* rwhv
= static_cast<RenderFrameHostImpl
*>(rfh
)
195 ->GetRenderWidgetHostView();
199 void SetAccessibilityModeOnFrame(AccessibilityMode mode
,
200 RenderFrameHost
* frame_host
) {
201 static_cast<RenderFrameHostImpl
*>(frame_host
)->SetAccessibilityMode(mode
);
206 WebContents
* WebContents::Create(const WebContents::CreateParams
& params
) {
207 return WebContentsImpl::CreateWithOpener(
208 params
, static_cast<WebContentsImpl
*>(params
.opener
));
211 WebContents
* WebContents::CreateWithSessionStorage(
212 const WebContents::CreateParams
& params
,
213 const SessionStorageNamespaceMap
& session_storage_namespace_map
) {
214 WebContentsImpl
* new_contents
= new WebContentsImpl(
215 params
.browser_context
, NULL
);
217 for (SessionStorageNamespaceMap::const_iterator it
=
218 session_storage_namespace_map
.begin();
219 it
!= session_storage_namespace_map
.end();
221 new_contents
->GetController()
222 .SetSessionStorageNamespace(it
->first
, it
->second
.get());
225 new_contents
->Init(params
);
229 void WebContentsImpl::FriendZone::AddCreatedCallbackForTesting(
230 const CreatedCallback
& callback
) {
231 g_created_callbacks
.Get().push_back(callback
);
234 void WebContentsImpl::FriendZone::RemoveCreatedCallbackForTesting(
235 const CreatedCallback
& callback
) {
236 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); ++i
) {
237 if (g_created_callbacks
.Get().at(i
).Equals(callback
)) {
238 g_created_callbacks
.Get().erase(g_created_callbacks
.Get().begin() + i
);
244 WebContents
* WebContents::FromRenderViewHost(const RenderViewHost
* rvh
) {
245 return rvh
->GetDelegate()->GetAsWebContents();
248 WebContents
* WebContents::FromRenderFrameHost(RenderFrameHost
* rfh
) {
249 RenderFrameHostImpl
* rfh_impl
= static_cast<RenderFrameHostImpl
*>(rfh
);
252 return rfh_impl
->delegate()->GetAsWebContents();
255 // WebContentsImpl::DestructionObserver ----------------------------------------
257 class WebContentsImpl::DestructionObserver
: public WebContentsObserver
{
259 DestructionObserver(WebContentsImpl
* owner
, WebContents
* watched_contents
)
260 : WebContentsObserver(watched_contents
),
264 // WebContentsObserver:
265 void WebContentsDestroyed() override
{
266 owner_
->OnWebContentsDestroyed(
267 static_cast<WebContentsImpl
*>(web_contents()));
271 WebContentsImpl
* owner_
;
273 DISALLOW_COPY_AND_ASSIGN(DestructionObserver
);
276 WebContentsImpl::ColorChooserInfo::ColorChooserInfo(int render_process_id
,
278 ColorChooser
* chooser
,
280 : render_process_id(render_process_id
),
281 render_frame_id(render_frame_id
),
283 identifier(identifier
) {
286 WebContentsImpl::ColorChooserInfo::~ColorChooserInfo() {
289 // WebContentsImpl -------------------------------------------------------------
291 WebContentsImpl::WebContentsImpl(BrowserContext
* browser_context
,
292 WebContentsImpl
* opener
)
294 controller_(this, browser_context
),
295 render_view_host_delegate_view_(NULL
),
297 created_with_opener_(!!opener
),
299 accessible_parent_(NULL
),
301 frame_tree_(new NavigatorImpl(&controller_
, this),
307 is_load_to_different_document_(false),
308 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING
),
309 crashed_error_code_(0),
310 waiting_for_response_(false),
311 load_state_(net::LOAD_STATE_IDLE
, base::string16()),
314 displayed_insecure_content_(false),
315 has_accessed_initial_document_(false),
316 theme_color_(SK_ColorTRANSPARENT
),
317 last_sent_theme_color_(SK_ColorTRANSPARENT
),
319 should_normally_be_visible_(true),
320 is_being_destroyed_(false),
321 notify_disconnection_(false),
322 dialog_manager_(NULL
),
323 is_showing_before_unload_dialog_(false),
324 last_active_time_(base::TimeTicks::Now()),
325 closed_by_user_gesture_(false),
326 minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor
* 100)),
327 maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor
* 100)),
328 render_view_message_source_(NULL
),
329 render_frame_message_source_(NULL
),
330 fullscreen_widget_routing_id_(MSG_ROUTING_NONE
),
331 fullscreen_widget_had_focus_at_shutdown_(false),
333 force_disable_overscroll_content_(false),
334 last_dialog_suppressed_(false),
335 geolocation_service_context_(new GeolocationServiceContext()),
337 BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()),
338 virtual_keyboard_requested_(false),
339 loading_weak_factory_(this) {
340 frame_tree_
.SetFrameRemoveListener(
341 base::Bind(&WebContentsImpl::OnFrameRemoved
,
342 base::Unretained(this)));
343 #if defined(ENABLE_BROWSER_CDMS)
344 media_web_contents_observer_
.reset(new MediaWebContentsObserver(this));
347 #if defined(OS_ANDROID)
348 audio_state_provider_
.reset(new MediaPlayersObserver(this));
350 audio_state_provider_
.reset(new AudioStreamMonitor(this));
354 WebContentsImpl::~WebContentsImpl() {
355 is_being_destroyed_
= true;
357 // Delete all RFH pending shutdown, which will lead the corresponding RVH to
358 // shutdown and be deleted as well.
360 base::Bind(&RenderFrameHostManager::ClearRFHsPendingShutdown
));
362 ClearAllPowerSaveBlockers();
364 for (std::set
<RenderWidgetHostImpl
*>::iterator iter
=
365 created_widgets_
.begin(); iter
!= created_widgets_
.end(); ++iter
) {
366 (*iter
)->DetachDelegate();
368 created_widgets_
.clear();
370 // Clear out any JavaScript state.
372 dialog_manager_
->ResetDialogState(this);
374 if (color_chooser_info_
.get())
375 color_chooser_info_
->chooser
->End();
377 NotifyDisconnected();
379 // Notify any observer that have a reference on this WebContents.
380 NotificationService::current()->Notify(
381 NOTIFICATION_WEB_CONTENTS_DESTROYED
,
382 Source
<WebContents
>(this),
383 NotificationService::NoDetails());
385 // Destroy all frame tree nodes except for the root; this notifies observers.
386 frame_tree_
.root()->ResetForNewProcess();
387 GetRenderManager()->ResetProxyHosts();
389 // Manually call the observer methods for the root frame tree node.
390 RenderFrameHostManager
* root
= GetRenderManager();
392 if (root
->pending_frame_host())
393 root
->pending_frame_host()->SetRenderFrameCreated(false);
394 root
->current_frame_host()->SetRenderFrameCreated(false);
396 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
397 FrameDeleted(root
->current_frame_host()));
399 if (root
->pending_render_view_host()) {
400 FOR_EACH_OBSERVER(WebContentsObserver
,
402 RenderViewDeleted(root
->pending_render_view_host()));
405 FOR_EACH_OBSERVER(WebContentsObserver
,
407 RenderViewDeleted(root
->current_host()));
409 FOR_EACH_OBSERVER(WebContentsObserver
,
411 WebContentsDestroyed());
413 FOR_EACH_OBSERVER(WebContentsObserver
,
419 STLDeleteContainerPairSecondPointers(destruction_observers_
.begin(),
420 destruction_observers_
.end());
423 WebContentsImpl
* WebContentsImpl::CreateWithOpener(
424 const WebContents::CreateParams
& params
,
425 WebContentsImpl
* opener
) {
426 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
427 WebContentsImpl
* new_contents
= new WebContentsImpl(
428 params
.browser_context
, params
.opener_suppressed
? NULL
: opener
);
430 if (params
.guest_delegate
) {
431 // This makes |new_contents| act as a guest.
432 // For more info, see comment above class BrowserPluginGuest.
433 BrowserPluginGuest::Create(new_contents
, params
.guest_delegate
);
434 // We are instantiating a WebContents for browser plugin. Set its subframe
436 new_contents
->is_subframe_
= true;
438 new_contents
->Init(params
);
443 std::vector
<WebContentsImpl
*> WebContentsImpl::GetAllWebContents() {
444 std::vector
<WebContentsImpl
*> result
;
445 scoped_ptr
<RenderWidgetHostIterator
> widgets(
446 RenderWidgetHostImpl::GetRenderWidgetHosts());
447 std::set
<WebContentsImpl
*> web_contents_set
;
448 while (RenderWidgetHost
* rwh
= widgets
->GetNextHost()) {
449 if (!rwh
->IsRenderView())
451 RenderViewHost
* rvh
= RenderViewHost::From(rwh
);
454 WebContents
* web_contents
= WebContents::FromRenderViewHost(rvh
);
457 WebContentsImpl
* wci
= static_cast<WebContentsImpl
*>(web_contents
);
458 if (web_contents_set
.find(wci
) == web_contents_set
.end()) {
459 web_contents_set
.insert(wci
);
460 result
.push_back(wci
);
466 RenderFrameHostManager
* WebContentsImpl::GetRenderManagerForTesting() {
467 return GetRenderManager();
470 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
471 const IPC::Message
& message
) {
472 return OnMessageReceived(render_view_host
, NULL
, message
);
475 bool WebContentsImpl::OnMessageReceived(RenderViewHost
* render_view_host
,
476 RenderFrameHost
* render_frame_host
,
477 const IPC::Message
& message
) {
478 DCHECK(render_view_host
|| render_frame_host
);
480 static_cast<WebUIImpl
*>(GetWebUI())->OnMessageReceived(message
)) {
484 ObserverListBase
<WebContentsObserver
>::Iterator
it(&observers_
);
485 WebContentsObserver
* observer
;
486 if (render_frame_host
) {
487 while ((observer
= it
.GetNext()) != NULL
)
488 if (observer
->OnMessageReceived(message
, render_frame_host
))
491 while ((observer
= it
.GetNext()) != NULL
)
492 if (observer
->OnMessageReceived(message
))
496 // Message handlers should be aware of which
497 // RenderViewHost/RenderFrameHost sent the message, which is temporarily
498 // stored in render_(view|frame)_message_source_.
499 if (render_frame_host
)
500 render_frame_message_source_
= render_frame_host
;
502 render_view_message_source_
= render_view_host
;
505 IPC_BEGIN_MESSAGE_MAP(WebContentsImpl
, message
)
506 IPC_MESSAGE_HANDLER(FrameHostMsg_DomOperationResponse
,
507 OnDomOperationResponse
)
508 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeThemeColor
,
510 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishDocumentLoad
,
511 OnDocumentLoadedInFrame
)
512 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFinishLoad
, OnDidFinishLoad
)
513 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenColorChooser
, OnOpenColorChooser
)
514 IPC_MESSAGE_HANDLER(FrameHostMsg_EndColorChooser
, OnEndColorChooser
)
515 IPC_MESSAGE_HANDLER(FrameHostMsg_SetSelectedColorInColorChooser
,
516 OnSetSelectedColorInColorChooser
)
517 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPlayingNotification
,
518 OnMediaPlayingNotification
)
519 IPC_MESSAGE_HANDLER(FrameHostMsg_MediaPausedNotification
,
520 OnMediaPausedNotification
)
521 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFirstVisuallyNonEmptyPaint
,
522 OnFirstVisuallyNonEmptyPaint
)
523 IPC_MESSAGE_HANDLER(ViewHostMsg_DidLoadResourceFromMemoryCache
,
524 OnDidLoadResourceFromMemoryCache
)
525 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisplayInsecureContent
,
526 OnDidDisplayInsecureContent
)
527 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRunInsecureContent
,
528 OnDidRunInsecureContent
)
529 IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset
, OnGoToEntryAtOffset
)
530 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits
, OnUpdateZoomLimits
)
531 IPC_MESSAGE_HANDLER(ViewHostMsg_EnumerateDirectory
, OnEnumerateDirectory
)
532 IPC_MESSAGE_HANDLER(ViewHostMsg_RegisterProtocolHandler
,
533 OnRegisterProtocolHandler
)
534 IPC_MESSAGE_HANDLER(ViewHostMsg_UnregisterProtocolHandler
,
535 OnUnregisterProtocolHandler
)
536 IPC_MESSAGE_HANDLER(ViewHostMsg_Find_Reply
, OnFindReply
)
537 IPC_MESSAGE_HANDLER(ViewHostMsg_AppCacheAccessed
, OnAppCacheAccessed
)
538 IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend
, OnWebUISend
)
539 #if defined(ENABLE_PLUGINS)
540 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung
, OnPepperPluginHung
)
541 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed
, OnPluginCrashed
)
542 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission
,
543 OnRequestPpapiBrokerPermission
)
544 IPC_MESSAGE_HANDLER_GENERIC(BrowserPluginHostMsg_Attach
,
545 OnBrowserPluginMessage(render_frame_host
,
548 IPC_MESSAGE_HANDLER(ImageHostMsg_DidDownloadImage
, OnDidDownloadImage
)
549 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateFaviconURL
, OnUpdateFaviconURL
)
550 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowValidationMessage
,
551 OnShowValidationMessage
)
552 IPC_MESSAGE_HANDLER(ViewHostMsg_HideValidationMessage
,
553 OnHideValidationMessage
)
554 IPC_MESSAGE_HANDLER(ViewHostMsg_MoveValidationMessage
,
555 OnMoveValidationMessage
)
556 #if defined(OS_ANDROID)
557 IPC_MESSAGE_HANDLER(ViewHostMsg_FindMatchRects_Reply
,
558 OnFindMatchRectsReply
)
559 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenDateTimeDialog
,
560 OnOpenDateTimeDialog
)
562 IPC_MESSAGE_UNHANDLED(handled
= false)
563 IPC_END_MESSAGE_MAP()
564 render_view_message_source_
= NULL
;
565 render_frame_message_source_
= NULL
;
570 bool WebContentsImpl::HasValidFrameSource() {
571 if (!render_frame_message_source_
) {
572 DCHECK(render_view_message_source_
);
573 bad_message::ReceivedBadMessage(GetRenderProcessHost(),
574 bad_message::WC_INVALID_FRAME_SOURCE
);
581 void WebContentsImpl::RunFileChooser(
582 RenderViewHost
* render_view_host
,
583 const FileChooserParams
& params
) {
585 delegate_
->RunFileChooser(this, params
);
588 NavigationControllerImpl
& WebContentsImpl::GetController() {
592 const NavigationControllerImpl
& WebContentsImpl::GetController() const {
596 BrowserContext
* WebContentsImpl::GetBrowserContext() const {
597 return controller_
.GetBrowserContext();
600 const GURL
& WebContentsImpl::GetURL() const {
601 // We may not have a navigation entry yet.
602 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
603 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
606 const GURL
& WebContentsImpl::GetVisibleURL() const {
607 // We may not have a navigation entry yet.
608 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
609 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
612 const GURL
& WebContentsImpl::GetLastCommittedURL() const {
613 // We may not have a navigation entry yet.
614 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
615 return entry
? entry
->GetVirtualURL() : GURL::EmptyGURL();
618 WebContentsDelegate
* WebContentsImpl::GetDelegate() {
622 void WebContentsImpl::SetDelegate(WebContentsDelegate
* delegate
) {
623 // TODO(cbentzel): remove this debugging code?
624 if (delegate
== delegate_
)
627 delegate_
->Detach(this);
628 delegate_
= delegate
;
630 delegate_
->Attach(this);
631 // Ensure the visible RVH reflects the new delegate's preferences.
633 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
637 RenderProcessHost
* WebContentsImpl::GetRenderProcessHost() const {
638 RenderViewHostImpl
* host
= GetRenderManager()->current_host();
639 return host
? host
->GetProcess() : NULL
;
642 RenderFrameHostImpl
* WebContentsImpl::GetMainFrame() {
643 return frame_tree_
.root()->current_frame_host();
646 RenderFrameHostImpl
* WebContentsImpl::GetFocusedFrame() {
647 FrameTreeNode
* focused_node
= frame_tree_
.GetFocusedFrame();
650 return focused_node
->current_frame_host();
653 void WebContentsImpl::ForEachFrame(
654 const base::Callback
<void(RenderFrameHost
*)>& on_frame
) {
655 frame_tree_
.ForEach(base::Bind(&ForEachFrameInternal
, on_frame
));
658 void WebContentsImpl::SendToAllFrames(IPC::Message
* message
) {
659 ForEachFrame(base::Bind(&SendToAllFramesInternal
, message
));
663 RenderViewHostImpl
* WebContentsImpl::GetRenderViewHost() const {
664 return GetRenderManager()->current_host();
667 int WebContentsImpl::GetRoutingID() const {
668 if (!GetRenderViewHost())
669 return MSG_ROUTING_NONE
;
671 return GetRenderViewHost()->GetRoutingID();
674 int WebContentsImpl::GetFullscreenWidgetRoutingID() const {
675 return fullscreen_widget_routing_id_
;
678 void WebContentsImpl::ClosePage() {
679 GetRenderViewHost()->ClosePage();
682 RenderWidgetHostView
* WebContentsImpl::GetRenderWidgetHostView() const {
683 return GetRenderManager()->GetRenderWidgetHostView();
686 RenderWidgetHostView
* WebContentsImpl::GetFullscreenRenderWidgetHostView()
688 RenderWidgetHost
* const widget_host
=
689 RenderWidgetHostImpl::FromID(GetRenderProcessHost()->GetID(),
690 GetFullscreenWidgetRoutingID());
691 return widget_host
? widget_host
->GetView() : NULL
;
694 WebContentsView
* WebContentsImpl::GetView() const {
698 SkColor
WebContentsImpl::GetThemeColor() const {
702 void WebContentsImpl::SetAccessibilityMode(AccessibilityMode mode
) {
703 if (mode
== accessibility_mode_
)
706 accessibility_mode_
= mode
;
708 base::Bind(&ForEachFrameInternal
,
709 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
711 base::Bind(&ForEachPendingFrameInternal
,
712 base::Bind(&SetAccessibilityModeOnFrame
, mode
)));
715 void WebContentsImpl::AddAccessibilityMode(AccessibilityMode mode
) {
716 SetAccessibilityMode(AddAccessibilityModeTo(accessibility_mode_
, mode
));
719 void WebContentsImpl::RemoveAccessibilityMode(AccessibilityMode mode
) {
720 SetAccessibilityMode(RemoveAccessibilityModeFrom(accessibility_mode_
, mode
));
723 void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback
) {
724 // TODO(dmazzoni): http://crbug.com/475608 This only returns the
725 // accessibility tree from the main frame and everything in the
726 // same site instance.
727 GetMainFrame()->RequestAXTreeSnapshot(callback
);
730 void WebContentsImpl::ClearNavigationTransitionData() {
731 FrameTreeNode
* node
= frame_tree_
.root();
732 node
->render_manager()->ClearNavigationTransitionData();
735 WebUI
* WebContentsImpl::CreateWebUI(const GURL
& url
) {
736 WebUIImpl
* web_ui
= new WebUIImpl(this);
737 WebUIController
* controller
= WebUIControllerFactoryRegistry::GetInstance()->
738 CreateWebUIControllerForURL(web_ui
, url
);
740 web_ui
->AddMessageHandler(new GenericHandler());
741 web_ui
->SetController(controller
);
749 WebUI
* WebContentsImpl::GetWebUI() const {
750 return GetRenderManager()->web_ui() ? GetRenderManager()->web_ui()
751 : GetRenderManager()->pending_web_ui();
754 WebUI
* WebContentsImpl::GetCommittedWebUI() const {
755 return GetRenderManager()->web_ui();
758 void WebContentsImpl::SetUserAgentOverride(const std::string
& override
) {
759 if (GetUserAgentOverride() == override
)
762 renderer_preferences_
.user_agent_override
= override
;
764 // Send the new override string to the renderer.
765 RenderViewHost
* host
= GetRenderViewHost();
767 host
->SyncRendererPrefs();
769 // Reload the page if a load is currently in progress to avoid having
770 // different parts of the page loaded using different user agents.
771 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
772 if (is_loading_
&& entry
!= NULL
&& entry
->GetIsOverridingUserAgent())
773 controller_
.ReloadIgnoringCache(true);
775 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
776 UserAgentOverrideSet(override
));
779 const std::string
& WebContentsImpl::GetUserAgentOverride() const {
780 return renderer_preferences_
.user_agent_override
;
783 void WebContentsImpl::EnableTreeOnlyAccessibilityMode() {
784 AddAccessibilityMode(AccessibilityModeTreeOnly
);
787 bool WebContentsImpl::IsTreeOnlyAccessibilityModeForTesting() const {
788 return accessibility_mode_
== AccessibilityModeTreeOnly
;
791 bool WebContentsImpl::IsFullAccessibilityModeForTesting() const {
792 return accessibility_mode_
== AccessibilityModeComplete
;
796 void WebContentsImpl::SetParentNativeViewAccessible(
797 gfx::NativeViewAccessible accessible_parent
) {
798 accessible_parent_
= accessible_parent
;
799 RenderFrameHostImpl
* rfh
= GetMainFrame();
801 rfh
->SetParentNativeViewAccessible(accessible_parent
);
805 const base::string16
& WebContentsImpl::GetTitle() const {
806 // Transient entries take precedence. They are used for interstitial pages
807 // that are shown on top of existing pages.
808 NavigationEntry
* entry
= controller_
.GetTransientEntry();
809 std::string accept_languages
=
810 GetContentClient()->browser()->GetAcceptLangs(
811 GetBrowserContext());
813 return entry
->GetTitleForDisplay(accept_languages
);
815 WebUI
* our_web_ui
= GetRenderManager()->pending_web_ui() ?
816 GetRenderManager()->pending_web_ui() : GetRenderManager()->web_ui();
818 // Don't override the title in view source mode.
819 entry
= controller_
.GetVisibleEntry();
820 if (!(entry
&& entry
->IsViewSourceMode())) {
821 // Give the Web UI the chance to override our title.
822 const base::string16
& title
= our_web_ui
->GetOverriddenTitle();
828 // We use the title for the last committed entry rather than a pending
829 // navigation entry. For example, when the user types in a URL, we want to
830 // keep the old page's title until the new load has committed and we get a new
832 entry
= controller_
.GetLastCommittedEntry();
834 // We make an exception for initial navigations.
835 if (controller_
.IsInitialNavigation()) {
836 // We only want to use the title from the visible entry in one of two cases:
837 // 1. There's already a committed entry for an initial navigation, in which
838 // case we are doing a history navigation in a new tab (e.g., Ctrl+Back).
839 // 2. The pending entry has been explicitly assigned a title to display.
841 // If there's no last committed entry and no assigned title, we should fall
842 // back to |page_title_when_no_navigation_entry_| rather than showing the
845 (controller_
.GetVisibleEntry() &&
846 !controller_
.GetVisibleEntry()->GetTitle().empty())) {
847 entry
= controller_
.GetVisibleEntry();
852 return entry
->GetTitleForDisplay(accept_languages
);
855 // |page_title_when_no_navigation_entry_| is finally used
856 // if no title cannot be retrieved.
857 return page_title_when_no_navigation_entry_
;
860 int32
WebContentsImpl::GetMaxPageID() {
861 return GetMaxPageIDForSiteInstance(GetSiteInstance());
864 int32
WebContentsImpl::GetMaxPageIDForSiteInstance(
865 SiteInstance
* site_instance
) {
866 if (max_page_ids_
.find(site_instance
->GetId()) == max_page_ids_
.end())
867 max_page_ids_
[site_instance
->GetId()] = -1;
869 return max_page_ids_
[site_instance
->GetId()];
872 void WebContentsImpl::UpdateMaxPageID(int32 page_id
) {
873 UpdateMaxPageIDForSiteInstance(GetSiteInstance(), page_id
);
876 void WebContentsImpl::UpdateMaxPageIDForSiteInstance(
877 SiteInstance
* site_instance
, int32 page_id
) {
878 if (GetMaxPageIDForSiteInstance(site_instance
) < page_id
)
879 max_page_ids_
[site_instance
->GetId()] = page_id
;
882 void WebContentsImpl::CopyMaxPageIDsFrom(WebContents
* web_contents
) {
883 WebContentsImpl
* contents
= static_cast<WebContentsImpl
*>(web_contents
);
884 max_page_ids_
= contents
->max_page_ids_
;
887 SiteInstanceImpl
* WebContentsImpl::GetSiteInstance() const {
888 return GetRenderManager()->current_host()->GetSiteInstance();
891 SiteInstanceImpl
* WebContentsImpl::GetPendingSiteInstance() const {
892 RenderViewHostImpl
* dest_rvh
=
893 GetRenderManager()->pending_render_view_host() ?
894 GetRenderManager()->pending_render_view_host() :
895 GetRenderManager()->current_host();
896 return dest_rvh
->GetSiteInstance();
899 bool WebContentsImpl::IsLoading() const {
903 bool WebContentsImpl::IsLoadingToDifferentDocument() const {
904 return is_loading_
&& is_load_to_different_document_
;
907 bool WebContentsImpl::IsWaitingForResponse() const {
908 return waiting_for_response_
&& is_load_to_different_document_
;
911 const net::LoadStateWithParam
& WebContentsImpl::GetLoadState() const {
915 const base::string16
& WebContentsImpl::GetLoadStateHost() const {
916 return load_state_host_
;
919 uint64
WebContentsImpl::GetUploadSize() const {
923 uint64
WebContentsImpl::GetUploadPosition() const {
924 return upload_position_
;
927 std::set
<GURL
> WebContentsImpl::GetSitesInTab() const {
928 std::set
<GURL
> sites
;
929 frame_tree_
.ForEach(base::Bind(&CollectSites
,
930 base::Unretained(GetBrowserContext()),
931 base::Unretained(&sites
)));
935 const std::string
& WebContentsImpl::GetEncoding() const {
936 return canonical_encoding_
;
939 bool WebContentsImpl::DisplayedInsecureContent() const {
940 return displayed_insecure_content_
;
943 void WebContentsImpl::IncrementCapturerCount(const gfx::Size
& capture_size
) {
944 DCHECK(!is_being_destroyed_
);
946 DVLOG(1) << "There are now " << capturer_count_
947 << " capturing(s) of WebContentsImpl@" << this;
949 // Note: This provides a hint to upstream code to size the views optimally
950 // for quality (e.g., to avoid scaling).
951 if (!capture_size
.IsEmpty() && preferred_size_for_capture_
.IsEmpty()) {
952 preferred_size_for_capture_
= capture_size
;
953 OnPreferredSizeChanged(preferred_size_
);
956 // Ensure that all views are un-occluded before capture begins.
960 void WebContentsImpl::DecrementCapturerCount() {
962 DVLOG(1) << "There are now " << capturer_count_
963 << " capturing(s) of WebContentsImpl@" << this;
964 DCHECK_LE(0, capturer_count_
);
966 if (is_being_destroyed_
)
969 if (capturer_count_
== 0) {
970 const gfx::Size old_size
= preferred_size_for_capture_
;
971 preferred_size_for_capture_
= gfx::Size();
972 OnPreferredSizeChanged(old_size
);
976 DVLOG(1) << "Executing delayed WasHidden().";
981 int WebContentsImpl::GetCapturerCount() const {
982 return capturer_count_
;
985 bool WebContentsImpl::IsAudioMuted() const {
986 return audio_muter_
.get() && audio_muter_
->is_muting();
989 void WebContentsImpl::SetAudioMuted(bool mute
) {
990 DVLOG(1) << "SetAudioMuted(mute=" << mute
<< "), was " << IsAudioMuted()
991 << " for WebContentsImpl@" << this;
993 if (mute
== IsAudioMuted())
998 audio_muter_
.reset(new WebContentsAudioMuter(this));
999 audio_muter_
->StartMuting();
1001 DCHECK(audio_muter_
);
1002 audio_muter_
->StopMuting();
1005 // Notification for UI updates in response to the changed muting state.
1006 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1009 bool WebContentsImpl::IsCrashed() const {
1010 return (crashed_status_
== base::TERMINATION_STATUS_PROCESS_CRASHED
||
1011 crashed_status_
== base::TERMINATION_STATUS_ABNORMAL_TERMINATION
||
1012 crashed_status_
== base::TERMINATION_STATUS_PROCESS_WAS_KILLED
);
1015 void WebContentsImpl::SetIsCrashed(base::TerminationStatus status
,
1017 if (status
== crashed_status_
)
1020 crashed_status_
= status
;
1021 crashed_error_code_
= error_code
;
1022 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB
);
1025 base::TerminationStatus
WebContentsImpl::GetCrashedStatus() const {
1026 return crashed_status_
;
1029 bool WebContentsImpl::IsBeingDestroyed() const {
1030 return is_being_destroyed_
;
1033 void WebContentsImpl::NotifyNavigationStateChanged(
1034 InvalidateTypes changed_flags
) {
1035 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
1037 tracked_objects::ScopedTracker
tracking_profile(
1038 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1039 "466285 WebContentsImpl::NotifyNavigationStateChanged"));
1040 // Create and release the audio power save blocker depending on whether the
1041 // tab is actively producing audio or not.
1042 if ((changed_flags
& INVALIDATE_TYPE_TAB
) &&
1043 audio_state_provider_
->IsAudioStateAvailable()) {
1044 if (WasRecentlyAudible()) {
1045 if (!audio_power_save_blocker_
)
1046 CreateAudioPowerSaveBlocker();
1048 audio_power_save_blocker_
.reset();
1053 delegate_
->NavigationStateChanged(this, changed_flags
);
1056 base::TimeTicks
WebContentsImpl::GetLastActiveTime() const {
1057 return last_active_time_
;
1060 void WebContentsImpl::WasShown() {
1061 controller_
.SetActive(true);
1063 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1066 #if defined(OS_MACOSX)
1067 view
->SetActive(true);
1072 last_active_time_
= base::TimeTicks::Now();
1074 // The resize rect might have changed while this was inactive -- send the new
1075 // one to make sure it's up to date.
1076 RenderViewHostImpl
* rvh
= GetRenderViewHost();
1078 rvh
->ResizeRectChanged(GetRootWindowResizerRect());
1080 // Restore power save blocker if there are active video players running.
1081 if (!active_video_players_
.empty() && !video_power_save_blocker_
)
1082 CreateVideoPowerSaveBlocker();
1084 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasShown());
1086 should_normally_be_visible_
= true;
1089 void WebContentsImpl::WasHidden() {
1090 // If there are entities capturing screenshots or video (e.g., mirroring),
1091 // don't activate the "disable rendering" optimization.
1092 if (capturer_count_
== 0) {
1093 // |GetRenderViewHost()| can be NULL if the user middle clicks a link to
1094 // open a tab in the background, then closes the tab before selecting it.
1095 // This is because closing the tab calls WebContentsImpl::Destroy(), which
1096 // removes the |GetRenderViewHost()|; then when we actually destroy the
1097 // window, OnWindowPosChanged() notices and calls WasHidden() (which
1099 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1104 // Release any video power save blockers held as video is not visible.
1105 video_power_save_blocker_
.reset();
1108 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, WasHidden());
1110 should_normally_be_visible_
= false;
1113 void WebContentsImpl::WasOccluded() {
1114 if (capturer_count_
> 0)
1117 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1119 view
->WasOccluded();
1123 void WebContentsImpl::WasUnOccluded() {
1124 for (RenderWidgetHostView
* view
: GetRenderWidgetHostViewsInTree()) {
1126 view
->WasUnOccluded();
1130 bool WebContentsImpl::NeedToFireBeforeUnload() {
1131 // TODO(creis): Should we fire even for interstitial pages?
1132 return WillNotifyDisconnection() && !ShowingInterstitialPage() &&
1133 !GetRenderViewHost()->SuddenTerminationAllowed();
1136 void WebContentsImpl::DispatchBeforeUnload(bool for_cross_site_transition
) {
1137 GetMainFrame()->DispatchBeforeUnload(for_cross_site_transition
);
1140 void WebContentsImpl::Stop() {
1141 GetRenderManager()->Stop();
1142 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, NavigationStopped());
1145 WebContents
* WebContentsImpl::Clone() {
1146 // We use our current SiteInstance since the cloned entry will use it anyway.
1147 // We pass our own opener so that the cloned page can access it if it was
1149 CreateParams
create_params(GetBrowserContext(), GetSiteInstance());
1150 create_params
.initial_size
= GetContainerBounds().size();
1151 WebContentsImpl
* tc
= CreateWithOpener(create_params
, opener_
);
1152 tc
->GetController().CopyStateFrom(controller_
);
1153 FOR_EACH_OBSERVER(WebContentsObserver
,
1155 DidCloneToNewWebContents(this, tc
));
1159 void WebContentsImpl::Observe(int type
,
1160 const NotificationSource
& source
,
1161 const NotificationDetails
& details
) {
1163 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
: {
1164 RenderWidgetHost
* host
= Source
<RenderWidgetHost
>(source
).ptr();
1165 RenderWidgetHostView
* view
= host
->GetView();
1166 if (view
== GetFullscreenRenderWidgetHostView()) {
1167 // We cannot just call view_->RestoreFocus() here. On some platforms,
1168 // attempting to focus the currently-invisible WebContentsView will be
1169 // flat-out ignored. Therefore, this boolean is used to track whether
1170 // we will request focus after the fullscreen widget has been
1172 fullscreen_widget_had_focus_at_shutdown_
= (view
&& view
->HasFocus());
1174 for (PendingWidgetViews::iterator i
= pending_widget_views_
.begin();
1175 i
!= pending_widget_views_
.end(); ++i
) {
1176 if (host
->GetView() == i
->second
) {
1177 pending_widget_views_
.erase(i
);
1189 WebContents
* WebContentsImpl::GetWebContents() {
1193 void WebContentsImpl::Init(const WebContents::CreateParams
& params
) {
1194 // This is set before initializing the render manager since
1195 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
1196 // it should be hidden.
1197 should_normally_be_visible_
= !params
.initially_hidden
;
1199 // Either both routing ids can be given, or neither can be.
1200 DCHECK((params
.routing_id
== MSG_ROUTING_NONE
&&
1201 params
.main_frame_routing_id
== MSG_ROUTING_NONE
) ||
1202 (params
.routing_id
!= MSG_ROUTING_NONE
&&
1203 params
.main_frame_routing_id
!= MSG_ROUTING_NONE
));
1204 GetRenderManager()->Init(
1205 params
.browser_context
, params
.site_instance
, params
.routing_id
,
1206 params
.main_frame_routing_id
);
1208 WebContentsViewDelegate
* delegate
=
1209 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
1211 if (browser_plugin_guest_
) {
1212 scoped_ptr
<WebContentsView
> platform_view(CreateWebContentsView(
1213 this, delegate
, &render_view_host_delegate_view_
));
1215 WebContentsViewGuest
* rv
= new WebContentsViewGuest(
1216 this, browser_plugin_guest_
.get(), platform_view
.Pass(),
1217 render_view_host_delegate_view_
);
1218 render_view_host_delegate_view_
= rv
;
1221 // Regular WebContentsView.
1222 view_
.reset(CreateWebContentsView(
1223 this, delegate
, &render_view_host_delegate_view_
));
1225 CHECK(render_view_host_delegate_view_
);
1228 gfx::Size initial_size
= params
.initial_size
;
1229 view_
->CreateView(initial_size
, params
.context
);
1231 // Listen for whether our opener gets destroyed.
1233 AddDestructionObserver(opener_
);
1235 #if defined(ENABLE_PLUGINS)
1236 plugin_content_origin_whitelist_
.reset(
1237 new PluginContentOriginWhitelist(this));
1240 registrar_
.Add(this,
1241 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED
,
1242 NotificationService::AllBrowserContextsAndSources());
1244 screen_orientation_dispatcher_host_
.reset(
1245 new ScreenOrientationDispatcherHostImpl(this));
1247 manifest_manager_host_
.reset(new ManifestManagerHost(this));
1249 #if defined(OS_ANDROID)
1250 date_time_chooser_
.reset(new DateTimeChooserAndroid());
1253 // BrowserPluginGuest::Init needs to be called after this WebContents has
1254 // a RenderWidgetHostViewGuest. That is, |view_->CreateView| above.
1255 if (browser_plugin_guest_
)
1256 browser_plugin_guest_
->Init();
1258 for (size_t i
= 0; i
< g_created_callbacks
.Get().size(); i
++)
1259 g_created_callbacks
.Get().at(i
).Run(this);
1261 // If the WebContents creation was renderer-initiated, it means that the
1262 // corresponding RenderView and main RenderFrame have already been created.
1263 // Ensure observers are notified about this.
1264 if (params
.renderer_initiated_creation
) {
1265 RenderViewCreated(GetRenderViewHost());
1266 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
1269 // Ensure that observers are notified of the creation of this WebContents's
1270 // main RenderFrameHost. It must be done here for main frames, since the
1271 // NotifySwappedFromRenderManager expects view_ to already be created and that
1272 // happens after RenderFrameHostManager::Init.
1273 NotifySwappedFromRenderManager(
1274 nullptr, GetRenderManager()->current_frame_host(), true);
1277 void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl
* web_contents
) {
1278 RemoveDestructionObserver(web_contents
);
1280 // Clear the opener if it has been closed.
1281 if (web_contents
== opener_
) {
1285 // Clear a pending contents that has been closed before being shown.
1286 for (PendingContents::iterator iter
= pending_contents_
.begin();
1287 iter
!= pending_contents_
.end();
1289 if (iter
->second
!= web_contents
)
1291 pending_contents_
.erase(iter
);
1297 void WebContentsImpl::AddDestructionObserver(WebContentsImpl
* web_contents
) {
1298 if (!ContainsKey(destruction_observers_
, web_contents
)) {
1299 destruction_observers_
[web_contents
] =
1300 new DestructionObserver(this, web_contents
);
1304 void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl
* web_contents
) {
1305 DestructionObservers::iterator iter
=
1306 destruction_observers_
.find(web_contents
);
1307 if (iter
!= destruction_observers_
.end()) {
1308 delete destruction_observers_
[web_contents
];
1309 destruction_observers_
.erase(iter
);
1313 void WebContentsImpl::AddObserver(WebContentsObserver
* observer
) {
1314 observers_
.AddObserver(observer
);
1317 void WebContentsImpl::RemoveObserver(WebContentsObserver
* observer
) {
1318 observers_
.RemoveObserver(observer
);
1321 std::set
<RenderWidgetHostView
*>
1322 WebContentsImpl::GetRenderWidgetHostViewsInTree() {
1323 std::set
<RenderWidgetHostView
*> set
;
1324 if (ShowingInterstitialPage()) {
1325 set
.insert(GetRenderWidgetHostView());
1328 base::Bind(&AddRenderWidgetHostViewToSet
, base::Unretained(&set
)));
1333 void WebContentsImpl::Activate() {
1335 delegate_
->ActivateContents(this);
1338 void WebContentsImpl::Deactivate() {
1340 delegate_
->DeactivateContents(this);
1343 void WebContentsImpl::LostCapture() {
1345 delegate_
->LostCapture();
1348 void WebContentsImpl::RenderWidgetDeleted(
1349 RenderWidgetHostImpl
* render_widget_host
) {
1350 if (is_being_destroyed_
) {
1351 // |created_widgets_| might have been destroyed.
1355 std::set
<RenderWidgetHostImpl
*>::iterator iter
=
1356 created_widgets_
.find(render_widget_host
);
1357 if (iter
!= created_widgets_
.end())
1358 created_widgets_
.erase(iter
);
1360 if (render_widget_host
&&
1361 render_widget_host
->GetRoutingID() == fullscreen_widget_routing_id_
) {
1362 if (delegate_
&& delegate_
->EmbedsFullscreenWidget())
1363 delegate_
->ExitFullscreenModeForTab(this);
1364 FOR_EACH_OBSERVER(WebContentsObserver
,
1366 DidDestroyFullscreenWidget(
1367 fullscreen_widget_routing_id_
));
1368 fullscreen_widget_routing_id_
= MSG_ROUTING_NONE
;
1369 if (fullscreen_widget_had_focus_at_shutdown_
)
1370 view_
->RestoreFocus();
1374 void WebContentsImpl::RenderWidgetGotFocus(
1375 RenderWidgetHostImpl
* render_widget_host
) {
1376 // Notify the observers if an embedded fullscreen widget was focused.
1377 if (delegate_
&& render_widget_host
&& delegate_
->EmbedsFullscreenWidget() &&
1378 render_widget_host
->GetView() == GetFullscreenRenderWidgetHostView()) {
1379 NotifyWebContentsFocused();
1383 void WebContentsImpl::RenderWidgetWasResized(
1384 RenderWidgetHostImpl
* render_widget_host
,
1385 bool width_changed
) {
1386 RenderFrameHostImpl
* rfh
= GetMainFrame();
1387 if (!rfh
|| render_widget_host
!= rfh
->GetRenderWidgetHost())
1390 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1391 MainFrameWasResized(width_changed
));
1394 void WebContentsImpl::ScreenInfoChanged() {
1395 if (browser_plugin_embedder_
)
1396 browser_plugin_embedder_
->ScreenInfoChanged();
1399 bool WebContentsImpl::PreHandleKeyboardEvent(
1400 const NativeWebKeyboardEvent
& event
,
1401 bool* is_keyboard_shortcut
) {
1403 delegate_
->PreHandleKeyboardEvent(this, event
, is_keyboard_shortcut
);
1406 void WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent
& event
) {
1407 if (browser_plugin_embedder_
&&
1408 browser_plugin_embedder_
->HandleKeyboardEvent(event
)) {
1412 delegate_
->HandleKeyboardEvent(this, event
);
1415 bool WebContentsImpl::HandleWheelEvent(
1416 const blink::WebMouseWheelEvent
& event
) {
1417 #if !defined(OS_MACOSX)
1418 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
1419 // this isn't done for two reasons:
1420 // -the OS already has a gesture to do this through pinch-zoom
1421 // -if a user starts an inertial scroll, let's go, and presses control
1422 // (i.e. control+tab) then the OS's buffered scroll events will come in
1423 // with control key set which isn't what the user wants
1424 if (delegate_
&& event
.wheelTicksY
&&
1425 (event
.modifiers
& blink::WebInputEvent::ControlKey
) &&
1427 delegate_
->ContentsZoomChange(event
.wheelTicksY
> 0);
1434 bool WebContentsImpl::PreHandleGestureEvent(
1435 const blink::WebGestureEvent
& event
) {
1436 return delegate_
&& delegate_
->PreHandleGestureEvent(this, event
);
1439 void WebContentsImpl::EnterFullscreenMode(const GURL
& origin
) {
1440 // This method is being called to enter renderer-initiated fullscreen mode.
1441 // Make sure any existing fullscreen widget is shut down first.
1442 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1444 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1447 delegate_
->EnterFullscreenModeForTab(this, origin
);
1449 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1450 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1453 void WebContentsImpl::ExitFullscreenMode() {
1454 // This method is being called to leave renderer-initiated fullscreen mode.
1455 // Make sure any existing fullscreen widget is shut down first.
1456 RenderWidgetHostView
* const widget_view
= GetFullscreenRenderWidgetHostView();
1458 RenderWidgetHostImpl::From(widget_view
->GetRenderWidgetHost())->Shutdown();
1460 #if defined(OS_ANDROID)
1461 ContentVideoView
* video_view
= ContentVideoView::GetInstance();
1462 if (video_view
!= NULL
)
1463 video_view
->OnExitFullscreen();
1467 delegate_
->ExitFullscreenModeForTab(this);
1469 // Ensure web contents exit fullscreen state by sending a resize message,
1470 // which includes the fullscreen state. This is required for the situation
1471 // of the browser moving the view into a fullscreen state "browser fullscreen"
1472 // and then the contents entering "tab fullscreen". Exiting the contents
1473 // "tab fullscreen" then won't have the side effect of the view resizing,
1474 // hence the explicit call here is required.
1475 if (RenderWidgetHostView
* rwh_view
= GetRenderWidgetHostView()) {
1476 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
1477 render_widget_host
->WasResized();
1480 FOR_EACH_OBSERVER(WebContentsObserver
,
1482 DidToggleFullscreenModeForTab(IsFullscreenForCurrentTab()));
1485 bool WebContentsImpl::IsFullscreenForCurrentTab() const {
1486 return delegate_
? delegate_
->IsFullscreenForTabOrPending(this) : false;
1489 blink::WebDisplayMode
WebContentsImpl::GetDisplayMode() const {
1490 return delegate_
? delegate_
->GetDisplayMode(this)
1491 : blink::WebDisplayModeBrowser
;
1494 void WebContentsImpl::RequestToLockMouse(bool user_gesture
,
1495 bool last_unlocked_by_target
) {
1497 delegate_
->RequestToLockMouse(this, user_gesture
, last_unlocked_by_target
);
1499 GotResponseToLockMouseRequest(false);
1503 void WebContentsImpl::LostMouseLock() {
1505 delegate_
->LostMouseLock();
1508 void WebContentsImpl::CreateNewWindow(
1509 int render_process_id
,
1511 int main_frame_route_id
,
1512 const ViewHostMsg_CreateWindow_Params
& params
,
1513 SessionStorageNamespace
* session_storage_namespace
) {
1514 // We usually create the new window in the same BrowsingInstance (group of
1515 // script-related windows), by passing in the current SiteInstance. However,
1516 // if the opener is being suppressed (in a non-guest), we create a new
1517 // SiteInstance in its own BrowsingInstance.
1518 bool is_guest
= BrowserPluginGuest::IsGuest(this);
1520 // If the opener is to be suppressed, the new window can be in any process.
1521 // Since routing ids are process specific, we must not have one passed in
1522 // as argument here.
1523 DCHECK(!params
.opener_suppressed
|| route_id
== MSG_ROUTING_NONE
);
1525 scoped_refptr
<SiteInstance
> site_instance
=
1526 params
.opener_suppressed
&& !is_guest
?
1527 SiteInstance::CreateForURL(GetBrowserContext(), params
.target_url
) :
1530 // A message to create a new window can only come from the active process for
1531 // this WebContentsImpl instance. If any other process sends the request,
1532 // it is invalid and the process must be terminated.
1533 if (GetRenderProcessHost()->GetID() != render_process_id
) {
1534 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1535 base::ProcessHandle process_handle
= rph
->GetHandle();
1536 if (process_handle
!= base::kNullProcessHandle
) {
1538 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWindow"));
1539 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1544 // We must assign the SessionStorageNamespace before calling Init().
1546 // http://crbug.com/142685
1547 const std::string
& partition_id
=
1548 GetContentClient()->browser()->
1549 GetStoragePartitionIdForSite(GetBrowserContext(),
1550 site_instance
->GetSiteURL());
1551 StoragePartition
* partition
= BrowserContext::GetStoragePartition(
1552 GetBrowserContext(), site_instance
.get());
1553 DOMStorageContextWrapper
* dom_storage_context
=
1554 static_cast<DOMStorageContextWrapper
*>(partition
->GetDOMStorageContext());
1555 SessionStorageNamespaceImpl
* session_storage_namespace_impl
=
1556 static_cast<SessionStorageNamespaceImpl
*>(session_storage_namespace
);
1557 CHECK(session_storage_namespace_impl
->IsFromContext(dom_storage_context
));
1560 !delegate_
->ShouldCreateWebContents(this,
1562 main_frame_route_id
,
1563 params
.window_container_type
,
1567 session_storage_namespace
)) {
1568 if (route_id
!= MSG_ROUTING_NONE
&&
1569 !RenderViewHost::FromID(render_process_id
, route_id
)) {
1570 // If the embedder didn't create a WebContents for this route, we need to
1571 // delete the RenderView that had already been created.
1572 Send(new ViewMsg_Close(route_id
));
1574 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(route_id
);
1575 GetRenderViewHost()->GetProcess()->ResumeRequestsForView(
1576 main_frame_route_id
);
1580 // Create the new web contents. This will automatically create the new
1581 // WebContentsView. In the future, we may want to create the view separately.
1582 CreateParams
create_params(GetBrowserContext(), site_instance
.get());
1583 create_params
.routing_id
= route_id
;
1584 create_params
.main_frame_routing_id
= main_frame_route_id
;
1585 create_params
.opener
= this;
1586 create_params
.opener_suppressed
= params
.opener_suppressed
;
1587 if (params
.disposition
== NEW_BACKGROUND_TAB
)
1588 create_params
.initially_hidden
= true;
1589 create_params
.renderer_initiated_creation
= true;
1591 WebContentsImpl
* new_contents
= NULL
;
1593 create_params
.context
= view_
->GetNativeView();
1594 create_params
.initial_size
= GetContainerBounds().size();
1595 new_contents
= static_cast<WebContentsImpl
*>(
1596 WebContents::Create(create_params
));
1598 new_contents
= GetBrowserPluginGuest()->CreateNewGuestWindow(create_params
);
1600 new_contents
->GetController().SetSessionStorageNamespace(
1602 session_storage_namespace
);
1604 // Save the window for later if we're not suppressing the opener (since it
1605 // will be shown immediately).
1606 if (!params
.opener_suppressed
) {
1608 WebContentsView
* new_view
= new_contents
->view_
.get();
1610 // TODO(brettw): It seems bogus that we have to call this function on the
1611 // newly created object and give it one of its own member variables.
1612 new_view
->CreateViewForWidget(new_contents
->GetRenderViewHost(), false);
1614 // Save the created window associated with the route so we can show it
1616 DCHECK_NE(MSG_ROUTING_NONE
, route_id
);
1617 pending_contents_
[route_id
] = new_contents
;
1618 AddDestructionObserver(new_contents
);
1622 delegate_
->WebContentsCreated(
1623 this, params
.opener_render_frame_id
, params
.frame_name
,
1624 params
.target_url
, new_contents
);
1627 if (params
.opener_suppressed
) {
1628 // When the opener is suppressed, the original renderer cannot access the
1629 // new window. As a result, we need to show and navigate the window here.
1630 bool was_blocked
= false;
1632 gfx::Rect initial_rect
;
1633 delegate_
->AddNewContents(
1634 this, new_contents
, params
.disposition
, initial_rect
,
1635 params
.user_gesture
, &was_blocked
);
1638 OpenURLParams
open_params(params
.target_url
,
1641 ui::PAGE_TRANSITION_LINK
,
1642 true /* is_renderer_initiated */);
1643 open_params
.user_gesture
= params
.user_gesture
;
1644 new_contents
->OpenURL(open_params
);
1649 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1651 blink::WebPopupType popup_type
) {
1652 CreateNewWidget(render_process_id
, route_id
, false, popup_type
);
1655 void WebContentsImpl::CreateNewFullscreenWidget(int render_process_id
,
1657 CreateNewWidget(render_process_id
, route_id
, true, blink::WebPopupTypeNone
);
1660 void WebContentsImpl::CreateNewWidget(int render_process_id
,
1663 blink::WebPopupType popup_type
) {
1664 RenderProcessHost
* process
= GetRenderProcessHost();
1665 // A message to create a new widget can only come from the active process for
1666 // this WebContentsImpl instance. If any other process sends the request,
1667 // it is invalid and the process must be terminated.
1668 if (process
->GetID() != render_process_id
) {
1669 RenderProcessHost
* rph
= RenderProcessHost::FromID(render_process_id
);
1670 base::ProcessHandle process_handle
= rph
->GetHandle();
1671 if (process_handle
!= base::kNullProcessHandle
) {
1673 base::UserMetricsAction("Terminate_ProcessMismatch_CreateNewWidget"));
1674 rph
->Shutdown(RESULT_CODE_KILLED
, false);
1679 RenderWidgetHostImpl
* widget_host
=
1680 new RenderWidgetHostImpl(this, process
, route_id
, IsHidden());
1681 created_widgets_
.insert(widget_host
);
1683 RenderWidgetHostViewBase
* widget_view
=
1684 static_cast<RenderWidgetHostViewBase
*>(
1685 view_
->CreateViewForPopupWidget(widget_host
));
1688 if (!is_fullscreen
) {
1689 // Popups should not get activated.
1690 widget_view
->SetPopupType(popup_type
);
1692 // Save the created widget associated with the route so we can show it later.
1693 pending_widget_views_
[route_id
] = widget_view
;
1695 #if defined(OS_MACOSX)
1696 // A RenderWidgetHostViewMac has lifetime scoped to the view. We'll retain it
1697 // to allow it to survive the trip without being hosted.
1698 base::mac::NSObjectRetain(widget_view
->GetNativeView());
1702 void WebContentsImpl::ShowCreatedWindow(int route_id
,
1703 WindowOpenDisposition disposition
,
1704 const gfx::Rect
& initial_rect
,
1705 bool user_gesture
) {
1706 WebContentsImpl
* contents
= GetCreatedWindow(route_id
);
1708 WebContentsDelegate
* delegate
= GetDelegate();
1709 if (!delegate
|| delegate
->ShouldResumeRequestsForCreatedWindow())
1710 contents
->ResumeLoadingCreatedWebContents();
1713 delegate
->AddNewContents(
1714 this, contents
, disposition
, initial_rect
, user_gesture
, NULL
);
1719 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1720 const gfx::Rect
& initial_rect
) {
1721 ShowCreatedWidget(route_id
, false, initial_rect
);
1724 void WebContentsImpl::ShowCreatedFullscreenWidget(int route_id
) {
1725 ShowCreatedWidget(route_id
, true, gfx::Rect());
1728 void WebContentsImpl::ShowCreatedWidget(int route_id
,
1730 const gfx::Rect
& initial_rect
) {
1731 RenderWidgetHostViewBase
* widget_host_view
=
1732 static_cast<RenderWidgetHostViewBase
*>(GetCreatedWidget(route_id
));
1733 if (!widget_host_view
)
1736 RenderWidgetHostView
* view
= NULL
;
1737 BrowserPluginGuest
* guest
= GetBrowserPluginGuest();
1738 if (guest
&& guest
->embedder_web_contents()) {
1739 view
= guest
->embedder_web_contents()->GetRenderWidgetHostView();
1741 view
= GetRenderWidgetHostView();
1744 if (is_fullscreen
) {
1745 DCHECK_EQ(MSG_ROUTING_NONE
, fullscreen_widget_routing_id_
);
1746 view_
->StoreFocus();
1747 fullscreen_widget_routing_id_
= route_id
;
1748 if (delegate_
&& delegate_
->EmbedsFullscreenWidget()) {
1749 widget_host_view
->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
1750 delegate_
->EnterFullscreenModeForTab(this, GURL());
1752 widget_host_view
->InitAsFullscreen(view
);
1754 FOR_EACH_OBSERVER(WebContentsObserver
,
1756 DidShowFullscreenWidget(route_id
));
1757 if (!widget_host_view
->HasFocus())
1758 widget_host_view
->Focus();
1760 widget_host_view
->InitAsPopup(view
, initial_rect
);
1763 RenderWidgetHostImpl
* render_widget_host_impl
=
1764 RenderWidgetHostImpl::From(widget_host_view
->GetRenderWidgetHost());
1765 render_widget_host_impl
->Init();
1766 // Only allow privileged mouse lock for fullscreen render widget, which is
1767 // used to implement Pepper Flash fullscreen.
1768 render_widget_host_impl
->set_allow_privileged_mouse_lock(is_fullscreen
);
1770 #if defined(OS_MACOSX)
1771 // A RenderWidgetHostViewMac has lifetime scoped to the view. Now that it's
1772 // properly embedded (or purposefully ignored) we can release the retain we
1773 // took in CreateNewWidget().
1774 base::mac::NSObjectRelease(widget_host_view
->GetNativeView());
1778 WebContentsImpl
* WebContentsImpl::GetCreatedWindow(int route_id
) {
1779 PendingContents::iterator iter
= pending_contents_
.find(route_id
);
1781 // Certain systems can block the creation of new windows. If we didn't succeed
1782 // in creating one, just return NULL.
1783 if (iter
== pending_contents_
.end()) {
1787 WebContentsImpl
* new_contents
= iter
->second
;
1788 pending_contents_
.erase(route_id
);
1789 RemoveDestructionObserver(new_contents
);
1791 // Don't initialize the guest WebContents immediately.
1792 if (BrowserPluginGuest::IsGuest(new_contents
))
1793 return new_contents
;
1795 if (!new_contents
->GetRenderProcessHost()->HasConnection() ||
1796 !new_contents
->GetRenderViewHost()->GetView())
1799 return new_contents
;
1802 RenderWidgetHostView
* WebContentsImpl::GetCreatedWidget(int route_id
) {
1803 PendingWidgetViews::iterator iter
= pending_widget_views_
.find(route_id
);
1804 if (iter
== pending_widget_views_
.end()) {
1809 RenderWidgetHostView
* widget_host_view
= iter
->second
;
1810 pending_widget_views_
.erase(route_id
);
1812 RenderWidgetHost
* widget_host
= widget_host_view
->GetRenderWidgetHost();
1813 if (!widget_host
->GetProcess()->HasConnection()) {
1814 // The view has gone away or the renderer crashed. Nothing to do.
1818 return widget_host_view
;
1821 void WebContentsImpl::RequestMediaAccessPermission(
1822 const MediaStreamRequest
& request
,
1823 const MediaResponseCallback
& callback
) {
1825 delegate_
->RequestMediaAccessPermission(this, request
, callback
);
1827 callback
.Run(MediaStreamDevices(),
1828 MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN
,
1829 scoped_ptr
<MediaStreamUI
>());
1833 bool WebContentsImpl::CheckMediaAccessPermission(const GURL
& security_origin
,
1834 MediaStreamType type
) {
1835 DCHECK(type
== MEDIA_DEVICE_AUDIO_CAPTURE
||
1836 type
== MEDIA_DEVICE_VIDEO_CAPTURE
);
1838 delegate_
->CheckMediaAccessPermission(this, security_origin
, type
);
1841 SessionStorageNamespace
* WebContentsImpl::GetSessionStorageNamespace(
1842 SiteInstance
* instance
) {
1843 return controller_
.GetSessionStorageNamespace(instance
);
1846 SessionStorageNamespaceMap
WebContentsImpl::GetSessionStorageNamespaceMap() {
1847 return controller_
.GetSessionStorageNamespaceMap();
1850 FrameTree
* WebContentsImpl::GetFrameTree() {
1851 return &frame_tree_
;
1854 void WebContentsImpl::SetIsVirtualKeyboardRequested(bool requested
) {
1855 virtual_keyboard_requested_
= requested
;
1858 bool WebContentsImpl::IsVirtualKeyboardRequested() {
1859 return virtual_keyboard_requested_
;
1862 AccessibilityMode
WebContentsImpl::GetAccessibilityMode() const {
1863 return accessibility_mode_
;
1866 void WebContentsImpl::AccessibilityEventReceived(
1867 const std::vector
<AXEventNotificationDetails
>& details
) {
1869 WebContentsObserver
, observers_
, AccessibilityEventReceived(details
));
1872 RenderFrameHost
* WebContentsImpl::GetGuestByInstanceID(
1873 RenderFrameHost
* render_frame_host
,
1874 int browser_plugin_instance_id
) {
1875 BrowserPluginGuestManager
* guest_manager
=
1876 GetBrowserContext()->GetGuestManager();
1880 WebContents
* guest
= guest_manager
->GetGuestByInstanceID(
1881 render_frame_host
->GetProcess()->GetID(), browser_plugin_instance_id
);
1885 return guest
->GetMainFrame();
1888 GeolocationServiceContext
* WebContentsImpl::GetGeolocationServiceContext() {
1889 return geolocation_service_context_
.get();
1892 void WebContentsImpl::OnShowValidationMessage(
1893 const gfx::Rect
& anchor_in_root_view
,
1894 const base::string16
& main_text
,
1895 const base::string16
& sub_text
) {
1897 delegate_
->ShowValidationMessage(
1898 this, anchor_in_root_view
, main_text
, sub_text
);
1901 void WebContentsImpl::OnHideValidationMessage() {
1903 delegate_
->HideValidationMessage(this);
1906 void WebContentsImpl::OnMoveValidationMessage(
1907 const gfx::Rect
& anchor_in_root_view
) {
1909 delegate_
->MoveValidationMessage(this, anchor_in_root_view
);
1912 void WebContentsImpl::DidSendScreenRects(RenderWidgetHostImpl
* rwh
) {
1913 if (browser_plugin_embedder_
)
1914 browser_plugin_embedder_
->DidSendScreenRects();
1917 BrowserAccessibilityManager
*
1918 WebContentsImpl::GetRootBrowserAccessibilityManager() {
1919 RenderFrameHostImpl
* rfh
= GetMainFrame();
1920 return rfh
? rfh
->browser_accessibility_manager() : nullptr;
1923 BrowserAccessibilityManager
*
1924 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
1925 RenderFrameHostImpl
* rfh
= GetMainFrame();
1926 return rfh
? rfh
->GetOrCreateBrowserAccessibilityManager() : nullptr;
1929 void WebContentsImpl::UpdatePreferredSize(const gfx::Size
& pref_size
) {
1930 const gfx::Size old_size
= GetPreferredSize();
1931 preferred_size_
= pref_size
;
1932 OnPreferredSizeChanged(old_size
);
1935 void WebContentsImpl::ResizeDueToAutoResize(const gfx::Size
& new_size
) {
1937 delegate_
->ResizeDueToAutoResize(this, new_size
);
1940 WebContents
* WebContentsImpl::OpenURL(const OpenURLParams
& params
) {
1944 WebContents
* new_contents
= delegate_
->OpenURLFromTab(this, params
);
1945 return new_contents
;
1948 bool WebContentsImpl::Send(IPC::Message
* message
) {
1949 if (!GetRenderViewHost()) {
1954 return GetRenderViewHost()->Send(message
);
1957 bool WebContentsImpl::NavigateToPendingEntry(
1958 NavigationController::ReloadType reload_type
) {
1959 FrameTreeNode
* node
= frame_tree_
.root();
1961 // Navigate in the FrameTreeNode specified in the pending entry, if any. This
1962 // is currently only used in --site-per-process and tests.
1963 // TODO(creis): Remove this method and NavigationEntryImpl::frame_tree_node_id
1964 // by using FrameNavigationEntries instead. See https://crbug.com/236848.
1965 NavigationEntryImpl
* pending_entry
= controller_
.GetPendingEntry();
1966 if (pending_entry
->frame_tree_node_id() != -1) {
1967 FrameTreeNode
* subframe
=
1968 frame_tree_
.FindByID(pending_entry
->frame_tree_node_id());
1974 return node
->navigator()->NavigateToPendingEntry(node
, reload_type
);
1977 void WebContentsImpl::RenderFrameForInterstitialPageCreated(
1978 RenderFrameHost
* render_frame_host
) {
1979 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1980 RenderFrameForInterstitialPageCreated(render_frame_host
));
1983 void WebContentsImpl::AttachInterstitialPage(
1984 InterstitialPageImpl
* interstitial_page
) {
1985 DCHECK(interstitial_page
);
1986 GetRenderManager()->set_interstitial_page(interstitial_page
);
1988 // Cancel any visible dialogs so that they don't interfere with the
1990 if (dialog_manager_
)
1991 dialog_manager_
->CancelActiveAndPendingDialogs(this);
1993 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
1994 DidAttachInterstitialPage());
1997 void WebContentsImpl::DetachInterstitialPage() {
1998 if (ShowingInterstitialPage())
1999 GetRenderManager()->remove_interstitial_page();
2000 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2001 DidDetachInterstitialPage());
2004 void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset
,
2005 int history_length
) {
2006 SetHistoryOffsetAndLengthForView(
2007 GetRenderViewHost(), history_offset
, history_length
);
2010 void WebContentsImpl::SetHistoryOffsetAndLengthForView(
2011 RenderViewHost
* render_view_host
,
2013 int history_length
) {
2014 render_view_host
->Send(new ViewMsg_SetHistoryOffsetAndLength(
2015 render_view_host
->GetRoutingID(), history_offset
, history_length
));
2018 void WebContentsImpl::ReloadFocusedFrame(bool ignore_cache
) {
2019 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2023 focused_frame
->Send(new FrameMsg_Reload(
2024 focused_frame
->GetRoutingID(), ignore_cache
));
2027 void WebContentsImpl::Undo() {
2028 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2032 focused_frame
->Send(new InputMsg_Undo(focused_frame
->GetRoutingID()));
2033 RecordAction(base::UserMetricsAction("Undo"));
2036 void WebContentsImpl::Redo() {
2037 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2040 focused_frame
->Send(new InputMsg_Redo(focused_frame
->GetRoutingID()));
2041 RecordAction(base::UserMetricsAction("Redo"));
2044 void WebContentsImpl::Cut() {
2045 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2049 focused_frame
->Send(new InputMsg_Cut(focused_frame
->GetRoutingID()));
2050 RecordAction(base::UserMetricsAction("Cut"));
2053 void WebContentsImpl::Copy() {
2054 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2058 focused_frame
->Send(new InputMsg_Copy(focused_frame
->GetRoutingID()));
2059 RecordAction(base::UserMetricsAction("Copy"));
2062 void WebContentsImpl::CopyToFindPboard() {
2063 #if defined(OS_MACOSX)
2064 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2068 // Windows/Linux don't have the concept of a find pasteboard.
2069 focused_frame
->Send(
2070 new InputMsg_CopyToFindPboard(focused_frame
->GetRoutingID()));
2071 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
2075 void WebContentsImpl::Paste() {
2076 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2080 focused_frame
->Send(new InputMsg_Paste(focused_frame
->GetRoutingID()));
2081 RecordAction(base::UserMetricsAction("Paste"));
2084 void WebContentsImpl::PasteAndMatchStyle() {
2085 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2089 focused_frame
->Send(new InputMsg_PasteAndMatchStyle(
2090 focused_frame
->GetRoutingID()));
2091 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
2094 void WebContentsImpl::Delete() {
2095 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2099 focused_frame
->Send(new InputMsg_Delete(focused_frame
->GetRoutingID()));
2100 RecordAction(base::UserMetricsAction("DeleteSelection"));
2103 void WebContentsImpl::SelectAll() {
2104 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2108 focused_frame
->Send(new InputMsg_SelectAll(focused_frame
->GetRoutingID()));
2109 RecordAction(base::UserMetricsAction("SelectAll"));
2112 void WebContentsImpl::Unselect() {
2113 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2117 focused_frame
->Send(new InputMsg_Unselect(focused_frame
->GetRoutingID()));
2118 RecordAction(base::UserMetricsAction("Unselect"));
2121 void WebContentsImpl::Replace(const base::string16
& word
) {
2122 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2126 focused_frame
->Send(new InputMsg_Replace(
2127 focused_frame
->GetRoutingID(), word
));
2130 void WebContentsImpl::ReplaceMisspelling(const base::string16
& word
) {
2131 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2135 focused_frame
->Send(new InputMsg_ReplaceMisspelling(
2136 focused_frame
->GetRoutingID(), word
));
2139 void WebContentsImpl::NotifyContextMenuClosed(
2140 const CustomContextMenuContext
& context
) {
2141 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2145 focused_frame
->Send(new FrameMsg_ContextMenuClosed(
2146 focused_frame
->GetRoutingID(), context
));
2149 void WebContentsImpl::ExecuteCustomContextMenuCommand(
2150 int action
, const CustomContextMenuContext
& context
) {
2151 RenderFrameHost
* focused_frame
= GetFocusedFrame();
2155 focused_frame
->Send(new FrameMsg_CustomContextMenuAction(
2156 focused_frame
->GetRoutingID(), context
, action
));
2159 gfx::NativeView
WebContentsImpl::GetNativeView() {
2160 return view_
->GetNativeView();
2163 gfx::NativeView
WebContentsImpl::GetContentNativeView() {
2164 return view_
->GetContentNativeView();
2167 gfx::NativeWindow
WebContentsImpl::GetTopLevelNativeWindow() {
2168 return view_
->GetTopLevelNativeWindow();
2171 gfx::Rect
WebContentsImpl::GetViewBounds() {
2172 return view_
->GetViewBounds();
2175 gfx::Rect
WebContentsImpl::GetContainerBounds() {
2177 view_
->GetContainerBounds(&rv
);
2181 DropData
* WebContentsImpl::GetDropData() {
2182 return view_
->GetDropData();
2185 void WebContentsImpl::Focus() {
2189 void WebContentsImpl::SetInitialFocus() {
2190 view_
->SetInitialFocus();
2193 void WebContentsImpl::StoreFocus() {
2194 view_
->StoreFocus();
2197 void WebContentsImpl::RestoreFocus() {
2198 view_
->RestoreFocus();
2201 void WebContentsImpl::FocusThroughTabTraversal(bool reverse
) {
2202 if (ShowingInterstitialPage()) {
2203 GetRenderManager()->interstitial_page()->FocusThroughTabTraversal(reverse
);
2206 RenderWidgetHostView
* const fullscreen_view
=
2207 GetFullscreenRenderWidgetHostView();
2208 if (fullscreen_view
) {
2209 fullscreen_view
->Focus();
2212 GetRenderViewHost()->SetInitialFocus(reverse
);
2215 bool WebContentsImpl::ShowingInterstitialPage() const {
2216 return GetRenderManager()->interstitial_page() != NULL
;
2219 InterstitialPage
* WebContentsImpl::GetInterstitialPage() const {
2220 return GetRenderManager()->interstitial_page();
2223 bool WebContentsImpl::IsSavable() {
2224 // WebKit creates Document object when MIME type is application/xhtml+xml,
2225 // so we also support this MIME type.
2226 return contents_mime_type_
== "text/html" ||
2227 contents_mime_type_
== "text/xml" ||
2228 contents_mime_type_
== "application/xhtml+xml" ||
2229 contents_mime_type_
== "text/plain" ||
2230 contents_mime_type_
== "text/css" ||
2231 mime_util::IsSupportedJavascriptMimeType(contents_mime_type_
);
2234 void WebContentsImpl::OnSavePage() {
2235 // If we can not save the page, try to download it.
2237 RecordDownloadSource(INITIATED_BY_SAVE_PACKAGE_ON_NON_HTML
);
2238 SaveFrame(GetLastCommittedURL(), Referrer());
2244 // Create the save package and possibly prompt the user for the name to save
2245 // the page as. The user prompt is an asynchronous operation that runs on
2247 save_package_
= new SavePackage(this);
2248 save_package_
->GetSaveInfo();
2251 // Used in automated testing to bypass prompting the user for file names.
2252 // Instead, the names and paths are hard coded rather than running them through
2253 // file name sanitation and extension / mime checking.
2254 bool WebContentsImpl::SavePage(const base::FilePath
& main_file
,
2255 const base::FilePath
& dir_path
,
2256 SavePageType save_type
) {
2257 // Stop the page from navigating.
2260 save_package_
= new SavePackage(this, save_type
, main_file
, dir_path
);
2261 return save_package_
->Init(SavePackageDownloadCreatedCallback());
2264 void WebContentsImpl::SaveFrame(const GURL
& url
,
2265 const Referrer
& referrer
) {
2266 SaveFrameWithHeaders(url
, referrer
, std::string());
2269 void WebContentsImpl::SaveFrameWithHeaders(const GURL
& url
,
2270 const Referrer
& referrer
,
2271 const std::string
& headers
) {
2272 if (!GetLastCommittedURL().is_valid())
2274 if (delegate_
&& delegate_
->SaveFrame(url
, referrer
))
2277 // TODO(nasko): This check for main frame is incorrect and should be fixed
2278 // by explicitly passing in which frame this method should target.
2279 bool is_main_frame
= (url
== GetLastCommittedURL());
2281 DownloadManager
* dlm
=
2282 BrowserContext::GetDownloadManager(GetBrowserContext());
2286 if (is_main_frame
) {
2287 const NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
2289 post_id
= entry
->GetPostID();
2291 scoped_ptr
<DownloadUrlParameters
> params(
2292 DownloadUrlParameters::FromWebContents(this, url
));
2293 params
->set_referrer(referrer
);
2294 params
->set_post_id(post_id
);
2296 params
->set_method("POST");
2297 params
->set_prompt(true);
2299 if (headers
.empty()) {
2300 params
->set_prefer_cache(true);
2302 std::vector
<std::string
> key_value_list
;
2303 base::SplitString(headers
, '\n', &key_value_list
);
2304 for (const auto& key_value
: key_value_list
) {
2305 std::vector
<std::string
> pair
;
2306 base::SplitString(key_value
, ':', &pair
);
2307 DCHECK_EQ(2ul, pair
.size());
2308 params
->add_request_header(pair
[0], pair
[1]);
2311 dlm
->DownloadUrl(params
.Pass());
2314 void WebContentsImpl::GenerateMHTML(
2315 const base::FilePath
& file
,
2316 const base::Callback
<void(int64
)>& callback
) {
2317 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, file
, callback
);
2320 const std::string
& WebContentsImpl::GetContentsMimeType() const {
2321 return contents_mime_type_
;
2324 bool WebContentsImpl::WillNotifyDisconnection() const {
2325 return notify_disconnection_
;
2328 void WebContentsImpl::SetOverrideEncoding(const std::string
& encoding
) {
2329 SetEncoding(encoding
);
2330 Send(new ViewMsg_SetPageEncoding(GetRoutingID(), encoding
));
2333 void WebContentsImpl::ResetOverrideEncoding() {
2334 canonical_encoding_
.clear();
2335 Send(new ViewMsg_ResetPageEncodingToDefault(GetRoutingID()));
2338 RendererPreferences
* WebContentsImpl::GetMutableRendererPrefs() {
2339 return &renderer_preferences_
;
2342 void WebContentsImpl::Close() {
2343 Close(GetRenderViewHost());
2346 void WebContentsImpl::DragSourceEndedAt(int client_x
, int client_y
,
2347 int screen_x
, int screen_y
, blink::WebDragOperation operation
) {
2348 if (browser_plugin_embedder_
.get())
2349 browser_plugin_embedder_
->DragSourceEndedAt(client_x
, client_y
,
2350 screen_x
, screen_y
, operation
);
2351 if (GetRenderViewHost())
2352 GetRenderViewHost()->DragSourceEndedAt(client_x
, client_y
, screen_x
,
2353 screen_y
, operation
);
2356 void WebContentsImpl::DidGetResourceResponseStart(
2357 const ResourceRequestDetails
& details
) {
2358 controller_
.ssl_manager()->DidStartResourceResponse(details
);
2360 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2361 DidGetResourceResponseStart(details
));
2363 // TODO(avi): Remove. http://crbug.com/170921
2364 NotificationService::current()->Notify(
2365 NOTIFICATION_RESOURCE_RESPONSE_STARTED
,
2366 Source
<WebContents
>(this),
2367 Details
<const ResourceRequestDetails
>(&details
));
2370 void WebContentsImpl::DidGetRedirectForResourceRequest(
2371 RenderFrameHost
* render_frame_host
,
2372 const ResourceRedirectDetails
& details
) {
2373 controller_
.ssl_manager()->DidReceiveResourceRedirect(details
);
2376 WebContentsObserver
,
2378 DidGetRedirectForResourceRequest(render_frame_host
, details
));
2380 // TODO(avi): Remove. http://crbug.com/170921
2381 NotificationService::current()->Notify(
2382 NOTIFICATION_RESOURCE_RECEIVED_REDIRECT
,
2383 Source
<WebContents
>(this),
2384 Details
<const ResourceRedirectDetails
>(&details
));
2387 void WebContentsImpl::NotifyWebContentsFocused() {
2388 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, OnWebContentsFocused());
2391 void WebContentsImpl::SystemDragEnded() {
2392 if (GetRenderViewHost())
2393 GetRenderViewHost()->DragSourceSystemDragEnded();
2394 if (browser_plugin_embedder_
.get())
2395 browser_plugin_embedder_
->SystemDragEnded();
2398 void WebContentsImpl::UserGestureDone() {
2402 void WebContentsImpl::SetClosedByUserGesture(bool value
) {
2403 closed_by_user_gesture_
= value
;
2406 bool WebContentsImpl::GetClosedByUserGesture() const {
2407 return closed_by_user_gesture_
;
2410 void WebContentsImpl::ViewSource() {
2414 NavigationEntry
* entry
= GetController().GetLastCommittedEntry();
2418 delegate_
->ViewSourceForTab(this, entry
->GetURL());
2421 void WebContentsImpl::ViewFrameSource(const GURL
& url
,
2422 const PageState
& page_state
) {
2426 delegate_
->ViewSourceForFrame(this, url
, page_state
);
2429 int WebContentsImpl::GetMinimumZoomPercent() const {
2430 return minimum_zoom_percent_
;
2433 int WebContentsImpl::GetMaximumZoomPercent() const {
2434 return maximum_zoom_percent_
;
2437 void WebContentsImpl::ResetPageScale() {
2438 Send(new ViewMsg_ResetPageScale(GetRoutingID()));
2441 gfx::Size
WebContentsImpl::GetPreferredSize() const {
2442 return capturer_count_
== 0 ? preferred_size_
: preferred_size_for_capture_
;
2445 bool WebContentsImpl::GotResponseToLockMouseRequest(bool allowed
) {
2446 if (GetBrowserPluginGuest())
2447 return GetBrowserPluginGuest()->LockMouse(allowed
);
2449 return GetRenderViewHost()
2450 ? GetRenderViewHost()->GotResponseToLockMouseRequest(allowed
)
2454 bool WebContentsImpl::HasOpener() const {
2455 return opener_
!= NULL
;
2458 WebContents
* WebContentsImpl::GetOpener() const {
2459 return static_cast<WebContents
*>(opener_
);
2462 void WebContentsImpl::DidChooseColorInColorChooser(SkColor color
) {
2463 if (!color_chooser_info_
.get())
2465 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2466 color_chooser_info_
->render_process_id
,
2467 color_chooser_info_
->render_frame_id
);
2471 rfh
->Send(new FrameMsg_DidChooseColorResponse(
2472 rfh
->GetRoutingID(), color_chooser_info_
->identifier
, color
));
2475 void WebContentsImpl::DidEndColorChooser() {
2476 if (!color_chooser_info_
.get())
2478 RenderFrameHost
* rfh
= RenderFrameHost::FromID(
2479 color_chooser_info_
->render_process_id
,
2480 color_chooser_info_
->render_frame_id
);
2484 rfh
->Send(new FrameMsg_DidEndColorChooser(
2485 rfh
->GetRoutingID(), color_chooser_info_
->identifier
));
2486 color_chooser_info_
.reset();
2489 int WebContentsImpl::DownloadImage(const GURL
& url
,
2491 uint32_t max_bitmap_size
,
2493 const ImageDownloadCallback
& callback
) {
2494 int id
= StartDownload(GetMainFrame(), url
, is_favicon
, max_bitmap_size
,
2496 image_download_map_
[id
] = callback
;
2500 bool WebContentsImpl::IsSubframe() const {
2501 return is_subframe_
;
2504 void WebContentsImpl::Find(int request_id
,
2505 const base::string16
& search_text
,
2506 const blink::WebFindOptions
& options
) {
2507 // See if a top level browser plugin handles the find request first.
2508 if (browser_plugin_embedder_
) {
2509 BrowserPluginGuest
* guest
= browser_plugin_embedder_
->GetFullPageGuest();
2510 if (guest
&& guest
->Find(request_id
, search_text
, options
))
2513 Send(new ViewMsg_Find(GetRoutingID(), request_id
, search_text
, options
));
2516 void WebContentsImpl::StopFinding(StopFindAction action
) {
2517 // See if a top level browser plugin handles the stop finding request first.
2518 if (browser_plugin_embedder_
) {
2519 BrowserPluginGuest
* guest
= browser_plugin_embedder_
->GetFullPageGuest();
2520 if (guest
&& guest
->StopFinding(action
))
2523 Send(new ViewMsg_StopFinding(GetRoutingID(), action
));
2526 void WebContentsImpl::InsertCSS(const std::string
& css
) {
2527 GetMainFrame()->Send(new FrameMsg_CSSInsertRequest(
2528 GetMainFrame()->GetRoutingID(), css
));
2531 bool WebContentsImpl::WasRecentlyAudible() {
2532 return audio_state_provider_
->WasRecentlyAudible();
2535 void WebContentsImpl::GetManifest(const GetManifestCallback
& callback
) {
2536 manifest_manager_host_
->GetManifest(GetMainFrame(), callback
);
2539 void WebContentsImpl::ExitFullscreen() {
2540 // Clean up related state and initiate the fullscreen exit.
2541 GetRenderViewHost()->RejectMouseLockOrUnlockIfNecessary();
2542 ExitFullscreenMode();
2545 void WebContentsImpl::ResumeLoadingCreatedWebContents() {
2546 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
2547 // TODO(brettw): It seems bogus to reach into here and initialize the host.
2548 GetRenderViewHost()->Init();
2549 GetMainFrame()->Init();
2552 bool WebContentsImpl::FocusLocationBarByDefault() {
2553 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2554 if (entry
&& entry
->GetURL() == GURL(url::kAboutBlankURL
))
2556 return delegate_
&& delegate_
->ShouldFocusLocationBarByDefault(this);
2559 void WebContentsImpl::SetFocusToLocationBar(bool select_all
) {
2561 delegate_
->SetFocusToLocationBar(select_all
);
2564 void WebContentsImpl::DidStartProvisionalLoad(
2565 RenderFrameHostImpl
* render_frame_host
,
2566 const GURL
& validated_url
,
2568 bool is_iframe_srcdoc
) {
2569 // Notify observers about the start of the provisional load.
2571 WebContentsObserver
,
2573 DidStartProvisionalLoadForFrame(
2574 render_frame_host
, validated_url
, is_error_page
, is_iframe_srcdoc
));
2576 // Notify accessibility if this is a reload.
2577 NavigationEntry
* entry
= controller_
.GetVisibleEntry();
2578 if (entry
&& ui::PageTransitionCoreTypeIs(
2579 entry
->GetTransitionType(), ui::PAGE_TRANSITION_RELOAD
)) {
2580 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2581 BrowserAccessibilityManager
* manager
=
2582 ftn
->current_frame_host()->browser_accessibility_manager();
2584 manager
->UserIsReloading();
2588 void WebContentsImpl::DidStartNavigationTransition(
2589 RenderFrameHostImpl
* render_frame_host
) {
2590 #if defined(OS_ANDROID)
2591 int render_frame_id
= render_frame_host
->GetRoutingID();
2592 GetWebContentsAndroid()->DidStartNavigationTransitionForFrame(
2597 void WebContentsImpl::DidFailProvisionalLoadWithError(
2598 RenderFrameHostImpl
* render_frame_host
,
2599 const FrameHostMsg_DidFailProvisionalLoadWithError_Params
& params
) {
2600 GURL
validated_url(params
.url
);
2601 FOR_EACH_OBSERVER(WebContentsObserver
,
2603 DidFailProvisionalLoad(render_frame_host
,
2606 params
.error_description
));
2608 FrameTreeNode
* ftn
= render_frame_host
->frame_tree_node();
2609 BrowserAccessibilityManager
* manager
=
2610 ftn
->current_frame_host()->browser_accessibility_manager();
2612 manager
->NavigationFailed();
2615 void WebContentsImpl::DidFailLoadWithError(
2616 RenderFrameHostImpl
* render_frame_host
,
2619 const base::string16
& error_description
) {
2621 WebContentsObserver
,
2623 DidFailLoad(render_frame_host
, url
, error_code
, error_description
));
2626 void WebContentsImpl::NotifyChangedNavigationState(
2627 InvalidateTypes changed_flags
) {
2628 NotifyNavigationStateChanged(changed_flags
);
2631 void WebContentsImpl::AboutToNavigateRenderFrame(
2632 RenderFrameHostImpl
* old_host
,
2633 RenderFrameHostImpl
* new_host
) {
2634 // Notify observers that we will navigate in this RenderFrame.
2636 WebContentsObserver
,
2638 AboutToNavigateRenderFrame(old_host
, new_host
));
2641 void WebContentsImpl::DidStartNavigationToPendingEntry(
2643 NavigationController::ReloadType reload_type
) {
2644 // Notify observers about navigation.
2646 WebContentsObserver
,
2648 DidStartNavigationToPendingEntry(url
, reload_type
));
2651 void WebContentsImpl::RequestOpenURL(RenderFrameHostImpl
* render_frame_host
,
2652 const OpenURLParams
& params
) {
2653 // OpenURL can blow away the source RFH. Use the process/frame routing ID as a
2654 // weak pointer of sorts.
2655 const int32_t process_id
= render_frame_host
->GetProcess()->GetID();
2656 const int32_t frame_id
= render_frame_host
->GetRoutingID();
2658 WebContents
* new_contents
= OpenURL(params
);
2660 if (new_contents
&& RenderFrameHost::FromID(process_id
, frame_id
)) {
2661 // Notify observers.
2662 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2663 DidOpenRequestedURL(new_contents
,
2668 params
.transition
));
2672 bool WebContentsImpl::ShouldPreserveAbortedURLs() {
2675 return delegate_
->ShouldPreserveAbortedURLs(this);
2678 void WebContentsImpl::DidCommitProvisionalLoad(
2679 RenderFrameHostImpl
* render_frame_host
,
2681 ui::PageTransition transition_type
) {
2682 // Notify observers about the commit of the provisional load.
2683 FOR_EACH_OBSERVER(WebContentsObserver
,
2685 DidCommitProvisionalLoadForFrame(
2686 render_frame_host
, url
, transition_type
));
2688 BrowserAccessibilityManager
* manager
=
2689 render_frame_host
->browser_accessibility_manager();
2691 manager
->NavigationSucceeded();
2694 void WebContentsImpl::DidNavigateMainFramePreCommit(
2695 bool navigation_is_within_page
) {
2696 // Ensure fullscreen mode is exited before committing the navigation to a
2697 // different page. The next page will not start out assuming it is in
2699 if (navigation_is_within_page
) {
2700 // No page change? Then, the renderer and browser can remain in fullscreen.
2703 if (IsFullscreenForCurrentTab())
2705 DCHECK(!IsFullscreenForCurrentTab());
2708 void WebContentsImpl::DidNavigateMainFramePostCommit(
2709 RenderFrameHostImpl
* render_frame_host
,
2710 const LoadCommittedDetails
& details
,
2711 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2712 if (details
.is_navigation_to_different_page()) {
2713 // Clear the status bubble. This is a workaround for a bug where WebKit
2714 // doesn't let us know that the cursor left an element during a
2715 // transition (this is also why the mouse cursor remains as a hand after
2716 // clicking on a link); see bugs 1184641 and 980803. We don't want to
2717 // clear the bubble when a user navigates to a named anchor in the same
2719 UpdateTargetURL(render_frame_host
->GetRenderViewHost(), GURL());
2721 RenderWidgetHostViewBase
* rwhvb
=
2722 static_cast<RenderWidgetHostViewBase
*>(GetRenderWidgetHostView());
2724 rwhvb
->OnDidNavigateMainFrameToNewPage();
2726 // Reset theme color on navigation to new page.
2727 theme_color_
= SK_ColorTRANSPARENT
;
2730 if (!details
.is_in_page
) {
2731 // Once the main frame is navigated, we're no longer considered to have
2732 // displayed insecure content.
2733 displayed_insecure_content_
= false;
2734 SSLManager::NotifySSLInternalStateChanged(
2735 GetController().GetBrowserContext());
2738 // Notify observers about navigation.
2739 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2740 DidNavigateMainFrame(details
, params
));
2743 delegate_
->DidNavigateMainFramePostCommit(this);
2744 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
2747 void WebContentsImpl::DidNavigateAnyFramePostCommit(
2748 RenderFrameHostImpl
* render_frame_host
,
2749 const LoadCommittedDetails
& details
,
2750 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
2751 // Now that something has committed, we don't need to track whether the
2752 // initial page has been accessed.
2753 has_accessed_initial_document_
= false;
2755 // If we navigate off the page, close all JavaScript dialogs.
2756 if (dialog_manager_
&& !details
.is_in_page
)
2757 dialog_manager_
->CancelActiveAndPendingDialogs(this);
2759 // Notify observers about navigation.
2760 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2761 DidNavigateAnyFrame(render_frame_host
, details
, params
));
2764 void WebContentsImpl::SetMainFrameMimeType(const std::string
& mime_type
) {
2765 contents_mime_type_
= mime_type
;
2768 bool WebContentsImpl::CanOverscrollContent() const {
2769 // Disable overscroll when touch emulation is on. See crbug.com/369938.
2770 if (force_disable_overscroll_content_
)
2774 return delegate_
->CanOverscrollContent();
2779 void WebContentsImpl::OnThemeColorChanged(SkColor theme_color
) {
2780 // Update the theme color. This is to be published to observers on visually
2782 theme_color_
= theme_color
;
2785 void WebContentsImpl::OnDidLoadResourceFromMemoryCache(
2787 const std::string
& security_info
,
2788 const std::string
& http_method
,
2789 const std::string
& mime_type
,
2790 ResourceType resource_type
) {
2792 // Send out a notification that we loaded a resource from our memory cache.
2794 net::CertStatus cert_status
= 0;
2795 int security_bits
= -1;
2796 int connection_status
= 0;
2797 SignedCertificateTimestampIDStatusList signed_certificate_timestamp_ids
;
2798 DeserializeSecurityInfo(security_info
, &cert_id
, &cert_status
,
2799 &security_bits
, &connection_status
,
2800 &signed_certificate_timestamp_ids
);
2801 // TODO(alcutter,eranm): Pass signed_certificate_timestamp_ids into details
2802 LoadFromMemoryCacheDetails
details(
2803 url
, GetRenderProcessHost()->GetID(), cert_id
, cert_status
, http_method
,
2804 mime_type
, resource_type
);
2806 controller_
.ssl_manager()->DidLoadFromMemoryCache(details
);
2808 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2809 DidLoadResourceFromMemoryCache(details
));
2811 if (url
.is_valid() && url
.SchemeIsHTTPOrHTTPS()) {
2812 scoped_refptr
<net::URLRequestContextGetter
> request_context(
2813 resource_type
== RESOURCE_TYPE_MEDIA
?
2814 GetBrowserContext()->GetMediaRequestContextForRenderProcess(
2815 GetRenderProcessHost()->GetID()) :
2816 GetBrowserContext()->GetRequestContextForRenderProcess(
2817 GetRenderProcessHost()->GetID()));
2818 BrowserThread::PostTask(
2821 base::Bind(&NotifyCacheOnIO
, request_context
, url
, http_method
));
2825 void WebContentsImpl::OnDidDisplayInsecureContent() {
2826 RecordAction(base::UserMetricsAction("SSL.DisplayedInsecureContent"));
2827 displayed_insecure_content_
= true;
2828 SSLManager::NotifySSLInternalStateChanged(
2829 GetController().GetBrowserContext());
2832 void WebContentsImpl::OnDidRunInsecureContent(
2833 const std::string
& security_origin
, const GURL
& target_url
) {
2834 LOG(WARNING
) << security_origin
<< " ran insecure content from "
2835 << target_url
.possibly_invalid_spec();
2836 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
2837 if (EndsWith(security_origin
, kDotGoogleDotCom
, false))
2838 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
2839 controller_
.ssl_manager()->DidRunInsecureContent(security_origin
);
2840 displayed_insecure_content_
= true;
2841 SSLManager::NotifySSLInternalStateChanged(
2842 GetController().GetBrowserContext());
2845 void WebContentsImpl::OnDocumentLoadedInFrame() {
2846 if (!HasValidFrameSource())
2849 RenderFrameHostImpl
* rfh
=
2850 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2852 WebContentsObserver
, observers_
, DocumentLoadedInFrame(rfh
));
2855 void WebContentsImpl::OnDidFinishLoad(const GURL
& url
) {
2856 if (!HasValidFrameSource())
2859 GURL
validated_url(url
);
2860 RenderProcessHost
* render_process_host
=
2861 render_frame_message_source_
->GetProcess();
2862 render_process_host
->FilterURL(false, &validated_url
);
2864 RenderFrameHostImpl
* rfh
=
2865 static_cast<RenderFrameHostImpl
*>(render_frame_message_source_
);
2867 WebContentsObserver
, observers_
, DidFinishLoad(rfh
, validated_url
));
2870 void WebContentsImpl::OnGoToEntryAtOffset(int offset
) {
2871 if (!delegate_
|| delegate_
->OnGoToEntryOffset(offset
))
2872 controller_
.GoToOffset(offset
);
2875 void WebContentsImpl::OnUpdateZoomLimits(int minimum_percent
,
2876 int maximum_percent
) {
2877 minimum_zoom_percent_
= minimum_percent
;
2878 maximum_zoom_percent_
= maximum_percent
;
2881 void WebContentsImpl::OnEnumerateDirectory(int request_id
,
2882 const base::FilePath
& path
) {
2886 ChildProcessSecurityPolicyImpl
* policy
=
2887 ChildProcessSecurityPolicyImpl::GetInstance();
2888 if (policy
->CanReadFile(GetRenderProcessHost()->GetID(), path
))
2889 delegate_
->EnumerateDirectory(this, request_id
, path
);
2892 void WebContentsImpl::OnRegisterProtocolHandler(const std::string
& protocol
,
2894 const base::string16
& title
,
2895 bool user_gesture
) {
2899 ChildProcessSecurityPolicyImpl
* policy
=
2900 ChildProcessSecurityPolicyImpl::GetInstance();
2901 if (policy
->IsPseudoScheme(protocol
))
2904 delegate_
->RegisterProtocolHandler(this, protocol
, url
, user_gesture
);
2907 void WebContentsImpl::OnUnregisterProtocolHandler(const std::string
& protocol
,
2909 bool user_gesture
) {
2913 ChildProcessSecurityPolicyImpl
* policy
=
2914 ChildProcessSecurityPolicyImpl::GetInstance();
2915 if (policy
->IsPseudoScheme(protocol
))
2918 delegate_
->UnregisterProtocolHandler(this, protocol
, url
, user_gesture
);
2921 void WebContentsImpl::OnFindReply(int request_id
,
2922 int number_of_matches
,
2923 const gfx::Rect
& selection_rect
,
2924 int active_match_ordinal
,
2925 bool final_update
) {
2927 delegate_
->FindReply(this, request_id
, number_of_matches
, selection_rect
,
2928 active_match_ordinal
, final_update
);
2932 #if defined(OS_ANDROID)
2933 void WebContentsImpl::OnFindMatchRectsReply(
2935 const std::vector
<gfx::RectF
>& rects
,
2936 const gfx::RectF
& active_rect
) {
2938 delegate_
->FindMatchRectsReply(this, version
, rects
, active_rect
);
2941 void WebContentsImpl::OnOpenDateTimeDialog(
2942 const ViewHostMsg_DateTimeDialogValue_Params
& value
) {
2943 date_time_chooser_
->ShowDialog(GetTopLevelNativeWindow(),
2944 GetRenderViewHost(),
2954 void WebContentsImpl::OnDomOperationResponse(const std::string
& json_string
,
2955 int automation_id
) {
2956 DomOperationNotificationDetails
details(json_string
, automation_id
);
2957 NotificationService::current()->Notify(
2958 NOTIFICATION_DOM_OPERATION_RESPONSE
,
2959 Source
<WebContents
>(this),
2960 Details
<DomOperationNotificationDetails
>(&details
));
2963 void WebContentsImpl::OnAppCacheAccessed(const GURL
& manifest_url
,
2964 bool blocked_by_policy
) {
2965 // Notify observers about navigation.
2966 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
2967 AppCacheAccessed(manifest_url
, blocked_by_policy
));
2970 void WebContentsImpl::OnOpenColorChooser(
2971 int color_chooser_id
,
2973 const std::vector
<ColorSuggestion
>& suggestions
) {
2974 if (!HasValidFrameSource())
2977 ColorChooser
* new_color_chooser
= delegate_
?
2978 delegate_
->OpenColorChooser(this, color
, suggestions
) :
2980 if (!new_color_chooser
)
2982 if (color_chooser_info_
.get())
2983 color_chooser_info_
->chooser
->End();
2985 color_chooser_info_
.reset(new ColorChooserInfo(
2986 render_frame_message_source_
->GetProcess()->GetID(),
2987 render_frame_message_source_
->GetRoutingID(),
2992 void WebContentsImpl::OnEndColorChooser(int color_chooser_id
) {
2993 if (color_chooser_info_
&&
2994 color_chooser_id
== color_chooser_info_
->identifier
)
2995 color_chooser_info_
->chooser
->End();
2998 void WebContentsImpl::OnSetSelectedColorInColorChooser(int color_chooser_id
,
3000 if (color_chooser_info_
&&
3001 color_chooser_id
== color_chooser_info_
->identifier
)
3002 color_chooser_info_
->chooser
->SetSelectedColor(color
);
3005 // This exists for render views that don't have a WebUI, but do have WebUI
3006 // bindings enabled.
3007 void WebContentsImpl::OnWebUISend(const GURL
& source_url
,
3008 const std::string
& name
,
3009 const base::ListValue
& args
) {
3011 delegate_
->WebUISend(this, source_url
, name
, args
);
3014 #if defined(ENABLE_PLUGINS)
3015 void WebContentsImpl::OnPepperPluginHung(int plugin_child_id
,
3016 const base::FilePath
& path
,
3018 UMA_HISTOGRAM_COUNTS("Pepper.PluginHung", 1);
3020 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3021 PluginHungStatusChanged(plugin_child_id
, path
, is_hung
));
3024 void WebContentsImpl::OnPluginCrashed(const base::FilePath
& plugin_path
,
3025 base::ProcessId plugin_pid
) {
3026 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3027 PluginCrashed(plugin_path
, plugin_pid
));
3030 void WebContentsImpl::OnRequestPpapiBrokerPermission(
3033 const base::FilePath
& plugin_path
) {
3035 OnPpapiBrokerPermissionResult(routing_id
, false);
3039 if (!delegate_
->RequestPpapiBrokerPermission(
3040 this, url
, plugin_path
,
3041 base::Bind(&WebContentsImpl::OnPpapiBrokerPermissionResult
,
3042 base::Unretained(this), routing_id
))) {
3044 OnPpapiBrokerPermissionResult(routing_id
, false);
3048 void WebContentsImpl::OnPpapiBrokerPermissionResult(int routing_id
,
3050 Send(new ViewMsg_PpapiBrokerPermissionResult(routing_id
, result
));
3053 void WebContentsImpl::OnBrowserPluginMessage(RenderFrameHost
* render_frame_host
,
3054 const IPC::Message
& message
) {
3055 CHECK(!browser_plugin_embedder_
.get());
3056 CreateBrowserPluginEmbedderIfNecessary();
3057 browser_plugin_embedder_
->OnMessageReceived(message
, render_frame_host
);
3059 #endif // defined(ENABLE_PLUGINS)
3061 void WebContentsImpl::OnDidDownloadImage(
3063 int http_status_code
,
3064 const GURL
& image_url
,
3065 const std::vector
<SkBitmap
>& bitmaps
,
3066 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
3067 if (bitmaps
.size() != original_bitmap_sizes
.size())
3070 ImageDownloadMap::iterator iter
= image_download_map_
.find(id
);
3071 if (iter
== image_download_map_
.end()) {
3072 // Currently WebContents notifies us of ANY downloads so that it is
3073 // possible to get here.
3076 if (!iter
->second
.is_null()) {
3078 id
, http_status_code
, image_url
, bitmaps
, original_bitmap_sizes
);
3080 image_download_map_
.erase(id
);
3083 void WebContentsImpl::OnUpdateFaviconURL(
3084 const std::vector
<FaviconURL
>& candidates
) {
3085 // We get updated favicon URLs after the page stops loading. If a cross-site
3086 // navigation occurs while a page is still loading, the initial page
3087 // may stop loading and send us updated favicon URLs after the navigation
3088 // for the new page has committed.
3089 RenderViewHostImpl
* rvhi
=
3090 static_cast<RenderViewHostImpl
*>(render_view_message_source_
);
3091 if (!rvhi
->is_active())
3094 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3095 DidUpdateFaviconURL(candidates
));
3098 void WebContentsImpl::CreateAudioPowerSaveBlocker() {
3099 DCHECK(!audio_power_save_blocker_
);
3100 audio_power_save_blocker_
= PowerSaveBlocker::Create(
3101 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
,
3102 PowerSaveBlocker::kReasonAudioPlayback
, "Playing audio");
3105 void WebContentsImpl::CreateVideoPowerSaveBlocker() {
3106 DCHECK(!video_power_save_blocker_
);
3107 DCHECK(!active_video_players_
.empty());
3108 video_power_save_blocker_
= PowerSaveBlocker::Create(
3109 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep
,
3110 PowerSaveBlocker::kReasonVideoPlayback
, "Playing video");
3111 #if defined(OS_ANDROID)
3112 static_cast<PowerSaveBlockerImpl
*>(video_power_save_blocker_
.get())
3113 ->InitDisplaySleepBlocker(this);
3117 void WebContentsImpl::MaybeReleasePowerSaveBlockers() {
3118 // If there are no more audio players and we don't have audio stream
3119 // monitoring, release the audio power save blocker here instead of during
3120 // NotifyNavigationStateChanged().
3121 if (active_audio_players_
.empty() &&
3122 !audio_state_provider_
->IsAudioStateAvailable()) {
3123 audio_power_save_blocker_
.reset();
3126 // If there are no more video players, clear the video power save blocker.
3127 if (active_video_players_
.empty())
3128 video_power_save_blocker_
.reset();
3131 void WebContentsImpl::OnMediaPlayingNotification(int64 player_cookie
,
3135 // Ignore the videos playing remotely and don't hold the wake lock for the
3137 if (is_remote
) return;
3140 AddMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3142 // If we don't have audio stream monitoring, allocate the audio power save
3143 // blocker here instead of during NotifyNavigationStateChanged().
3144 if (!audio_power_save_blocker_
&&
3145 !audio_state_provider_
->IsAudioStateAvailable()) {
3146 CreateAudioPowerSaveBlocker();
3151 AddMediaPlayerEntry(player_cookie
, &active_video_players_
);
3153 // If we're not hidden and have just created a player, create a blocker.
3154 if (!video_power_save_blocker_
&& !IsHidden())
3155 CreateVideoPowerSaveBlocker();
3158 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, MediaStartedPlaying());
3161 void WebContentsImpl::OnMediaPausedNotification(int64 player_cookie
) {
3162 RemoveMediaPlayerEntry(player_cookie
, &active_audio_players_
);
3163 RemoveMediaPlayerEntry(player_cookie
, &active_video_players_
);
3164 MaybeReleasePowerSaveBlockers();
3166 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, MediaPaused());
3169 void WebContentsImpl::OnFirstVisuallyNonEmptyPaint() {
3170 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3171 DidFirstVisuallyNonEmptyPaint());
3173 if (theme_color_
!= last_sent_theme_color_
) {
3174 // Theme color should have updated by now if there was one.
3175 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3176 DidChangeThemeColor(theme_color_
));
3177 last_sent_theme_color_
= theme_color_
;
3181 void WebContentsImpl::DidChangeVisibleSSLState() {
3183 delegate_
->VisibleSSLStateChanged(this);
3186 void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
3187 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3188 BeforeFormRepostWarningShow());
3191 void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
3194 delegate_
->ShowRepostFormWarningDialog(this);
3197 bool WebContentsImpl::HasAccessedInitialDocument() {
3198 return has_accessed_initial_document_
;
3201 // Notifies the RenderWidgetHost instance about the fact that the page is
3202 // loading, or done loading.
3203 void WebContentsImpl::SetIsLoading(bool is_loading
,
3204 bool to_different_document
,
3205 LoadNotificationDetails
* details
) {
3206 if (is_loading
== is_loading_
)
3210 load_state_
= net::LoadStateWithParam(net::LOAD_STATE_IDLE
,
3212 load_state_host_
.clear();
3214 upload_position_
= 0;
3217 GetRenderManager()->SetIsLoading(is_loading
);
3219 is_loading_
= is_loading
;
3220 waiting_for_response_
= is_loading
;
3221 is_load_to_different_document_
= to_different_document
;
3224 delegate_
->LoadingStateChanged(this, to_different_document
);
3225 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD
);
3227 std::string url
= (details
? details
->url
.possibly_invalid_spec() : "NULL");
3229 TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "WebContentsImpl Loading",
3231 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidStartLoading());
3233 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
3235 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidStopLoading());
3238 // TODO(avi): Remove. http://crbug.com/170921
3239 int type
= is_loading
? NOTIFICATION_LOAD_START
: NOTIFICATION_LOAD_STOP
;
3240 NotificationDetails det
= NotificationService::NoDetails();
3242 det
= Details
<LoadNotificationDetails
>(details
);
3243 NotificationService::current()->Notify(
3244 type
, Source
<NavigationController
>(&controller_
), det
);
3247 void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point
& extent
) {
3248 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3252 focused_frame
->Send(new InputMsg_MoveRangeSelectionExtent(
3253 focused_frame
->GetRoutingID(), extent
));
3256 void WebContentsImpl::SelectRange(const gfx::Point
& base
,
3257 const gfx::Point
& extent
) {
3258 RenderFrameHost
* focused_frame
= GetFocusedFrame();
3262 focused_frame
->Send(
3263 new InputMsg_SelectRange(focused_frame
->GetRoutingID(), base
, extent
));
3266 void WebContentsImpl::UpdateMaxPageIDIfNecessary(RenderViewHost
* rvh
) {
3267 // If we are creating a RVH for a restored controller, then we need to make
3268 // sure the RenderView starts with a next_page_id_ larger than the number
3269 // of restored entries. This must be called before the RenderView starts
3270 // navigating (to avoid a race between the browser updating max_page_id and
3271 // the renderer updating next_page_id_). Because of this, we only call this
3272 // from CreateRenderView and allow that to notify the RenderView for us.
3273 int max_restored_page_id
= controller_
.GetMaxRestoredPageID();
3274 if (max_restored_page_id
>
3275 GetMaxPageIDForSiteInstance(rvh
->GetSiteInstance()))
3276 UpdateMaxPageIDForSiteInstance(rvh
->GetSiteInstance(),
3277 max_restored_page_id
);
3280 bool WebContentsImpl::UpdateTitleForEntry(NavigationEntryImpl
* entry
,
3281 const base::string16
& title
) {
3282 // For file URLs without a title, use the pathname instead. In the case of a
3283 // synthesized title, we don't want the update to count toward the "one set
3284 // per page of the title to history."
3285 base::string16 final_title
;
3287 if (entry
&& entry
->GetURL().SchemeIsFile() && title
.empty()) {
3288 final_title
= base::UTF8ToUTF16(entry
->GetURL().ExtractFileName());
3289 explicit_set
= false; // Don't count synthetic titles toward the set limit.
3291 base::TrimWhitespace(title
, base::TRIM_ALL
, &final_title
);
3292 explicit_set
= true;
3295 // If a page is created via window.open and never navigated,
3296 // there will be no navigation entry. In this situation,
3297 // |page_title_when_no_navigation_entry_| will be used for page title.
3299 if (final_title
== entry
->GetTitle())
3300 return false; // Nothing changed, don't bother.
3302 entry
->SetTitle(final_title
);
3304 if (page_title_when_no_navigation_entry_
== final_title
)
3305 return false; // Nothing changed, don't bother.
3307 page_title_when_no_navigation_entry_
= final_title
;
3310 // Lastly, set the title for the view.
3311 view_
->SetPageTitle(final_title
);
3313 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3314 TitleWasSet(entry
, explicit_set
));
3316 // TODO(avi): Remove. http://crbug.com/170921
3317 std::pair
<NavigationEntry
*, bool> details
=
3318 std::make_pair(entry
, explicit_set
);
3319 NotificationService::current()->Notify(
3320 NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED
,
3321 Source
<WebContents
>(this),
3322 Details
<std::pair
<NavigationEntry
*, bool> >(&details
));
3327 void WebContentsImpl::SendChangeLoadProgress() {
3328 loading_last_progress_update_
= base::TimeTicks::Now();
3330 delegate_
->LoadProgressChanged(this, frame_tree_
.load_progress());
3333 void WebContentsImpl::ResetLoadProgressState() {
3334 frame_tree_
.ResetLoadProgress();
3335 loading_weak_factory_
.InvalidateWeakPtrs();
3336 loading_last_progress_update_
= base::TimeTicks();
3339 void WebContentsImpl::NotifyViewSwapped(RenderViewHost
* old_host
,
3340 RenderViewHost
* new_host
) {
3341 // After sending out a swap notification, we need to send a disconnect
3342 // notification so that clients that pick up a pointer to |this| can NULL the
3343 // pointer. See Bug 1230284.
3344 notify_disconnection_
= true;
3345 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3346 RenderViewHostChanged(old_host
, new_host
));
3348 // TODO(avi): Remove. http://crbug.com/170921
3349 std::pair
<RenderViewHost
*, RenderViewHost
*> details
=
3350 std::make_pair(old_host
, new_host
);
3351 NotificationService::current()->Notify(
3352 NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
3353 Source
<WebContents
>(this),
3354 Details
<std::pair
<RenderViewHost
*, RenderViewHost
*> >(&details
));
3356 // Ensure that the associated embedder gets cleared after a RenderViewHost
3357 // gets swapped, so we don't reuse the same embedder next time a
3358 // RenderViewHost is attached to this WebContents.
3359 RemoveBrowserPluginEmbedder();
3362 void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost
* old_host
,
3363 RenderFrameHost
* new_host
) {
3364 FOR_EACH_OBSERVER(WebContentsObserver
,
3366 RenderFrameHostChanged(old_host
, new_host
));
3369 // TODO(avi): Remove this entire function because this notification is already
3370 // covered by two observer functions. http://crbug.com/170921
3371 void WebContentsImpl::NotifyDisconnected() {
3372 if (!notify_disconnection_
)
3375 notify_disconnection_
= false;
3376 NotificationService::current()->Notify(
3377 NOTIFICATION_WEB_CONTENTS_DISCONNECTED
,
3378 Source
<WebContents
>(this),
3379 NotificationService::NoDetails());
3382 void WebContentsImpl::NotifyNavigationEntryCommitted(
3383 const LoadCommittedDetails
& load_details
) {
3385 WebContentsObserver
, observers_
, NavigationEntryCommitted(load_details
));
3388 bool WebContentsImpl::OnMessageReceived(RenderFrameHost
* render_frame_host
,
3389 const IPC::Message
& message
) {
3390 return OnMessageReceived(NULL
, render_frame_host
, message
);
3393 const GURL
& WebContentsImpl::GetMainFrameLastCommittedURL() const {
3394 return GetLastCommittedURL();
3397 void WebContentsImpl::RenderFrameCreated(RenderFrameHost
* render_frame_host
) {
3398 // Note this is only for subframes, the notification for the main frame
3399 // happens in RenderViewCreated.
3400 FOR_EACH_OBSERVER(WebContentsObserver
,
3402 RenderFrameCreated(render_frame_host
));
3403 SetAccessibilityModeOnFrame(accessibility_mode_
, render_frame_host
);
3406 void WebContentsImpl::RenderFrameDeleted(RenderFrameHost
* render_frame_host
) {
3407 ClearPowerSaveBlockers(render_frame_host
);
3408 FOR_EACH_OBSERVER(WebContentsObserver
,
3410 RenderFrameDeleted(render_frame_host
));
3413 void WebContentsImpl::WorkerCrashed(RenderFrameHost
* render_frame_host
) {
3415 delegate_
->WorkerCrashed(this);
3418 void WebContentsImpl::ShowContextMenu(RenderFrameHost
* render_frame_host
,
3419 const ContextMenuParams
& params
) {
3420 ContextMenuParams
context_menu_params(params
);
3421 // Allow WebContentsDelegates to handle the context menu operation first.
3422 if (delegate_
&& delegate_
->HandleContextMenu(context_menu_params
))
3425 render_view_host_delegate_view_
->ShowContextMenu(render_frame_host
,
3426 context_menu_params
);
3429 void WebContentsImpl::RunJavaScriptMessage(
3430 RenderFrameHost
* render_frame_host
,
3431 const base::string16
& message
,
3432 const base::string16
& default_prompt
,
3433 const GURL
& frame_url
,
3434 JavaScriptMessageType javascript_message_type
,
3435 IPC::Message
* reply_msg
) {
3436 // Suppress JavaScript dialogs when requested. Also suppress messages when
3437 // showing an interstitial as it's shown over the previous page and we don't
3438 // want the hidden page's dialogs to interfere with the interstitial.
3439 bool suppress_this_message
=
3440 static_cast<RenderFrameHostImpl
*>(render_frame_host
)->is_swapped_out() ||
3441 ShowingInterstitialPage() || !delegate_
||
3442 delegate_
->ShouldSuppressDialogs(this) ||
3443 !delegate_
->GetJavaScriptDialogManager(this);
3445 if (!suppress_this_message
) {
3446 std::string accept_lang
= GetContentClient()->browser()->
3447 GetAcceptLangs(GetBrowserContext());
3448 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3449 dialog_manager_
->RunJavaScriptDialog(
3451 frame_url
.GetOrigin(),
3453 javascript_message_type
,
3456 base::Bind(&WebContentsImpl::OnDialogClosed
,
3457 base::Unretained(this),
3458 render_frame_host
->GetProcess()->GetID(),
3459 render_frame_host
->GetRoutingID(),
3462 &suppress_this_message
);
3465 if (suppress_this_message
) {
3466 // If we are suppressing messages, just reply as if the user immediately
3467 // pressed "Cancel", passing true to |dialog_was_suppressed|.
3468 OnDialogClosed(render_frame_host
->GetProcess()->GetID(),
3469 render_frame_host
->GetRoutingID(), reply_msg
,
3470 true, false, base::string16());
3473 // OnDialogClosed (two lines up) may have caused deletion of this object (see
3474 // http://crbug.com/288961 ). The only safe thing to do here is return.
3477 void WebContentsImpl::RunBeforeUnloadConfirm(
3478 RenderFrameHost
* render_frame_host
,
3479 const base::string16
& message
,
3481 IPC::Message
* reply_msg
) {
3482 RenderFrameHostImpl
* rfhi
=
3483 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
3485 delegate_
->WillRunBeforeUnloadConfirm();
3487 bool suppress_this_message
=
3488 rfhi
->rfh_state() != RenderFrameHostImpl::STATE_DEFAULT
|| !delegate_
||
3489 delegate_
->ShouldSuppressDialogs(this) ||
3490 !delegate_
->GetJavaScriptDialogManager(this);
3491 if (suppress_this_message
) {
3492 rfhi
->JavaScriptDialogClosed(reply_msg
, true, base::string16(), true);
3496 is_showing_before_unload_dialog_
= true;
3497 dialog_manager_
= delegate_
->GetJavaScriptDialogManager(this);
3498 dialog_manager_
->RunBeforeUnloadDialog(
3499 this, message
, is_reload
,
3500 base::Bind(&WebContentsImpl::OnDialogClosed
, base::Unretained(this),
3501 render_frame_host
->GetProcess()->GetID(),
3502 render_frame_host
->GetRoutingID(), reply_msg
,
3506 WebContents
* WebContentsImpl::GetAsWebContents() {
3510 bool WebContentsImpl::IsNeverVisible() {
3513 return delegate_
->IsNeverVisible(this);
3517 gfx::NativeViewAccessible
WebContentsImpl::GetParentNativeViewAccessible() {
3518 return accessible_parent_
;
3522 RenderViewHostDelegateView
* WebContentsImpl::GetDelegateView() {
3523 return render_view_host_delegate_view_
;
3526 RendererPreferences
WebContentsImpl::GetRendererPrefs(
3527 BrowserContext
* browser_context
) const {
3528 return renderer_preferences_
;
3531 gfx::Rect
WebContentsImpl::GetRootWindowResizerRect() const {
3533 return delegate_
->GetRootWindowResizerRect();
3537 void WebContentsImpl::RemoveBrowserPluginEmbedder() {
3538 if (browser_plugin_embedder_
)
3539 browser_plugin_embedder_
.reset();
3542 void WebContentsImpl::RenderViewCreated(RenderViewHost
* render_view_host
) {
3543 // Don't send notifications if we are just creating a swapped-out RVH for
3544 // the opener chain. These won't be used for view-source or WebUI, so it's
3545 // ok to return early.
3546 if (!static_cast<RenderViewHostImpl
*>(render_view_host
)->is_active())
3550 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
3552 NotificationService::current()->Notify(
3553 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
3554 Source
<WebContents
>(this),
3555 Details
<RenderViewHost
>(render_view_host
));
3557 // When we're creating views, we're still doing initial setup, so we always
3558 // use the pending Web UI rather than any possibly existing committed one.
3559 if (GetRenderManager()->pending_web_ui())
3560 GetRenderManager()->pending_web_ui()->RenderViewCreated(render_view_host
);
3562 NavigationEntry
* entry
= controller_
.GetPendingEntry();
3563 if (entry
&& entry
->IsViewSourceMode()) {
3564 // Put the renderer in view source mode.
3565 render_view_host
->Send(
3566 new ViewMsg_EnableViewSourceMode(render_view_host
->GetRoutingID()));
3569 view_
->RenderViewCreated(render_view_host
);
3572 WebContentsObserver
, observers_
, RenderViewCreated(render_view_host
));
3575 void WebContentsImpl::RenderViewReady(RenderViewHost
* rvh
) {
3576 if (rvh
!= GetRenderViewHost()) {
3577 // Don't notify the world, since this came from a renderer in the
3582 notify_disconnection_
= true;
3583 // TODO(avi): Remove. http://crbug.com/170921
3584 NotificationService::current()->Notify(
3585 NOTIFICATION_WEB_CONTENTS_CONNECTED
,
3586 Source
<WebContents
>(this),
3587 NotificationService::NoDetails());
3589 bool was_crashed
= IsCrashed();
3590 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING
, 0);
3592 // Restore the focus to the tab (otherwise the focus will be on the top
3594 if (was_crashed
&& !FocusLocationBarByDefault() &&
3595 (!delegate_
|| delegate_
->ShouldFocusPageAfterCrash())) {
3599 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewReady());
3602 void WebContentsImpl::RenderViewTerminated(RenderViewHost
* rvh
,
3603 base::TerminationStatus status
,
3605 if (rvh
!= GetRenderViewHost()) {
3606 // The pending page's RenderViewHost is gone.
3610 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
3611 // renderer may not have made a clean exit.
3612 if (IsFullscreenForCurrentTab())
3613 ExitFullscreenMode();
3615 // Cancel any visible dialogs so they are not left dangling over the sad tab.
3616 if (dialog_manager_
)
3617 dialog_manager_
->CancelActiveAndPendingDialogs(this);
3620 delegate_
->HideValidationMessage(this);
3622 SetIsLoading(false, true, nullptr);
3623 NotifyDisconnected();
3624 SetIsCrashed(status
, error_code
);
3626 // Reset the loading progress. TODO(avi): What does it mean to have a
3627 // "renderer crash" when there is more than one renderer process serving a
3628 // webpage? Once this function is called at a more granular frame level, we
3629 // probably will need to more granularly reset the state here.
3630 ResetLoadProgressState();
3632 FOR_EACH_OBSERVER(WebContentsObserver
,
3634 RenderProcessGone(GetCrashedStatus()));
3637 void WebContentsImpl::RenderViewDeleted(RenderViewHost
* rvh
) {
3638 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, RenderViewDeleted(rvh
));
3641 void WebContentsImpl::UpdateState(RenderViewHost
* rvh
,
3643 const PageState
& page_state
) {
3644 // Ensure that this state update comes from a RenderViewHost that belongs to
3645 // this WebContents.
3646 // TODO(nasko): This should go through RenderFrameHost.
3647 // TODO(creis): We can't update state for cross-process subframes until we
3648 // have FrameNavigationEntries. Once we do, this should be a DCHECK.
3649 if (rvh
->GetDelegate()->GetAsWebContents() != this)
3652 // We must be prepared to handle state updates for any page, these occur
3653 // when the user is scrolling and entering form data, as well as when we're
3654 // leaving a page, in which case our state may have already been moved to
3655 // the next page. The navigation controller will look up the appropriate
3656 // NavigationEntry and update it when it is notified via the delegate.
3658 int entry_index
= controller_
.GetEntryIndexWithPageID(
3659 rvh
->GetSiteInstance(), page_id
);
3660 if (entry_index
< 0)
3662 NavigationEntry
* entry
= controller_
.GetEntryAtIndex(entry_index
);
3664 if (page_state
== entry
->GetPageState())
3665 return; // Nothing to update.
3666 entry
->SetPageState(page_state
);
3667 controller_
.NotifyEntryChanged(entry
, entry_index
);
3670 void WebContentsImpl::UpdateTargetURL(RenderViewHost
* render_view_host
,
3672 if (fullscreen_widget_routing_id_
!= MSG_ROUTING_NONE
) {
3673 // If we're fullscreen only update the url if it's from the fullscreen
3675 RenderWidgetHostView
* fs
= GetFullscreenRenderWidgetHostView();
3676 if (fs
&& fs
->GetRenderWidgetHost() != render_view_host
)
3680 delegate_
->UpdateTargetURL(this, url
);
3683 void WebContentsImpl::Close(RenderViewHost
* rvh
) {
3684 #if defined(OS_MACOSX)
3685 // The UI may be in an event-tracking loop, such as between the
3686 // mouse-down and mouse-up in text selection or a button click.
3687 // Defer the close until after tracking is complete, so that we
3688 // don't free objects out from under the UI.
3689 // TODO(shess): This could get more fine-grained. For instance,
3690 // closing a tab in another window while selecting text in the
3691 // current window's Omnibox should be just fine.
3692 if (view_
->IsEventTracking()) {
3693 view_
->CloseTabAfterEventTracking();
3698 // Ignore this if it comes from a RenderViewHost that we aren't showing.
3699 if (delegate_
&& rvh
== GetRenderViewHost())
3700 delegate_
->CloseContents(this);
3703 void WebContentsImpl::SwappedOut(RenderFrameHost
* rfh
) {
3704 if (delegate_
&& rfh
->GetRenderViewHost() == GetRenderViewHost())
3705 delegate_
->SwappedOut(this);
3708 void WebContentsImpl::DidDeferAfterResponseStarted(
3709 const TransitionLayerData
& transition_data
) {
3710 #if defined(OS_ANDROID)
3711 GetWebContentsAndroid()->DidDeferAfterResponseStarted(transition_data
);
3715 bool WebContentsImpl::WillHandleDeferAfterResponseStarted() {
3716 #if defined(OS_ANDROID)
3717 return GetWebContentsAndroid()->WillHandleDeferAfterResponseStarted();
3723 void WebContentsImpl::RequestMove(const gfx::Rect
& new_bounds
) {
3724 if (delegate_
&& delegate_
->IsPopupOrPanel(this))
3725 delegate_
->MoveContents(this, new_bounds
);
3728 void WebContentsImpl::DidStartLoading(FrameTreeNode
* frame_tree_node
,
3729 bool to_different_document
) {
3730 SetIsLoading(true, to_different_document
, nullptr);
3732 // Notify accessibility that the user is navigating away from the
3733 // current document.
3735 // TODO(dmazzoni): do this using a WebContentsObserver.
3736 BrowserAccessibilityManager
* manager
=
3737 frame_tree_node
->current_frame_host()->browser_accessibility_manager();
3739 manager
->UserIsNavigatingAway();
3742 void WebContentsImpl::DidStopLoading() {
3743 scoped_ptr
<LoadNotificationDetails
> details
;
3745 // Use the last committed entry rather than the active one, in case a
3746 // pending entry has been created.
3747 NavigationEntry
* entry
= controller_
.GetLastCommittedEntry();
3748 Navigator
* navigator
= frame_tree_
.root()->navigator();
3750 // An entry may not exist for a stop when loading an initial blank page or
3751 // if an iframe injected by script into a blank page finishes loading.
3753 base::TimeDelta elapsed
=
3754 base::TimeTicks::Now() - navigator
->GetCurrentLoadStart();
3756 details
.reset(new LoadNotificationDetails(
3757 entry
->GetVirtualURL(),
3758 entry
->GetTransitionType(),
3761 controller_
.GetCurrentEntryIndex()));
3764 SetIsLoading(false, true, details
.get());
3767 void WebContentsImpl::DidChangeLoadProgress() {
3768 double load_progress
= frame_tree_
.load_progress();
3770 // The delegate is notified immediately for the first and last updates. Also,
3771 // since the message loop may be pretty busy when a page is loaded, it might
3772 // not execute a posted task in a timely manner so the progress report is sent
3773 // immediately if enough time has passed.
3774 base::TimeDelta min_delay
=
3775 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS
);
3776 bool delay_elapsed
= loading_last_progress_update_
.is_null() ||
3777 base::TimeTicks::Now() - loading_last_progress_update_
> min_delay
;
3779 if (load_progress
== 0.0 || load_progress
== 1.0 || delay_elapsed
) {
3780 // If there is a pending task to send progress, it is now obsolete.
3781 loading_weak_factory_
.InvalidateWeakPtrs();
3783 // Notify the load progress change.
3784 SendChangeLoadProgress();
3786 // Clean-up the states if needed.
3787 if (load_progress
== 1.0)
3788 ResetLoadProgressState();
3792 if (loading_weak_factory_
.HasWeakPtrs())
3795 base::MessageLoop::current()->PostDelayedTask(
3797 base::Bind(&WebContentsImpl::SendChangeLoadProgress
,
3798 loading_weak_factory_
.GetWeakPtr()),
3802 void WebContentsImpl::DidCancelLoading() {
3803 controller_
.DiscardNonCommittedEntries();
3805 // Update the URL display.
3806 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3809 void WebContentsImpl::DidAccessInitialDocument() {
3810 has_accessed_initial_document_
= true;
3812 // We may have left a failed browser-initiated navigation in the address bar
3813 // to let the user edit it and try again. Clear it now that content might
3814 // show up underneath it.
3815 if (!IsLoading() && controller_
.GetPendingEntry())
3816 controller_
.DiscardPendingEntry(false);
3818 // Update the URL display.
3819 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
3822 void WebContentsImpl::DidChangeName(RenderFrameHost
* render_frame_host
,
3823 const std::string
& name
) {
3824 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3825 FrameNameChanged(render_frame_host
, name
));
3828 void WebContentsImpl::DidDisownOpener(RenderFrameHost
* render_frame_host
) {
3829 // No action is necessary if the opener has already been cleared.
3833 // Clear our opener so that future cross-process navigations don't have an
3835 RemoveDestructionObserver(opener_
);
3838 // Notify all swapped out RenderViewHosts for this tab. This is important
3839 // in case we go back to them, or if another window in those processes tries
3840 // to access window.opener.
3841 GetRenderManager()->DidDisownOpener(render_frame_host
);
3844 void WebContentsImpl::DocumentOnLoadCompleted(
3845 RenderFrameHost
* render_frame_host
) {
3846 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3847 DocumentOnLoadCompletedInMainFrame());
3849 // TODO(avi): Remove. http://crbug.com/170921
3850 NotificationService::current()->Notify(
3851 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME
,
3852 Source
<WebContents
>(this),
3853 NotificationService::NoDetails());
3856 void WebContentsImpl::UpdateTitle(RenderFrameHost
* render_frame_host
,
3858 const base::string16
& title
,
3859 base::i18n::TextDirection title_direction
) {
3860 RenderViewHost
* rvh
= render_frame_host
->GetRenderViewHost();
3862 // If we have a title, that's a pretty good indication that we've started
3863 // getting useful data.
3864 SetNotWaitingForResponse();
3866 // Try to find the navigation entry, which might not be the current one.
3867 // For example, it might be from a pending RVH for the pending entry.
3868 NavigationEntryImpl
* entry
= controller_
.GetEntryWithPageID(
3869 rvh
->GetSiteInstance(), page_id
);
3871 // Re http://crbug.com/369661, page id is going away. This function should
3872 // only ever be called for the last committed entry. When this is verified,
3873 // this function can be greatly simplified.
3874 CHECK_EQ(entry
, controller_
.GetLastCommittedEntry());
3876 // We can handle title updates when we don't have an entry in
3877 // UpdateTitleForEntry, but only if the update is from the current RVH.
3878 // TODO(avi): Change to make decisions based on the RenderFrameHost.
3879 if (!entry
&& rvh
!= GetRenderViewHost())
3882 // TODO(evan): make use of title_direction.
3883 // http://code.google.com/p/chromium/issues/detail?id=27094
3884 if (!UpdateTitleForEntry(entry
, title
))
3887 // Broadcast notifications when the UI should be updated.
3888 if (entry
== controller_
.GetEntryAtOffset(0))
3889 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE
);
3892 void WebContentsImpl::UpdateEncoding(RenderFrameHost
* render_frame_host
,
3893 const std::string
& encoding
) {
3894 SetEncoding(encoding
);
3897 void WebContentsImpl::DocumentAvailableInMainFrame(
3898 RenderViewHost
* render_view_host
) {
3899 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
3900 DocumentAvailableInMainFrame());
3903 void WebContentsImpl::RouteCloseEvent(RenderViewHost
* rvh
) {
3904 // Tell the active RenderViewHost to run unload handlers and close, as long
3905 // as the request came from a RenderViewHost in the same BrowsingInstance.
3906 // In most cases, we receive this from a swapped out RenderViewHost.
3907 // It is possible to receive it from one that has just been swapped in,
3908 // in which case we might as well deliver the message anyway.
3909 if (rvh
->GetSiteInstance()->IsRelatedSiteInstance(GetSiteInstance()))
3913 bool WebContentsImpl::ShouldRouteMessageEvent(
3914 RenderFrameHost
* target_rfh
,
3915 SiteInstance
* source_site_instance
) const {
3916 // Allow the message if this WebContents is dedicated to a browser plugin
3918 // Note: This check means that an embedder could theoretically receive a
3919 // postMessage from anyone (not just its own guests). However, this is
3920 // probably not a risk for apps since other pages won't have references
3922 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
3925 int WebContentsImpl::EnsureOpenerRenderViewsExist(
3926 RenderFrameHost
* source_rfh
) {
3927 WebContentsImpl
* source_web_contents
= static_cast<WebContentsImpl
*>(
3928 WebContents::FromRenderFrameHost(source_rfh
));
3930 if (source_web_contents
) {
3931 if (GetBrowserPluginGuest()) {
3932 // We create a swapped out RenderView for the embedder in the guest's
3933 // render process but we intentionally do not expose the embedder's
3934 // opener chain to it.
3936 source_web_contents
->CreateSwappedOutRenderView(GetSiteInstance());
3938 return source_web_contents
->CreateOpenerRenderViews(GetSiteInstance());
3942 return MSG_ROUTING_NONE
;
3945 bool WebContentsImpl::AddMessageToConsole(int32 level
,
3946 const base::string16
& message
,
3948 const base::string16
& source_id
) {
3951 return delegate_
->AddMessageToConsole(this, level
, message
, line_no
,
3955 int WebContentsImpl::CreateSwappedOutRenderView(
3956 SiteInstance
* instance
) {
3957 int render_view_routing_id
= MSG_ROUTING_NONE
;
3958 GetRenderManager()->CreateRenderFrame(
3959 instance
, nullptr, MSG_ROUTING_NONE
,
3960 CREATE_RF_SWAPPED_OUT
| CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
3962 &render_view_routing_id
);
3963 return render_view_routing_id
;
3966 void WebContentsImpl::OnUserGesture() {
3967 // Notify observers.
3968 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetUserGesture());
3970 ResourceDispatcherHostImpl
* rdh
= ResourceDispatcherHostImpl::Get();
3971 if (rdh
) // NULL in unittests.
3972 rdh
->OnUserGesture(this);
3975 void WebContentsImpl::OnIgnoredUIEvent() {
3976 // Notify observers.
3977 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
, DidGetIgnoredUIEvent());
3980 void WebContentsImpl::RendererUnresponsive(RenderViewHost
* render_view_host
) {
3981 // Don't show hung renderer dialog for a swapped out RVH.
3982 if (render_view_host
!= GetRenderViewHost())
3985 RenderViewHostImpl
* rvhi
= static_cast<RenderViewHostImpl
*>(render_view_host
);
3986 RenderFrameHostImpl
* rfhi
=
3987 static_cast<RenderFrameHostImpl
*>(rvhi
->GetMainFrame());
3989 // Ignore renderer unresponsive event if debugger is attached to the tab
3990 // since the event may be a result of the renderer sitting on a breakpoint.
3991 // See http://crbug.com/65458
3992 if (DevToolsAgentHost::IsDebuggerAttached(this))
3995 if (rfhi
->IsWaitingForBeforeUnloadACK() ||
3996 rfhi
->IsWaitingForUnloadACK()) {
3997 // Hang occurred while firing the beforeunload/unload handler.
3998 // Pretend the handler fired so tab closing continues as if it had.
3999 rvhi
->set_sudden_termination_allowed(true);
4001 if (!GetRenderManager()->ShouldCloseTabOnUnresponsiveRenderer())
4004 // If the tab hangs in the beforeunload/unload handler there's really
4005 // nothing we can do to recover. If the hang is in the beforeunload handler,
4006 // pretend the beforeunload listeners have all fired and allow the delegate
4007 // to continue closing; the user will not have the option of cancelling the
4008 // close. Otherwise, pretend the unload listeners have all fired and close
4011 if (rfhi
->IsWaitingForBeforeUnloadACK() && delegate_
) {
4012 delegate_
->BeforeUnloadFired(this, true, &close
);
4019 if (!GetRenderViewHost() || !GetRenderViewHost()->IsRenderViewLive())
4023 delegate_
->RendererUnresponsive(this);
4026 void WebContentsImpl::RendererResponsive(RenderViewHost
* render_view_host
) {
4028 delegate_
->RendererResponsive(this);
4031 void WebContentsImpl::LoadStateChanged(
4033 const net::LoadStateWithParam
& load_state
,
4034 uint64 upload_position
,
4035 uint64 upload_size
) {
4036 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466285
4038 tracked_objects::ScopedTracker
tracking_profile1(
4039 FROM_HERE_WITH_EXPLICIT_FUNCTION(
4040 "466285 WebContentsImpl::LoadStateChanged::Start"));
4041 load_state_
= load_state
;
4042 upload_position_
= upload_position
;
4043 upload_size_
= upload_size
;
4044 load_state_host_
= net::IDNToUnicode(url
.host(),
4045 GetContentClient()->browser()->GetAcceptLangs(
4046 GetBrowserContext()));
4047 if (load_state_
.state
== net::LOAD_STATE_READING_RESPONSE
)
4048 SetNotWaitingForResponse();
4050 NotifyNavigationStateChanged(static_cast<InvalidateTypes
>(
4051 INVALIDATE_TYPE_LOAD
| INVALIDATE_TYPE_TAB
));
4055 void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
4056 bool proceed
, const base::TimeTicks
& proceed_time
,
4057 bool* proceed_to_fire_unload
) {
4058 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4059 BeforeUnloadFired(proceed_time
));
4061 delegate_
->BeforeUnloadFired(this, proceed
, proceed_to_fire_unload
);
4062 // Note: |this| might be deleted at this point.
4065 void WebContentsImpl::RenderProcessGoneFromRenderManager(
4066 RenderViewHost
* render_view_host
) {
4067 DCHECK(crashed_status_
!= base::TERMINATION_STATUS_STILL_RUNNING
);
4068 RenderViewTerminated(render_view_host
, crashed_status_
, crashed_error_code_
);
4071 void WebContentsImpl::UpdateRenderViewSizeForRenderManager() {
4072 // TODO(brettw) this is a hack. See WebContentsView::SizeContents.
4073 gfx::Size size
= GetSizeForNewRenderView();
4074 // 0x0 isn't a valid window size (minimal window size is 1x1) but it may be
4075 // here during container initialization and normal window size will be set
4076 // later. In case of tab duplication this resizing to 0x0 prevents setting
4077 // normal size later so just ignore it.
4078 if (!size
.IsEmpty())
4079 view_
->SizeContents(size
);
4082 void WebContentsImpl::CancelModalDialogsForRenderManager() {
4083 // We need to cancel modal dialogs when doing a process swap, since the load
4084 // deferrer would prevent us from swapping out. We also clear the state
4085 // because this is a cross-process navigation, which means that it's a new
4086 // site that should not have to pay for the sins of its predecessor.
4087 if (dialog_manager_
)
4088 dialog_manager_
->ResetDialogState(this);
4091 void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost
* old_host
,
4092 RenderFrameHost
* new_host
,
4093 bool is_main_frame
) {
4094 if (is_main_frame
) {
4095 NotifyViewSwapped(old_host
? old_host
->GetRenderViewHost() : nullptr,
4096 new_host
->GetRenderViewHost());
4098 // Make sure the visible RVH reflects the new delegate's preferences.
4100 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4102 view_
->RenderViewSwappedIn(new_host
->GetRenderViewHost());
4105 NotifyFrameSwapped(old_host
, new_host
);
4108 void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
4109 RenderViewHost
* old_host
,
4110 RenderViewHost
* new_host
) {
4111 NotifyViewSwapped(old_host
, new_host
);
4114 int WebContentsImpl::CreateOpenerRenderViewsForRenderManager(
4115 SiteInstance
* instance
) {
4117 return MSG_ROUTING_NONE
;
4119 // Recursively create RenderViews for anything else in the opener chain.
4120 return opener_
->CreateOpenerRenderViews(instance
);
4123 int WebContentsImpl::CreateOpenerRenderViews(SiteInstance
* instance
) {
4124 int opener_route_id
= MSG_ROUTING_NONE
;
4126 // If this tab has an opener, ensure it has a RenderView in the given
4127 // SiteInstance as well.
4129 opener_route_id
= opener_
->CreateOpenerRenderViews(instance
);
4131 // If any of the renderers (current, pending, or swapped out) for this
4132 // WebContents has the same SiteInstance, use it.
4133 if (GetRenderManager()->current_host()->GetSiteInstance() == instance
)
4134 return GetRenderManager()->current_host()->GetRoutingID();
4136 if (GetRenderManager()->pending_render_view_host() &&
4137 GetRenderManager()->pending_render_view_host()->GetSiteInstance() ==
4139 return GetRenderManager()->pending_render_view_host()->GetRoutingID();
4141 RenderViewHostImpl
* rvh
= GetRenderManager()->GetSwappedOutRenderViewHost(
4144 return rvh
->GetRoutingID();
4146 // Create a swapped out RenderView in the given SiteInstance if none exists,
4147 // setting its opener to the given route_id. Return the new view's route_id.
4148 int render_view_routing_id
= MSG_ROUTING_NONE
;
4149 GetRenderManager()->CreateRenderFrame(instance
, nullptr, opener_route_id
,
4150 CREATE_RF_FOR_MAIN_FRAME_NAVIGATION
|
4151 CREATE_RF_SWAPPED_OUT
|
4153 &render_view_routing_id
);
4154 return render_view_routing_id
;
4157 NavigationControllerImpl
& WebContentsImpl::GetControllerForRenderManager() {
4158 return GetController();
4161 scoped_ptr
<WebUIImpl
> WebContentsImpl::CreateWebUIForRenderManager(
4163 return scoped_ptr
<WebUIImpl
>(static_cast<WebUIImpl
*>(CreateWebUI(url
)));
4167 WebContentsImpl::GetLastCommittedNavigationEntryForRenderManager() {
4168 return controller_
.GetLastCommittedEntry();
4171 bool WebContentsImpl::CreateRenderViewForRenderManager(
4172 RenderViewHost
* render_view_host
,
4173 int opener_route_id
,
4174 int proxy_routing_id
,
4175 bool for_main_frame_navigation
) {
4176 TRACE_EVENT0("browser,navigation",
4177 "WebContentsImpl::CreateRenderViewForRenderManager");
4178 // Can be NULL during tests.
4179 RenderWidgetHostViewBase
* rwh_view
;
4180 // TODO(kenrb): RenderWidgetHostViewChildFrame special casing is temporary
4181 // until RenderWidgetHost is attached to RenderFrameHost. We need to special
4182 // case this because RWH is still a base class of RenderViewHost, and child
4183 // frame RWHVs are unique in that they do not have their own WebContents.
4184 if (!for_main_frame_navigation
) {
4185 RenderWidgetHostViewChildFrame
* rwh_view_child
=
4186 new RenderWidgetHostViewChildFrame(render_view_host
);
4187 rwh_view
= rwh_view_child
;
4189 rwh_view
= view_
->CreateViewForWidget(render_view_host
, false);
4192 // Now that the RenderView has been created, we need to tell it its size.
4194 rwh_view
->SetSize(GetSizeForNewRenderView());
4196 // Make sure we use the correct starting page_id in the new RenderView.
4197 UpdateMaxPageIDIfNecessary(render_view_host
);
4199 GetMaxPageIDForSiteInstance(render_view_host
->GetSiteInstance());
4201 if (!static_cast<RenderViewHostImpl
*>(
4202 render_view_host
)->CreateRenderView(base::string16(),
4206 created_with_opener_
)) {
4210 SetHistoryOffsetAndLengthForView(render_view_host
,
4211 controller_
.GetLastCommittedEntryIndex(),
4212 controller_
.GetEntryCount());
4214 #if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
4215 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
4216 // linux. See crbug.com/83941.
4218 if (RenderWidgetHost
* render_widget_host
= rwh_view
->GetRenderWidgetHost())
4219 render_widget_host
->WasResized();
4226 bool WebContentsImpl::CreateRenderFrameForRenderManager(
4227 RenderFrameHost
* render_frame_host
,
4228 int parent_routing_id
,
4229 int previous_sibling_routing_id
,
4230 int proxy_routing_id
) {
4231 TRACE_EVENT0("browser,navigation",
4232 "WebContentsImpl::CreateRenderFrameForRenderManager");
4234 RenderFrameHostImpl
* rfh
=
4235 static_cast<RenderFrameHostImpl
*>(render_frame_host
);
4236 if (!rfh
->CreateRenderFrame(parent_routing_id
, previous_sibling_routing_id
,
4240 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
4241 // RenderFrameHost will have to be associated with the appropriate
4242 // RenderWidgetHostView or a new one should be created here.
4247 #if defined(OS_ANDROID)
4249 base::android::ScopedJavaLocalRef
<jobject
>
4250 WebContentsImpl::GetJavaWebContents() {
4251 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
4252 return GetWebContentsAndroid()->GetJavaObject();
4255 WebContentsAndroid
* WebContentsImpl::GetWebContentsAndroid() {
4256 WebContentsAndroid
* web_contents_android
=
4257 static_cast<WebContentsAndroid
*>(GetUserData(kWebContentsAndroidKey
));
4258 if (!web_contents_android
) {
4259 web_contents_android
= new WebContentsAndroid(this);
4260 SetUserData(kWebContentsAndroidKey
, web_contents_android
);
4262 return web_contents_android
;
4265 bool WebContentsImpl::CreateRenderViewForInitialEmptyDocument() {
4266 return CreateRenderViewForRenderManager(GetRenderViewHost(),
4272 #elif defined(OS_MACOSX)
4274 void WebContentsImpl::SetAllowOtherViews(bool allow
) {
4275 view_
->SetAllowOtherViews(allow
);
4278 bool WebContentsImpl::GetAllowOtherViews() {
4279 return view_
->GetAllowOtherViews();
4284 void WebContentsImpl::OnDialogClosed(int render_process_id
,
4285 int render_frame_id
,
4286 IPC::Message
* reply_msg
,
4287 bool dialog_was_suppressed
,
4289 const base::string16
& user_input
) {
4290 RenderFrameHostImpl
* rfh
= RenderFrameHostImpl::FromID(render_process_id
,
4292 last_dialog_suppressed_
= dialog_was_suppressed
;
4294 if (is_showing_before_unload_dialog_
&& !success
) {
4295 // If a beforeunload dialog is canceled, we need to stop the throbber from
4296 // spinning, since we forced it to start spinning in Navigate.
4299 controller_
.DiscardNonCommittedEntries();
4301 FOR_EACH_OBSERVER(WebContentsObserver
, observers_
,
4302 BeforeUnloadDialogCancelled());
4305 is_showing_before_unload_dialog_
= false;
4307 rfh
->JavaScriptDialogClosed(reply_msg
, success
, user_input
,
4308 dialog_was_suppressed
);
4310 // Don't leak the sync IPC reply if the RFH or process is gone.
4315 void WebContentsImpl::SetEncoding(const std::string
& encoding
) {
4316 if (encoding
== last_reported_encoding_
)
4318 last_reported_encoding_
= encoding
;
4320 canonical_encoding_
= GetContentClient()->browser()->
4321 GetCanonicalEncodingNameByAliasName(encoding
);
4324 bool WebContentsImpl::IsHidden() {
4325 return capturer_count_
== 0 && !should_normally_be_visible_
;
4328 RenderFrameHostManager
* WebContentsImpl::GetRenderManager() const {
4329 return frame_tree_
.root()->render_manager();
4332 BrowserPluginGuest
* WebContentsImpl::GetBrowserPluginGuest() const {
4333 return browser_plugin_guest_
.get();
4336 void WebContentsImpl::SetBrowserPluginGuest(BrowserPluginGuest
* guest
) {
4337 CHECK(!browser_plugin_guest_
);
4338 browser_plugin_guest_
.reset(guest
);
4341 BrowserPluginEmbedder
* WebContentsImpl::GetBrowserPluginEmbedder() const {
4342 return browser_plugin_embedder_
.get();
4345 void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
4346 if (browser_plugin_embedder_
)
4348 browser_plugin_embedder_
.reset(BrowserPluginEmbedder::Create(this));
4351 void WebContentsImpl::ClearPowerSaveBlockers(
4352 RenderFrameHost
* render_frame_host
) {
4353 RemoveAllMediaPlayerEntries(render_frame_host
, &active_audio_players_
);
4354 RemoveAllMediaPlayerEntries(render_frame_host
, &active_video_players_
);
4355 MaybeReleasePowerSaveBlockers();
4358 void WebContentsImpl::ClearAllPowerSaveBlockers() {
4359 active_audio_players_
.clear();
4360 active_video_players_
.clear();
4361 audio_power_save_blocker_
.reset();
4362 video_power_save_blocker_
.reset();
4365 gfx::Size
WebContentsImpl::GetSizeForNewRenderView() {
4368 size
= delegate_
->GetSizeForNewRenderView(this);
4370 size
= GetContainerBounds().size();
4374 void WebContentsImpl::OnFrameRemoved(RenderFrameHost
* render_frame_host
) {
4376 WebContentsObserver
, observers_
, FrameDeleted(render_frame_host
));
4379 void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size
& old_size
) {
4382 const gfx::Size new_size
= GetPreferredSize();
4383 if (new_size
!= old_size
)
4384 delegate_
->UpdatePreferredSize(this, new_size
);
4387 void WebContentsImpl::AddMediaPlayerEntry(int64 player_cookie
,
4388 ActiveMediaPlayerMap
* player_map
) {
4389 if (!HasValidFrameSource())
4392 const uintptr_t key
=
4393 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4394 DCHECK(std::find((*player_map
)[key
].begin(),
4395 (*player_map
)[key
].end(),
4396 player_cookie
) == (*player_map
)[key
].end());
4397 (*player_map
)[key
].push_back(player_cookie
);
4400 void WebContentsImpl::RemoveMediaPlayerEntry(int64 player_cookie
,
4401 ActiveMediaPlayerMap
* player_map
) {
4402 if (!HasValidFrameSource())
4405 const uintptr_t key
=
4406 reinterpret_cast<uintptr_t>(render_frame_message_source_
);
4407 ActiveMediaPlayerMap::iterator it
= player_map
->find(key
);
4408 if (it
== player_map
->end())
4411 // Remove the player.
4412 PlayerList::iterator player_it
=
4413 std::find(it
->second
.begin(), it
->second
.end(), player_cookie
);
4414 if (player_it
!= it
->second
.end())
4415 it
->second
.erase(player_it
);
4417 // If there are no players left, remove the map entry.
4418 if (it
->second
.empty())
4419 player_map
->erase(it
);
4422 void WebContentsImpl::RemoveAllMediaPlayerEntries(
4423 RenderFrameHost
* render_frame_host
,
4424 ActiveMediaPlayerMap
* player_map
) {
4425 ActiveMediaPlayerMap::iterator it
=
4426 player_map
->find(reinterpret_cast<uintptr_t>(render_frame_host
));
4427 if (it
== player_map
->end())
4429 player_map
->erase(it
);
4432 void WebContentsImpl::ResumeResponseDeferredAtStart() {
4433 FrameTreeNode
* node
= frame_tree_
.root();
4434 node
->render_manager()->ResumeResponseDeferredAtStart();
4437 void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable
) {
4438 force_disable_overscroll_content_
= force_disable
;
4440 view_
->SetOverscrollControllerEnabled(CanOverscrollContent());
4443 } // namespace content