[refactor] More post-NSS WebCrypto cleanups (utility functions).
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blob8f6c99c269f96de55707f4f34fffa855cced9901
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 frame_tree_node()->navigator()->OnBeginNavigation(
1363 frame_tree_node(), common_params, begin_params, body);
1366 void RenderFrameHostImpl::OnDispatchLoad() {
1367 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
1368 // Only frames with an out-of-process parent frame should be sending this
1369 // message.
1370 RenderFrameProxyHost* proxy =
1371 frame_tree_node()->render_manager()->GetProxyToParent();
1372 if (!proxy) {
1373 bad_message::ReceivedBadMessage(GetProcess(),
1374 bad_message::RFH_NO_PROXY_TO_PARENT);
1375 return;
1378 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1381 void RenderFrameHostImpl::OnAccessibilityEvents(
1382 const std::vector<AccessibilityHostMsg_EventParams>& params,
1383 int reset_token) {
1384 // Don't process this IPC if either we're waiting on a reset and this
1385 // IPC doesn't have the matching token ID, or if we're not waiting on a
1386 // reset but this message includes a reset token.
1387 if (accessibility_reset_token_ != reset_token) {
1388 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1389 return;
1391 accessibility_reset_token_ = 0;
1393 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1394 frame_tree_node_->frame_tree()
1395 ->GetMainFrame()
1396 ->render_view_host_->GetView());
1398 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1399 if ((accessibility_mode != AccessibilityModeOff) && view &&
1400 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1401 if (accessibility_mode & AccessibilityModeFlagPlatform)
1402 GetOrCreateBrowserAccessibilityManager();
1404 std::vector<AXEventNotificationDetails> details;
1405 details.reserve(params.size());
1406 for (size_t i = 0; i < params.size(); ++i) {
1407 const AccessibilityHostMsg_EventParams& param = params[i];
1408 AXEventNotificationDetails detail;
1409 detail.event_type = param.event_type;
1410 detail.id = param.id;
1411 detail.ax_tree_id = GetAXTreeID();
1412 detail.update.node_id_to_clear = param.update.node_id_to_clear;
1413 detail.update.nodes.resize(param.update.nodes.size());
1414 for (size_t i = 0; i < param.update.nodes.size(); ++i) {
1415 AXContentNodeDataToAXNodeData(param.update.nodes[i],
1416 &detail.update.nodes[i]);
1418 details.push_back(detail);
1421 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1422 if (browser_accessibility_manager_)
1423 browser_accessibility_manager_->OnAccessibilityEvents(details);
1426 // Send the updates to the automation extension API.
1427 delegate_->AccessibilityEventReceived(details);
1429 // For testing only.
1430 if (!accessibility_testing_callback_.is_null()) {
1431 for (size_t i = 0; i < details.size(); i++) {
1432 const AXEventNotificationDetails& detail = details[i];
1433 if (static_cast<int>(detail.event_type) < 0)
1434 continue;
1436 if (!ax_tree_for_testing_) {
1437 if (browser_accessibility_manager_) {
1438 ax_tree_for_testing_.reset(new ui::AXTree(
1439 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1440 } else {
1441 ax_tree_for_testing_.reset(new ui::AXTree());
1442 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1443 << ax_tree_for_testing_->error();
1445 } else {
1446 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1447 << ax_tree_for_testing_->error();
1449 accessibility_testing_callback_.Run(detail.event_type, detail.id);
1454 // Always send an ACK or the renderer can be in a bad state.
1455 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1458 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1459 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1460 if (accessibility_reset_token_)
1461 return;
1463 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1464 render_view_host_->GetView());
1465 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1466 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1467 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1468 BrowserAccessibilityManager* manager =
1469 GetOrCreateBrowserAccessibilityManager();
1470 if (manager)
1471 manager->OnLocationChanges(params);
1473 // TODO(aboxhall): send location change events to web contents observers too
1477 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1478 const AccessibilityHostMsg_FindInPageResultParams& params) {
1479 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1480 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1481 BrowserAccessibilityManager* manager =
1482 GetOrCreateBrowserAccessibilityManager();
1483 if (manager) {
1484 manager->OnFindInPageResult(
1485 params.request_id, params.match_index, params.start_id,
1486 params.start_offset, params.end_id, params.end_offset);
1491 void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
1492 int callback_id,
1493 const ui::AXTreeUpdate<AXContentNodeData>& snapshot) {
1494 const auto& it = ax_tree_snapshot_callbacks_.find(callback_id);
1495 if (it != ax_tree_snapshot_callbacks_.end()) {
1496 ui::AXTreeUpdate<ui::AXNodeData> dst_snapshot;
1497 dst_snapshot.nodes.resize(snapshot.nodes.size());
1498 for (size_t i = 0; i < snapshot.nodes.size(); ++i) {
1499 AXContentNodeDataToAXNodeData(snapshot.nodes[i],
1500 &dst_snapshot.nodes[i]);
1502 it->second.Run(dst_snapshot);
1503 ax_tree_snapshot_callbacks_.erase(it);
1504 } else {
1505 NOTREACHED() << "Received AX tree snapshot response for unknown id";
1509 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1510 if (enter_fullscreen)
1511 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1512 else
1513 delegate_->ExitFullscreenMode();
1515 // The previous call might change the fullscreen state. We need to make sure
1516 // the renderer is aware of that, which is done via the resize message.
1517 render_view_host_->WasResized();
1520 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
1521 // Any main frame load to a new document should reset the load since it will
1522 // replace the current page and any frames.
1523 if (to_different_document && !GetParent())
1524 is_loading_ = false;
1526 // This method should never be called when the frame is loading.
1527 // Unfortunately, it can happen if a history navigation happens during a
1528 // BeforeUnload or Unload event.
1529 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1530 // refactored in Blink. See crbug.com/466089
1531 if (is_loading_) {
1532 LOG(WARNING) << "OnDidStartLoading was called twice.";
1533 return;
1536 frame_tree_node_->DidStartLoading(to_different_document);
1537 is_loading_ = true;
1540 void RenderFrameHostImpl::OnDidStopLoading() {
1541 // This method should never be called when the frame is not loading.
1542 // Unfortunately, it can happen if a history navigation happens during a
1543 // BeforeUnload or Unload event.
1544 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1545 // refactored in Blink. See crbug.com/466089
1546 if (!is_loading_) {
1547 LOG(WARNING) << "OnDidStopLoading was called twice.";
1548 return;
1551 is_loading_ = false;
1552 frame_tree_node_->DidStopLoading();
1553 navigation_handle_.reset();
1556 void RenderFrameHostImpl::OnDidChangeLoadProgress(double load_progress) {
1557 frame_tree_node_->DidChangeLoadProgress(load_progress);
1560 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1561 void RenderFrameHostImpl::OnShowPopup(
1562 const FrameHostMsg_ShowPopup_Params& params) {
1563 RenderViewHostDelegateView* view =
1564 render_view_host_->delegate_->GetDelegateView();
1565 if (view) {
1566 view->ShowPopupMenu(this,
1567 params.bounds,
1568 params.item_height,
1569 params.item_font_size,
1570 params.selected_item,
1571 params.popup_items,
1572 params.right_aligned,
1573 params.allow_multiple_selection);
1577 void RenderFrameHostImpl::OnHidePopup() {
1578 RenderViewHostDelegateView* view =
1579 render_view_host_->delegate_->GetDelegateView();
1580 if (view)
1581 view->HidePopupMenu();
1583 #endif
1585 void RenderFrameHostImpl::RegisterMojoServices() {
1586 GeolocationServiceContext* geolocation_service_context =
1587 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1588 if (geolocation_service_context) {
1589 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1590 // can perform permissions checks once site isolation is complete.
1591 // crbug.com/426384
1592 GetServiceRegistry()->AddService<GeolocationService>(
1593 base::Bind(&GeolocationServiceContext::CreateService,
1594 base::Unretained(geolocation_service_context),
1595 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1596 base::Unretained(this))));
1599 if (!permission_service_context_)
1600 permission_service_context_.reset(new PermissionServiceContext(this));
1602 GetServiceRegistry()->AddService<PermissionService>(
1603 base::Bind(&PermissionServiceContext::CreateService,
1604 base::Unretained(permission_service_context_.get())));
1606 GetServiceRegistry()->AddService<presentation::PresentationService>(
1607 base::Bind(&PresentationServiceImpl::CreateMojoService,
1608 base::Unretained(this)));
1610 if (!frame_mojo_shell_)
1611 frame_mojo_shell_.reset(new FrameMojoShell(this));
1613 GetServiceRegistry()->AddService<mojo::Shell>(base::Bind(
1614 &FrameMojoShell::BindRequest, base::Unretained(frame_mojo_shell_.get())));
1616 #if defined(ENABLE_WEBVR)
1617 const base::CommandLine& browser_command_line =
1618 *base::CommandLine::ForCurrentProcess();
1620 if (browser_command_line.HasSwitch(switches::kEnableWebVR)) {
1621 GetServiceRegistry()->AddService<VRService>(
1622 base::Bind(&VRDeviceManager::BindRequest));
1624 #endif
1627 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1628 // Only main frames should be swapped out and retained inside a proxy host.
1629 if (rfh_state == STATE_SWAPPED_OUT)
1630 CHECK(!GetParent());
1632 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1633 // out status of a RenderFrameHost gets flipped to/from active.
1634 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1635 GetSiteInstance()->increment_active_frame_count();
1636 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1637 GetSiteInstance()->decrement_active_frame_count();
1639 // The active and swapped out state of the RVH is determined by its main
1640 // frame, since subframes should have their own widgets.
1641 if (frame_tree_node_->IsMainFrame()) {
1642 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1643 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1646 // Whenever we change the RFH state to and from active or swapped out state,
1647 // we should not be waiting for beforeunload or close acks. We clear them
1648 // here to be safe, since they can cause navigations to be ignored in
1649 // OnDidCommitProvisionalLoad.
1650 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1651 if (rfh_state == STATE_DEFAULT ||
1652 rfh_state == STATE_SWAPPED_OUT ||
1653 rfh_state_ == STATE_DEFAULT ||
1654 rfh_state_ == STATE_SWAPPED_OUT) {
1655 if (is_waiting_for_beforeunload_ack_) {
1656 is_waiting_for_beforeunload_ack_ = false;
1657 render_view_host_->decrement_in_flight_event_count();
1658 render_view_host_->StopHangMonitorTimeout();
1660 send_before_unload_start_time_ = base::TimeTicks();
1661 render_view_host_->is_waiting_for_close_ack_ = false;
1663 rfh_state_ = rfh_state;
1666 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1667 // TODO(creis): We should also check for WebUI pages here. Also, when the
1668 // out-of-process iframes implementation is ready, we should check for
1669 // cross-site URLs that are not allowed to commit in this process.
1671 // Give the client a chance to disallow URLs from committing.
1672 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1675 void RenderFrameHostImpl::Navigate(
1676 const CommonNavigationParams& common_params,
1677 const StartNavigationParams& start_params,
1678 const RequestNavigationParams& request_params) {
1679 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1680 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1681 switches::kEnableBrowserSideNavigation));
1683 UpdatePermissionsForNavigation(common_params, request_params);
1685 // Only send the message if we aren't suspended at the start of a cross-site
1686 // request.
1687 if (navigations_suspended_) {
1688 // Shouldn't be possible to have a second navigation while suspended, since
1689 // navigations will only be suspended during a cross-site request. If a
1690 // second navigation occurs, RenderFrameHostManager will cancel this pending
1691 // RFH and create a new pending RFH.
1692 DCHECK(!suspended_nav_params_.get());
1693 suspended_nav_params_.reset(
1694 new NavigationParams(common_params, start_params, request_params));
1695 } else {
1696 // Get back to a clean state, in case we start a new navigation without
1697 // completing a RFH swap or unload handler.
1698 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1700 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1701 request_params));
1704 // Force the throbber to start. This is done because Blink's "started loading"
1705 // message will be received asynchronously from the UI of the browser. But the
1706 // throbber needs to be kept in sync with what's happening in the UI. For
1707 // example, the throbber will start immediately when the user navigates even
1708 // if the renderer is delayed. There is also an issue with the throbber
1709 // starting because the WebUI (which controls whether the favicon is
1710 // displayed) happens synchronously. If the start loading messages was
1711 // asynchronous, then the default favicon would flash in.
1713 // Blink doesn't send throb notifications for JavaScript URLs, so it is not
1714 // done here either.
1715 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1716 frame_tree_node_->DidStartLoading(true);
1719 void RenderFrameHostImpl::NavigateToInterstitialURL(const GURL& data_url) {
1720 DCHECK(data_url.SchemeIs(url::kDataScheme));
1721 CommonNavigationParams common_params(
1722 data_url, Referrer(), ui::PAGE_TRANSITION_LINK,
1723 FrameMsg_Navigate_Type::NORMAL, false, false, base::TimeTicks::Now(),
1724 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
1725 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1726 switches::kEnableBrowserSideNavigation)) {
1727 CommitNavigation(nullptr, nullptr, common_params,
1728 RequestNavigationParams());
1729 } else {
1730 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1734 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1735 SiteInstance* source_site_instance) {
1736 GURL validated_url(params.url);
1737 GetProcess()->FilterURL(false, &validated_url);
1739 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1740 validated_url.possibly_invalid_spec());
1741 frame_tree_node_->navigator()->RequestOpenURL(
1742 this, validated_url, source_site_instance, params.referrer,
1743 params.disposition, params.should_replace_current_entry,
1744 params.user_gesture);
1747 void RenderFrameHostImpl::Stop() {
1748 Send(new FrameMsg_Stop(routing_id_));
1751 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1752 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1753 // the handler ran and allowed the navigation to proceed.
1754 if (!ShouldDispatchBeforeUnload()) {
1755 DCHECK(!(base::CommandLine::ForCurrentProcess()->HasSwitch(
1756 switches::kEnableBrowserSideNavigation) &&
1757 for_navigation));
1758 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1759 for_navigation, true, base::TimeTicks::Now());
1760 return;
1762 TRACE_EVENT_ASYNC_BEGIN0(
1763 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1765 // This may be called more than once (if the user clicks the tab close button
1766 // several times, or if she clicks the tab close button then the browser close
1767 // button), and we only send the message once.
1768 if (is_waiting_for_beforeunload_ack_) {
1769 // Some of our close messages could be for the tab, others for cross-site
1770 // transitions. We always want to think it's for closing the tab if any
1771 // of the messages were, since otherwise it might be impossible to close
1772 // (if there was a cross-site "close" request pending when the user clicked
1773 // the close button). We want to keep the "for cross site" flag only if
1774 // both the old and the new ones are also for cross site.
1775 unload_ack_is_for_navigation_ =
1776 unload_ack_is_for_navigation_ && for_navigation;
1777 } else {
1778 // Start the hang monitor in case the renderer hangs in the beforeunload
1779 // handler.
1780 is_waiting_for_beforeunload_ack_ = true;
1781 unload_ack_is_for_navigation_ = for_navigation;
1782 // Increment the in-flight event count, to ensure that input events won't
1783 // cancel the timeout timer.
1784 render_view_host_->increment_in_flight_event_count();
1785 render_view_host_->StartHangMonitorTimeout(
1786 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1787 send_before_unload_start_time_ = base::TimeTicks::Now();
1788 Send(new FrameMsg_BeforeUnload(routing_id_));
1792 bool RenderFrameHostImpl::ShouldDispatchBeforeUnload() {
1793 // TODO(creis): Support beforeunload on subframes.
1794 return !GetParent() && IsRenderFrameLive();
1797 void RenderFrameHostImpl::UpdateOpener() {
1798 // This frame (the frame whose opener is being updated) might not have had
1799 // proxies for the new opener chain in its SiteInstance. Make sure they
1800 // exist.
1801 if (frame_tree_node_->opener()) {
1802 frame_tree_node_->opener()->render_manager()->CreateOpenerProxies(
1803 GetSiteInstance(), frame_tree_node_);
1806 int opener_routing_id =
1807 frame_tree_node_->render_manager()->GetOpenerRoutingID(GetSiteInstance());
1808 Send(new FrameMsg_UpdateOpener(GetRoutingID(), opener_routing_id));
1811 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1812 size_t after) {
1813 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1816 void RenderFrameHostImpl::JavaScriptDialogClosed(
1817 IPC::Message* reply_msg,
1818 bool success,
1819 const base::string16& user_input,
1820 bool dialog_was_suppressed) {
1821 GetProcess()->SetIgnoreInputEvents(false);
1822 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1824 // If we are executing as part of (before)unload event handling, we don't
1825 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1826 // leave the current page. In this case, use the regular timeout value used
1827 // during the (before)unload handling.
1828 if (is_waiting) {
1829 render_view_host_->StartHangMonitorTimeout(
1830 success
1831 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1832 : render_view_host_->hung_renderer_delay_);
1835 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1836 success, user_input);
1837 Send(reply_msg);
1839 // If we are waiting for an unload or beforeunload ack and the user has
1840 // suppressed messages, kill the tab immediately; a page that's spamming
1841 // alerts in onbeforeunload is presumably malicious, so there's no point in
1842 // continuing to run its script and dragging out the process.
1843 // This must be done after sending the reply since RenderView can't close
1844 // correctly while waiting for a response.
1845 if (is_waiting && dialog_was_suppressed)
1846 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1849 // PlzNavigate
1850 void RenderFrameHostImpl::CommitNavigation(
1851 ResourceResponse* response,
1852 scoped_ptr<StreamHandle> body,
1853 const CommonNavigationParams& common_params,
1854 const RequestNavigationParams& request_params) {
1855 DCHECK((response && body.get()) ||
1856 !ShouldMakeNetworkRequestForURL(common_params.url));
1857 UpdatePermissionsForNavigation(common_params, request_params);
1859 // Get back to a clean state, in case we start a new navigation without
1860 // completing a RFH swap or unload handler.
1861 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1863 const GURL body_url = body.get() ? body->GetURL() : GURL();
1864 const ResourceResponseHead head = response ?
1865 response->head : ResourceResponseHead();
1866 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1867 request_params));
1868 // TODO(clamy): Check if we should start the throbber for non javascript urls
1869 // here.
1871 // TODO(clamy): Release the stream handle once the renderer has finished
1872 // reading it.
1873 stream_handle_ = body.Pass();
1875 // When navigating to a Javascript url, no commit is expected from the
1876 // RenderFrameHost, nor should the throbber start.
1877 if (!common_params.url.SchemeIs(url::kJavaScriptScheme)) {
1878 pending_commit_ = true;
1879 is_loading_ = true;
1881 frame_tree_node_->ResetNavigationRequest(true);
1884 void RenderFrameHostImpl::FailedNavigation(
1885 const CommonNavigationParams& common_params,
1886 const RequestNavigationParams& request_params,
1887 bool has_stale_copy_in_cache,
1888 int error_code) {
1889 // Get back to a clean state, in case a new navigation started without
1890 // completing a RFH swap or unload handler.
1891 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1893 Send(new FrameMsg_FailedNavigation(routing_id_, common_params, request_params,
1894 has_stale_copy_in_cache, error_code));
1896 // An error page is expected to commit, hence why is_loading_ is set to true.
1897 is_loading_ = true;
1898 frame_tree_node_->ResetNavigationRequest(true);
1901 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1902 if (service_registry_.get())
1903 return;
1905 service_registry_.reset(new ServiceRegistryImpl());
1906 if (!GetProcess()->GetServiceRegistry())
1907 return;
1909 RegisterMojoServices();
1910 RenderFrameSetupPtr setup;
1911 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(
1912 mojo::GetProxy(&setup));
1914 mojo::ServiceProviderPtr exposed_services;
1915 service_registry_->Bind(GetProxy(&exposed_services));
1917 mojo::ServiceProviderPtr services;
1918 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1919 exposed_services.Pass());
1920 service_registry_->BindRemoteServiceProvider(services.Pass());
1922 #if defined(OS_ANDROID)
1923 service_registry_android_.reset(
1924 new ServiceRegistryAndroid(service_registry_.get()));
1925 ServiceRegistrarAndroid::RegisterFrameHostServices(
1926 service_registry_android_.get());
1927 #endif
1930 void RenderFrameHostImpl::InvalidateMojoConnection() {
1931 #if defined(OS_ANDROID)
1932 // The Android-specific service registry has a reference to
1933 // |service_registry_| and thus must be torn down first.
1934 service_registry_android_.reset();
1935 #endif
1937 service_registry_.reset();
1939 // Disconnect with ImageDownloader Mojo service in RenderFrame.
1940 mojo_image_downloader_.reset();
1943 bool RenderFrameHostImpl::IsFocused() {
1944 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1945 // returning nullptr in some cases. See https://crbug.com/455245.
1946 return RenderWidgetHostImpl::From(
1947 GetView()->GetRenderWidgetHost())->is_focused() &&
1948 frame_tree_->GetFocusedFrame() &&
1949 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1950 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1953 const image_downloader::ImageDownloaderPtr&
1954 RenderFrameHostImpl::GetMojoImageDownloader() {
1955 if (!mojo_image_downloader_.get() && GetServiceRegistry()) {
1956 GetServiceRegistry()->ConnectToRemoteService(
1957 mojo::GetProxy(&mojo_image_downloader_));
1959 return mojo_image_downloader_;
1962 bool RenderFrameHostImpl::IsSameSiteInstance(
1963 RenderFrameHostImpl* other_render_frame_host) {
1964 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1965 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1966 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1967 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1970 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1971 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1974 void RenderFrameHostImpl::RequestAXTreeSnapshot(
1975 AXTreeSnapshotCallback callback) {
1976 static int next_id = 1;
1977 int callback_id = next_id++;
1978 Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
1979 ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
1982 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1983 const base::Callback<void(ui::AXEvent, int)>& callback) {
1984 accessibility_testing_callback_ = callback;
1987 void RenderFrameHostImpl::SetTextTrackSettings(
1988 const FrameMsg_TextTrackSettings_Params& params) {
1989 DCHECK(!GetParent());
1990 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
1993 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1994 return ax_tree_for_testing_.get();
1997 BrowserAccessibilityManager*
1998 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1999 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2000 frame_tree_node_->frame_tree()
2001 ->GetMainFrame()
2002 ->render_view_host_->GetView());
2003 if (view &&
2004 !browser_accessibility_manager_ &&
2005 !no_create_browser_accessibility_manager_for_testing_) {
2006 browser_accessibility_manager_.reset(
2007 view->CreateBrowserAccessibilityManager(this));
2008 if (browser_accessibility_manager_)
2009 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
2010 else
2011 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
2013 return browser_accessibility_manager_.get();
2016 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
2017 int request_id) {
2018 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
2019 if (accessibility_mode & AccessibilityModeFlagPlatform) {
2020 BrowserAccessibilityManager* manager =
2021 GetOrCreateBrowserAccessibilityManager();
2022 if (manager)
2023 manager->ActivateFindInPageResult(request_id);
2027 void RenderFrameHostImpl::InsertVisualStateCallback(
2028 const VisualStateCallback& callback) {
2029 static uint64 next_id = 1;
2030 uint64 key = next_id++;
2031 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
2032 visual_state_callbacks_.insert(std::make_pair(key, callback));
2035 bool RenderFrameHostImpl::IsRenderFrameLive() {
2036 bool is_live = GetProcess()->HasConnection() && render_frame_created_;
2038 // Sanity check: the RenderView should always be live if the RenderFrame is.
2039 DCHECK_IMPLIES(is_live, render_view_host_->IsRenderViewLive());
2041 return is_live;
2044 #if defined(OS_WIN)
2046 void RenderFrameHostImpl::SetParentNativeViewAccessible(
2047 gfx::NativeViewAccessible accessible_parent) {
2048 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2049 render_view_host_->GetView());
2050 if (view)
2051 view->SetParentNativeViewAccessible(accessible_parent);
2054 gfx::NativeViewAccessible
2055 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
2056 return delegate_->GetParentNativeViewAccessible();
2059 #elif defined(OS_MACOSX)
2061 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
2062 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
2065 void RenderFrameHostImpl::DidCancelPopupMenu() {
2066 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
2069 #elif defined(OS_ANDROID)
2071 void RenderFrameHostImpl::DidSelectPopupMenuItems(
2072 const std::vector<int>& selected_indices) {
2073 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
2076 void RenderFrameHostImpl::DidCancelPopupMenu() {
2077 Send(new FrameMsg_SelectPopupMenuItems(
2078 routing_id_, true, std::vector<int>()));
2081 #endif
2083 void RenderFrameHostImpl::SetNavigationsSuspended(
2084 bool suspend,
2085 const base::TimeTicks& proceed_time) {
2086 // This should only be called to toggle the state.
2087 DCHECK(navigations_suspended_ != suspend);
2089 navigations_suspended_ = suspend;
2090 if (navigations_suspended_) {
2091 TRACE_EVENT_ASYNC_BEGIN0("navigation",
2092 "RenderFrameHostImpl navigation suspended", this);
2093 } else {
2094 TRACE_EVENT_ASYNC_END0("navigation",
2095 "RenderFrameHostImpl navigation suspended", this);
2098 if (!suspend && suspended_nav_params_) {
2099 // There's navigation message params waiting to be sent. Now that we're not
2100 // suspended anymore, resume navigation by sending them. If we were swapped
2101 // out, we should also stop filtering out the IPC messages now.
2102 SetState(RenderFrameHostImpl::STATE_DEFAULT);
2104 DCHECK(!proceed_time.is_null());
2105 suspended_nav_params_->request_params.browser_navigation_start =
2106 proceed_time;
2107 Send(new FrameMsg_Navigate(routing_id_,
2108 suspended_nav_params_->common_params,
2109 suspended_nav_params_->start_params,
2110 suspended_nav_params_->request_params));
2111 suspended_nav_params_.reset();
2115 void RenderFrameHostImpl::CancelSuspendedNavigations() {
2116 // Clear any state if a pending navigation is canceled or preempted.
2117 if (suspended_nav_params_)
2118 suspended_nav_params_.reset();
2120 TRACE_EVENT_ASYNC_END0("navigation",
2121 "RenderFrameHostImpl navigation suspended", this);
2122 navigations_suspended_ = false;
2125 void RenderFrameHostImpl::DidUseGeolocationPermission() {
2126 PermissionManager* permission_manager =
2127 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
2128 if (!permission_manager)
2129 return;
2131 permission_manager->RegisterPermissionUsage(
2132 PermissionType::GEOLOCATION,
2133 GetLastCommittedURL().GetOrigin(),
2134 frame_tree_node()->frame_tree()->GetMainFrame()
2135 ->GetLastCommittedURL().GetOrigin());
2138 void RenderFrameHostImpl::UpdatePermissionsForNavigation(
2139 const CommonNavigationParams& common_params,
2140 const RequestNavigationParams& request_params) {
2141 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
2142 // so do not grant them the ability to request additional URLs.
2143 if (!GetProcess()->IsForGuestsOnly()) {
2144 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2145 GetProcess()->GetID(), common_params.url);
2146 if (common_params.url.SchemeIs(url::kDataScheme) &&
2147 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
2148 // If 'data:' is used, and we have a 'file:' base url, grant access to
2149 // local files.
2150 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2151 GetProcess()->GetID(), common_params.base_url_for_data_url);
2155 // We may be returning to an existing NavigationEntry that had been granted
2156 // file access. If this is a different process, we will need to grant the
2157 // access again. The files listed in the page state are validated when they
2158 // are received from the renderer to prevent abuse.
2159 if (request_params.page_state.IsValid()) {
2160 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
2164 bool RenderFrameHostImpl::CanExecuteJavaScript() {
2165 return g_allow_injecting_javascript ||
2166 !frame_tree_node_->current_url().is_valid() ||
2167 frame_tree_node_->current_url().SchemeIs(kChromeDevToolsScheme) ||
2168 ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2169 GetProcess()->GetID()) ||
2170 // It's possible to load about:blank in a Web UI renderer.
2171 // See http://crbug.com/42547
2172 (frame_tree_node_->current_url().spec() == url::kAboutBlankURL) ||
2173 // InterstitialPageImpl should be the only case matching this.
2174 (delegate_->GetAsWebContents() == nullptr);
2177 AXTreeIDRegistry::AXTreeID RenderFrameHostImpl::RoutingIDToAXTreeID(
2178 int routing_id) {
2179 RenderFrameHostImpl* rfh = nullptr;
2180 RenderFrameProxyHost* rfph = RenderFrameProxyHost::FromID(
2181 GetProcess()->GetID(), routing_id);
2182 if (rfph) {
2183 FrameTree* frame_tree = frame_tree_node()->frame_tree();
2184 FrameTreeNode* frame_tree_node = frame_tree->FindByRoutingID(
2185 GetProcess()->GetID(), routing_id);
2186 rfh = frame_tree_node->render_manager()->current_frame_host();
2187 } else {
2188 rfh = RenderFrameHostImpl::FromID(GetProcess()->GetID(), routing_id);
2191 if (!rfh)
2192 return AXTreeIDRegistry::kNoAXTreeID;
2194 // As a sanity check, make sure we're within the same frame tree and
2195 // crash the renderer if not.
2196 if (rfh->frame_tree_node()->frame_tree() != frame_tree_node()->frame_tree()) {
2197 AccessibilityFatalError();
2198 return AXTreeIDRegistry::kNoAXTreeID;
2201 return rfh->GetAXTreeID();
2204 AXTreeIDRegistry::AXTreeID
2205 RenderFrameHostImpl::BrowserPluginInstanceIDToAXTreeID(
2206 int instance_id) {
2207 RenderFrameHost* guest = delegate()->GetGuestByInstanceID(
2208 this, instance_id);
2209 if (!guest)
2210 return AXTreeIDRegistry::kNoAXTreeID;
2212 return guest->GetAXTreeID();
2215 void RenderFrameHostImpl::AXContentNodeDataToAXNodeData(
2216 const AXContentNodeData& src,
2217 ui::AXNodeData* dst) {
2218 // Copy the common fields.
2219 *dst = src;
2221 // Map content-specific attributes based on routing IDs or browser plugin
2222 // instance IDs to generic attributes with global AXTreeIDs.
2223 for (auto iter : src.content_int_attributes) {
2224 AXContentIntAttribute attr = iter.first;
2225 int32 value = iter.second;
2226 switch (attr) {
2227 case AX_CONTENT_ATTR_ROUTING_ID:
2228 dst->int_attributes.push_back(std::make_pair(
2229 ui::AX_ATTR_TREE_ID, RoutingIDToAXTreeID(value)));
2230 break;
2231 case AX_CONTENT_ATTR_PARENT_ROUTING_ID:
2232 dst->int_attributes.push_back(std::make_pair(
2233 ui::AX_ATTR_PARENT_TREE_ID, RoutingIDToAXTreeID(value)));
2234 break;
2235 case AX_CONTENT_ATTR_CHILD_ROUTING_ID:
2236 dst->int_attributes.push_back(std::make_pair(
2237 ui::AX_ATTR_CHILD_TREE_ID, RoutingIDToAXTreeID(value)));
2238 break;
2239 case AX_CONTENT_ATTR_CHILD_BROWSER_PLUGIN_INSTANCE_ID:
2240 dst->int_attributes.push_back(std::make_pair(
2241 ui::AX_ATTR_CHILD_TREE_ID,
2242 BrowserPluginInstanceIDToAXTreeID(value)));
2243 break;
2244 case AX_CONTENT_INT_ATTRIBUTE_LAST:
2245 NOTREACHED();
2246 break;
2251 } // namespace content