Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blobaed2daa51f90b3aa515e83da771d57a128753e33
1 // Copyright 2013 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/frame_host/render_frame_host_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/containers/hash_tables.h"
10 #include "base/lazy_instance.h"
11 #include "base/metrics/histogram.h"
12 #include "base/process/kill.h"
13 #include "base/time/time.h"
14 #include "content/browser/accessibility/accessibility_mode_helper.h"
15 #include "content/browser/accessibility/ax_tree_id_registry.h"
16 #include "content/browser/accessibility/browser_accessibility_manager.h"
17 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
18 #include "content/browser/bad_message.h"
19 #include "content/browser/child_process_security_policy_impl.h"
20 #include "content/browser/frame_host/cross_process_frame_connector.h"
21 #include "content/browser/frame_host/cross_site_transferring_request.h"
22 #include "content/browser/frame_host/frame_mojo_shell.h"
23 #include "content/browser/frame_host/frame_tree.h"
24 #include "content/browser/frame_host/frame_tree_node.h"
25 #include "content/browser/frame_host/navigation_handle_impl.h"
26 #include "content/browser/frame_host/navigation_request.h"
27 #include "content/browser/frame_host/navigator.h"
28 #include "content/browser/frame_host/navigator_impl.h"
29 #include "content/browser/frame_host/render_frame_host_delegate.h"
30 #include "content/browser/frame_host/render_frame_proxy_host.h"
31 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
32 #include "content/browser/geolocation/geolocation_service_context.h"
33 #include "content/browser/permissions/permission_service_context.h"
34 #include "content/browser/permissions/permission_service_impl.h"
35 #include "content/browser/presentation/presentation_service_impl.h"
36 #include "content/browser/renderer_host/input/input_router.h"
37 #include "content/browser/renderer_host/input/timeout_monitor.h"
38 #include "content/browser/renderer_host/render_process_host_impl.h"
39 #include "content/browser/renderer_host/render_view_host_delegate.h"
40 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
41 #include "content/browser/renderer_host/render_view_host_impl.h"
42 #include "content/browser/renderer_host/render_widget_host_impl.h"
43 #include "content/browser/renderer_host/render_widget_host_view_base.h"
44 #include "content/common/accessibility_messages.h"
45 #include "content/common/frame_messages.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/inter_process_time_ticks_converter.h"
48 #include "content/common/navigation_params.h"
49 #include "content/common/render_frame_setup.mojom.h"
50 #include "content/common/site_isolation_policy.h"
51 #include "content/common/swapped_out_messages.h"
52 #include "content/public/browser/ax_event_notification_details.h"
53 #include "content/public/browser/browser_accessibility_state.h"
54 #include "content/public/browser/browser_context.h"
55 #include "content/public/browser/browser_plugin_guest_manager.h"
56 #include "content/public/browser/browser_thread.h"
57 #include "content/public/browser/content_browser_client.h"
58 #include "content/public/browser/permission_manager.h"
59 #include "content/public/browser/permission_type.h"
60 #include "content/public/browser/render_process_host.h"
61 #include "content/public/browser/render_widget_host_view.h"
62 #include "content/public/browser/stream_handle.h"
63 #include "content/public/browser/user_metrics.h"
64 #include "content/public/common/content_constants.h"
65 #include "content/public/common/content_switches.h"
66 #include "content/public/common/isolated_world_ids.h"
67 #include "content/public/common/url_constants.h"
68 #include "content/public/common/url_utils.h"
69 #include "ui/accessibility/ax_tree.h"
70 #include "ui/accessibility/ax_tree_update.h"
71 #include "url/gurl.h"
73 #if defined(OS_ANDROID)
74 #include "content/browser/mojo/service_registrar_android.h"
75 #endif
77 #if defined(OS_MACOSX)
78 #include "content/browser/frame_host/popup_menu_helper_mac.h"
79 #endif
81 #if defined(ENABLE_WEBVR)
82 #include "content/browser/vr/vr_device_manager.h"
83 #endif
85 using base::TimeDelta;
87 namespace content {
89 namespace {
91 // The next value to use for the accessibility reset token.
92 int g_next_accessibility_reset_token = 1;
94 // The next value to use for the javascript callback id.
95 int g_next_javascript_callback_id = 1;
97 // Whether to allow injecting javascript into any kind of frame (for Android
98 // WebView).
99 bool g_allow_injecting_javascript = false;
101 // The (process id, routing id) pair that identifies one RenderFrame.
102 typedef std::pair<int32, int32> RenderFrameHostID;
103 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
104 RoutingIDFrameMap;
105 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
106 LAZY_INSTANCE_INITIALIZER;
108 // Translate a WebKit text direction into a base::i18n one.
109 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
110 blink::WebTextDirection dir) {
111 switch (dir) {
112 case blink::WebTextDirectionLeftToRight:
113 return base::i18n::LEFT_TO_RIGHT;
114 case blink::WebTextDirectionRightToLeft:
115 return base::i18n::RIGHT_TO_LEFT;
116 default:
117 NOTREACHED();
118 return base::i18n::UNKNOWN_DIRECTION;
122 } // namespace
124 // static
125 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
126 return rfh_state == STATE_DEFAULT;
129 // static
130 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
131 int render_frame_id) {
132 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
135 // static
136 void RenderFrameHost::AllowInjectingJavaScriptForAndroidWebView() {
137 g_allow_injecting_javascript = true;
140 // static
141 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
142 int routing_id) {
143 DCHECK_CURRENTLY_ON(BrowserThread::UI);
144 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
145 RoutingIDFrameMap::iterator it = frames->find(
146 RenderFrameHostID(process_id, routing_id));
147 return it == frames->end() ? NULL : it->second;
150 // static
151 RenderFrameHost* RenderFrameHost::FromAXTreeID(
152 int ax_tree_id) {
153 return RenderFrameHostImpl::FromAXTreeID(ax_tree_id);
156 // static
157 RenderFrameHostImpl* RenderFrameHostImpl::FromAXTreeID(
158 AXTreeIDRegistry::AXTreeID ax_tree_id) {
159 DCHECK_CURRENTLY_ON(BrowserThread::UI);
160 AXTreeIDRegistry::FrameID frame_id =
161 AXTreeIDRegistry::GetInstance()->GetFrameID(ax_tree_id);
162 return RenderFrameHostImpl::FromID(frame_id.first, frame_id.second);
165 RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
166 RenderViewHostImpl* render_view_host,
167 RenderFrameHostDelegate* delegate,
168 RenderWidgetHostDelegate* rwh_delegate,
169 FrameTree* frame_tree,
170 FrameTreeNode* frame_tree_node,
171 int32 routing_id,
172 int32 widget_routing_id,
173 int32 surface_id,
174 int flags)
175 : render_view_host_(render_view_host),
176 delegate_(delegate),
177 site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
178 process_(site_instance->GetProcess()),
179 cross_process_frame_connector_(NULL),
180 render_frame_proxy_host_(NULL),
181 frame_tree_(frame_tree),
182 frame_tree_node_(frame_tree_node),
183 render_widget_host_(nullptr),
184 routing_id_(routing_id),
185 render_frame_created_(false),
186 navigations_suspended_(false),
187 is_waiting_for_beforeunload_ack_(false),
188 unload_ack_is_for_navigation_(false),
189 is_loading_(false),
190 pending_commit_(false),
191 accessibility_reset_token_(0),
192 accessibility_reset_count_(0),
193 no_create_browser_accessibility_manager_for_testing_(false),
194 weak_ptr_factory_(this) {
195 bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
196 bool hidden = !!(flags & CREATE_RF_HIDDEN);
197 frame_tree_->AddRenderViewHostRef(render_view_host_);
198 GetProcess()->AddRoute(routing_id_, this);
199 g_routing_id_frame_map.Get().insert(std::make_pair(
200 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
201 this));
203 if (is_swapped_out) {
204 rfh_state_ = STATE_SWAPPED_OUT;
205 } else {
206 rfh_state_ = STATE_DEFAULT;
207 GetSiteInstance()->increment_active_frame_count();
210 SetUpMojoIfNeeded();
211 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
212 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
214 if (widget_routing_id != MSG_ROUTING_NONE) {
215 render_widget_host_ = new RenderWidgetHostImpl(
216 rwh_delegate, GetProcess(), widget_routing_id, surface_id, hidden);
217 render_widget_host_->set_owned_by_render_frame_host(true);
218 } else {
219 DCHECK_EQ(0, surface_id);
223 RenderFrameHostImpl::~RenderFrameHostImpl() {
224 GetProcess()->RemoveRoute(routing_id_);
225 g_routing_id_frame_map.Get().erase(
226 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
228 if (delegate_ && render_frame_created_)
229 delegate_->RenderFrameDeleted(this);
231 // If this was swapped out, it already decremented the active frame count of
232 // the SiteInstance it belongs to.
233 if (IsRFHStateActive(rfh_state_))
234 GetSiteInstance()->decrement_active_frame_count();
236 // Notify the FrameTree that this RFH is going away, allowing it to shut down
237 // the corresponding RenderViewHost if it is no longer needed.
238 frame_tree_->ReleaseRenderViewHostRef(render_view_host_);
240 // NULL out the swapout timer; in crash dumps this member will be null only if
241 // the dtor has run.
242 swapout_event_monitor_timeout_.reset();
244 for (const auto& iter: visual_state_callbacks_) {
245 iter.second.Run(false);
248 if (render_widget_host_) {
249 // Shutdown causes the RenderWidgetHost to delete itself.
250 render_widget_host_->Shutdown();
254 int RenderFrameHostImpl::GetRoutingID() {
255 return routing_id_;
258 AXTreeIDRegistry::AXTreeID RenderFrameHostImpl::GetAXTreeID() {
259 return AXTreeIDRegistry::GetInstance()->GetOrCreateAXTreeID(
260 GetProcess()->GetID(), routing_id_);
263 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
264 return site_instance_.get();
267 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
268 return process_;
271 RenderFrameHost* RenderFrameHostImpl::GetParent() {
272 FrameTreeNode* parent_node = frame_tree_node_->parent();
273 if (!parent_node)
274 return NULL;
275 return parent_node->current_frame_host();
278 const std::string& RenderFrameHostImpl::GetFrameName() {
279 return frame_tree_node_->frame_name();
282 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
283 FrameTreeNode* parent_node = frame_tree_node_->parent();
284 if (!parent_node)
285 return false;
286 return GetSiteInstance() !=
287 parent_node->current_frame_host()->GetSiteInstance();
290 GURL RenderFrameHostImpl::GetLastCommittedURL() {
291 return frame_tree_node_->current_url();
294 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
295 RenderWidgetHostView* view = render_view_host_->GetView();
296 if (!view)
297 return NULL;
298 return view->GetNativeView();
301 void RenderFrameHostImpl::AddMessageToConsole(ConsoleMessageLevel level,
302 const std::string& message) {
303 Send(new FrameMsg_AddMessageToConsole(routing_id_, level, message));
306 void RenderFrameHostImpl::ExecuteJavaScript(
307 const base::string16& javascript) {
308 CHECK(CanExecuteJavaScript());
309 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
310 javascript,
311 0, false));
314 void RenderFrameHostImpl::ExecuteJavaScript(
315 const base::string16& javascript,
316 const JavaScriptResultCallback& callback) {
317 CHECK(CanExecuteJavaScript());
318 int key = g_next_javascript_callback_id++;
319 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
320 javascript,
321 key, true));
322 javascript_callbacks_.insert(std::make_pair(key, callback));
325 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
326 const base::string16& javascript) {
327 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
328 javascript,
329 0, false, false));
332 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
333 const base::string16& javascript,
334 const JavaScriptResultCallback& callback) {
335 int key = g_next_javascript_callback_id++;
336 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_, javascript,
337 key, true, false));
338 javascript_callbacks_.insert(std::make_pair(key, callback));
342 void RenderFrameHostImpl::ExecuteJavaScriptWithUserGestureForTests(
343 const base::string16& javascript) {
344 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
345 javascript,
346 0, false, true));
349 void RenderFrameHostImpl::ExecuteJavaScriptInIsolatedWorld(
350 const base::string16& javascript,
351 const JavaScriptResultCallback& callback,
352 int world_id) {
353 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
354 world_id > ISOLATED_WORLD_ID_MAX) {
355 // Return if the world_id is not valid.
356 NOTREACHED();
357 return;
360 int key = 0;
361 bool request_reply = false;
362 if (!callback.is_null()) {
363 request_reply = true;
364 key = g_next_javascript_callback_id++;
365 javascript_callbacks_.insert(std::make_pair(key, callback));
368 Send(new FrameMsg_JavaScriptExecuteRequestInIsolatedWorld(
369 routing_id_, javascript, key, request_reply, world_id));
372 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
373 return render_view_host_;
376 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
377 return service_registry_.get();
380 blink::WebPageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
381 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
382 // returning nullptr in some cases. See https://crbug.com/455245.
383 blink::WebPageVisibilityState visibility_state =
384 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())->is_hidden()
385 ? blink::WebPageVisibilityStateHidden
386 : blink::WebPageVisibilityStateVisible;
387 GetContentClient()->browser()->OverridePageVisibilityState(this,
388 &visibility_state);
389 return visibility_state;
392 bool RenderFrameHostImpl::Send(IPC::Message* message) {
393 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
394 return render_view_host_->input_router()->SendInput(
395 make_scoped_ptr(message));
398 return GetProcess()->Send(message);
401 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
402 // Filter out most IPC messages if this frame is swapped out.
403 // We still want to handle certain ACKs to keep our state consistent.
404 if (is_swapped_out()) {
405 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
406 // If this is a synchronous message and we decided not to handle it,
407 // we must send an error reply, or else the renderer will be stuck
408 // and won't respond to future requests.
409 if (msg.is_sync()) {
410 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
411 reply->set_reply_error();
412 Send(reply);
414 // Don't continue looking for someone to handle it.
415 return true;
419 if (delegate_->OnMessageReceived(this, msg))
420 return true;
422 RenderFrameProxyHost* proxy =
423 frame_tree_node_->render_manager()->GetProxyToParent();
424 if (proxy && proxy->cross_process_frame_connector() &&
425 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
426 return true;
428 bool handled = true;
429 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
430 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
431 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
432 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
433 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
434 OnDidStartProvisionalLoadForFrame)
435 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
436 OnDidFailProvisionalLoadWithError)
437 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
438 OnDidFailLoadWithError)
439 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
440 OnDidCommitProvisionalLoad(msg))
441 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation)
442 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
443 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
444 OnDocumentOnLoadCompleted)
445 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
446 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
447 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
448 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
449 OnJavaScriptExecuteResponse)
450 IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
451 OnVisualStateResponse)
452 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
453 OnRunJavaScriptMessage)
454 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
455 OnRunBeforeUnloadConfirm)
456 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
457 OnDidAccessInitialDocument)
458 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
459 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeName, OnDidChangeName)
460 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
461 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeSandboxFlags,
462 OnDidChangeSandboxFlags)
463 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
464 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
465 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
466 OnBeginNavigation)
467 IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
468 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
469 OnTextSurroundingSelectionResponse)
470 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
471 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
472 OnAccessibilityLocationChanges)
473 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
474 OnAccessibilityFindInPageResult)
475 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
476 OnAccessibilitySnapshotResponse)
477 IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
478 // The following message is synthetic and doesn't come from RenderFrame, but
479 // from RenderProcessHost.
480 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
481 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
482 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
483 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
484 OnDidChangeLoadProgress)
485 #if defined(OS_MACOSX) || defined(OS_ANDROID)
486 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
487 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
488 #endif
489 IPC_END_MESSAGE_MAP()
491 // No further actions here, since we may have been deleted.
492 return handled;
495 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
496 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
499 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
500 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
503 void RenderFrameHostImpl::AccessibilityShowContextMenu(int acc_obj_id) {
504 Send(new AccessibilityMsg_ShowContextMenu(routing_id_, acc_obj_id));
507 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
508 int acc_obj_id, const gfx::Rect& subfocus) {
509 Send(new AccessibilityMsg_ScrollToMakeVisible(
510 routing_id_, acc_obj_id, subfocus));
513 void RenderFrameHostImpl::AccessibilityScrollToPoint(
514 int acc_obj_id, const gfx::Point& point) {
515 Send(new AccessibilityMsg_ScrollToPoint(
516 routing_id_, acc_obj_id, point));
519 void RenderFrameHostImpl::AccessibilitySetScrollOffset(
520 int acc_obj_id, const gfx::Point& offset) {
521 Send(new AccessibilityMsg_SetScrollOffset(
522 routing_id_, acc_obj_id, offset));
525 void RenderFrameHostImpl::AccessibilitySetTextSelection(
526 int object_id, int start_offset, int end_offset) {
527 Send(new AccessibilityMsg_SetTextSelection(
528 routing_id_, object_id, start_offset, end_offset));
531 void RenderFrameHostImpl::AccessibilitySetValue(
532 int object_id, const base::string16& value) {
533 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
536 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
537 RenderWidgetHostView* view = render_view_host_->GetView();
538 if (view)
539 return view->HasFocus();
540 return false;
543 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
544 RenderWidgetHostView* view = render_view_host_->GetView();
545 if (view)
546 return view->GetViewBounds();
547 return gfx::Rect();
550 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
551 const gfx::Rect& bounds) const {
552 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
553 render_view_host_->GetView());
554 if (view)
555 return view->AccessibilityOriginInScreen(bounds);
556 return gfx::Point();
559 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
560 Send(new AccessibilityMsg_HitTest(routing_id_, point));
563 void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) {
564 Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id));
567 void RenderFrameHostImpl::AccessibilityReset() {
568 accessibility_reset_token_ = g_next_accessibility_reset_token++;
569 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
572 void RenderFrameHostImpl::AccessibilityFatalError() {
573 browser_accessibility_manager_.reset(NULL);
574 if (accessibility_reset_token_)
575 return;
577 accessibility_reset_count_++;
578 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
579 Send(new AccessibilityMsg_FatalError(routing_id_));
580 } else {
581 accessibility_reset_token_ = g_next_accessibility_reset_token++;
582 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
583 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
587 gfx::AcceleratedWidget
588 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
589 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
590 render_view_host_->GetView());
591 if (view)
592 return view->AccessibilityGetAcceleratedWidget();
593 return gfx::kNullAcceleratedWidget;
596 gfx::NativeViewAccessible
597 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
598 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
599 render_view_host_->GetView());
600 if (view)
601 return view->AccessibilityGetNativeViewAccessible();
602 return NULL;
605 bool RenderFrameHostImpl::CreateRenderFrame(int proxy_routing_id,
606 int opener_routing_id,
607 int parent_routing_id,
608 int previous_sibling_routing_id) {
609 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
610 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
612 // The process may (if we're sharing a process with another host that already
613 // initialized it) or may not (we have our own process or the old process
614 // crashed) have been initialized. Calling Init multiple times will be
615 // ignored, so this is safe.
616 if (!GetProcess()->Init())
617 return false;
619 DCHECK(GetProcess()->HasConnection());
621 FrameMsg_NewFrame_Params params;
622 params.routing_id = routing_id_;
623 params.proxy_routing_id = proxy_routing_id;
624 params.opener_routing_id = opener_routing_id;
625 params.parent_routing_id = parent_routing_id;
626 params.previous_sibling_routing_id = previous_sibling_routing_id;
627 params.replication_state = frame_tree_node()->current_replication_state();
629 if (render_widget_host_) {
630 params.widget_params.routing_id = render_widget_host_->GetRoutingID();
631 params.widget_params.surface_id = render_widget_host_->surface_id();
632 params.widget_params.hidden = render_widget_host_->is_hidden();
633 } else {
634 // MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
635 // the renderer process.
636 params.widget_params.routing_id = MSG_ROUTING_NONE;
637 params.widget_params.surface_id = 0;
638 params.widget_params.hidden = true;
641 Send(new FrameMsg_NewFrame(params));
643 // The RenderWidgetHost takes ownership of its view. It is tied to the
644 // lifetime of the current RenderProcessHost for this RenderFrameHost.
645 if (render_widget_host_) {
646 RenderWidgetHostView* rwhv =
647 new RenderWidgetHostViewChildFrame(render_widget_host_);
648 rwhv->Hide();
651 if (proxy_routing_id != MSG_ROUTING_NONE) {
652 RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
653 GetProcess()->GetID(), proxy_routing_id);
654 // We have also created a RenderFrameProxy in FrameMsg_NewFrame above, so
655 // remember that.
656 proxy->set_render_frame_proxy_created(true);
659 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
660 // this path is only used for out-of-process iframes. Main frame RenderFrames
661 // are created with their RenderView, and same-site iframes are created at the
662 // time of OnCreateChildFrame.
663 SetRenderFrameCreated(true);
665 return true;
668 void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
669 bool was_created = render_frame_created_;
670 render_frame_created_ = created;
672 // If the current status is different than the new status, the delegate
673 // needs to be notified.
674 if (delegate_ && (created != was_created)) {
675 if (created)
676 delegate_->RenderFrameCreated(this);
677 else
678 delegate_->RenderFrameDeleted(this);
681 if (created && render_widget_host_)
682 render_widget_host_->InitForFrame();
685 void RenderFrameHostImpl::Init() {
686 GetProcess()->ResumeRequestsForView(routing_id_);
689 void RenderFrameHostImpl::OnAddMessageToConsole(
690 int32 level,
691 const base::string16& message,
692 int32 line_no,
693 const base::string16& source_id) {
694 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
695 return;
697 // Pass through log level only on WebUI pages to limit console spew.
698 const bool is_web_ui =
699 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL());
700 const int32 resolved_level = is_web_ui ? level : ::logging::LOG_INFO;
702 // LogMessages can be persisted so this shouldn't be logged in incognito mode.
703 // This rule is not applied to WebUI pages, because source code of WebUI is a
704 // part of Chrome source code, and we want to treat messages from WebUI the
705 // same way as we treat log messages from native code.
706 if (::logging::GetMinLogLevel() <= resolved_level &&
707 (is_web_ui ||
708 !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord())) {
709 logging::LogMessage("CONSOLE", line_no, resolved_level).stream()
710 << "\"" << message << "\", source: " << source_id << " (" << line_no
711 << ")";
715 void RenderFrameHostImpl::OnCreateChildFrame(
716 int new_routing_id,
717 blink::WebTreeScopeType scope,
718 const std::string& frame_name,
719 blink::WebSandboxFlags sandbox_flags) {
720 // It is possible that while a new RenderFrameHost was committed, the
721 // RenderFrame corresponding to this host sent an IPC message to create a
722 // frame and it is delivered after this host is swapped out.
723 // Ignore such messages, as we know this RenderFrameHost is going away.
724 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
725 return;
727 RenderFrameHostImpl* new_frame =
728 frame_tree_->AddFrame(frame_tree_node_, GetProcess()->GetID(),
729 new_routing_id, scope, frame_name, sandbox_flags);
730 if (!new_frame)
731 return;
733 // We know that the RenderFrame has been created in this case, immediately
734 // after the CreateChildFrame IPC was sent.
735 new_frame->SetRenderFrameCreated(true);
738 void RenderFrameHostImpl::OnDetach() {
739 frame_tree_->RemoveFrame(frame_tree_node_);
742 void RenderFrameHostImpl::OnFrameFocused() {
743 frame_tree_->SetFocusedFrame(frame_tree_node_);
746 void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
747 OpenURL(params, GetSiteInstance());
750 void RenderFrameHostImpl::OnDocumentOnLoadCompleted(
751 FrameMsg_UILoadMetricsReportType::Value report_type,
752 base::TimeTicks ui_timestamp) {
753 if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
754 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Link",
755 base::TimeTicks::Now() - ui_timestamp,
756 base::TimeDelta::FromMilliseconds(10),
757 base::TimeDelta::FromMinutes(10), 100);
758 } else if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
759 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Intent",
760 base::TimeTicks::Now() - ui_timestamp,
761 base::TimeDelta::FromMilliseconds(10),
762 base::TimeDelta::FromMinutes(10), 100);
764 // This message is only sent for top-level frames. TODO(avi): when frame tree
765 // mirroring works correctly, add a check here to enforce it.
766 delegate_->DocumentOnLoadCompleted(this);
769 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(const GURL& url) {
770 frame_tree_node_->navigator()->DidStartProvisionalLoad(
771 this, url);
774 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
775 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
776 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
777 switches::kEnableBrowserSideNavigation) &&
778 navigation_handle_) {
779 navigation_handle_->set_net_error_code(
780 static_cast<net::Error>(params.error_code));
782 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
785 void RenderFrameHostImpl::OnDidFailLoadWithError(
786 const GURL& url,
787 int error_code,
788 const base::string16& error_description,
789 bool was_ignored_by_handler) {
790 GURL validated_url(url);
791 GetProcess()->FilterURL(false, &validated_url);
793 frame_tree_node_->navigator()->DidFailLoadWithError(
794 this, validated_url, error_code, error_description,
795 was_ignored_by_handler);
798 // Called when the renderer navigates. For every frame loaded, we'll get this
799 // notification containing parameters identifying the navigation.
801 // Subframes are identified by the page transition type. For subframes loaded
802 // as part of a wider page load, the page_id will be the same as for the top
803 // level frame. If the user explicitly requests a subframe navigation, we will
804 // get a new page_id because we need to create a new navigation entry for that
805 // action.
806 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
807 RenderProcessHost* process = GetProcess();
809 // Read the parameters out of the IPC message directly to avoid making another
810 // copy when we filter the URLs.
811 base::PickleIterator iter(msg);
812 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
813 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
814 Read(&msg, &iter, &validated_params)) {
815 bad_message::ReceivedBadMessage(
816 process, bad_message::RFH_COMMIT_DESERIALIZATION_FAILED);
817 return;
819 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
820 "url", validated_params.url.possibly_invalid_spec());
822 // Sanity-check the page transition for frame type.
823 DCHECK_EQ(ui::PageTransitionIsMainFrame(validated_params.transition),
824 !GetParent());
826 // If we're waiting for a cross-site beforeunload ack from this renderer and
827 // we receive a Navigate message from the main frame, then the renderer was
828 // navigating already and sent it before hearing the FrameMsg_Stop message.
829 // Treat this as an implicit beforeunload ack to allow the pending navigation
830 // to continue.
831 if (is_waiting_for_beforeunload_ack_ &&
832 unload_ack_is_for_navigation_ &&
833 !GetParent()) {
834 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
835 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
838 // If we're waiting for an unload ack from this renderer and we receive a
839 // Navigate message, then the renderer was navigating before it received the
840 // unload request. It will either respond to the unload request soon or our
841 // timer will expire. Either way, we should ignore this message, because we
842 // have already committed to closing this renderer.
843 if (IsWaitingForUnloadACK())
844 return;
846 if (validated_params.report_type ==
847 FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
848 UMA_HISTOGRAM_CUSTOM_TIMES(
849 "Navigation.UI_OnCommitProvisionalLoad.Link",
850 base::TimeTicks::Now() - validated_params.ui_timestamp,
851 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
852 100);
853 } else if (validated_params.report_type ==
854 FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
855 UMA_HISTOGRAM_CUSTOM_TIMES(
856 "Navigation.UI_OnCommitProvisionalLoad.Intent",
857 base::TimeTicks::Now() - validated_params.ui_timestamp,
858 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
859 100);
862 // Attempts to commit certain off-limits URL should be caught more strictly
863 // than our FilterURL checks below. If a renderer violates this policy, it
864 // should be killed.
865 if (!CanCommitURL(validated_params.url)) {
866 VLOG(1) << "Blocked URL " << validated_params.url.spec();
867 validated_params.url = GURL(url::kAboutBlankURL);
868 // Kills the process.
869 bad_message::ReceivedBadMessage(process,
870 bad_message::RFH_CAN_COMMIT_URL_BLOCKED);
873 // Without this check, an evil renderer can trick the browser into creating
874 // a navigation entry for a banned URL. If the user clicks the back button
875 // followed by the forward button (or clicks reload, or round-trips through
876 // session restore, etc), we'll think that the browser commanded the
877 // renderer to load the URL and grant the renderer the privileges to request
878 // the URL. To prevent this attack, we block the renderer from inserting
879 // banned URLs into the navigation controller in the first place.
880 process->FilterURL(false, &validated_params.url);
881 process->FilterURL(true, &validated_params.referrer.url);
882 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
883 it != validated_params.redirects.end(); ++it) {
884 process->FilterURL(false, &(*it));
886 process->FilterURL(true, &validated_params.searchable_form_url);
888 // Without this check, the renderer can trick the browser into using
889 // filenames it can't access in a future session restore.
890 if (!render_view_host_->CanAccessFilesOfPageState(
891 validated_params.page_state)) {
892 bad_message::ReceivedBadMessage(
893 GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
894 return;
897 // If the URL does not match what the NavigationHandle expects, treat the
898 // commit as a new navigation. This can happen if an ongoing slow
899 // same-process navigation is interrupted by a synchronous renderer-initiated
900 // navigation.
901 if (navigation_handle_ &&
902 navigation_handle_->GetURL() != validated_params.url) {
903 navigation_handle_.reset();
906 // Synchronous renderer-initiated navigations will send a
907 // DidCommitProvisionalLoad IPC without a prior DidStartProvisionalLoad
908 // message.
909 if (!navigation_handle_) {
910 navigation_handle_ = NavigationHandleImpl::Create(
911 validated_params.url, frame_tree_node_->IsMainFrame(),
912 frame_tree_node_->navigator()->GetDelegate());
915 accessibility_reset_count_ = 0;
916 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
918 // For a top-level frame, there are potential security concerns associated
919 // with displaying graphics from a previously loaded page after the URL in
920 // the omnibar has been changed. It is unappealing to clear the page
921 // immediately, but if the renderer is taking a long time to issue any
922 // compositor output (possibly because of script deliberately creating this
923 // situation) then we clear it after a while anyway.
924 // See https://crbug.com/497588.
925 if (frame_tree_node_->IsMainFrame() && GetView() &&
926 !validated_params.was_within_same_page) {
927 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())
928 ->StartNewContentRenderingTimeout();
931 // PlzNavigate
932 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
933 switches::kEnableBrowserSideNavigation)) {
934 pending_commit_ = false;
938 void RenderFrameHostImpl::OnDidDropNavigation() {
939 // At the end of Navigate(), the FrameTreeNode's DidStartLoading is called to
940 // force the spinner to start, even if the renderer didn't yet begin the load.
941 // If it turns out that the renderer dropped the navigation, the spinner needs
942 // to be turned off.
943 frame_tree_node_->DidStopLoading();
944 navigation_handle_.reset();
947 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
948 if (render_widget_host_)
949 return render_widget_host_;
951 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
952 // we can remove this fallback. Currently it is only used for the main
953 // frame.
954 if (!GetParent())
955 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
957 return nullptr;
960 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
961 RenderFrameHostImpl* frame = this;
962 while (frame) {
963 if (frame->render_widget_host_)
964 return frame->render_widget_host_->GetView();
965 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
968 return render_view_host_->GetView();
971 int RenderFrameHostImpl::GetEnabledBindings() {
972 return render_view_host_->GetEnabledBindings();
975 void RenderFrameHostImpl::SetNavigationHandle(
976 scoped_ptr<NavigationHandleImpl> navigation_handle) {
977 navigation_handle_ = navigation_handle.Pass();
980 scoped_ptr<NavigationHandleImpl>
981 RenderFrameHostImpl::PassNavigationHandleOwnership() {
982 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
983 switches::kEnableBrowserSideNavigation));
984 navigation_handle_->set_is_transferring(true);
985 return navigation_handle_.Pass();
988 void RenderFrameHostImpl::OnCrossSiteResponse(
989 const GlobalRequestID& global_request_id,
990 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
991 const std::vector<GURL>& transfer_url_chain,
992 const Referrer& referrer,
993 ui::PageTransition page_transition,
994 bool should_replace_current_entry) {
995 frame_tree_node_->render_manager()->OnCrossSiteResponse(
996 this, global_request_id, cross_site_transferring_request.Pass(),
997 transfer_url_chain, referrer, page_transition,
998 should_replace_current_entry);
1001 void RenderFrameHostImpl::SwapOut(
1002 RenderFrameProxyHost* proxy,
1003 bool is_loading) {
1004 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
1005 // the operation and sends back an IPC message.
1006 // The trace event may not end properly if the ACK times out. We expect this
1007 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
1008 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
1010 // If this RenderFrameHost is not in the default state, it must have already
1011 // gone through this, therefore just return.
1012 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
1013 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
1014 return;
1017 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
1018 swapout_event_monitor_timeout_->Start(
1019 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1021 // There may be no proxy if there are no active views in the process.
1022 int proxy_routing_id = MSG_ROUTING_NONE;
1023 FrameReplicationState replication_state;
1024 if (proxy) {
1025 set_render_frame_proxy_host(proxy);
1026 proxy_routing_id = proxy->GetRoutingID();
1027 replication_state = proxy->frame_tree_node()->current_replication_state();
1030 if (IsRenderFrameLive()) {
1031 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
1032 replication_state));
1035 if (!GetParent())
1036 delegate_->SwappedOut(this);
1039 void RenderFrameHostImpl::OnBeforeUnloadACK(
1040 bool proceed,
1041 const base::TimeTicks& renderer_before_unload_start_time,
1042 const base::TimeTicks& renderer_before_unload_end_time) {
1043 TRACE_EVENT_ASYNC_END0(
1044 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1045 DCHECK(!GetParent());
1046 // If this renderer navigated while the beforeunload request was in flight, we
1047 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
1048 // can ignore this message.
1049 // However renderer might also be swapped out but we still want to proceed
1050 // with navigation, otherwise it would block future navigations. This can
1051 // happen when pending cross-site navigation is canceled by a second one just
1052 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
1053 // but second navigation is started from the beginning.
1054 if (!is_waiting_for_beforeunload_ack_) {
1055 return;
1057 DCHECK(!send_before_unload_start_time_.is_null());
1059 // Sets a default value for before_unload_end_time so that the browser
1060 // survives a hacked renderer.
1061 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
1062 if (!renderer_before_unload_start_time.is_null() &&
1063 !renderer_before_unload_end_time.is_null()) {
1064 // When passing TimeTicks across process boundaries, we need to compensate
1065 // for any skew between the processes. Here we are converting the
1066 // renderer's notion of before_unload_end_time to TimeTicks in the browser
1067 // process. See comments in inter_process_time_ticks_converter.h for more.
1068 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
1069 InterProcessTimeTicksConverter converter(
1070 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
1071 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
1072 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
1073 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1074 LocalTimeTicks browser_before_unload_end_time =
1075 converter.ToLocalTimeTicks(
1076 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1077 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1079 // Collect UMA on the inter-process skew.
1080 bool is_skew_additive = false;
1081 if (converter.IsSkewAdditiveForMetrics()) {
1082 is_skew_additive = true;
1083 base::TimeDelta skew = converter.GetSkewForMetrics();
1084 if (skew >= base::TimeDelta()) {
1085 UMA_HISTOGRAM_TIMES(
1086 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
1087 } else {
1088 UMA_HISTOGRAM_TIMES(
1089 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
1092 UMA_HISTOGRAM_BOOLEAN(
1093 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
1094 is_skew_additive);
1096 base::TimeDelta on_before_unload_overhead_time =
1097 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1098 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1099 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1100 on_before_unload_overhead_time);
1102 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1103 renderer_before_unload_start_time, renderer_before_unload_end_time);
1105 // Resets beforeunload waiting state.
1106 is_waiting_for_beforeunload_ack_ = false;
1107 render_view_host_->decrement_in_flight_event_count();
1108 render_view_host_->StopHangMonitorTimeout();
1109 send_before_unload_start_time_ = base::TimeTicks();
1111 // PlzNavigate: if the ACK is for a navigation, send it to the Navigator to
1112 // have the current navigation stop/proceed. Otherwise, send it to the
1113 // RenderFrameHostManager which handles closing.
1114 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1115 switches::kEnableBrowserSideNavigation) &&
1116 unload_ack_is_for_navigation_) {
1117 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1118 // Navigator.
1119 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1120 frame_tree_node_, proceed);
1121 } else {
1122 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1123 unload_ack_is_for_navigation_, proceed,
1124 before_unload_end_time);
1127 // If canceled, notify the delegate to cancel its pending navigation entry.
1128 if (!proceed)
1129 render_view_host_->GetDelegate()->DidCancelLoading();
1132 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1133 return render_view_host_->is_waiting_for_close_ack_ ||
1134 rfh_state_ == STATE_PENDING_SWAP_OUT;
1137 void RenderFrameHostImpl::OnSwapOutACK() {
1138 OnSwappedOut();
1141 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1142 if (frame_tree_node_->IsMainFrame()) {
1143 // Keep the termination status so we can get at it later when we
1144 // need to know why it died.
1145 render_view_host_->render_view_termination_status_ =
1146 static_cast<base::TerminationStatus>(status);
1149 // Reset frame tree state associated with this process. This must happen
1150 // before RenderViewTerminated because observers expect the subframes of any
1151 // affected frames to be cleared first.
1152 // Note: When a RenderFrameHost is swapped out there is a different one
1153 // which is the current host. In this case, the FrameTreeNode state must
1154 // not be reset.
1155 if (!is_swapped_out())
1156 frame_tree_node_->ResetForNewProcess();
1158 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1159 // reset.
1160 SetRenderFrameCreated(false);
1161 InvalidateMojoConnection();
1163 // Execute any pending AX tree snapshot callbacks with an empty response,
1164 // since we're never going to get a response from this renderer.
1165 for (const auto& iter : ax_tree_snapshot_callbacks_)
1166 iter.second.Run(ui::AXTreeUpdate<ui::AXNodeData>());
1167 ax_tree_snapshot_callbacks_.clear();
1169 // Note: don't add any more code at this point in the function because
1170 // |this| may be deleted. Any additional cleanup should happen before
1171 // the last block of code here.
1174 void RenderFrameHostImpl::OnSwappedOut() {
1175 // Ignore spurious swap out ack.
1176 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1177 return;
1179 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1180 swapout_event_monitor_timeout_->Stop();
1183 // If this is a main frame RFH that's about to be deleted, update its RVH's
1184 // swapped-out state here, since SetState won't be called once this RFH is
1185 // deleted below. https://crbug.com/505887
1186 if (frame_tree_node_->IsMainFrame() &&
1187 frame_tree_node_->render_manager()->IsPendingDeletion(this)) {
1188 render_view_host_->set_is_active(false);
1189 render_view_host_->set_is_swapped_out(true);
1192 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1193 // We are now deleted.
1194 return;
1197 // If this RFH wasn't pending deletion, then it is now swapped out.
1198 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1201 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1202 // Validate the URLs in |params|. If the renderer can't request the URLs
1203 // directly, don't show them in the context menu.
1204 ContextMenuParams validated_params(params);
1205 RenderProcessHost* process = GetProcess();
1207 // We don't validate |unfiltered_link_url| so that this field can be used
1208 // when users want to copy the original link URL.
1209 process->FilterURL(true, &validated_params.link_url);
1210 process->FilterURL(true, &validated_params.src_url);
1211 process->FilterURL(false, &validated_params.page_url);
1212 process->FilterURL(true, &validated_params.frame_url);
1214 delegate_->ShowContextMenu(this, validated_params);
1217 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1218 int id, const base::ListValue& result) {
1219 const base::Value* result_value;
1220 if (!result.Get(0, &result_value)) {
1221 // Programming error or rogue renderer.
1222 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1223 return;
1226 std::map<int, JavaScriptResultCallback>::iterator it =
1227 javascript_callbacks_.find(id);
1228 if (it != javascript_callbacks_.end()) {
1229 it->second.Run(result_value);
1230 javascript_callbacks_.erase(it);
1231 } else {
1232 NOTREACHED() << "Received script response for unknown request";
1236 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1237 auto it = visual_state_callbacks_.find(id);
1238 if (it != visual_state_callbacks_.end()) {
1239 it->second.Run(true);
1240 visual_state_callbacks_.erase(it);
1241 } else {
1242 NOTREACHED() << "Received script response for unknown request";
1246 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1247 const base::string16& message,
1248 const base::string16& default_prompt,
1249 const GURL& frame_url,
1250 JavaScriptMessageType type,
1251 IPC::Message* reply_msg) {
1252 // While a JS message dialog is showing, tabs in the same process shouldn't
1253 // process input events.
1254 GetProcess()->SetIgnoreInputEvents(true);
1255 render_view_host_->StopHangMonitorTimeout();
1256 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1257 frame_url, type, reply_msg);
1260 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1261 const GURL& frame_url,
1262 const base::string16& message,
1263 bool is_reload,
1264 IPC::Message* reply_msg) {
1265 // While a JS beforeunload dialog is showing, tabs in the same process
1266 // shouldn't process input events.
1267 GetProcess()->SetIgnoreInputEvents(true);
1268 render_view_host_->StopHangMonitorTimeout();
1269 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1272 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1273 const base::string16& content,
1274 size_t start_offset,
1275 size_t end_offset) {
1276 render_view_host_->OnTextSurroundingSelectionResponse(
1277 content, start_offset, end_offset);
1280 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1281 delegate_->DidAccessInitialDocument();
1284 void RenderFrameHostImpl::OnDidChangeOpener(int32 opener_routing_id) {
1285 frame_tree_node_->render_manager()->DidChangeOpener(opener_routing_id,
1286 GetSiteInstance());
1289 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1290 std::string old_name = frame_tree_node()->frame_name();
1291 frame_tree_node()->SetFrameName(name);
1292 if (old_name.empty() && !name.empty())
1293 frame_tree_node_->render_manager()->CreateProxiesForNewNamedFrame();
1294 delegate_->DidChangeName(this, name);
1297 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1298 // Update the RVH's current page ID so that future IPCs from the renderer
1299 // correspond to the new page.
1300 render_view_host_->page_id_ = page_id;
1303 void RenderFrameHostImpl::OnDidChangeSandboxFlags(
1304 int32 frame_routing_id,
1305 blink::WebSandboxFlags flags) {
1306 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1307 FrameTreeNode* child =
1308 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1309 if (!child)
1310 return;
1312 // Ensure that a frame can only update sandbox flags for its immediate
1313 // children. If this is not the case, the renderer is considered malicious
1314 // and is killed.
1315 if (child->parent() != frame_tree_node()) {
1316 bad_message::ReceivedBadMessage(GetProcess(),
1317 bad_message::RFH_SANDBOX_FLAGS);
1318 return;
1321 child->set_sandbox_flags(flags);
1323 // Notify the RenderFrame if it lives in a different process from its
1324 // parent. The frame's proxies in other processes also need to learn about
1325 // the updated sandbox flags, but these notifications are sent later in
1326 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1327 // navigates and the new sandbox flags take effect.
1328 RenderFrameHost* child_rfh = child->current_frame_host();
1329 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1330 child_rfh->Send(
1331 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1335 void RenderFrameHostImpl::OnUpdateTitle(
1336 const base::string16& title,
1337 blink::WebTextDirection title_direction) {
1338 // This message is only sent for top-level frames. TODO(avi): when frame tree
1339 // mirroring works correctly, add a check here to enforce it.
1340 if (title.length() > kMaxTitleChars) {
1341 NOTREACHED() << "Renderer sent too many characters in title.";
1342 return;
1345 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1346 WebTextDirectionToChromeTextDirection(
1347 title_direction));
1350 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1351 // This message is only sent for top-level frames. TODO(avi): when frame tree
1352 // mirroring works correctly, add a check here to enforce it.
1353 delegate_->UpdateEncoding(this, encoding_name);
1356 void RenderFrameHostImpl::OnBeginNavigation(
1357 const CommonNavigationParams& common_params,
1358 const BeginNavigationParams& begin_params,
1359 scoped_refptr<ResourceRequestBody> body) {
1360 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1361 switches::kEnableBrowserSideNavigation));
1362 CommonNavigationParams validated_params = common_params;
1363 GetProcess()->FilterURL(false, &validated_params.url);
1364 frame_tree_node()->navigator()->OnBeginNavigation(
1365 frame_tree_node(), validated_params, begin_params, body);
1368 void RenderFrameHostImpl::OnDispatchLoad() {
1369 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
1370 // Only frames with an out-of-process parent frame should be sending this
1371 // message.
1372 RenderFrameProxyHost* proxy =
1373 frame_tree_node()->render_manager()->GetProxyToParent();
1374 if (!proxy) {
1375 bad_message::ReceivedBadMessage(GetProcess(),
1376 bad_message::RFH_NO_PROXY_TO_PARENT);
1377 return;
1380 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1383 void RenderFrameHostImpl::OnAccessibilityEvents(
1384 const std::vector<AccessibilityHostMsg_EventParams>& params,
1385 int reset_token) {
1386 // Don't process this IPC if either we're waiting on a reset and this
1387 // IPC doesn't have the matching token ID, or if we're not waiting on a
1388 // reset but this message includes a reset token.
1389 if (accessibility_reset_token_ != reset_token) {
1390 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1391 return;
1393 accessibility_reset_token_ = 0;
1395 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1396 frame_tree_node_->frame_tree()
1397 ->GetMainFrame()
1398 ->render_view_host_->GetView());
1400 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1401 if ((accessibility_mode != AccessibilityModeOff) && view &&
1402 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1403 if (accessibility_mode & AccessibilityModeFlagPlatform)
1404 GetOrCreateBrowserAccessibilityManager();
1406 std::vector<AXEventNotificationDetails> details;
1407 details.reserve(params.size());
1408 for (size_t i = 0; i < params.size(); ++i) {
1409 const AccessibilityHostMsg_EventParams& param = params[i];
1410 AXEventNotificationDetails detail;
1411 detail.event_type = param.event_type;
1412 detail.id = param.id;
1413 detail.ax_tree_id = GetAXTreeID();
1414 detail.update.node_id_to_clear = param.update.node_id_to_clear;
1415 detail.update.nodes.resize(param.update.nodes.size());
1416 for (size_t i = 0; i < param.update.nodes.size(); ++i) {
1417 AXContentNodeDataToAXNodeData(param.update.nodes[i],
1418 &detail.update.nodes[i]);
1420 details.push_back(detail);
1423 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1424 if (browser_accessibility_manager_)
1425 browser_accessibility_manager_->OnAccessibilityEvents(details);
1428 // Send the updates to the automation extension API.
1429 delegate_->AccessibilityEventReceived(details);
1431 // For testing only.
1432 if (!accessibility_testing_callback_.is_null()) {
1433 for (size_t i = 0; i < details.size(); i++) {
1434 const AXEventNotificationDetails& detail = details[i];
1435 if (static_cast<int>(detail.event_type) < 0)
1436 continue;
1438 if (!ax_tree_for_testing_) {
1439 if (browser_accessibility_manager_) {
1440 ax_tree_for_testing_.reset(new ui::AXTree(
1441 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1442 } else {
1443 ax_tree_for_testing_.reset(new ui::AXTree());
1444 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1445 << ax_tree_for_testing_->error();
1447 } else {
1448 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1449 << ax_tree_for_testing_->error();
1451 accessibility_testing_callback_.Run(detail.event_type, detail.id);
1456 // Always send an ACK or the renderer can be in a bad state.
1457 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1460 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1461 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1462 if (accessibility_reset_token_)
1463 return;
1465 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1466 render_view_host_->GetView());
1467 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1468 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1469 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1470 BrowserAccessibilityManager* manager =
1471 GetOrCreateBrowserAccessibilityManager();
1472 if (manager)
1473 manager->OnLocationChanges(params);
1475 // TODO(aboxhall): send location change events to web contents observers too
1479 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1480 const AccessibilityHostMsg_FindInPageResultParams& params) {
1481 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1482 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1483 BrowserAccessibilityManager* manager =
1484 GetOrCreateBrowserAccessibilityManager();
1485 if (manager) {
1486 manager->OnFindInPageResult(
1487 params.request_id, params.match_index, params.start_id,
1488 params.start_offset, params.end_id, params.end_offset);
1493 void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
1494 int callback_id,
1495 const ui::AXTreeUpdate<AXContentNodeData>& snapshot) {
1496 const auto& it = ax_tree_snapshot_callbacks_.find(callback_id);
1497 if (it != ax_tree_snapshot_callbacks_.end()) {
1498 ui::AXTreeUpdate<ui::AXNodeData> dst_snapshot;
1499 dst_snapshot.nodes.resize(snapshot.nodes.size());
1500 for (size_t i = 0; i < snapshot.nodes.size(); ++i) {
1501 AXContentNodeDataToAXNodeData(snapshot.nodes[i],
1502 &dst_snapshot.nodes[i]);
1504 it->second.Run(dst_snapshot);
1505 ax_tree_snapshot_callbacks_.erase(it);
1506 } else {
1507 NOTREACHED() << "Received AX tree snapshot response for unknown id";
1511 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1512 if (enter_fullscreen)
1513 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1514 else
1515 delegate_->ExitFullscreenMode();
1517 // The previous call might change the fullscreen state. We need to make sure
1518 // the renderer is aware of that, which is done via the resize message.
1519 render_view_host_->WasResized();
1522 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
1523 // Any main frame load to a new document should reset the load since it will
1524 // replace the current page and any frames.
1525 if (to_different_document && !GetParent())
1526 is_loading_ = false;
1528 // This method should never be called when the frame is loading.
1529 // Unfortunately, it can happen if a history navigation happens during a
1530 // BeforeUnload or Unload event.
1531 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1532 // refactored in Blink. See crbug.com/466089
1533 if (is_loading_) {
1534 LOG(WARNING) << "OnDidStartLoading was called twice.";
1535 return;
1538 frame_tree_node_->DidStartLoading(to_different_document);
1539 is_loading_ = true;
1542 void RenderFrameHostImpl::OnDidStopLoading() {
1543 // This method should never be called when the frame is not loading.
1544 // Unfortunately, it can happen if a history navigation happens during a
1545 // BeforeUnload or Unload event.
1546 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1547 // refactored in Blink. See crbug.com/466089
1548 if (!is_loading_) {
1549 LOG(WARNING) << "OnDidStopLoading was called twice.";
1550 return;
1553 is_loading_ = false;
1554 frame_tree_node_->DidStopLoading();
1555 navigation_handle_.reset();
1558 void RenderFrameHostImpl::OnDidChangeLoadProgress(double load_progress) {
1559 frame_tree_node_->DidChangeLoadProgress(load_progress);
1562 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1563 void RenderFrameHostImpl::OnShowPopup(
1564 const FrameHostMsg_ShowPopup_Params& params) {
1565 RenderViewHostDelegateView* view =
1566 render_view_host_->delegate_->GetDelegateView();
1567 if (view) {
1568 view->ShowPopupMenu(this,
1569 params.bounds,
1570 params.item_height,
1571 params.item_font_size,
1572 params.selected_item,
1573 params.popup_items,
1574 params.right_aligned,
1575 params.allow_multiple_selection);
1579 void RenderFrameHostImpl::OnHidePopup() {
1580 RenderViewHostDelegateView* view =
1581 render_view_host_->delegate_->GetDelegateView();
1582 if (view)
1583 view->HidePopupMenu();
1585 #endif
1587 void RenderFrameHostImpl::RegisterMojoServices() {
1588 GeolocationServiceContext* geolocation_service_context =
1589 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1590 if (geolocation_service_context) {
1591 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1592 // can perform permissions checks once site isolation is complete.
1593 // crbug.com/426384
1594 GetServiceRegistry()->AddService<GeolocationService>(
1595 base::Bind(&GeolocationServiceContext::CreateService,
1596 base::Unretained(geolocation_service_context),
1597 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1598 base::Unretained(this))));
1601 if (!permission_service_context_)
1602 permission_service_context_.reset(new PermissionServiceContext(this));
1604 GetServiceRegistry()->AddService<PermissionService>(
1605 base::Bind(&PermissionServiceContext::CreateService,
1606 base::Unretained(permission_service_context_.get())));
1608 GetServiceRegistry()->AddService<presentation::PresentationService>(
1609 base::Bind(&PresentationServiceImpl::CreateMojoService,
1610 base::Unretained(this)));
1612 if (!frame_mojo_shell_)
1613 frame_mojo_shell_.reset(new FrameMojoShell(this));
1615 GetServiceRegistry()->AddService<mojo::Shell>(base::Bind(
1616 &FrameMojoShell::BindRequest, base::Unretained(frame_mojo_shell_.get())));
1618 #if defined(ENABLE_WEBVR)
1619 const base::CommandLine& browser_command_line =
1620 *base::CommandLine::ForCurrentProcess();
1622 if (browser_command_line.HasSwitch(switches::kEnableWebVR)) {
1623 GetServiceRegistry()->AddService<VRService>(
1624 base::Bind(&VRDeviceManager::BindRequest));
1626 #endif
1629 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1630 // Only main frames should be swapped out and retained inside a proxy host.
1631 if (rfh_state == STATE_SWAPPED_OUT)
1632 CHECK(!GetParent());
1634 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1635 // out status of a RenderFrameHost gets flipped to/from active.
1636 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1637 GetSiteInstance()->increment_active_frame_count();
1638 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1639 GetSiteInstance()->decrement_active_frame_count();
1641 // The active and swapped out state of the RVH is determined by its main
1642 // frame, since subframes should have their own widgets.
1643 if (frame_tree_node_->IsMainFrame()) {
1644 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1645 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1648 // Whenever we change the RFH state to and from active or swapped out state,
1649 // we should not be waiting for beforeunload or close acks. We clear them
1650 // here to be safe, since they can cause navigations to be ignored in
1651 // OnDidCommitProvisionalLoad.
1652 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1653 if (rfh_state == STATE_DEFAULT ||
1654 rfh_state == STATE_SWAPPED_OUT ||
1655 rfh_state_ == STATE_DEFAULT ||
1656 rfh_state_ == STATE_SWAPPED_OUT) {
1657 if (is_waiting_for_beforeunload_ack_) {
1658 is_waiting_for_beforeunload_ack_ = false;
1659 render_view_host_->decrement_in_flight_event_count();
1660 render_view_host_->StopHangMonitorTimeout();
1662 send_before_unload_start_time_ = base::TimeTicks();
1663 render_view_host_->is_waiting_for_close_ack_ = false;
1665 rfh_state_ = rfh_state;
1668 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1669 // TODO(creis): We should also check for WebUI pages here. Also, when the
1670 // out-of-process iframes implementation is ready, we should check for
1671 // cross-site URLs that are not allowed to commit in this process.
1673 // Give the client a chance to disallow URLs from committing.
1674 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1677 void RenderFrameHostImpl::Navigate(
1678 const CommonNavigationParams& common_params,
1679 const StartNavigationParams& start_params,
1680 const RequestNavigationParams& request_params) {
1681 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1682 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1683 switches::kEnableBrowserSideNavigation));
1685 UpdatePermissionsForNavigation(common_params, request_params);
1687 // Only send the message if we aren't suspended at the start of a cross-site
1688 // request.
1689 if (navigations_suspended_) {
1690 // Shouldn't be possible to have a second navigation while suspended, since
1691 // navigations will only be suspended during a cross-site request. If a
1692 // second navigation occurs, RenderFrameHostManager will cancel this pending
1693 // RFH and create a new pending RFH.
1694 DCHECK(!suspended_nav_params_.get());
1695 suspended_nav_params_.reset(
1696 new NavigationParams(common_params, start_params, request_params));
1697 } else {
1698 // Get back to a clean state, in case we start a new navigation without
1699 // completing a RFH swap or unload handler.
1700 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1702 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1703 request_params));
1706 // Force the throbber to start. This is done because Blink's "started loading"
1707 // message will be received asynchronously from the UI of the browser. But the
1708 // throbber needs to be kept in sync with what's happening in the UI. For
1709 // example, the throbber will start immediately when the user navigates even
1710 // if the renderer is delayed. There is also an issue with the throbber
1711 // starting because the WebUI (which controls whether the favicon is
1712 // displayed) happens synchronously. If the start loading messages was
1713 // asynchronous, then the default favicon would flash in.
1715 // Blink doesn't send throb notifications for JavaScript URLs, so it is not
1716 // done here either.
1717 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1718 frame_tree_node_->DidStartLoading(true);
1721 void RenderFrameHostImpl::NavigateToInterstitialURL(const GURL& data_url) {
1722 DCHECK(data_url.SchemeIs(url::kDataScheme));
1723 CommonNavigationParams common_params(
1724 data_url, Referrer(), ui::PAGE_TRANSITION_LINK,
1725 FrameMsg_Navigate_Type::NORMAL, false, false, base::TimeTicks::Now(),
1726 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
1727 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1728 switches::kEnableBrowserSideNavigation)) {
1729 CommitNavigation(nullptr, nullptr, common_params,
1730 RequestNavigationParams());
1731 } else {
1732 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1736 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1737 SiteInstance* source_site_instance) {
1738 GURL validated_url(params.url);
1739 GetProcess()->FilterURL(false, &validated_url);
1741 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1742 validated_url.possibly_invalid_spec());
1743 frame_tree_node_->navigator()->RequestOpenURL(
1744 this, validated_url, source_site_instance, params.referrer,
1745 params.disposition, params.should_replace_current_entry,
1746 params.user_gesture);
1749 void RenderFrameHostImpl::Stop() {
1750 Send(new FrameMsg_Stop(routing_id_));
1753 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1754 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1755 // the handler ran and allowed the navigation to proceed.
1756 if (!ShouldDispatchBeforeUnload()) {
1757 DCHECK(!(base::CommandLine::ForCurrentProcess()->HasSwitch(
1758 switches::kEnableBrowserSideNavigation) &&
1759 for_navigation));
1760 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1761 for_navigation, true, base::TimeTicks::Now());
1762 return;
1764 TRACE_EVENT_ASYNC_BEGIN0(
1765 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1767 // This may be called more than once (if the user clicks the tab close button
1768 // several times, or if she clicks the tab close button then the browser close
1769 // button), and we only send the message once.
1770 if (is_waiting_for_beforeunload_ack_) {
1771 // Some of our close messages could be for the tab, others for cross-site
1772 // transitions. We always want to think it's for closing the tab if any
1773 // of the messages were, since otherwise it might be impossible to close
1774 // (if there was a cross-site "close" request pending when the user clicked
1775 // the close button). We want to keep the "for cross site" flag only if
1776 // both the old and the new ones are also for cross site.
1777 unload_ack_is_for_navigation_ =
1778 unload_ack_is_for_navigation_ && for_navigation;
1779 } else {
1780 // Start the hang monitor in case the renderer hangs in the beforeunload
1781 // handler.
1782 is_waiting_for_beforeunload_ack_ = true;
1783 unload_ack_is_for_navigation_ = for_navigation;
1784 // Increment the in-flight event count, to ensure that input events won't
1785 // cancel the timeout timer.
1786 render_view_host_->increment_in_flight_event_count();
1787 render_view_host_->StartHangMonitorTimeout(
1788 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1789 send_before_unload_start_time_ = base::TimeTicks::Now();
1790 Send(new FrameMsg_BeforeUnload(routing_id_));
1794 bool RenderFrameHostImpl::ShouldDispatchBeforeUnload() {
1795 // TODO(creis): Support beforeunload on subframes.
1796 return !GetParent() && IsRenderFrameLive();
1799 void RenderFrameHostImpl::UpdateOpener() {
1800 // This frame (the frame whose opener is being updated) might not have had
1801 // proxies for the new opener chain in its SiteInstance. Make sure they
1802 // exist.
1803 if (frame_tree_node_->opener()) {
1804 frame_tree_node_->opener()->render_manager()->CreateOpenerProxies(
1805 GetSiteInstance(), frame_tree_node_);
1808 int opener_routing_id =
1809 frame_tree_node_->render_manager()->GetOpenerRoutingID(GetSiteInstance());
1810 Send(new FrameMsg_UpdateOpener(GetRoutingID(), opener_routing_id));
1813 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1814 size_t after) {
1815 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1818 void RenderFrameHostImpl::JavaScriptDialogClosed(
1819 IPC::Message* reply_msg,
1820 bool success,
1821 const base::string16& user_input,
1822 bool dialog_was_suppressed) {
1823 GetProcess()->SetIgnoreInputEvents(false);
1824 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1826 // If we are executing as part of (before)unload event handling, we don't
1827 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1828 // leave the current page. In this case, use the regular timeout value used
1829 // during the (before)unload handling.
1830 if (is_waiting) {
1831 render_view_host_->StartHangMonitorTimeout(
1832 success
1833 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1834 : render_view_host_->hung_renderer_delay_);
1837 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1838 success, user_input);
1839 Send(reply_msg);
1841 // If we are waiting for an unload or beforeunload ack and the user has
1842 // suppressed messages, kill the tab immediately; a page that's spamming
1843 // alerts in onbeforeunload is presumably malicious, so there's no point in
1844 // continuing to run its script and dragging out the process.
1845 // This must be done after sending the reply since RenderView can't close
1846 // correctly while waiting for a response.
1847 if (is_waiting && dialog_was_suppressed)
1848 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1851 // PlzNavigate
1852 void RenderFrameHostImpl::CommitNavigation(
1853 ResourceResponse* response,
1854 scoped_ptr<StreamHandle> body,
1855 const CommonNavigationParams& common_params,
1856 const RequestNavigationParams& request_params) {
1857 DCHECK((response && body.get()) ||
1858 !ShouldMakeNetworkRequestForURL(common_params.url));
1859 UpdatePermissionsForNavigation(common_params, request_params);
1861 // Get back to a clean state, in case we start a new navigation without
1862 // completing a RFH swap or unload handler.
1863 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1865 const GURL body_url = body.get() ? body->GetURL() : GURL();
1866 const ResourceResponseHead head = response ?
1867 response->head : ResourceResponseHead();
1868 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1869 request_params));
1870 // TODO(clamy): Check if we should start the throbber for non javascript urls
1871 // here.
1873 // TODO(clamy): Release the stream handle once the renderer has finished
1874 // reading it.
1875 stream_handle_ = body.Pass();
1877 // When navigating to a Javascript url, no commit is expected from the
1878 // RenderFrameHost, nor should the throbber start.
1879 if (!common_params.url.SchemeIs(url::kJavaScriptScheme)) {
1880 pending_commit_ = true;
1881 is_loading_ = true;
1883 frame_tree_node_->ResetNavigationRequest(true);
1886 void RenderFrameHostImpl::FailedNavigation(
1887 const CommonNavigationParams& common_params,
1888 const RequestNavigationParams& request_params,
1889 bool has_stale_copy_in_cache,
1890 int error_code) {
1891 // Get back to a clean state, in case a new navigation started without
1892 // completing a RFH swap or unload handler.
1893 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1895 Send(new FrameMsg_FailedNavigation(routing_id_, common_params, request_params,
1896 has_stale_copy_in_cache, error_code));
1898 // An error page is expected to commit, hence why is_loading_ is set to true.
1899 is_loading_ = true;
1900 frame_tree_node_->ResetNavigationRequest(true);
1903 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1904 if (service_registry_.get())
1905 return;
1907 service_registry_.reset(new ServiceRegistryImpl());
1908 if (!GetProcess()->GetServiceRegistry())
1909 return;
1911 RegisterMojoServices();
1912 RenderFrameSetupPtr setup;
1913 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(
1914 mojo::GetProxy(&setup));
1916 mojo::ServiceProviderPtr exposed_services;
1917 service_registry_->Bind(GetProxy(&exposed_services));
1919 mojo::ServiceProviderPtr services;
1920 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1921 exposed_services.Pass());
1922 service_registry_->BindRemoteServiceProvider(services.Pass());
1924 #if defined(OS_ANDROID)
1925 service_registry_android_.reset(
1926 new ServiceRegistryAndroid(service_registry_.get()));
1927 ServiceRegistrarAndroid::RegisterFrameHostServices(
1928 service_registry_android_.get());
1929 #endif
1932 void RenderFrameHostImpl::InvalidateMojoConnection() {
1933 #if defined(OS_ANDROID)
1934 // The Android-specific service registry has a reference to
1935 // |service_registry_| and thus must be torn down first.
1936 service_registry_android_.reset();
1937 #endif
1939 service_registry_.reset();
1941 // Disconnect with ImageDownloader Mojo service in RenderFrame.
1942 mojo_image_downloader_.reset();
1945 bool RenderFrameHostImpl::IsFocused() {
1946 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1947 // returning nullptr in some cases. See https://crbug.com/455245.
1948 return RenderWidgetHostImpl::From(
1949 GetView()->GetRenderWidgetHost())->is_focused() &&
1950 frame_tree_->GetFocusedFrame() &&
1951 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1952 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1955 const image_downloader::ImageDownloaderPtr&
1956 RenderFrameHostImpl::GetMojoImageDownloader() {
1957 if (!mojo_image_downloader_.get() && GetServiceRegistry()) {
1958 GetServiceRegistry()->ConnectToRemoteService(
1959 mojo::GetProxy(&mojo_image_downloader_));
1961 return mojo_image_downloader_;
1964 bool RenderFrameHostImpl::IsSameSiteInstance(
1965 RenderFrameHostImpl* other_render_frame_host) {
1966 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1967 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1968 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1969 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1972 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1973 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1976 void RenderFrameHostImpl::RequestAXTreeSnapshot(
1977 AXTreeSnapshotCallback callback) {
1978 static int next_id = 1;
1979 int callback_id = next_id++;
1980 Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
1981 ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
1984 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1985 const base::Callback<void(ui::AXEvent, int)>& callback) {
1986 accessibility_testing_callback_ = callback;
1989 void RenderFrameHostImpl::SetTextTrackSettings(
1990 const FrameMsg_TextTrackSettings_Params& params) {
1991 DCHECK(!GetParent());
1992 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
1995 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1996 return ax_tree_for_testing_.get();
1999 BrowserAccessibilityManager*
2000 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
2001 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2002 frame_tree_node_->frame_tree()
2003 ->GetMainFrame()
2004 ->render_view_host_->GetView());
2005 if (view &&
2006 !browser_accessibility_manager_ &&
2007 !no_create_browser_accessibility_manager_for_testing_) {
2008 browser_accessibility_manager_.reset(
2009 view->CreateBrowserAccessibilityManager(this));
2010 if (browser_accessibility_manager_)
2011 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
2012 else
2013 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
2015 return browser_accessibility_manager_.get();
2018 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
2019 int request_id) {
2020 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
2021 if (accessibility_mode & AccessibilityModeFlagPlatform) {
2022 BrowserAccessibilityManager* manager =
2023 GetOrCreateBrowserAccessibilityManager();
2024 if (manager)
2025 manager->ActivateFindInPageResult(request_id);
2029 void RenderFrameHostImpl::InsertVisualStateCallback(
2030 const VisualStateCallback& callback) {
2031 static uint64 next_id = 1;
2032 uint64 key = next_id++;
2033 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
2034 visual_state_callbacks_.insert(std::make_pair(key, callback));
2037 bool RenderFrameHostImpl::IsRenderFrameLive() {
2038 bool is_live = GetProcess()->HasConnection() && render_frame_created_;
2040 // Sanity check: the RenderView should always be live if the RenderFrame is.
2041 DCHECK_IMPLIES(is_live, render_view_host_->IsRenderViewLive());
2043 return is_live;
2046 #if defined(OS_WIN)
2048 void RenderFrameHostImpl::SetParentNativeViewAccessible(
2049 gfx::NativeViewAccessible accessible_parent) {
2050 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2051 render_view_host_->GetView());
2052 if (view)
2053 view->SetParentNativeViewAccessible(accessible_parent);
2056 gfx::NativeViewAccessible
2057 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
2058 return delegate_->GetParentNativeViewAccessible();
2061 #elif defined(OS_MACOSX)
2063 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
2064 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
2067 void RenderFrameHostImpl::DidCancelPopupMenu() {
2068 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
2071 #elif defined(OS_ANDROID)
2073 void RenderFrameHostImpl::DidSelectPopupMenuItems(
2074 const std::vector<int>& selected_indices) {
2075 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
2078 void RenderFrameHostImpl::DidCancelPopupMenu() {
2079 Send(new FrameMsg_SelectPopupMenuItems(
2080 routing_id_, true, std::vector<int>()));
2083 #endif
2085 void RenderFrameHostImpl::SetNavigationsSuspended(
2086 bool suspend,
2087 const base::TimeTicks& proceed_time) {
2088 // This should only be called to toggle the state.
2089 DCHECK(navigations_suspended_ != suspend);
2091 navigations_suspended_ = suspend;
2092 if (navigations_suspended_) {
2093 TRACE_EVENT_ASYNC_BEGIN0("navigation",
2094 "RenderFrameHostImpl navigation suspended", this);
2095 } else {
2096 TRACE_EVENT_ASYNC_END0("navigation",
2097 "RenderFrameHostImpl navigation suspended", this);
2100 if (!suspend && suspended_nav_params_) {
2101 // There's navigation message params waiting to be sent. Now that we're not
2102 // suspended anymore, resume navigation by sending them. If we were swapped
2103 // out, we should also stop filtering out the IPC messages now.
2104 SetState(RenderFrameHostImpl::STATE_DEFAULT);
2106 DCHECK(!proceed_time.is_null());
2107 suspended_nav_params_->request_params.browser_navigation_start =
2108 proceed_time;
2109 Send(new FrameMsg_Navigate(routing_id_,
2110 suspended_nav_params_->common_params,
2111 suspended_nav_params_->start_params,
2112 suspended_nav_params_->request_params));
2113 suspended_nav_params_.reset();
2117 void RenderFrameHostImpl::CancelSuspendedNavigations() {
2118 // Clear any state if a pending navigation is canceled or preempted.
2119 if (suspended_nav_params_)
2120 suspended_nav_params_.reset();
2122 TRACE_EVENT_ASYNC_END0("navigation",
2123 "RenderFrameHostImpl navigation suspended", this);
2124 navigations_suspended_ = false;
2127 void RenderFrameHostImpl::DidUseGeolocationPermission() {
2128 PermissionManager* permission_manager =
2129 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
2130 if (!permission_manager)
2131 return;
2133 permission_manager->RegisterPermissionUsage(
2134 PermissionType::GEOLOCATION,
2135 GetLastCommittedURL().GetOrigin(),
2136 frame_tree_node()->frame_tree()->GetMainFrame()
2137 ->GetLastCommittedURL().GetOrigin());
2140 void RenderFrameHostImpl::UpdatePermissionsForNavigation(
2141 const CommonNavigationParams& common_params,
2142 const RequestNavigationParams& request_params) {
2143 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
2144 // so do not grant them the ability to request additional URLs.
2145 if (!GetProcess()->IsForGuestsOnly()) {
2146 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2147 GetProcess()->GetID(), common_params.url);
2148 if (common_params.url.SchemeIs(url::kDataScheme) &&
2149 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
2150 // If 'data:' is used, and we have a 'file:' base url, grant access to
2151 // local files.
2152 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2153 GetProcess()->GetID(), common_params.base_url_for_data_url);
2157 // We may be returning to an existing NavigationEntry that had been granted
2158 // file access. If this is a different process, we will need to grant the
2159 // access again. The files listed in the page state are validated when they
2160 // are received from the renderer to prevent abuse.
2161 if (request_params.page_state.IsValid()) {
2162 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
2166 bool RenderFrameHostImpl::CanExecuteJavaScript() {
2167 return g_allow_injecting_javascript ||
2168 !frame_tree_node_->current_url().is_valid() ||
2169 frame_tree_node_->current_url().SchemeIs(kChromeDevToolsScheme) ||
2170 ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2171 GetProcess()->GetID()) ||
2172 // It's possible to load about:blank in a Web UI renderer.
2173 // See http://crbug.com/42547
2174 (frame_tree_node_->current_url().spec() == url::kAboutBlankURL) ||
2175 // InterstitialPageImpl should be the only case matching this.
2176 (delegate_->GetAsWebContents() == nullptr);
2179 AXTreeIDRegistry::AXTreeID RenderFrameHostImpl::RoutingIDToAXTreeID(
2180 int routing_id) {
2181 RenderFrameHostImpl* rfh = nullptr;
2182 RenderFrameProxyHost* rfph = RenderFrameProxyHost::FromID(
2183 GetProcess()->GetID(), routing_id);
2184 if (rfph) {
2185 FrameTree* frame_tree = frame_tree_node()->frame_tree();
2186 FrameTreeNode* frame_tree_node = frame_tree->FindByRoutingID(
2187 GetProcess()->GetID(), routing_id);
2188 rfh = frame_tree_node->render_manager()->current_frame_host();
2189 } else {
2190 rfh = RenderFrameHostImpl::FromID(GetProcess()->GetID(), routing_id);
2193 if (!rfh)
2194 return AXTreeIDRegistry::kNoAXTreeID;
2196 // As a sanity check, make sure we're within the same frame tree and
2197 // crash the renderer if not.
2198 if (rfh->frame_tree_node()->frame_tree() != frame_tree_node()->frame_tree()) {
2199 AccessibilityFatalError();
2200 return AXTreeIDRegistry::kNoAXTreeID;
2203 return rfh->GetAXTreeID();
2206 AXTreeIDRegistry::AXTreeID
2207 RenderFrameHostImpl::BrowserPluginInstanceIDToAXTreeID(
2208 int instance_id) {
2209 RenderFrameHost* guest = delegate()->GetGuestByInstanceID(
2210 this, instance_id);
2211 if (!guest)
2212 return AXTreeIDRegistry::kNoAXTreeID;
2214 return guest->GetAXTreeID();
2217 void RenderFrameHostImpl::AXContentNodeDataToAXNodeData(
2218 const AXContentNodeData& src,
2219 ui::AXNodeData* dst) {
2220 // Copy the common fields.
2221 *dst = src;
2223 // Map content-specific attributes based on routing IDs or browser plugin
2224 // instance IDs to generic attributes with global AXTreeIDs.
2225 for (auto iter : src.content_int_attributes) {
2226 AXContentIntAttribute attr = iter.first;
2227 int32 value = iter.second;
2228 switch (attr) {
2229 case AX_CONTENT_ATTR_ROUTING_ID:
2230 dst->int_attributes.push_back(std::make_pair(
2231 ui::AX_ATTR_TREE_ID, RoutingIDToAXTreeID(value)));
2232 break;
2233 case AX_CONTENT_ATTR_PARENT_ROUTING_ID:
2234 dst->int_attributes.push_back(std::make_pair(
2235 ui::AX_ATTR_PARENT_TREE_ID, RoutingIDToAXTreeID(value)));
2236 break;
2237 case AX_CONTENT_ATTR_CHILD_ROUTING_ID:
2238 dst->int_attributes.push_back(std::make_pair(
2239 ui::AX_ATTR_CHILD_TREE_ID, RoutingIDToAXTreeID(value)));
2240 break;
2241 case AX_CONTENT_ATTR_CHILD_BROWSER_PLUGIN_INSTANCE_ID:
2242 dst->int_attributes.push_back(std::make_pair(
2243 ui::AX_ATTR_CHILD_TREE_ID,
2244 BrowserPluginInstanceIDToAXTreeID(value)));
2245 break;
2246 case AX_CONTENT_INT_ATTRIBUTE_LAST:
2247 NOTREACHED();
2248 break;
2253 } // namespace content