Revert of Wake Lock API implementation (Chromium part) (patchset #12 id:220001 of...
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blobe99f01bae631d60ab02460926c77217186a2ff0a
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 // PlzNavigate
919 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
920 switches::kEnableBrowserSideNavigation)) {
921 pending_commit_ = false;
925 void RenderFrameHostImpl::OnDidDropNavigation() {
926 // At the end of Navigate(), the FrameTreeNode's DidStartLoading is called to
927 // force the spinner to start, even if the renderer didn't yet begin the load.
928 // If it turns out that the renderer dropped the navigation, the spinner needs
929 // to be turned off.
930 frame_tree_node_->DidStopLoading();
931 navigation_handle_.reset();
934 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
935 if (render_widget_host_)
936 return render_widget_host_;
938 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
939 // we can remove this fallback. Currently it is only used for the main
940 // frame.
941 if (!GetParent())
942 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
944 return nullptr;
947 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
948 RenderFrameHostImpl* frame = this;
949 while (frame) {
950 if (frame->render_widget_host_)
951 return frame->render_widget_host_->GetView();
952 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
955 return render_view_host_->GetView();
958 int RenderFrameHostImpl::GetEnabledBindings() {
959 return render_view_host_->GetEnabledBindings();
962 void RenderFrameHostImpl::SetNavigationHandle(
963 scoped_ptr<NavigationHandleImpl> navigation_handle) {
964 navigation_handle_ = navigation_handle.Pass();
967 scoped_ptr<NavigationHandleImpl>
968 RenderFrameHostImpl::PassNavigationHandleOwnership() {
969 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
970 switches::kEnableBrowserSideNavigation));
971 navigation_handle_->set_is_transferring(true);
972 return navigation_handle_.Pass();
975 void RenderFrameHostImpl::OnCrossSiteResponse(
976 const GlobalRequestID& global_request_id,
977 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
978 const std::vector<GURL>& transfer_url_chain,
979 const Referrer& referrer,
980 ui::PageTransition page_transition,
981 bool should_replace_current_entry) {
982 frame_tree_node_->render_manager()->OnCrossSiteResponse(
983 this, global_request_id, cross_site_transferring_request.Pass(),
984 transfer_url_chain, referrer, page_transition,
985 should_replace_current_entry);
988 void RenderFrameHostImpl::SwapOut(
989 RenderFrameProxyHost* proxy,
990 bool is_loading) {
991 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
992 // the operation and sends back an IPC message.
993 // The trace event may not end properly if the ACK times out. We expect this
994 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
995 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
997 // If this RenderFrameHost is not in the default state, it must have already
998 // gone through this, therefore just return.
999 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
1000 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
1001 return;
1004 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
1005 swapout_event_monitor_timeout_->Start(
1006 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1008 // There may be no proxy if there are no active views in the process.
1009 int proxy_routing_id = MSG_ROUTING_NONE;
1010 FrameReplicationState replication_state;
1011 if (proxy) {
1012 set_render_frame_proxy_host(proxy);
1013 proxy_routing_id = proxy->GetRoutingID();
1014 replication_state = proxy->frame_tree_node()->current_replication_state();
1017 if (IsRenderFrameLive()) {
1018 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
1019 replication_state));
1022 if (!GetParent())
1023 delegate_->SwappedOut(this);
1026 void RenderFrameHostImpl::OnBeforeUnloadACK(
1027 bool proceed,
1028 const base::TimeTicks& renderer_before_unload_start_time,
1029 const base::TimeTicks& renderer_before_unload_end_time) {
1030 TRACE_EVENT_ASYNC_END0(
1031 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1032 DCHECK(!GetParent());
1033 // If this renderer navigated while the beforeunload request was in flight, we
1034 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
1035 // can ignore this message.
1036 // However renderer might also be swapped out but we still want to proceed
1037 // with navigation, otherwise it would block future navigations. This can
1038 // happen when pending cross-site navigation is canceled by a second one just
1039 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
1040 // but second navigation is started from the beginning.
1041 if (!is_waiting_for_beforeunload_ack_) {
1042 return;
1044 DCHECK(!send_before_unload_start_time_.is_null());
1046 // Sets a default value for before_unload_end_time so that the browser
1047 // survives a hacked renderer.
1048 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
1049 if (!renderer_before_unload_start_time.is_null() &&
1050 !renderer_before_unload_end_time.is_null()) {
1051 // When passing TimeTicks across process boundaries, we need to compensate
1052 // for any skew between the processes. Here we are converting the
1053 // renderer's notion of before_unload_end_time to TimeTicks in the browser
1054 // process. See comments in inter_process_time_ticks_converter.h for more.
1055 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
1056 InterProcessTimeTicksConverter converter(
1057 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
1058 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
1059 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
1060 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1061 LocalTimeTicks browser_before_unload_end_time =
1062 converter.ToLocalTimeTicks(
1063 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1064 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1066 // Collect UMA on the inter-process skew.
1067 bool is_skew_additive = false;
1068 if (converter.IsSkewAdditiveForMetrics()) {
1069 is_skew_additive = true;
1070 base::TimeDelta skew = converter.GetSkewForMetrics();
1071 if (skew >= base::TimeDelta()) {
1072 UMA_HISTOGRAM_TIMES(
1073 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
1074 } else {
1075 UMA_HISTOGRAM_TIMES(
1076 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
1079 UMA_HISTOGRAM_BOOLEAN(
1080 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
1081 is_skew_additive);
1083 base::TimeDelta on_before_unload_overhead_time =
1084 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1085 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1086 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1087 on_before_unload_overhead_time);
1089 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1090 renderer_before_unload_start_time, renderer_before_unload_end_time);
1092 // Resets beforeunload waiting state.
1093 is_waiting_for_beforeunload_ack_ = false;
1094 render_view_host_->decrement_in_flight_event_count();
1095 render_view_host_->StopHangMonitorTimeout();
1096 send_before_unload_start_time_ = base::TimeTicks();
1098 // PlzNavigate: if the ACK is for a navigation, send it to the Navigator to
1099 // have the current navigation stop/proceed. Otherwise, send it to the
1100 // RenderFrameHostManager which handles closing.
1101 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1102 switches::kEnableBrowserSideNavigation) &&
1103 unload_ack_is_for_navigation_) {
1104 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1105 // Navigator.
1106 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1107 frame_tree_node_, proceed);
1108 } else {
1109 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1110 unload_ack_is_for_navigation_, proceed,
1111 before_unload_end_time);
1114 // If canceled, notify the delegate to cancel its pending navigation entry.
1115 if (!proceed)
1116 render_view_host_->GetDelegate()->DidCancelLoading();
1119 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1120 return render_view_host_->is_waiting_for_close_ack_ ||
1121 rfh_state_ == STATE_PENDING_SWAP_OUT;
1124 void RenderFrameHostImpl::OnSwapOutACK() {
1125 OnSwappedOut();
1128 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1129 if (frame_tree_node_->IsMainFrame()) {
1130 // Keep the termination status so we can get at it later when we
1131 // need to know why it died.
1132 render_view_host_->render_view_termination_status_ =
1133 static_cast<base::TerminationStatus>(status);
1136 // Reset frame tree state associated with this process. This must happen
1137 // before RenderViewTerminated because observers expect the subframes of any
1138 // affected frames to be cleared first.
1139 // Note: When a RenderFrameHost is swapped out there is a different one
1140 // which is the current host. In this case, the FrameTreeNode state must
1141 // not be reset.
1142 if (!is_swapped_out())
1143 frame_tree_node_->ResetForNewProcess();
1145 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1146 // reset.
1147 SetRenderFrameCreated(false);
1148 InvalidateMojoConnection();
1150 // Execute any pending AX tree snapshot callbacks with an empty response,
1151 // since we're never going to get a response from this renderer.
1152 for (const auto& iter : ax_tree_snapshot_callbacks_)
1153 iter.second.Run(ui::AXTreeUpdate<ui::AXNodeData>());
1154 ax_tree_snapshot_callbacks_.clear();
1156 // Note: don't add any more code at this point in the function because
1157 // |this| may be deleted. Any additional cleanup should happen before
1158 // the last block of code here.
1161 void RenderFrameHostImpl::OnSwappedOut() {
1162 // Ignore spurious swap out ack.
1163 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1164 return;
1166 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1167 swapout_event_monitor_timeout_->Stop();
1170 // If this is a main frame RFH that's about to be deleted, update its RVH's
1171 // swapped-out state here, since SetState won't be called once this RFH is
1172 // deleted below. https://crbug.com/505887
1173 if (frame_tree_node_->IsMainFrame() &&
1174 frame_tree_node_->render_manager()->IsPendingDeletion(this)) {
1175 render_view_host_->set_is_active(false);
1176 render_view_host_->set_is_swapped_out(true);
1179 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1180 // We are now deleted.
1181 return;
1184 // If this RFH wasn't pending deletion, then it is now swapped out.
1185 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1188 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1189 // Validate the URLs in |params|. If the renderer can't request the URLs
1190 // directly, don't show them in the context menu.
1191 ContextMenuParams validated_params(params);
1192 RenderProcessHost* process = GetProcess();
1194 // We don't validate |unfiltered_link_url| so that this field can be used
1195 // when users want to copy the original link URL.
1196 process->FilterURL(true, &validated_params.link_url);
1197 process->FilterURL(true, &validated_params.src_url);
1198 process->FilterURL(false, &validated_params.page_url);
1199 process->FilterURL(true, &validated_params.frame_url);
1201 delegate_->ShowContextMenu(this, validated_params);
1204 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1205 int id, const base::ListValue& result) {
1206 const base::Value* result_value;
1207 if (!result.Get(0, &result_value)) {
1208 // Programming error or rogue renderer.
1209 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1210 return;
1213 std::map<int, JavaScriptResultCallback>::iterator it =
1214 javascript_callbacks_.find(id);
1215 if (it != javascript_callbacks_.end()) {
1216 it->second.Run(result_value);
1217 javascript_callbacks_.erase(it);
1218 } else {
1219 NOTREACHED() << "Received script response for unknown request";
1223 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1224 auto it = visual_state_callbacks_.find(id);
1225 if (it != visual_state_callbacks_.end()) {
1226 it->second.Run(true);
1227 visual_state_callbacks_.erase(it);
1228 } else {
1229 NOTREACHED() << "Received script response for unknown request";
1233 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1234 const base::string16& message,
1235 const base::string16& default_prompt,
1236 const GURL& frame_url,
1237 JavaScriptMessageType type,
1238 IPC::Message* reply_msg) {
1239 // While a JS message dialog is showing, tabs in the same process shouldn't
1240 // process input events.
1241 GetProcess()->SetIgnoreInputEvents(true);
1242 render_view_host_->StopHangMonitorTimeout();
1243 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1244 frame_url, type, reply_msg);
1247 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1248 const GURL& frame_url,
1249 const base::string16& message,
1250 bool is_reload,
1251 IPC::Message* reply_msg) {
1252 // While a JS beforeunload dialog is showing, tabs in the same process
1253 // shouldn't process input events.
1254 GetProcess()->SetIgnoreInputEvents(true);
1255 render_view_host_->StopHangMonitorTimeout();
1256 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1259 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1260 const base::string16& content,
1261 size_t start_offset,
1262 size_t end_offset) {
1263 render_view_host_->OnTextSurroundingSelectionResponse(
1264 content, start_offset, end_offset);
1267 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1268 delegate_->DidAccessInitialDocument();
1271 void RenderFrameHostImpl::OnDidChangeOpener(int32 opener_routing_id) {
1272 frame_tree_node_->render_manager()->DidChangeOpener(opener_routing_id,
1273 GetSiteInstance());
1276 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1277 std::string old_name = frame_tree_node()->frame_name();
1278 frame_tree_node()->SetFrameName(name);
1279 if (old_name.empty() && !name.empty())
1280 frame_tree_node_->render_manager()->CreateProxiesForNewNamedFrame();
1281 delegate_->DidChangeName(this, name);
1284 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1285 // Update the RVH's current page ID so that future IPCs from the renderer
1286 // correspond to the new page.
1287 render_view_host_->page_id_ = page_id;
1290 void RenderFrameHostImpl::OnDidChangeSandboxFlags(
1291 int32 frame_routing_id,
1292 blink::WebSandboxFlags flags) {
1293 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1294 FrameTreeNode* child =
1295 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1296 if (!child)
1297 return;
1299 // Ensure that a frame can only update sandbox flags for its immediate
1300 // children. If this is not the case, the renderer is considered malicious
1301 // and is killed.
1302 if (child->parent() != frame_tree_node()) {
1303 bad_message::ReceivedBadMessage(GetProcess(),
1304 bad_message::RFH_SANDBOX_FLAGS);
1305 return;
1308 child->set_sandbox_flags(flags);
1310 // Notify the RenderFrame if it lives in a different process from its
1311 // parent. The frame's proxies in other processes also need to learn about
1312 // the updated sandbox flags, but these notifications are sent later in
1313 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1314 // navigates and the new sandbox flags take effect.
1315 RenderFrameHost* child_rfh = child->current_frame_host();
1316 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1317 child_rfh->Send(
1318 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1322 void RenderFrameHostImpl::OnUpdateTitle(
1323 const base::string16& title,
1324 blink::WebTextDirection title_direction) {
1325 // This message is only sent for top-level frames. TODO(avi): when frame tree
1326 // mirroring works correctly, add a check here to enforce it.
1327 if (title.length() > kMaxTitleChars) {
1328 NOTREACHED() << "Renderer sent too many characters in title.";
1329 return;
1332 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1333 WebTextDirectionToChromeTextDirection(
1334 title_direction));
1337 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
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 delegate_->UpdateEncoding(this, encoding_name);
1343 void RenderFrameHostImpl::OnBeginNavigation(
1344 const CommonNavigationParams& common_params,
1345 const BeginNavigationParams& begin_params,
1346 scoped_refptr<ResourceRequestBody> body) {
1347 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1348 switches::kEnableBrowserSideNavigation));
1349 frame_tree_node()->navigator()->OnBeginNavigation(
1350 frame_tree_node(), common_params, begin_params, body);
1353 void RenderFrameHostImpl::OnDispatchLoad() {
1354 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
1355 // Only frames with an out-of-process parent frame should be sending this
1356 // message.
1357 RenderFrameProxyHost* proxy =
1358 frame_tree_node()->render_manager()->GetProxyToParent();
1359 if (!proxy) {
1360 bad_message::ReceivedBadMessage(GetProcess(),
1361 bad_message::RFH_NO_PROXY_TO_PARENT);
1362 return;
1365 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1368 void RenderFrameHostImpl::OnAccessibilityEvents(
1369 const std::vector<AccessibilityHostMsg_EventParams>& params,
1370 int reset_token) {
1371 // Don't process this IPC if either we're waiting on a reset and this
1372 // IPC doesn't have the matching token ID, or if we're not waiting on a
1373 // reset but this message includes a reset token.
1374 if (accessibility_reset_token_ != reset_token) {
1375 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1376 return;
1378 accessibility_reset_token_ = 0;
1380 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1381 frame_tree_node_->frame_tree()
1382 ->GetMainFrame()
1383 ->render_view_host_->GetView());
1385 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1386 if ((accessibility_mode != AccessibilityModeOff) && view &&
1387 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1388 if (accessibility_mode & AccessibilityModeFlagPlatform)
1389 GetOrCreateBrowserAccessibilityManager();
1391 std::vector<AXEventNotificationDetails> details;
1392 details.reserve(params.size());
1393 for (size_t i = 0; i < params.size(); ++i) {
1394 const AccessibilityHostMsg_EventParams& param = params[i];
1395 AXEventNotificationDetails detail;
1396 detail.event_type = param.event_type;
1397 detail.id = param.id;
1398 detail.ax_tree_id = GetAXTreeID();
1399 detail.update.node_id_to_clear = param.update.node_id_to_clear;
1400 detail.update.nodes.resize(param.update.nodes.size());
1401 for (size_t i = 0; i < param.update.nodes.size(); ++i) {
1402 AXContentNodeDataToAXNodeData(param.update.nodes[i],
1403 &detail.update.nodes[i]);
1405 details.push_back(detail);
1408 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1409 if (browser_accessibility_manager_)
1410 browser_accessibility_manager_->OnAccessibilityEvents(details);
1413 // Send the updates to the automation extension API.
1414 delegate_->AccessibilityEventReceived(details);
1416 // For testing only.
1417 if (!accessibility_testing_callback_.is_null()) {
1418 for (size_t i = 0; i < details.size(); i++) {
1419 const AXEventNotificationDetails& detail = details[i];
1420 if (static_cast<int>(detail.event_type) < 0)
1421 continue;
1423 if (!ax_tree_for_testing_) {
1424 if (browser_accessibility_manager_) {
1425 ax_tree_for_testing_.reset(new ui::AXTree(
1426 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1427 } else {
1428 ax_tree_for_testing_.reset(new ui::AXTree());
1429 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1430 << ax_tree_for_testing_->error();
1432 } else {
1433 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1434 << ax_tree_for_testing_->error();
1436 accessibility_testing_callback_.Run(detail.event_type, detail.id);
1441 // Always send an ACK or the renderer can be in a bad state.
1442 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1445 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1446 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1447 if (accessibility_reset_token_)
1448 return;
1450 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1451 render_view_host_->GetView());
1452 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1453 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1454 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1455 BrowserAccessibilityManager* manager =
1456 GetOrCreateBrowserAccessibilityManager();
1457 if (manager)
1458 manager->OnLocationChanges(params);
1460 // TODO(aboxhall): send location change events to web contents observers too
1464 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1465 const AccessibilityHostMsg_FindInPageResultParams& params) {
1466 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1467 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1468 BrowserAccessibilityManager* manager =
1469 GetOrCreateBrowserAccessibilityManager();
1470 if (manager) {
1471 manager->OnFindInPageResult(
1472 params.request_id, params.match_index, params.start_id,
1473 params.start_offset, params.end_id, params.end_offset);
1478 void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
1479 int callback_id,
1480 const ui::AXTreeUpdate<AXContentNodeData>& snapshot) {
1481 const auto& it = ax_tree_snapshot_callbacks_.find(callback_id);
1482 if (it != ax_tree_snapshot_callbacks_.end()) {
1483 ui::AXTreeUpdate<ui::AXNodeData> dst_snapshot;
1484 dst_snapshot.nodes.resize(snapshot.nodes.size());
1485 for (size_t i = 0; i < snapshot.nodes.size(); ++i) {
1486 AXContentNodeDataToAXNodeData(snapshot.nodes[i],
1487 &dst_snapshot.nodes[i]);
1489 it->second.Run(dst_snapshot);
1490 ax_tree_snapshot_callbacks_.erase(it);
1491 } else {
1492 NOTREACHED() << "Received AX tree snapshot response for unknown id";
1496 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1497 if (enter_fullscreen)
1498 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1499 else
1500 delegate_->ExitFullscreenMode();
1502 // The previous call might change the fullscreen state. We need to make sure
1503 // the renderer is aware of that, which is done via the resize message.
1504 render_view_host_->WasResized();
1507 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
1508 // Any main frame load to a new document should reset the load since it will
1509 // replace the current page and any frames.
1510 if (to_different_document && !GetParent())
1511 is_loading_ = false;
1513 // This method should never be called when the frame is loading.
1514 // Unfortunately, it can happen if a history navigation happens during a
1515 // BeforeUnload or Unload event.
1516 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1517 // refactored in Blink. See crbug.com/466089
1518 if (is_loading_) {
1519 LOG(WARNING) << "OnDidStartLoading was called twice.";
1520 return;
1523 frame_tree_node_->DidStartLoading(to_different_document);
1524 is_loading_ = true;
1527 void RenderFrameHostImpl::OnDidStopLoading() {
1528 // This method should never be called when the frame is not loading.
1529 // Unfortunately, it can happen if a history navigation happens during a
1530 // BeforeUnload or Unload event.
1531 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1532 // refactored in Blink. See crbug.com/466089
1533 if (!is_loading_) {
1534 LOG(WARNING) << "OnDidStopLoading was called twice.";
1535 return;
1538 is_loading_ = false;
1539 frame_tree_node_->DidStopLoading();
1540 navigation_handle_.reset();
1543 void RenderFrameHostImpl::OnDidChangeLoadProgress(double load_progress) {
1544 frame_tree_node_->DidChangeLoadProgress(load_progress);
1547 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1548 void RenderFrameHostImpl::OnShowPopup(
1549 const FrameHostMsg_ShowPopup_Params& params) {
1550 RenderViewHostDelegateView* view =
1551 render_view_host_->delegate_->GetDelegateView();
1552 if (view) {
1553 view->ShowPopupMenu(this,
1554 params.bounds,
1555 params.item_height,
1556 params.item_font_size,
1557 params.selected_item,
1558 params.popup_items,
1559 params.right_aligned,
1560 params.allow_multiple_selection);
1564 void RenderFrameHostImpl::OnHidePopup() {
1565 RenderViewHostDelegateView* view =
1566 render_view_host_->delegate_->GetDelegateView();
1567 if (view)
1568 view->HidePopupMenu();
1570 #endif
1572 void RenderFrameHostImpl::RegisterMojoServices() {
1573 GeolocationServiceContext* geolocation_service_context =
1574 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1575 if (geolocation_service_context) {
1576 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1577 // can perform permissions checks once site isolation is complete.
1578 // crbug.com/426384
1579 GetServiceRegistry()->AddService<GeolocationService>(
1580 base::Bind(&GeolocationServiceContext::CreateService,
1581 base::Unretained(geolocation_service_context),
1582 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1583 base::Unretained(this))));
1586 if (!permission_service_context_)
1587 permission_service_context_.reset(new PermissionServiceContext(this));
1589 GetServiceRegistry()->AddService<PermissionService>(
1590 base::Bind(&PermissionServiceContext::CreateService,
1591 base::Unretained(permission_service_context_.get())));
1593 GetServiceRegistry()->AddService<presentation::PresentationService>(
1594 base::Bind(&PresentationServiceImpl::CreateMojoService,
1595 base::Unretained(this)));
1597 if (!frame_mojo_shell_)
1598 frame_mojo_shell_.reset(new FrameMojoShell(this));
1600 GetServiceRegistry()->AddService<mojo::Shell>(base::Bind(
1601 &FrameMojoShell::BindRequest, base::Unretained(frame_mojo_shell_.get())));
1603 #if defined(ENABLE_WEBVR)
1604 const base::CommandLine& browser_command_line =
1605 *base::CommandLine::ForCurrentProcess();
1607 if (browser_command_line.HasSwitch(switches::kEnableWebVR)) {
1608 GetServiceRegistry()->AddService<VRService>(
1609 base::Bind(&VRDeviceManager::BindRequest));
1611 #endif
1614 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1615 // Only main frames should be swapped out and retained inside a proxy host.
1616 if (rfh_state == STATE_SWAPPED_OUT)
1617 CHECK(!GetParent());
1619 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1620 // out status of a RenderFrameHost gets flipped to/from active.
1621 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1622 GetSiteInstance()->increment_active_frame_count();
1623 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1624 GetSiteInstance()->decrement_active_frame_count();
1626 // The active and swapped out state of the RVH is determined by its main
1627 // frame, since subframes should have their own widgets.
1628 if (frame_tree_node_->IsMainFrame()) {
1629 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1630 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1633 // Whenever we change the RFH state to and from active or swapped out state,
1634 // we should not be waiting for beforeunload or close acks. We clear them
1635 // here to be safe, since they can cause navigations to be ignored in
1636 // OnDidCommitProvisionalLoad.
1637 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1638 if (rfh_state == STATE_DEFAULT ||
1639 rfh_state == STATE_SWAPPED_OUT ||
1640 rfh_state_ == STATE_DEFAULT ||
1641 rfh_state_ == STATE_SWAPPED_OUT) {
1642 if (is_waiting_for_beforeunload_ack_) {
1643 is_waiting_for_beforeunload_ack_ = false;
1644 render_view_host_->decrement_in_flight_event_count();
1645 render_view_host_->StopHangMonitorTimeout();
1647 send_before_unload_start_time_ = base::TimeTicks();
1648 render_view_host_->is_waiting_for_close_ack_ = false;
1650 rfh_state_ = rfh_state;
1653 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1654 // TODO(creis): We should also check for WebUI pages here. Also, when the
1655 // out-of-process iframes implementation is ready, we should check for
1656 // cross-site URLs that are not allowed to commit in this process.
1658 // Give the client a chance to disallow URLs from committing.
1659 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1662 void RenderFrameHostImpl::Navigate(
1663 const CommonNavigationParams& common_params,
1664 const StartNavigationParams& start_params,
1665 const RequestNavigationParams& request_params) {
1666 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1667 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1668 switches::kEnableBrowserSideNavigation));
1670 UpdatePermissionsForNavigation(common_params, request_params);
1672 // Only send the message if we aren't suspended at the start of a cross-site
1673 // request.
1674 if (navigations_suspended_) {
1675 // Shouldn't be possible to have a second navigation while suspended, since
1676 // navigations will only be suspended during a cross-site request. If a
1677 // second navigation occurs, RenderFrameHostManager will cancel this pending
1678 // RFH and create a new pending RFH.
1679 DCHECK(!suspended_nav_params_.get());
1680 suspended_nav_params_.reset(
1681 new NavigationParams(common_params, start_params, request_params));
1682 } else {
1683 // Get back to a clean state, in case we start a new navigation without
1684 // completing a RFH swap or unload handler.
1685 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1687 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1688 request_params));
1691 // Force the throbber to start. This is done because Blink's "started loading"
1692 // message will be received asynchronously from the UI of the browser. But the
1693 // throbber needs to be kept in sync with what's happening in the UI. For
1694 // example, the throbber will start immediately when the user navigates even
1695 // if the renderer is delayed. There is also an issue with the throbber
1696 // starting because the WebUI (which controls whether the favicon is
1697 // displayed) happens synchronously. If the start loading messages was
1698 // asynchronous, then the default favicon would flash in.
1700 // Blink doesn't send throb notifications for JavaScript URLs, so it is not
1701 // done here either.
1702 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1703 frame_tree_node_->DidStartLoading(true);
1706 void RenderFrameHostImpl::NavigateToInterstitialURL(const GURL& data_url) {
1707 DCHECK(data_url.SchemeIs(url::kDataScheme));
1708 CommonNavigationParams common_params(
1709 data_url, Referrer(), ui::PAGE_TRANSITION_LINK,
1710 FrameMsg_Navigate_Type::NORMAL, false, false, base::TimeTicks::Now(),
1711 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
1712 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1713 switches::kEnableBrowserSideNavigation)) {
1714 CommitNavigation(nullptr, nullptr, common_params,
1715 RequestNavigationParams());
1716 } else {
1717 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1721 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1722 SiteInstance* source_site_instance) {
1723 GURL validated_url(params.url);
1724 GetProcess()->FilterURL(false, &validated_url);
1726 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1727 validated_url.possibly_invalid_spec());
1728 frame_tree_node_->navigator()->RequestOpenURL(
1729 this, validated_url, source_site_instance, params.referrer,
1730 params.disposition, params.should_replace_current_entry,
1731 params.user_gesture);
1734 void RenderFrameHostImpl::Stop() {
1735 Send(new FrameMsg_Stop(routing_id_));
1738 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1739 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1740 // the handler ran and allowed the navigation to proceed.
1741 if (!ShouldDispatchBeforeUnload()) {
1742 DCHECK(!(base::CommandLine::ForCurrentProcess()->HasSwitch(
1743 switches::kEnableBrowserSideNavigation) &&
1744 for_navigation));
1745 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1746 for_navigation, true, base::TimeTicks::Now());
1747 return;
1749 TRACE_EVENT_ASYNC_BEGIN0(
1750 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1752 // This may be called more than once (if the user clicks the tab close button
1753 // several times, or if she clicks the tab close button then the browser close
1754 // button), and we only send the message once.
1755 if (is_waiting_for_beforeunload_ack_) {
1756 // Some of our close messages could be for the tab, others for cross-site
1757 // transitions. We always want to think it's for closing the tab if any
1758 // of the messages were, since otherwise it might be impossible to close
1759 // (if there was a cross-site "close" request pending when the user clicked
1760 // the close button). We want to keep the "for cross site" flag only if
1761 // both the old and the new ones are also for cross site.
1762 unload_ack_is_for_navigation_ =
1763 unload_ack_is_for_navigation_ && for_navigation;
1764 } else {
1765 // Start the hang monitor in case the renderer hangs in the beforeunload
1766 // handler.
1767 is_waiting_for_beforeunload_ack_ = true;
1768 unload_ack_is_for_navigation_ = for_navigation;
1769 // Increment the in-flight event count, to ensure that input events won't
1770 // cancel the timeout timer.
1771 render_view_host_->increment_in_flight_event_count();
1772 render_view_host_->StartHangMonitorTimeout(
1773 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1774 send_before_unload_start_time_ = base::TimeTicks::Now();
1775 Send(new FrameMsg_BeforeUnload(routing_id_));
1779 bool RenderFrameHostImpl::ShouldDispatchBeforeUnload() {
1780 // TODO(creis): Support beforeunload on subframes.
1781 return !GetParent() && IsRenderFrameLive();
1784 void RenderFrameHostImpl::UpdateOpener() {
1785 // This frame (the frame whose opener is being updated) might not have had
1786 // proxies for the new opener chain in its SiteInstance. Make sure they
1787 // exist.
1788 if (frame_tree_node_->opener()) {
1789 frame_tree_node_->opener()->render_manager()->CreateOpenerProxies(
1790 GetSiteInstance(), frame_tree_node_);
1793 int opener_routing_id =
1794 frame_tree_node_->render_manager()->GetOpenerRoutingID(GetSiteInstance());
1795 Send(new FrameMsg_UpdateOpener(GetRoutingID(), opener_routing_id));
1798 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1799 size_t after) {
1800 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1803 void RenderFrameHostImpl::JavaScriptDialogClosed(
1804 IPC::Message* reply_msg,
1805 bool success,
1806 const base::string16& user_input,
1807 bool dialog_was_suppressed) {
1808 GetProcess()->SetIgnoreInputEvents(false);
1809 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1811 // If we are executing as part of (before)unload event handling, we don't
1812 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1813 // leave the current page. In this case, use the regular timeout value used
1814 // during the (before)unload handling.
1815 if (is_waiting) {
1816 render_view_host_->StartHangMonitorTimeout(
1817 success
1818 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1819 : render_view_host_->hung_renderer_delay_);
1822 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1823 success, user_input);
1824 Send(reply_msg);
1826 // If we are waiting for an unload or beforeunload ack and the user has
1827 // suppressed messages, kill the tab immediately; a page that's spamming
1828 // alerts in onbeforeunload is presumably malicious, so there's no point in
1829 // continuing to run its script and dragging out the process.
1830 // This must be done after sending the reply since RenderView can't close
1831 // correctly while waiting for a response.
1832 if (is_waiting && dialog_was_suppressed)
1833 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1836 // PlzNavigate
1837 void RenderFrameHostImpl::CommitNavigation(
1838 ResourceResponse* response,
1839 scoped_ptr<StreamHandle> body,
1840 const CommonNavigationParams& common_params,
1841 const RequestNavigationParams& request_params) {
1842 DCHECK((response && body.get()) ||
1843 !ShouldMakeNetworkRequestForURL(common_params.url));
1844 UpdatePermissionsForNavigation(common_params, request_params);
1846 // Get back to a clean state, in case we start a new navigation without
1847 // completing a RFH swap or unload handler.
1848 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1850 const GURL body_url = body.get() ? body->GetURL() : GURL();
1851 const ResourceResponseHead head = response ?
1852 response->head : ResourceResponseHead();
1853 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1854 request_params));
1855 // TODO(clamy): Check if we should start the throbber for non javascript urls
1856 // here.
1858 // TODO(clamy): Release the stream handle once the renderer has finished
1859 // reading it.
1860 stream_handle_ = body.Pass();
1862 // When navigating to a Javascript url, no commit is expected from the
1863 // RenderFrameHost, nor should the throbber start.
1864 if (!common_params.url.SchemeIs(url::kJavaScriptScheme)) {
1865 pending_commit_ = true;
1866 is_loading_ = true;
1868 frame_tree_node_->ResetNavigationRequest(true);
1871 void RenderFrameHostImpl::FailedNavigation(
1872 const CommonNavigationParams& common_params,
1873 const RequestNavigationParams& request_params,
1874 bool has_stale_copy_in_cache,
1875 int error_code) {
1876 // Get back to a clean state, in case a new navigation started without
1877 // completing a RFH swap or unload handler.
1878 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1880 Send(new FrameMsg_FailedNavigation(routing_id_, common_params, request_params,
1881 has_stale_copy_in_cache, error_code));
1883 // An error page is expected to commit, hence why is_loading_ is set to true.
1884 is_loading_ = true;
1885 frame_tree_node_->ResetNavigationRequest(true);
1888 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1889 if (service_registry_.get())
1890 return;
1892 service_registry_.reset(new ServiceRegistryImpl());
1893 if (!GetProcess()->GetServiceRegistry())
1894 return;
1896 RegisterMojoServices();
1897 RenderFrameSetupPtr setup;
1898 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(
1899 mojo::GetProxy(&setup));
1901 mojo::ServiceProviderPtr exposed_services;
1902 service_registry_->Bind(GetProxy(&exposed_services));
1904 mojo::ServiceProviderPtr services;
1905 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1906 exposed_services.Pass());
1907 service_registry_->BindRemoteServiceProvider(services.Pass());
1909 #if defined(OS_ANDROID)
1910 service_registry_android_.reset(
1911 new ServiceRegistryAndroid(service_registry_.get()));
1912 ServiceRegistrarAndroid::RegisterFrameHostServices(
1913 service_registry_android_.get());
1914 #endif
1917 void RenderFrameHostImpl::InvalidateMojoConnection() {
1918 #if defined(OS_ANDROID)
1919 // The Android-specific service registry has a reference to
1920 // |service_registry_| and thus must be torn down first.
1921 service_registry_android_.reset();
1922 #endif
1924 service_registry_.reset();
1926 // Disconnect with ImageDownloader Mojo service in RenderFrame.
1927 mojo_image_downloader_.reset();
1930 bool RenderFrameHostImpl::IsFocused() {
1931 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1932 // returning nullptr in some cases. See https://crbug.com/455245.
1933 return RenderWidgetHostImpl::From(
1934 GetView()->GetRenderWidgetHost())->is_focused() &&
1935 frame_tree_->GetFocusedFrame() &&
1936 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1937 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1940 const image_downloader::ImageDownloaderPtr&
1941 RenderFrameHostImpl::GetMojoImageDownloader() {
1942 if (!mojo_image_downloader_.get() && GetServiceRegistry()) {
1943 GetServiceRegistry()->ConnectToRemoteService(
1944 mojo::GetProxy(&mojo_image_downloader_));
1946 return mojo_image_downloader_;
1949 bool RenderFrameHostImpl::IsSameSiteInstance(
1950 RenderFrameHostImpl* other_render_frame_host) {
1951 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1952 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1953 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1954 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1957 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1958 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1961 void RenderFrameHostImpl::RequestAXTreeSnapshot(
1962 AXTreeSnapshotCallback callback) {
1963 static int next_id = 1;
1964 int callback_id = next_id++;
1965 Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
1966 ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
1969 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1970 const base::Callback<void(ui::AXEvent, int)>& callback) {
1971 accessibility_testing_callback_ = callback;
1974 void RenderFrameHostImpl::SetTextTrackSettings(
1975 const FrameMsg_TextTrackSettings_Params& params) {
1976 DCHECK(!GetParent());
1977 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
1980 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1981 return ax_tree_for_testing_.get();
1984 BrowserAccessibilityManager*
1985 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1986 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1987 frame_tree_node_->frame_tree()
1988 ->GetMainFrame()
1989 ->render_view_host_->GetView());
1990 if (view &&
1991 !browser_accessibility_manager_ &&
1992 !no_create_browser_accessibility_manager_for_testing_) {
1993 browser_accessibility_manager_.reset(
1994 view->CreateBrowserAccessibilityManager(this));
1995 if (browser_accessibility_manager_)
1996 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
1997 else
1998 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
2000 return browser_accessibility_manager_.get();
2003 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
2004 int request_id) {
2005 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
2006 if (accessibility_mode & AccessibilityModeFlagPlatform) {
2007 BrowserAccessibilityManager* manager =
2008 GetOrCreateBrowserAccessibilityManager();
2009 if (manager)
2010 manager->ActivateFindInPageResult(request_id);
2014 void RenderFrameHostImpl::InsertVisualStateCallback(
2015 const VisualStateCallback& callback) {
2016 static uint64 next_id = 1;
2017 uint64 key = next_id++;
2018 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
2019 visual_state_callbacks_.insert(std::make_pair(key, callback));
2022 bool RenderFrameHostImpl::IsRenderFrameLive() {
2023 bool is_live = GetProcess()->HasConnection() && render_frame_created_;
2025 // Sanity check: the RenderView should always be live if the RenderFrame is.
2026 DCHECK_IMPLIES(is_live, render_view_host_->IsRenderViewLive());
2028 return is_live;
2031 #if defined(OS_WIN)
2033 void RenderFrameHostImpl::SetParentNativeViewAccessible(
2034 gfx::NativeViewAccessible accessible_parent) {
2035 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2036 render_view_host_->GetView());
2037 if (view)
2038 view->SetParentNativeViewAccessible(accessible_parent);
2041 gfx::NativeViewAccessible
2042 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
2043 return delegate_->GetParentNativeViewAccessible();
2046 #elif defined(OS_MACOSX)
2048 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
2049 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
2052 void RenderFrameHostImpl::DidCancelPopupMenu() {
2053 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
2056 #elif defined(OS_ANDROID)
2058 void RenderFrameHostImpl::DidSelectPopupMenuItems(
2059 const std::vector<int>& selected_indices) {
2060 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
2063 void RenderFrameHostImpl::DidCancelPopupMenu() {
2064 Send(new FrameMsg_SelectPopupMenuItems(
2065 routing_id_, true, std::vector<int>()));
2068 #endif
2070 void RenderFrameHostImpl::SetNavigationsSuspended(
2071 bool suspend,
2072 const base::TimeTicks& proceed_time) {
2073 // This should only be called to toggle the state.
2074 DCHECK(navigations_suspended_ != suspend);
2076 navigations_suspended_ = suspend;
2077 if (navigations_suspended_) {
2078 TRACE_EVENT_ASYNC_BEGIN0("navigation",
2079 "RenderFrameHostImpl navigation suspended", this);
2080 } else {
2081 TRACE_EVENT_ASYNC_END0("navigation",
2082 "RenderFrameHostImpl navigation suspended", this);
2085 if (!suspend && suspended_nav_params_) {
2086 // There's navigation message params waiting to be sent. Now that we're not
2087 // suspended anymore, resume navigation by sending them. If we were swapped
2088 // out, we should also stop filtering out the IPC messages now.
2089 SetState(RenderFrameHostImpl::STATE_DEFAULT);
2091 DCHECK(!proceed_time.is_null());
2092 suspended_nav_params_->request_params.browser_navigation_start =
2093 proceed_time;
2094 Send(new FrameMsg_Navigate(routing_id_,
2095 suspended_nav_params_->common_params,
2096 suspended_nav_params_->start_params,
2097 suspended_nav_params_->request_params));
2098 suspended_nav_params_.reset();
2102 void RenderFrameHostImpl::CancelSuspendedNavigations() {
2103 // Clear any state if a pending navigation is canceled or preempted.
2104 if (suspended_nav_params_)
2105 suspended_nav_params_.reset();
2107 TRACE_EVENT_ASYNC_END0("navigation",
2108 "RenderFrameHostImpl navigation suspended", this);
2109 navigations_suspended_ = false;
2112 void RenderFrameHostImpl::DidUseGeolocationPermission() {
2113 PermissionManager* permission_manager =
2114 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
2115 if (!permission_manager)
2116 return;
2118 permission_manager->RegisterPermissionUsage(
2119 PermissionType::GEOLOCATION,
2120 GetLastCommittedURL().GetOrigin(),
2121 frame_tree_node()->frame_tree()->GetMainFrame()
2122 ->GetLastCommittedURL().GetOrigin());
2125 void RenderFrameHostImpl::UpdatePermissionsForNavigation(
2126 const CommonNavigationParams& common_params,
2127 const RequestNavigationParams& request_params) {
2128 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
2129 // so do not grant them the ability to request additional URLs.
2130 if (!GetProcess()->IsForGuestsOnly()) {
2131 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2132 GetProcess()->GetID(), common_params.url);
2133 if (common_params.url.SchemeIs(url::kDataScheme) &&
2134 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
2135 // If 'data:' is used, and we have a 'file:' base url, grant access to
2136 // local files.
2137 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2138 GetProcess()->GetID(), common_params.base_url_for_data_url);
2142 // We may be returning to an existing NavigationEntry that had been granted
2143 // file access. If this is a different process, we will need to grant the
2144 // access again. The files listed in the page state are validated when they
2145 // are received from the renderer to prevent abuse.
2146 if (request_params.page_state.IsValid()) {
2147 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
2151 bool RenderFrameHostImpl::CanExecuteJavaScript() {
2152 return g_allow_injecting_javascript ||
2153 !frame_tree_node_->current_url().is_valid() ||
2154 frame_tree_node_->current_url().SchemeIs(kChromeDevToolsScheme) ||
2155 ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2156 GetProcess()->GetID()) ||
2157 // It's possible to load about:blank in a Web UI renderer.
2158 // See http://crbug.com/42547
2159 (frame_tree_node_->current_url().spec() == url::kAboutBlankURL) ||
2160 // InterstitialPageImpl should be the only case matching this.
2161 (delegate_->GetAsWebContents() == nullptr);
2164 AXTreeIDRegistry::AXTreeID RenderFrameHostImpl::RoutingIDToAXTreeID(
2165 int routing_id) {
2166 RenderFrameHostImpl* rfh = nullptr;
2167 RenderFrameProxyHost* rfph = RenderFrameProxyHost::FromID(
2168 GetProcess()->GetID(), routing_id);
2169 if (rfph) {
2170 FrameTree* frame_tree = frame_tree_node()->frame_tree();
2171 FrameTreeNode* frame_tree_node = frame_tree->FindByRoutingID(
2172 GetProcess()->GetID(), routing_id);
2173 rfh = frame_tree_node->render_manager()->current_frame_host();
2174 } else {
2175 rfh = RenderFrameHostImpl::FromID(GetProcess()->GetID(), routing_id);
2178 if (!rfh)
2179 return AXTreeIDRegistry::kNoAXTreeID;
2181 // As a sanity check, make sure we're within the same frame tree and
2182 // crash the renderer if not.
2183 if (rfh->frame_tree_node()->frame_tree() != frame_tree_node()->frame_tree()) {
2184 AccessibilityFatalError();
2185 return AXTreeIDRegistry::kNoAXTreeID;
2188 return rfh->GetAXTreeID();
2191 AXTreeIDRegistry::AXTreeID
2192 RenderFrameHostImpl::BrowserPluginInstanceIDToAXTreeID(
2193 int instance_id) {
2194 RenderFrameHost* guest = delegate()->GetGuestByInstanceID(
2195 this, instance_id);
2196 if (!guest)
2197 return AXTreeIDRegistry::kNoAXTreeID;
2199 return guest->GetAXTreeID();
2202 void RenderFrameHostImpl::AXContentNodeDataToAXNodeData(
2203 const AXContentNodeData& src,
2204 ui::AXNodeData* dst) {
2205 // Copy the common fields.
2206 *dst = src;
2208 // Map content-specific attributes based on routing IDs or browser plugin
2209 // instance IDs to generic attributes with global AXTreeIDs.
2210 for (auto iter : src.content_int_attributes) {
2211 AXContentIntAttribute attr = iter.first;
2212 int32 value = iter.second;
2213 switch (attr) {
2214 case AX_CONTENT_ATTR_ROUTING_ID:
2215 dst->int_attributes.push_back(std::make_pair(
2216 ui::AX_ATTR_TREE_ID, RoutingIDToAXTreeID(value)));
2217 break;
2218 case AX_CONTENT_ATTR_PARENT_ROUTING_ID:
2219 dst->int_attributes.push_back(std::make_pair(
2220 ui::AX_ATTR_PARENT_TREE_ID, RoutingIDToAXTreeID(value)));
2221 break;
2222 case AX_CONTENT_ATTR_CHILD_ROUTING_ID:
2223 dst->int_attributes.push_back(std::make_pair(
2224 ui::AX_ATTR_CHILD_TREE_ID, RoutingIDToAXTreeID(value)));
2225 break;
2226 case AX_CONTENT_ATTR_CHILD_BROWSER_PLUGIN_INSTANCE_ID:
2227 dst->int_attributes.push_back(std::make_pair(
2228 ui::AX_ATTR_CHILD_TREE_ID,
2229 BrowserPluginInstanceIDToAXTreeID(value)));
2230 break;
2231 case AX_CONTENT_INT_ATTRIBUTE_LAST:
2232 NOTREACHED();
2233 break;
2238 } // namespace content