Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blobaa802dca8ca3ba8df35f4c26e0b16b507e26dd52
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/browser_accessibility_manager.h"
16 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
17 #include "content/browser/bad_message.h"
18 #include "content/browser/child_process_security_policy_impl.h"
19 #include "content/browser/frame_host/cross_process_frame_connector.h"
20 #include "content/browser/frame_host/cross_site_transferring_request.h"
21 #include "content/browser/frame_host/frame_accessibility.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 RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
151 RenderViewHostImpl* render_view_host,
152 RenderFrameHostDelegate* delegate,
153 RenderWidgetHostDelegate* rwh_delegate,
154 FrameTree* frame_tree,
155 FrameTreeNode* frame_tree_node,
156 int routing_id,
157 int flags)
158 : render_view_host_(render_view_host),
159 delegate_(delegate),
160 site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
161 process_(site_instance->GetProcess()),
162 cross_process_frame_connector_(NULL),
163 render_frame_proxy_host_(NULL),
164 frame_tree_(frame_tree),
165 frame_tree_node_(frame_tree_node),
166 render_widget_host_(nullptr),
167 routing_id_(routing_id),
168 render_frame_created_(false),
169 navigations_suspended_(false),
170 is_waiting_for_beforeunload_ack_(false),
171 unload_ack_is_for_navigation_(false),
172 is_loading_(false),
173 pending_commit_(false),
174 accessibility_reset_token_(0),
175 accessibility_reset_count_(0),
176 no_create_browser_accessibility_manager_for_testing_(false),
177 weak_ptr_factory_(this) {
178 bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
179 bool hidden = !!(flags & CREATE_RF_HIDDEN);
180 frame_tree_->AddRenderViewHostRef(render_view_host_);
181 GetProcess()->AddRoute(routing_id_, this);
182 g_routing_id_frame_map.Get().insert(std::make_pair(
183 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
184 this));
186 if (is_swapped_out) {
187 rfh_state_ = STATE_SWAPPED_OUT;
188 } else {
189 rfh_state_ = STATE_DEFAULT;
190 GetSiteInstance()->increment_active_frame_count();
193 SetUpMojoIfNeeded();
194 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
195 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
197 if (flags & CREATE_RF_NEEDS_RENDER_WIDGET_HOST) {
198 render_widget_host_ = new RenderWidgetHostImpl(rwh_delegate, GetProcess(),
199 MSG_ROUTING_NONE, hidden);
200 render_widget_host_->set_owned_by_render_frame_host(true);
204 RenderFrameHostImpl::~RenderFrameHostImpl() {
205 GetProcess()->RemoveRoute(routing_id_);
206 g_routing_id_frame_map.Get().erase(
207 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
209 if (delegate_ && render_frame_created_)
210 delegate_->RenderFrameDeleted(this);
212 FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this);
214 // If this was swapped out, it already decremented the active frame count of
215 // the SiteInstance it belongs to.
216 if (IsRFHStateActive(rfh_state_))
217 GetSiteInstance()->decrement_active_frame_count();
219 // Notify the FrameTree that this RFH is going away, allowing it to shut down
220 // the corresponding RenderViewHost if it is no longer needed.
221 frame_tree_->ReleaseRenderViewHostRef(render_view_host_);
223 // NULL out the swapout timer; in crash dumps this member will be null only if
224 // the dtor has run.
225 swapout_event_monitor_timeout_.reset();
227 for (const auto& iter: visual_state_callbacks_) {
228 iter.second.Run(false);
231 if (render_widget_host_) {
232 // Shutdown causes the RenderWidgetHost to delete itself.
233 render_widget_host_->Shutdown();
237 int RenderFrameHostImpl::GetRoutingID() {
238 return routing_id_;
241 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
242 return site_instance_.get();
245 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
246 return process_;
249 RenderFrameHost* RenderFrameHostImpl::GetParent() {
250 FrameTreeNode* parent_node = frame_tree_node_->parent();
251 if (!parent_node)
252 return NULL;
253 return parent_node->current_frame_host();
256 const std::string& RenderFrameHostImpl::GetFrameName() {
257 return frame_tree_node_->frame_name();
260 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
261 FrameTreeNode* parent_node = frame_tree_node_->parent();
262 if (!parent_node)
263 return false;
264 return GetSiteInstance() !=
265 parent_node->current_frame_host()->GetSiteInstance();
268 GURL RenderFrameHostImpl::GetLastCommittedURL() {
269 return frame_tree_node_->current_url();
272 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
273 RenderWidgetHostView* view = render_view_host_->GetView();
274 if (!view)
275 return NULL;
276 return view->GetNativeView();
279 void RenderFrameHostImpl::AddMessageToConsole(ConsoleMessageLevel level,
280 const std::string& message) {
281 Send(new FrameMsg_AddMessageToConsole(routing_id_, level, message));
284 void RenderFrameHostImpl::ExecuteJavaScript(
285 const base::string16& javascript) {
286 CHECK(CanExecuteJavaScript());
287 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
288 javascript,
289 0, false));
292 void RenderFrameHostImpl::ExecuteJavaScript(
293 const base::string16& javascript,
294 const JavaScriptResultCallback& callback) {
295 CHECK(CanExecuteJavaScript());
296 int key = g_next_javascript_callback_id++;
297 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
298 javascript,
299 key, true));
300 javascript_callbacks_.insert(std::make_pair(key, callback));
303 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
304 const base::string16& javascript) {
305 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
306 javascript,
307 0, false, false));
310 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
311 const base::string16& javascript,
312 const JavaScriptResultCallback& callback) {
313 int key = g_next_javascript_callback_id++;
314 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_, javascript,
315 key, true, false));
316 javascript_callbacks_.insert(std::make_pair(key, callback));
320 void RenderFrameHostImpl::ExecuteJavaScriptWithUserGestureForTests(
321 const base::string16& javascript) {
322 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
323 javascript,
324 0, false, true));
327 void RenderFrameHostImpl::ExecuteJavaScriptInIsolatedWorld(
328 const base::string16& javascript,
329 const JavaScriptResultCallback& callback,
330 int world_id) {
331 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
332 world_id > ISOLATED_WORLD_ID_MAX) {
333 // Return if the world_id is not valid.
334 NOTREACHED();
335 return;
338 int key = 0;
339 bool request_reply = false;
340 if (!callback.is_null()) {
341 request_reply = true;
342 key = g_next_javascript_callback_id++;
343 javascript_callbacks_.insert(std::make_pair(key, callback));
346 Send(new FrameMsg_JavaScriptExecuteRequestInIsolatedWorld(
347 routing_id_, javascript, key, request_reply, world_id));
350 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
351 return render_view_host_;
354 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
355 return service_registry_.get();
358 blink::WebPageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
359 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
360 // returning nullptr in some cases. See https://crbug.com/455245.
361 blink::WebPageVisibilityState visibility_state =
362 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())->is_hidden()
363 ? blink::WebPageVisibilityStateHidden
364 : blink::WebPageVisibilityStateVisible;
365 GetContentClient()->browser()->OverridePageVisibilityState(this,
366 &visibility_state);
367 return visibility_state;
370 bool RenderFrameHostImpl::Send(IPC::Message* message) {
371 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
372 return render_view_host_->input_router()->SendInput(
373 make_scoped_ptr(message));
376 return GetProcess()->Send(message);
379 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
380 // Filter out most IPC messages if this frame is swapped out.
381 // We still want to handle certain ACKs to keep our state consistent.
382 if (is_swapped_out()) {
383 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
384 // If this is a synchronous message and we decided not to handle it,
385 // we must send an error reply, or else the renderer will be stuck
386 // and won't respond to future requests.
387 if (msg.is_sync()) {
388 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
389 reply->set_reply_error();
390 Send(reply);
392 // Don't continue looking for someone to handle it.
393 return true;
397 if (delegate_->OnMessageReceived(this, msg))
398 return true;
400 RenderFrameProxyHost* proxy =
401 frame_tree_node_->render_manager()->GetProxyToParent();
402 if (proxy && proxy->cross_process_frame_connector() &&
403 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
404 return true;
406 bool handled = true;
407 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
408 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
409 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
410 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
411 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
412 OnDidStartProvisionalLoadForFrame)
413 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
414 OnDidFailProvisionalLoadWithError)
415 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
416 OnDidFailLoadWithError)
417 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
418 OnDidCommitProvisionalLoad(msg))
419 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation)
420 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
421 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
422 OnDocumentOnLoadCompleted)
423 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
424 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
425 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
426 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
427 OnJavaScriptExecuteResponse)
428 IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
429 OnVisualStateResponse)
430 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
431 OnRunJavaScriptMessage)
432 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
433 OnRunBeforeUnloadConfirm)
434 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
435 OnDidAccessInitialDocument)
436 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
437 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeName, OnDidChangeName)
438 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
439 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeSandboxFlags,
440 OnDidChangeSandboxFlags)
441 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
442 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
443 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
444 OnBeginNavigation)
445 IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
446 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
447 OnTextSurroundingSelectionResponse)
448 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
449 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
450 OnAccessibilityLocationChanges)
451 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
452 OnAccessibilityFindInPageResult)
453 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
454 OnAccessibilitySnapshotResponse)
455 IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
456 // The following message is synthetic and doesn't come from RenderFrame, but
457 // from RenderProcessHost.
458 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
459 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
460 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
461 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
462 OnDidChangeLoadProgress)
463 #if defined(OS_MACOSX) || defined(OS_ANDROID)
464 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
465 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
466 #endif
467 IPC_END_MESSAGE_MAP()
469 // No further actions here, since we may have been deleted.
470 return handled;
473 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
474 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
477 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
478 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
481 void RenderFrameHostImpl::AccessibilityShowContextMenu(int acc_obj_id) {
482 Send(new AccessibilityMsg_ShowContextMenu(routing_id_, acc_obj_id));
485 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
486 int acc_obj_id, const gfx::Rect& subfocus) {
487 Send(new AccessibilityMsg_ScrollToMakeVisible(
488 routing_id_, acc_obj_id, subfocus));
491 void RenderFrameHostImpl::AccessibilityScrollToPoint(
492 int acc_obj_id, const gfx::Point& point) {
493 Send(new AccessibilityMsg_ScrollToPoint(
494 routing_id_, acc_obj_id, point));
497 void RenderFrameHostImpl::AccessibilitySetScrollOffset(
498 int acc_obj_id, const gfx::Point& offset) {
499 Send(new AccessibilityMsg_SetScrollOffset(
500 routing_id_, acc_obj_id, offset));
503 void RenderFrameHostImpl::AccessibilitySetTextSelection(
504 int object_id, int start_offset, int end_offset) {
505 Send(new AccessibilityMsg_SetTextSelection(
506 routing_id_, object_id, start_offset, end_offset));
509 void RenderFrameHostImpl::AccessibilitySetValue(
510 int object_id, const base::string16& value) {
511 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
514 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
515 RenderWidgetHostView* view = render_view_host_->GetView();
516 if (view)
517 return view->HasFocus();
518 return false;
521 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
522 RenderWidgetHostView* view = render_view_host_->GetView();
523 if (view)
524 return view->GetViewBounds();
525 return gfx::Rect();
528 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
529 const gfx::Rect& bounds) const {
530 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
531 render_view_host_->GetView());
532 if (view)
533 return view->AccessibilityOriginInScreen(bounds);
534 return gfx::Point();
537 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
538 Send(new AccessibilityMsg_HitTest(routing_id_, point));
541 void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) {
542 Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id));
545 void RenderFrameHostImpl::AccessibilityReset() {
546 accessibility_reset_token_ = g_next_accessibility_reset_token++;
547 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
550 void RenderFrameHostImpl::AccessibilityFatalError() {
551 browser_accessibility_manager_.reset(NULL);
552 if (accessibility_reset_token_)
553 return;
555 accessibility_reset_count_++;
556 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
557 Send(new AccessibilityMsg_FatalError(routing_id_));
558 } else {
559 accessibility_reset_token_ = g_next_accessibility_reset_token++;
560 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
561 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
565 gfx::AcceleratedWidget
566 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
567 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
568 render_view_host_->GetView());
569 if (view)
570 return view->AccessibilityGetAcceleratedWidget();
571 return gfx::kNullAcceleratedWidget;
574 gfx::NativeViewAccessible
575 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
576 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
577 render_view_host_->GetView());
578 if (view)
579 return view->AccessibilityGetNativeViewAccessible();
580 return NULL;
583 BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame(
584 int accessibility_node_id) {
585 RenderFrameHostImpl* child_frame =
586 FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id);
587 if (!child_frame || IsSameSiteInstance(child_frame))
588 return nullptr;
590 return child_frame->GetOrCreateBrowserAccessibilityManager();
593 void RenderFrameHostImpl::AccessibilityGetAllChildFrames(
594 std::vector<BrowserAccessibilityManager*>* child_frames) {
595 std::vector<RenderFrameHostImpl*> child_frame_hosts;
596 FrameAccessibility::GetInstance()->GetAllChildFrames(
597 this, &child_frame_hosts);
598 for (size_t i = 0; i < child_frame_hosts.size(); ++i) {
599 RenderFrameHostImpl* child_frame_host = child_frame_hosts[i];
600 if (!child_frame_host || IsSameSiteInstance(child_frame_host))
601 continue;
603 BrowserAccessibilityManager* manager =
604 child_frame_host->GetOrCreateBrowserAccessibilityManager();
605 if (manager)
606 child_frames->push_back(manager);
610 BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() {
611 RenderFrameHostImpl* parent_frame = NULL;
612 int parent_node_id = 0;
613 if (!FrameAccessibility::GetInstance()->GetParent(
614 this, &parent_frame, &parent_node_id)) {
615 return NULL;
618 // As a sanity check, make sure the frame we're going to return belongs
619 // to the same BrowserContext.
620 if (GetSiteInstance()->GetBrowserContext() !=
621 parent_frame->GetSiteInstance()->GetBrowserContext()) {
622 NOTREACHED();
623 return NULL;
626 BrowserAccessibilityManager* manager =
627 parent_frame->browser_accessibility_manager();
628 if (!manager)
629 return NULL;
631 return manager->GetFromID(parent_node_id);
634 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id,
635 int previous_sibling_routing_id,
636 int proxy_routing_id) {
637 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
638 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
640 // The process may (if we're sharing a process with another host that already
641 // initialized it) or may not (we have our own process or the old process
642 // crashed) have been initialized. Calling Init multiple times will be
643 // ignored, so this is safe.
644 if (!GetProcess()->Init())
645 return false;
647 DCHECK(GetProcess()->HasConnection());
649 FrameMsg_NewFrame_Params params;
650 params.routing_id = routing_id_;
651 params.parent_routing_id = parent_routing_id;
652 params.proxy_routing_id = proxy_routing_id;
653 params.previous_sibling_routing_id = previous_sibling_routing_id;
654 params.replication_state = frame_tree_node()->current_replication_state();
656 if (render_widget_host_) {
657 params.widget_params.routing_id = render_widget_host_->GetRoutingID();
658 params.widget_params.surface_id = render_widget_host_->surface_id();
659 params.widget_params.hidden = render_widget_host_->is_hidden();
660 } else {
661 // MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
662 // the renderer process.
663 params.widget_params.routing_id = MSG_ROUTING_NONE;
664 params.widget_params.surface_id = 0;
665 params.widget_params.hidden = true;
668 Send(new FrameMsg_NewFrame(params));
670 // The RenderWidgetHost takes ownership of its view. It is tied to the
671 // lifetime of the current RenderProcessHost for this RenderFrameHost.
672 if (render_widget_host_) {
673 RenderWidgetHostView* rwhv =
674 new RenderWidgetHostViewChildFrame(render_widget_host_);
675 rwhv->Hide();
678 if (proxy_routing_id != MSG_ROUTING_NONE) {
679 RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
680 GetProcess()->GetID(), proxy_routing_id);
681 // We have also created a RenderFrameProxy in FrameMsg_NewFrame above, so
682 // remember that.
683 proxy->set_render_frame_proxy_created(true);
686 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
687 // this path is only used for out-of-process iframes. Main frame RenderFrames
688 // are created with their RenderView, and same-site iframes are created at the
689 // time of OnCreateChildFrame.
690 SetRenderFrameCreated(true);
692 return true;
695 void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
696 bool was_created = render_frame_created_;
697 render_frame_created_ = created;
699 // If the current status is different than the new status, the delegate
700 // needs to be notified.
701 if (delegate_ && (created != was_created)) {
702 if (created)
703 delegate_->RenderFrameCreated(this);
704 else
705 delegate_->RenderFrameDeleted(this);
708 if (created && render_widget_host_)
709 render_widget_host_->InitForFrame();
712 void RenderFrameHostImpl::Init() {
713 GetProcess()->ResumeRequestsForView(routing_id_);
716 void RenderFrameHostImpl::OnAddMessageToConsole(
717 int32 level,
718 const base::string16& message,
719 int32 line_no,
720 const base::string16& source_id) {
721 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
722 return;
724 // Pass through log level only on WebUI pages to limit console spew.
725 const bool is_web_ui =
726 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL());
727 const int32 resolved_level = is_web_ui ? level : ::logging::LOG_INFO;
729 // LogMessages can be persisted so this shouldn't be logged in incognito mode.
730 // This rule is not applied to WebUI pages, because source code of WebUI is a
731 // part of Chrome source code, and we want to treat messages from WebUI the
732 // same way as we treat log messages from native code.
733 if (::logging::GetMinLogLevel() <= resolved_level &&
734 (is_web_ui ||
735 !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord())) {
736 logging::LogMessage("CONSOLE", line_no, resolved_level).stream()
737 << "\"" << message << "\", source: " << source_id << " (" << line_no
738 << ")";
742 void RenderFrameHostImpl::OnCreateChildFrame(
743 int new_routing_id,
744 blink::WebTreeScopeType scope,
745 const std::string& frame_name,
746 blink::WebSandboxFlags sandbox_flags) {
747 // It is possible that while a new RenderFrameHost was committed, the
748 // RenderFrame corresponding to this host sent an IPC message to create a
749 // frame and it is delivered after this host is swapped out.
750 // Ignore such messages, as we know this RenderFrameHost is going away.
751 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
752 return;
754 RenderFrameHostImpl* new_frame =
755 frame_tree_->AddFrame(frame_tree_node_, GetProcess()->GetID(),
756 new_routing_id, scope, frame_name, sandbox_flags);
757 if (!new_frame)
758 return;
760 // We know that the RenderFrame has been created in this case, immediately
761 // after the CreateChildFrame IPC was sent.
762 new_frame->SetRenderFrameCreated(true);
765 void RenderFrameHostImpl::OnDetach() {
766 frame_tree_->RemoveFrame(frame_tree_node_);
769 void RenderFrameHostImpl::OnFrameFocused() {
770 frame_tree_->SetFocusedFrame(frame_tree_node_);
773 void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
774 OpenURL(params, GetSiteInstance());
777 void RenderFrameHostImpl::OnDocumentOnLoadCompleted(
778 FrameMsg_UILoadMetricsReportType::Value report_type,
779 base::TimeTicks ui_timestamp) {
780 if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
781 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Link",
782 base::TimeTicks::Now() - ui_timestamp,
783 base::TimeDelta::FromMilliseconds(10),
784 base::TimeDelta::FromMinutes(10), 100);
785 } else if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
786 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Intent",
787 base::TimeTicks::Now() - ui_timestamp,
788 base::TimeDelta::FromMilliseconds(10),
789 base::TimeDelta::FromMinutes(10), 100);
791 // This message is only sent for top-level frames. TODO(avi): when frame tree
792 // mirroring works correctly, add a check here to enforce it.
793 delegate_->DocumentOnLoadCompleted(this);
796 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(const GURL& url) {
797 frame_tree_node_->navigator()->DidStartProvisionalLoad(
798 this, url);
801 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
802 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
803 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
804 switches::kEnableBrowserSideNavigation) &&
805 navigation_handle_) {
806 navigation_handle_->set_net_error_code(
807 static_cast<net::Error>(params.error_code));
809 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
812 void RenderFrameHostImpl::OnDidFailLoadWithError(
813 const GURL& url,
814 int error_code,
815 const base::string16& error_description,
816 bool was_ignored_by_handler) {
817 GURL validated_url(url);
818 GetProcess()->FilterURL(false, &validated_url);
820 frame_tree_node_->navigator()->DidFailLoadWithError(
821 this, validated_url, error_code, error_description,
822 was_ignored_by_handler);
825 // Called when the renderer navigates. For every frame loaded, we'll get this
826 // notification containing parameters identifying the navigation.
828 // Subframes are identified by the page transition type. For subframes loaded
829 // as part of a wider page load, the page_id will be the same as for the top
830 // level frame. If the user explicitly requests a subframe navigation, we will
831 // get a new page_id because we need to create a new navigation entry for that
832 // action.
833 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
834 RenderProcessHost* process = GetProcess();
836 // Read the parameters out of the IPC message directly to avoid making another
837 // copy when we filter the URLs.
838 base::PickleIterator iter(msg);
839 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
840 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
841 Read(&msg, &iter, &validated_params)) {
842 bad_message::ReceivedBadMessage(
843 process, bad_message::RFH_COMMIT_DESERIALIZATION_FAILED);
844 return;
846 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
847 "url", validated_params.url.possibly_invalid_spec());
849 // Sanity-check the page transition for frame type.
850 DCHECK_EQ(ui::PageTransitionIsMainFrame(validated_params.transition),
851 !GetParent());
853 // If we're waiting for a cross-site beforeunload ack from this renderer and
854 // we receive a Navigate message from the main frame, then the renderer was
855 // navigating already and sent it before hearing the FrameMsg_Stop message.
856 // Treat this as an implicit beforeunload ack to allow the pending navigation
857 // to continue.
858 if (is_waiting_for_beforeunload_ack_ &&
859 unload_ack_is_for_navigation_ &&
860 !GetParent()) {
861 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
862 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
865 // If we're waiting for an unload ack from this renderer and we receive a
866 // Navigate message, then the renderer was navigating before it received the
867 // unload request. It will either respond to the unload request soon or our
868 // timer will expire. Either way, we should ignore this message, because we
869 // have already committed to closing this renderer.
870 if (IsWaitingForUnloadACK())
871 return;
873 if (validated_params.report_type ==
874 FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
875 UMA_HISTOGRAM_CUSTOM_TIMES(
876 "Navigation.UI_OnCommitProvisionalLoad.Link",
877 base::TimeTicks::Now() - validated_params.ui_timestamp,
878 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
879 100);
880 } else if (validated_params.report_type ==
881 FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
882 UMA_HISTOGRAM_CUSTOM_TIMES(
883 "Navigation.UI_OnCommitProvisionalLoad.Intent",
884 base::TimeTicks::Now() - validated_params.ui_timestamp,
885 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
886 100);
889 // Attempts to commit certain off-limits URL should be caught more strictly
890 // than our FilterURL checks below. If a renderer violates this policy, it
891 // should be killed.
892 if (!CanCommitURL(validated_params.url)) {
893 VLOG(1) << "Blocked URL " << validated_params.url.spec();
894 validated_params.url = GURL(url::kAboutBlankURL);
895 // Kills the process.
896 bad_message::ReceivedBadMessage(process,
897 bad_message::RFH_CAN_COMMIT_URL_BLOCKED);
900 // Without this check, an evil renderer can trick the browser into creating
901 // a navigation entry for a banned URL. If the user clicks the back button
902 // followed by the forward button (or clicks reload, or round-trips through
903 // session restore, etc), we'll think that the browser commanded the
904 // renderer to load the URL and grant the renderer the privileges to request
905 // the URL. To prevent this attack, we block the renderer from inserting
906 // banned URLs into the navigation controller in the first place.
907 process->FilterURL(false, &validated_params.url);
908 process->FilterURL(true, &validated_params.referrer.url);
909 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
910 it != validated_params.redirects.end(); ++it) {
911 process->FilterURL(false, &(*it));
913 process->FilterURL(true, &validated_params.searchable_form_url);
915 // Without this check, the renderer can trick the browser into using
916 // filenames it can't access in a future session restore.
917 if (!render_view_host_->CanAccessFilesOfPageState(
918 validated_params.page_state)) {
919 bad_message::ReceivedBadMessage(
920 GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
921 return;
924 // If the URL does not match what the NavigationHandle expects, treat the
925 // commit as a new navigation. This can happen if an ongoing slow
926 // same-process navigation is interrupted by a synchronous renderer-initiated
927 // navigation.
928 if (navigation_handle_ &&
929 navigation_handle_->GetURL() != validated_params.url) {
930 navigation_handle_.reset();
933 // Synchronous renderer-initiated navigations will send a
934 // DidCommitProvisionalLoad IPC without a prior DidStartProvisionalLoad
935 // message.
936 if (!navigation_handle_) {
937 navigation_handle_ = NavigationHandleImpl::Create(
938 validated_params.url, frame_tree_node_->IsMainFrame(),
939 frame_tree_node_->navigator()->GetDelegate());
942 accessibility_reset_count_ = 0;
943 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
945 // PlzNavigate
946 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
947 switches::kEnableBrowserSideNavigation)) {
948 pending_commit_ = false;
952 void RenderFrameHostImpl::OnDidDropNavigation() {
953 // At the end of Navigate(), the FrameTreeNode's DidStartLoading is called to
954 // force the spinner to start, even if the renderer didn't yet begin the load.
955 // If it turns out that the renderer dropped the navigation, the spinner needs
956 // to be turned off.
957 frame_tree_node_->DidStopLoading();
958 navigation_handle_.reset();
961 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
962 if (render_widget_host_)
963 return render_widget_host_;
965 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
966 // we can remove this fallback. Currently it is only used for the main
967 // frame.
968 if (!GetParent())
969 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
971 return nullptr;
974 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
975 RenderFrameHostImpl* frame = this;
976 while (frame) {
977 if (frame->render_widget_host_)
978 return frame->render_widget_host_->GetView();
979 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
982 return render_view_host_->GetView();
985 int RenderFrameHostImpl::GetEnabledBindings() {
986 return render_view_host_->GetEnabledBindings();
989 void RenderFrameHostImpl::SetNavigationHandle(
990 scoped_ptr<NavigationHandleImpl> navigation_handle) {
991 navigation_handle_ = navigation_handle.Pass();
994 scoped_ptr<NavigationHandleImpl>
995 RenderFrameHostImpl::PassNavigationHandleOwnership() {
996 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
997 switches::kEnableBrowserSideNavigation));
998 navigation_handle_->set_is_transferring(true);
999 return navigation_handle_.Pass();
1002 void RenderFrameHostImpl::OnCrossSiteResponse(
1003 const GlobalRequestID& global_request_id,
1004 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
1005 const std::vector<GURL>& transfer_url_chain,
1006 const Referrer& referrer,
1007 ui::PageTransition page_transition,
1008 bool should_replace_current_entry) {
1009 frame_tree_node_->render_manager()->OnCrossSiteResponse(
1010 this, global_request_id, cross_site_transferring_request.Pass(),
1011 transfer_url_chain, referrer, page_transition,
1012 should_replace_current_entry);
1015 void RenderFrameHostImpl::SwapOut(
1016 RenderFrameProxyHost* proxy,
1017 bool is_loading) {
1018 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
1019 // the operation and sends back an IPC message.
1020 // The trace event may not end properly if the ACK times out. We expect this
1021 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
1022 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
1024 // If this RenderFrameHost is not in the default state, it must have already
1025 // gone through this, therefore just return.
1026 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
1027 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
1028 return;
1031 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
1032 swapout_event_monitor_timeout_->Start(
1033 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1035 // There may be no proxy if there are no active views in the process.
1036 int proxy_routing_id = MSG_ROUTING_NONE;
1037 FrameReplicationState replication_state;
1038 if (proxy) {
1039 set_render_frame_proxy_host(proxy);
1040 proxy_routing_id = proxy->GetRoutingID();
1041 replication_state = proxy->frame_tree_node()->current_replication_state();
1044 if (IsRenderFrameLive()) {
1045 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
1046 replication_state));
1049 if (!GetParent())
1050 delegate_->SwappedOut(this);
1053 void RenderFrameHostImpl::OnBeforeUnloadACK(
1054 bool proceed,
1055 const base::TimeTicks& renderer_before_unload_start_time,
1056 const base::TimeTicks& renderer_before_unload_end_time) {
1057 TRACE_EVENT_ASYNC_END0(
1058 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1059 DCHECK(!GetParent());
1060 // If this renderer navigated while the beforeunload request was in flight, we
1061 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
1062 // can ignore this message.
1063 // However renderer might also be swapped out but we still want to proceed
1064 // with navigation, otherwise it would block future navigations. This can
1065 // happen when pending cross-site navigation is canceled by a second one just
1066 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
1067 // but second navigation is started from the beginning.
1068 if (!is_waiting_for_beforeunload_ack_) {
1069 return;
1071 DCHECK(!send_before_unload_start_time_.is_null());
1073 // Sets a default value for before_unload_end_time so that the browser
1074 // survives a hacked renderer.
1075 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
1076 if (!renderer_before_unload_start_time.is_null() &&
1077 !renderer_before_unload_end_time.is_null()) {
1078 // When passing TimeTicks across process boundaries, we need to compensate
1079 // for any skew between the processes. Here we are converting the
1080 // renderer's notion of before_unload_end_time to TimeTicks in the browser
1081 // process. See comments in inter_process_time_ticks_converter.h for more.
1082 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
1083 InterProcessTimeTicksConverter converter(
1084 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
1085 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
1086 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
1087 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1088 LocalTimeTicks browser_before_unload_end_time =
1089 converter.ToLocalTimeTicks(
1090 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1091 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1093 // Collect UMA on the inter-process skew.
1094 bool is_skew_additive = false;
1095 if (converter.IsSkewAdditiveForMetrics()) {
1096 is_skew_additive = true;
1097 base::TimeDelta skew = converter.GetSkewForMetrics();
1098 if (skew >= base::TimeDelta()) {
1099 UMA_HISTOGRAM_TIMES(
1100 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
1101 } else {
1102 UMA_HISTOGRAM_TIMES(
1103 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
1106 UMA_HISTOGRAM_BOOLEAN(
1107 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
1108 is_skew_additive);
1110 base::TimeDelta on_before_unload_overhead_time =
1111 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1112 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1113 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1114 on_before_unload_overhead_time);
1116 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1117 renderer_before_unload_start_time, renderer_before_unload_end_time);
1119 // Resets beforeunload waiting state.
1120 is_waiting_for_beforeunload_ack_ = false;
1121 render_view_host_->decrement_in_flight_event_count();
1122 render_view_host_->StopHangMonitorTimeout();
1123 send_before_unload_start_time_ = base::TimeTicks();
1125 // PlzNavigate: if the ACK is for a navigation, send it to the Navigator to
1126 // have the current navigation stop/proceed. Otherwise, send it to the
1127 // RenderFrameHostManager which handles closing.
1128 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1129 switches::kEnableBrowserSideNavigation) &&
1130 unload_ack_is_for_navigation_) {
1131 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1132 // Navigator.
1133 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1134 frame_tree_node_, proceed);
1135 } else {
1136 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1137 unload_ack_is_for_navigation_, proceed,
1138 before_unload_end_time);
1141 // If canceled, notify the delegate to cancel its pending navigation entry.
1142 if (!proceed)
1143 render_view_host_->GetDelegate()->DidCancelLoading();
1146 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1147 return render_view_host_->is_waiting_for_close_ack_ ||
1148 rfh_state_ == STATE_PENDING_SWAP_OUT;
1151 void RenderFrameHostImpl::OnSwapOutACK() {
1152 OnSwappedOut();
1155 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1156 if (frame_tree_node_->IsMainFrame()) {
1157 // Keep the termination status so we can get at it later when we
1158 // need to know why it died.
1159 render_view_host_->render_view_termination_status_ =
1160 static_cast<base::TerminationStatus>(status);
1163 // Reset frame tree state associated with this process. This must happen
1164 // before RenderViewTerminated because observers expect the subframes of any
1165 // affected frames to be cleared first.
1166 // Note: When a RenderFrameHost is swapped out there is a different one
1167 // which is the current host. In this case, the FrameTreeNode state must
1168 // not be reset.
1169 if (!is_swapped_out())
1170 frame_tree_node_->ResetForNewProcess();
1172 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1173 // reset.
1174 SetRenderFrameCreated(false);
1175 InvalidateMojoConnection();
1177 // Execute any pending AX tree snapshot callbacks with an empty response,
1178 // since we're never going to get a response from this renderer.
1179 for (const auto& iter : ax_tree_snapshot_callbacks_)
1180 iter.second.Run(ui::AXTreeUpdate());
1181 ax_tree_snapshot_callbacks_.clear();
1183 // Note: don't add any more code at this point in the function because
1184 // |this| may be deleted. Any additional cleanup should happen before
1185 // the last block of code here.
1188 void RenderFrameHostImpl::OnSwappedOut() {
1189 // Ignore spurious swap out ack.
1190 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1191 return;
1193 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1194 swapout_event_monitor_timeout_->Stop();
1197 // If this is a main frame RFH that's about to be deleted, update its RVH's
1198 // swapped-out state here, since SetState won't be called once this RFH is
1199 // deleted below. https://crbug.com/505887
1200 if (frame_tree_node_->IsMainFrame() &&
1201 frame_tree_node_->render_manager()->IsPendingDeletion(this)) {
1202 render_view_host_->set_is_active(false);
1203 render_view_host_->set_is_swapped_out(true);
1206 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1207 // We are now deleted.
1208 return;
1211 // If this RFH wasn't pending deletion, then it is now swapped out.
1212 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1215 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1216 // Validate the URLs in |params|. If the renderer can't request the URLs
1217 // directly, don't show them in the context menu.
1218 ContextMenuParams validated_params(params);
1219 RenderProcessHost* process = GetProcess();
1221 // We don't validate |unfiltered_link_url| so that this field can be used
1222 // when users want to copy the original link URL.
1223 process->FilterURL(true, &validated_params.link_url);
1224 process->FilterURL(true, &validated_params.src_url);
1225 process->FilterURL(false, &validated_params.page_url);
1226 process->FilterURL(true, &validated_params.frame_url);
1228 delegate_->ShowContextMenu(this, validated_params);
1231 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1232 int id, const base::ListValue& result) {
1233 const base::Value* result_value;
1234 if (!result.Get(0, &result_value)) {
1235 // Programming error or rogue renderer.
1236 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1237 return;
1240 std::map<int, JavaScriptResultCallback>::iterator it =
1241 javascript_callbacks_.find(id);
1242 if (it != javascript_callbacks_.end()) {
1243 it->second.Run(result_value);
1244 javascript_callbacks_.erase(it);
1245 } else {
1246 NOTREACHED() << "Received script response for unknown request";
1250 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1251 auto it = visual_state_callbacks_.find(id);
1252 if (it != visual_state_callbacks_.end()) {
1253 it->second.Run(true);
1254 visual_state_callbacks_.erase(it);
1255 } else {
1256 NOTREACHED() << "Received script response for unknown request";
1260 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1261 const base::string16& message,
1262 const base::string16& default_prompt,
1263 const GURL& frame_url,
1264 JavaScriptMessageType type,
1265 IPC::Message* reply_msg) {
1266 // While a JS message dialog is showing, tabs in the same process shouldn't
1267 // process input events.
1268 GetProcess()->SetIgnoreInputEvents(true);
1269 render_view_host_->StopHangMonitorTimeout();
1270 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1271 frame_url, type, reply_msg);
1274 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1275 const GURL& frame_url,
1276 const base::string16& message,
1277 bool is_reload,
1278 IPC::Message* reply_msg) {
1279 // While a JS beforeunload dialog is showing, tabs in the same process
1280 // shouldn't process input events.
1281 GetProcess()->SetIgnoreInputEvents(true);
1282 render_view_host_->StopHangMonitorTimeout();
1283 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1286 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1287 const base::string16& content,
1288 size_t start_offset,
1289 size_t end_offset) {
1290 render_view_host_->OnTextSurroundingSelectionResponse(
1291 content, start_offset, end_offset);
1294 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1295 delegate_->DidAccessInitialDocument();
1298 void RenderFrameHostImpl::OnDidDisownOpener() {
1299 // This message is only sent for top-level frames for now.
1300 // TODO(alexmos): This should eventually support subframe openers as well,
1301 // and it should allow openers to be updated to another frame (which can
1302 // happen via window.open('','framename')) in addition to being disowned.
1304 // No action is necessary if the opener has already been cleared.
1305 if (!frame_tree_node_->opener())
1306 return;
1308 // Clear our opener so that future cross-process navigations don't have an
1309 // opener assigned.
1310 frame_tree_node_->SetOpener(nullptr);
1312 // Notify all other RenderFrameHosts and RenderFrameProxies for this frame.
1313 // This is important in case we go back to them, or if another window in
1314 // those processes tries to access window.opener.
1315 frame_tree_node_->render_manager()->DidDisownOpener(this);
1318 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1319 std::string old_name = frame_tree_node()->frame_name();
1320 frame_tree_node()->SetFrameName(name);
1321 if (old_name.empty() && !name.empty())
1322 frame_tree_node_->render_manager()->CreateProxiesForNewNamedFrame();
1323 delegate_->DidChangeName(this, name);
1326 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1327 // Update the RVH's current page ID so that future IPCs from the renderer
1328 // correspond to the new page.
1329 render_view_host_->page_id_ = page_id;
1332 void RenderFrameHostImpl::OnDidChangeSandboxFlags(
1333 int32 frame_routing_id,
1334 blink::WebSandboxFlags flags) {
1335 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1336 FrameTreeNode* child =
1337 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1338 if (!child)
1339 return;
1341 // Ensure that a frame can only update sandbox flags for its immediate
1342 // children. If this is not the case, the renderer is considered malicious
1343 // and is killed.
1344 if (child->parent() != frame_tree_node()) {
1345 bad_message::ReceivedBadMessage(GetProcess(),
1346 bad_message::RFH_SANDBOX_FLAGS);
1347 return;
1350 child->set_sandbox_flags(flags);
1352 // Notify the RenderFrame if it lives in a different process from its
1353 // parent. The frame's proxies in other processes also need to learn about
1354 // the updated sandbox flags, but these notifications are sent later in
1355 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1356 // navigates and the new sandbox flags take effect.
1357 RenderFrameHost* child_rfh = child->current_frame_host();
1358 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1359 child_rfh->Send(
1360 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1364 void RenderFrameHostImpl::OnUpdateTitle(
1365 const base::string16& title,
1366 blink::WebTextDirection title_direction) {
1367 // This message is only sent for top-level frames. TODO(avi): when frame tree
1368 // mirroring works correctly, add a check here to enforce it.
1369 if (title.length() > kMaxTitleChars) {
1370 NOTREACHED() << "Renderer sent too many characters in title.";
1371 return;
1374 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1375 WebTextDirectionToChromeTextDirection(
1376 title_direction));
1379 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1380 // This message is only sent for top-level frames. TODO(avi): when frame tree
1381 // mirroring works correctly, add a check here to enforce it.
1382 delegate_->UpdateEncoding(this, encoding_name);
1385 void RenderFrameHostImpl::OnBeginNavigation(
1386 const CommonNavigationParams& common_params,
1387 const BeginNavigationParams& begin_params,
1388 scoped_refptr<ResourceRequestBody> body) {
1389 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1390 switches::kEnableBrowserSideNavigation));
1391 frame_tree_node()->navigator()->OnBeginNavigation(
1392 frame_tree_node(), common_params, begin_params, body);
1395 void RenderFrameHostImpl::OnDispatchLoad() {
1396 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
1397 // Only frames with an out-of-process parent frame should be sending this
1398 // message.
1399 RenderFrameProxyHost* proxy =
1400 frame_tree_node()->render_manager()->GetProxyToParent();
1401 if (!proxy) {
1402 bad_message::ReceivedBadMessage(GetProcess(),
1403 bad_message::RFH_NO_PROXY_TO_PARENT);
1404 return;
1407 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1410 void RenderFrameHostImpl::OnAccessibilityEvents(
1411 const std::vector<AccessibilityHostMsg_EventParams>& params,
1412 int reset_token) {
1413 // Don't process this IPC if either we're waiting on a reset and this
1414 // IPC doesn't have the matching token ID, or if we're not waiting on a
1415 // reset but this message includes a reset token.
1416 if (accessibility_reset_token_ != reset_token) {
1417 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1418 return;
1420 accessibility_reset_token_ = 0;
1422 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1423 render_view_host_->GetView());
1425 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1426 if ((accessibility_mode != AccessibilityModeOff) && view &&
1427 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1428 if (browser_accessibility_manager_) {
1429 // Get the frame routing ids from out-of-process iframes and
1430 // browser plugin instance ids from guests and update the mappings in
1431 // FrameAccessibility.
1432 for (size_t i = 0; i < params.size(); ++i) {
1433 const AccessibilityHostMsg_EventParams& param = params[i];
1434 UpdateCrossProcessIframeAccessibility(
1435 param.node_to_frame_routing_id_map);
1436 UpdateGuestFrameAccessibility(
1437 param.node_to_browser_plugin_instance_id_map);
1441 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1442 GetOrCreateBrowserAccessibilityManager();
1443 if (browser_accessibility_manager_)
1444 browser_accessibility_manager_->OnAccessibilityEvents(params);
1447 // Send the updates to the automation extension API.
1448 std::vector<AXEventNotificationDetails> details;
1449 details.reserve(params.size());
1450 for (size_t i = 0; i < params.size(); ++i) {
1451 const AccessibilityHostMsg_EventParams& param = params[i];
1452 AXEventNotificationDetails detail(
1453 param.update.node_id_to_clear,
1454 param.update.nodes,
1455 param.event_type,
1456 param.id,
1457 param.node_to_browser_plugin_instance_id_map,
1458 GetProcess()->GetID(),
1459 routing_id_);
1460 details.push_back(detail);
1463 delegate_->AccessibilityEventReceived(details);
1466 // Always send an ACK or the renderer can be in a bad state.
1467 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1469 // The rest of this code is just for testing; bail out if we're not
1470 // in that mode.
1471 if (accessibility_testing_callback_.is_null())
1472 return;
1474 for (size_t i = 0; i < params.size(); i++) {
1475 const AccessibilityHostMsg_EventParams& param = params[i];
1476 if (static_cast<int>(param.event_type) < 0)
1477 continue;
1479 if (!ax_tree_for_testing_) {
1480 if (browser_accessibility_manager_) {
1481 ax_tree_for_testing_.reset(new ui::AXTree(
1482 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1483 } else {
1484 ax_tree_for_testing_.reset(new ui::AXTree());
1485 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1486 << ax_tree_for_testing_->error();
1488 } else {
1489 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1490 << ax_tree_for_testing_->error();
1492 accessibility_testing_callback_.Run(param.event_type, param.id);
1496 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1497 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1498 if (accessibility_reset_token_)
1499 return;
1501 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1502 render_view_host_->GetView());
1503 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1504 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1505 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1506 BrowserAccessibilityManager* manager =
1507 GetOrCreateBrowserAccessibilityManager();
1508 if (manager)
1509 manager->OnLocationChanges(params);
1511 // TODO(aboxhall): send location change events to web contents observers too
1515 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1516 const AccessibilityHostMsg_FindInPageResultParams& params) {
1517 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1518 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1519 BrowserAccessibilityManager* manager =
1520 GetOrCreateBrowserAccessibilityManager();
1521 if (manager) {
1522 manager->OnFindInPageResult(
1523 params.request_id, params.match_index, params.start_id,
1524 params.start_offset, params.end_id, params.end_offset);
1529 void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
1530 int callback_id,
1531 const ui::AXTreeUpdate& snapshot) {
1532 const auto& it = ax_tree_snapshot_callbacks_.find(callback_id);
1533 if (it != ax_tree_snapshot_callbacks_.end()) {
1534 it->second.Run(snapshot);
1535 ax_tree_snapshot_callbacks_.erase(it);
1536 } else {
1537 NOTREACHED() << "Received AX tree snapshot response for unknown id";
1541 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1542 if (enter_fullscreen)
1543 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1544 else
1545 delegate_->ExitFullscreenMode();
1547 // The previous call might change the fullscreen state. We need to make sure
1548 // the renderer is aware of that, which is done via the resize message.
1549 render_view_host_->WasResized();
1552 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
1553 // Any main frame load to a new document should reset the load since it will
1554 // replace the current page and any frames.
1555 if (to_different_document && !GetParent())
1556 is_loading_ = false;
1558 // This method should never be called when the frame is loading.
1559 // Unfortunately, it can happen if a history navigation happens during a
1560 // BeforeUnload or Unload event.
1561 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1562 // refactored in Blink. See crbug.com/466089
1563 if (is_loading_) {
1564 LOG(WARNING) << "OnDidStartLoading was called twice.";
1565 return;
1568 frame_tree_node_->DidStartLoading(to_different_document);
1569 is_loading_ = true;
1572 void RenderFrameHostImpl::OnDidStopLoading() {
1573 // This method should never be called when the frame is not loading.
1574 // Unfortunately, it can happen if a history navigation happens during a
1575 // BeforeUnload or Unload event.
1576 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1577 // refactored in Blink. See crbug.com/466089
1578 if (!is_loading_) {
1579 LOG(WARNING) << "OnDidStopLoading was called twice.";
1580 return;
1583 is_loading_ = false;
1584 frame_tree_node_->DidStopLoading();
1585 navigation_handle_.reset();
1588 void RenderFrameHostImpl::OnDidChangeLoadProgress(double load_progress) {
1589 frame_tree_node_->DidChangeLoadProgress(load_progress);
1592 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1593 void RenderFrameHostImpl::OnShowPopup(
1594 const FrameHostMsg_ShowPopup_Params& params) {
1595 RenderViewHostDelegateView* view =
1596 render_view_host_->delegate_->GetDelegateView();
1597 if (view) {
1598 view->ShowPopupMenu(this,
1599 params.bounds,
1600 params.item_height,
1601 params.item_font_size,
1602 params.selected_item,
1603 params.popup_items,
1604 params.right_aligned,
1605 params.allow_multiple_selection);
1609 void RenderFrameHostImpl::OnHidePopup() {
1610 RenderViewHostDelegateView* view =
1611 render_view_host_->delegate_->GetDelegateView();
1612 if (view)
1613 view->HidePopupMenu();
1615 #endif
1617 void RenderFrameHostImpl::RegisterMojoServices() {
1618 GeolocationServiceContext* geolocation_service_context =
1619 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1620 if (geolocation_service_context) {
1621 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1622 // can perform permissions checks once site isolation is complete.
1623 // crbug.com/426384
1624 GetServiceRegistry()->AddService<GeolocationService>(
1625 base::Bind(&GeolocationServiceContext::CreateService,
1626 base::Unretained(geolocation_service_context),
1627 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1628 base::Unretained(this))));
1631 if (!permission_service_context_)
1632 permission_service_context_.reset(new PermissionServiceContext(this));
1634 GetServiceRegistry()->AddService<PermissionService>(
1635 base::Bind(&PermissionServiceContext::CreateService,
1636 base::Unretained(permission_service_context_.get())));
1638 GetServiceRegistry()->AddService<presentation::PresentationService>(
1639 base::Bind(&PresentationServiceImpl::CreateMojoService,
1640 base::Unretained(this)));
1642 if (!frame_mojo_shell_)
1643 frame_mojo_shell_.reset(new FrameMojoShell(this));
1645 GetServiceRegistry()->AddService<mojo::Shell>(base::Bind(
1646 &FrameMojoShell::BindRequest, base::Unretained(frame_mojo_shell_.get())));
1648 #if defined(ENABLE_WEBVR)
1649 const base::CommandLine& browser_command_line =
1650 *base::CommandLine::ForCurrentProcess();
1652 if (browser_command_line.HasSwitch(switches::kEnableWebVR)) {
1653 GetServiceRegistry()->AddService<VRService>(
1654 base::Bind(&VRDeviceManager::BindRequest));
1656 #endif
1659 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1660 // Only main frames should be swapped out and retained inside a proxy host.
1661 if (rfh_state == STATE_SWAPPED_OUT)
1662 CHECK(!GetParent());
1664 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1665 // out status of a RenderFrameHost gets flipped to/from active.
1666 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1667 GetSiteInstance()->increment_active_frame_count();
1668 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1669 GetSiteInstance()->decrement_active_frame_count();
1671 // The active and swapped out state of the RVH is determined by its main
1672 // frame, since subframes should have their own widgets.
1673 if (frame_tree_node_->IsMainFrame()) {
1674 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1675 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1678 // Whenever we change the RFH state to and from active or swapped out state,
1679 // we should not be waiting for beforeunload or close acks. We clear them
1680 // here to be safe, since they can cause navigations to be ignored in
1681 // OnDidCommitProvisionalLoad.
1682 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1683 if (rfh_state == STATE_DEFAULT ||
1684 rfh_state == STATE_SWAPPED_OUT ||
1685 rfh_state_ == STATE_DEFAULT ||
1686 rfh_state_ == STATE_SWAPPED_OUT) {
1687 if (is_waiting_for_beforeunload_ack_) {
1688 is_waiting_for_beforeunload_ack_ = false;
1689 render_view_host_->decrement_in_flight_event_count();
1690 render_view_host_->StopHangMonitorTimeout();
1692 send_before_unload_start_time_ = base::TimeTicks();
1693 render_view_host_->is_waiting_for_close_ack_ = false;
1695 rfh_state_ = rfh_state;
1698 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1699 // TODO(creis): We should also check for WebUI pages here. Also, when the
1700 // out-of-process iframes implementation is ready, we should check for
1701 // cross-site URLs that are not allowed to commit in this process.
1703 // Give the client a chance to disallow URLs from committing.
1704 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1707 void RenderFrameHostImpl::Navigate(
1708 const CommonNavigationParams& common_params,
1709 const StartNavigationParams& start_params,
1710 const RequestNavigationParams& request_params) {
1711 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1713 UpdatePermissionsForNavigation(common_params, request_params);
1715 // Only send the message if we aren't suspended at the start of a cross-site
1716 // request.
1717 if (navigations_suspended_) {
1718 // Shouldn't be possible to have a second navigation while suspended, since
1719 // navigations will only be suspended during a cross-site request. If a
1720 // second navigation occurs, RenderFrameHostManager will cancel this pending
1721 // RFH and create a new pending RFH.
1722 DCHECK(!suspended_nav_params_.get());
1723 suspended_nav_params_.reset(
1724 new NavigationParams(common_params, start_params, request_params));
1725 } else {
1726 // Get back to a clean state, in case we start a new navigation without
1727 // completing a RFH swap or unload handler.
1728 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1730 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1731 request_params));
1734 // Force the throbber to start. This is done because Blink's "started loading"
1735 // message will be received asynchronously from the UI of the browser. But the
1736 // throbber needs to be kept in sync with what's happening in the UI. For
1737 // example, the throbber will start immediately when the user navigates even
1738 // if the renderer is delayed. There is also an issue with the throbber
1739 // starting because the WebUI (which controls whether the favicon is
1740 // displayed) happens synchronously. If the start loading messages was
1741 // asynchronous, then the default favicon would flash in.
1743 // Blink doesn't send throb notifications for JavaScript URLs, so it is not
1744 // done here either.
1745 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1746 frame_tree_node_->DidStartLoading(true);
1749 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1750 CommonNavigationParams common_params(
1751 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::NORMAL,
1752 true, false, base::TimeTicks::Now(),
1753 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
1754 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1757 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1758 SiteInstance* source_site_instance) {
1759 GURL validated_url(params.url);
1760 GetProcess()->FilterURL(false, &validated_url);
1762 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1763 validated_url.possibly_invalid_spec());
1764 frame_tree_node_->navigator()->RequestOpenURL(
1765 this, validated_url, source_site_instance, params.referrer,
1766 params.disposition, params.should_replace_current_entry,
1767 params.user_gesture);
1770 void RenderFrameHostImpl::Stop() {
1771 Send(new FrameMsg_Stop(routing_id_));
1774 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1775 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1776 // the handler ran and allowed the navigation to proceed.
1777 if (!ShouldDispatchBeforeUnload()) {
1778 DCHECK(!(base::CommandLine::ForCurrentProcess()->HasSwitch(
1779 switches::kEnableBrowserSideNavigation) &&
1780 for_navigation));
1781 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1782 for_navigation, true, base::TimeTicks::Now());
1783 return;
1785 TRACE_EVENT_ASYNC_BEGIN0(
1786 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1788 // This may be called more than once (if the user clicks the tab close button
1789 // several times, or if she clicks the tab close button then the browser close
1790 // button), and we only send the message once.
1791 if (is_waiting_for_beforeunload_ack_) {
1792 // Some of our close messages could be for the tab, others for cross-site
1793 // transitions. We always want to think it's for closing the tab if any
1794 // of the messages were, since otherwise it might be impossible to close
1795 // (if there was a cross-site "close" request pending when the user clicked
1796 // the close button). We want to keep the "for cross site" flag only if
1797 // both the old and the new ones are also for cross site.
1798 unload_ack_is_for_navigation_ =
1799 unload_ack_is_for_navigation_ && for_navigation;
1800 } else {
1801 // Start the hang monitor in case the renderer hangs in the beforeunload
1802 // handler.
1803 is_waiting_for_beforeunload_ack_ = true;
1804 unload_ack_is_for_navigation_ = for_navigation;
1805 // Increment the in-flight event count, to ensure that input events won't
1806 // cancel the timeout timer.
1807 render_view_host_->increment_in_flight_event_count();
1808 render_view_host_->StartHangMonitorTimeout(
1809 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1810 send_before_unload_start_time_ = base::TimeTicks::Now();
1811 Send(new FrameMsg_BeforeUnload(routing_id_));
1815 bool RenderFrameHostImpl::ShouldDispatchBeforeUnload() {
1816 // TODO(creis): Support beforeunload on subframes.
1817 return !GetParent() && IsRenderFrameLive();
1820 void RenderFrameHostImpl::DisownOpener() {
1821 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1824 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1825 size_t after) {
1826 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1829 void RenderFrameHostImpl::JavaScriptDialogClosed(
1830 IPC::Message* reply_msg,
1831 bool success,
1832 const base::string16& user_input,
1833 bool dialog_was_suppressed) {
1834 GetProcess()->SetIgnoreInputEvents(false);
1835 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1837 // If we are executing as part of (before)unload event handling, we don't
1838 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1839 // leave the current page. In this case, use the regular timeout value used
1840 // during the (before)unload handling.
1841 if (is_waiting) {
1842 render_view_host_->StartHangMonitorTimeout(
1843 success
1844 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1845 : render_view_host_->hung_renderer_delay_);
1848 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1849 success, user_input);
1850 Send(reply_msg);
1852 // If we are waiting for an unload or beforeunload ack and the user has
1853 // suppressed messages, kill the tab immediately; a page that's spamming
1854 // alerts in onbeforeunload is presumably malicious, so there's no point in
1855 // continuing to run its script and dragging out the process.
1856 // This must be done after sending the reply since RenderView can't close
1857 // correctly while waiting for a response.
1858 if (is_waiting && dialog_was_suppressed)
1859 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1862 // PlzNavigate
1863 void RenderFrameHostImpl::CommitNavigation(
1864 ResourceResponse* response,
1865 scoped_ptr<StreamHandle> body,
1866 const CommonNavigationParams& common_params,
1867 const RequestNavigationParams& request_params) {
1868 DCHECK((response && body.get()) ||
1869 !ShouldMakeNetworkRequestForURL(common_params.url));
1870 UpdatePermissionsForNavigation(common_params, request_params);
1872 // Get back to a clean state, in case we start a new navigation without
1873 // completing a RFH swap or unload handler.
1874 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1876 const GURL body_url = body.get() ? body->GetURL() : GURL();
1877 const ResourceResponseHead head = response ?
1878 response->head : ResourceResponseHead();
1879 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1880 request_params));
1881 // TODO(clamy): Check if we should start the throbber for non javascript urls
1882 // here.
1884 // TODO(clamy): Release the stream handle once the renderer has finished
1885 // reading it.
1886 stream_handle_ = body.Pass();
1888 // When navigating to a Javascript url, no commit is expected from the
1889 // RenderFrameHost, nor should the throbber start.
1890 if (!common_params.url.SchemeIs(url::kJavaScriptScheme)) {
1891 pending_commit_ = true;
1892 is_loading_ = true;
1894 frame_tree_node_->ResetNavigationRequest(true);
1897 void RenderFrameHostImpl::FailedNavigation(
1898 const CommonNavigationParams& common_params,
1899 const RequestNavigationParams& request_params,
1900 bool has_stale_copy_in_cache,
1901 int error_code) {
1902 // Get back to a clean state, in case a new navigation started without
1903 // completing a RFH swap or unload handler.
1904 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1906 Send(new FrameMsg_FailedNavigation(routing_id_, common_params, request_params,
1907 has_stale_copy_in_cache, error_code));
1909 // An error page is expected to commit, hence why is_loading_ is set to true.
1910 is_loading_ = true;
1911 frame_tree_node_->ResetNavigationRequest(true);
1914 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1915 if (service_registry_.get())
1916 return;
1918 service_registry_.reset(new ServiceRegistryImpl());
1919 if (!GetProcess()->GetServiceRegistry())
1920 return;
1922 RegisterMojoServices();
1923 RenderFrameSetupPtr setup;
1924 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(
1925 mojo::GetProxy(&setup));
1927 mojo::ServiceProviderPtr exposed_services;
1928 service_registry_->Bind(GetProxy(&exposed_services));
1930 mojo::ServiceProviderPtr services;
1931 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1932 exposed_services.Pass());
1933 service_registry_->BindRemoteServiceProvider(services.Pass());
1935 #if defined(OS_ANDROID)
1936 service_registry_android_.reset(
1937 new ServiceRegistryAndroid(service_registry_.get()));
1938 ServiceRegistrarAndroid::RegisterFrameHostServices(
1939 service_registry_android_.get());
1940 #endif
1943 void RenderFrameHostImpl::InvalidateMojoConnection() {
1944 #if defined(OS_ANDROID)
1945 // The Android-specific service registry has a reference to
1946 // |service_registry_| and thus must be torn down first.
1947 service_registry_android_.reset();
1948 #endif
1950 service_registry_.reset();
1952 // Disconnect with ImageDownloader Mojo service in RenderFrame.
1953 mojo_image_downloader_.reset();
1956 bool RenderFrameHostImpl::IsFocused() {
1957 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1958 // returning nullptr in some cases. See https://crbug.com/455245.
1959 return RenderWidgetHostImpl::From(
1960 GetView()->GetRenderWidgetHost())->is_focused() &&
1961 frame_tree_->GetFocusedFrame() &&
1962 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1963 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1966 const image_downloader::ImageDownloaderPtr&
1967 RenderFrameHostImpl::GetMojoImageDownloader() {
1968 if (!mojo_image_downloader_.get() && GetServiceRegistry()) {
1969 GetServiceRegistry()->ConnectToRemoteService(
1970 mojo::GetProxy(&mojo_image_downloader_));
1972 return mojo_image_downloader_;
1975 void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility(
1976 const std::map<int32, int>& node_to_frame_routing_id_map) {
1977 for (const auto& iter : node_to_frame_routing_id_map) {
1978 // This is the id of the accessibility node that has a child frame.
1979 int32 node_id = iter.first;
1980 // The routing id from either a RenderFrame or a RenderFrameProxy.
1981 int frame_routing_id = iter.second;
1983 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1984 FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID(
1985 GetProcess()->GetID(), frame_routing_id);
1987 if (child_frame_tree_node) {
1988 FrameAccessibility::GetInstance()->AddChildFrame(
1989 this, node_id, child_frame_tree_node->frame_tree_node_id());
1994 void RenderFrameHostImpl::UpdateGuestFrameAccessibility(
1995 const std::map<int32, int>& node_to_browser_plugin_instance_id_map) {
1996 for (const auto& iter : node_to_browser_plugin_instance_id_map) {
1997 // This is the id of the accessibility node that hosts a plugin.
1998 int32 node_id = iter.first;
1999 // The id of the browser plugin.
2000 int browser_plugin_instance_id = iter.second;
2001 FrameAccessibility::GetInstance()->AddGuestWebContents(
2002 this, node_id, browser_plugin_instance_id);
2006 bool RenderFrameHostImpl::IsSameSiteInstance(
2007 RenderFrameHostImpl* other_render_frame_host) {
2008 // As a sanity check, make sure the frame belongs to the same BrowserContext.
2009 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
2010 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
2011 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
2014 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
2015 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
2018 void RenderFrameHostImpl::RequestAXTreeSnapshot(
2019 AXTreeSnapshotCallback callback) {
2020 static int next_id = 1;
2021 int callback_id = next_id++;
2022 Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
2023 ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
2026 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
2027 const base::Callback<void(ui::AXEvent, int)>& callback) {
2028 accessibility_testing_callback_ = callback;
2031 void RenderFrameHostImpl::SetTextTrackSettings(
2032 const FrameMsg_TextTrackSettings_Params& params) {
2033 DCHECK(!GetParent());
2034 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
2037 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
2038 return ax_tree_for_testing_.get();
2041 BrowserAccessibilityManager*
2042 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
2043 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2044 render_view_host_->GetView());
2045 if (view &&
2046 !browser_accessibility_manager_ &&
2047 !no_create_browser_accessibility_manager_for_testing_) {
2048 browser_accessibility_manager_.reset(
2049 view->CreateBrowserAccessibilityManager(this));
2050 if (browser_accessibility_manager_)
2051 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
2052 else
2053 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
2055 return browser_accessibility_manager_.get();
2058 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
2059 int request_id) {
2060 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
2061 if (accessibility_mode & AccessibilityModeFlagPlatform) {
2062 BrowserAccessibilityManager* manager =
2063 GetOrCreateBrowserAccessibilityManager();
2064 if (manager)
2065 manager->ActivateFindInPageResult(request_id);
2069 void RenderFrameHostImpl::InsertVisualStateCallback(
2070 const VisualStateCallback& callback) {
2071 static uint64 next_id = 1;
2072 uint64 key = next_id++;
2073 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
2074 visual_state_callbacks_.insert(std::make_pair(key, callback));
2077 bool RenderFrameHostImpl::IsRenderFrameLive() {
2078 bool is_live = GetProcess()->HasConnection() && render_frame_created_;
2080 // Sanity check: the RenderView should always be live if the RenderFrame is.
2081 DCHECK_IMPLIES(is_live, render_view_host_->IsRenderViewLive());
2083 return is_live;
2086 #if defined(OS_WIN)
2088 void RenderFrameHostImpl::SetParentNativeViewAccessible(
2089 gfx::NativeViewAccessible accessible_parent) {
2090 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2091 render_view_host_->GetView());
2092 if (view)
2093 view->SetParentNativeViewAccessible(accessible_parent);
2096 gfx::NativeViewAccessible
2097 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
2098 return delegate_->GetParentNativeViewAccessible();
2101 #elif defined(OS_MACOSX)
2103 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
2104 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
2107 void RenderFrameHostImpl::DidCancelPopupMenu() {
2108 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
2111 #elif defined(OS_ANDROID)
2113 void RenderFrameHostImpl::DidSelectPopupMenuItems(
2114 const std::vector<int>& selected_indices) {
2115 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
2118 void RenderFrameHostImpl::DidCancelPopupMenu() {
2119 Send(new FrameMsg_SelectPopupMenuItems(
2120 routing_id_, true, std::vector<int>()));
2123 #endif
2125 void RenderFrameHostImpl::SetNavigationsSuspended(
2126 bool suspend,
2127 const base::TimeTicks& proceed_time) {
2128 // This should only be called to toggle the state.
2129 DCHECK(navigations_suspended_ != suspend);
2131 navigations_suspended_ = suspend;
2132 if (navigations_suspended_) {
2133 TRACE_EVENT_ASYNC_BEGIN0("navigation",
2134 "RenderFrameHostImpl navigation suspended", this);
2135 } else {
2136 TRACE_EVENT_ASYNC_END0("navigation",
2137 "RenderFrameHostImpl navigation suspended", this);
2140 if (!suspend && suspended_nav_params_) {
2141 // There's navigation message params waiting to be sent. Now that we're not
2142 // suspended anymore, resume navigation by sending them. If we were swapped
2143 // out, we should also stop filtering out the IPC messages now.
2144 SetState(RenderFrameHostImpl::STATE_DEFAULT);
2146 DCHECK(!proceed_time.is_null());
2147 suspended_nav_params_->request_params.browser_navigation_start =
2148 proceed_time;
2149 Send(new FrameMsg_Navigate(routing_id_,
2150 suspended_nav_params_->common_params,
2151 suspended_nav_params_->start_params,
2152 suspended_nav_params_->request_params));
2153 suspended_nav_params_.reset();
2157 void RenderFrameHostImpl::CancelSuspendedNavigations() {
2158 // Clear any state if a pending navigation is canceled or preempted.
2159 if (suspended_nav_params_)
2160 suspended_nav_params_.reset();
2162 TRACE_EVENT_ASYNC_END0("navigation",
2163 "RenderFrameHostImpl navigation suspended", this);
2164 navigations_suspended_ = false;
2167 void RenderFrameHostImpl::DidUseGeolocationPermission() {
2168 PermissionManager* permission_manager =
2169 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
2170 if (!permission_manager)
2171 return;
2173 permission_manager->RegisterPermissionUsage(
2174 PermissionType::GEOLOCATION,
2175 GetLastCommittedURL().GetOrigin(),
2176 frame_tree_node()->frame_tree()->GetMainFrame()
2177 ->GetLastCommittedURL().GetOrigin());
2180 void RenderFrameHostImpl::UpdatePermissionsForNavigation(
2181 const CommonNavigationParams& common_params,
2182 const RequestNavigationParams& request_params) {
2183 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
2184 // so do not grant them the ability to request additional URLs.
2185 if (!GetProcess()->IsForGuestsOnly()) {
2186 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2187 GetProcess()->GetID(), common_params.url);
2188 if (common_params.url.SchemeIs(url::kDataScheme) &&
2189 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
2190 // If 'data:' is used, and we have a 'file:' base url, grant access to
2191 // local files.
2192 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2193 GetProcess()->GetID(), common_params.base_url_for_data_url);
2197 // We may be returning to an existing NavigationEntry that had been granted
2198 // file access. If this is a different process, we will need to grant the
2199 // access again. The files listed in the page state are validated when they
2200 // are received from the renderer to prevent abuse.
2201 if (request_params.page_state.IsValid()) {
2202 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
2206 bool RenderFrameHostImpl::CanExecuteJavaScript() {
2207 return g_allow_injecting_javascript ||
2208 !frame_tree_node_->current_url().is_valid() ||
2209 frame_tree_node_->current_url().SchemeIs(kChromeDevToolsScheme) ||
2210 ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2211 GetProcess()->GetID()) ||
2212 // It's possible to load about:blank in a Web UI renderer.
2213 // See http://crbug.com/42547
2214 (frame_tree_node_->current_url().spec() == url::kAboutBlankURL) ||
2215 // InterstitialPageImpl should be the only case matching this.
2216 (delegate_->GetAsWebContents() == nullptr);
2219 } // namespace content