Fix various typos, error handling for GN auto-roller.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blob4835e883c407eefb42bddc350de3436985f3fd7e
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/render_frame_host_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/containers/hash_tables.h"
10 #include "base/lazy_instance.h"
11 #include "base/metrics/histogram.h"
12 #include "base/process/kill.h"
13 #include "base/time/time.h"
14 #include "content/browser/accessibility/accessibility_mode_helper.h"
15 #include "content/browser/accessibility/browser_accessibility_manager.h"
16 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
17 #include "content/browser/bad_message.h"
18 #include "content/browser/child_process_security_policy_impl.h"
19 #include "content/browser/frame_host/cross_process_frame_connector.h"
20 #include "content/browser/frame_host/cross_site_transferring_request.h"
21 #include "content/browser/frame_host/frame_accessibility.h"
22 #include "content/browser/frame_host/frame_mojo_shell.h"
23 #include "content/browser/frame_host/frame_tree.h"
24 #include "content/browser/frame_host/frame_tree_node.h"
25 #include "content/browser/frame_host/navigation_request.h"
26 #include "content/browser/frame_host/navigator.h"
27 #include "content/browser/frame_host/navigator_impl.h"
28 #include "content/browser/frame_host/render_frame_host_delegate.h"
29 #include "content/browser/frame_host/render_frame_proxy_host.h"
30 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
31 #include "content/browser/geolocation/geolocation_service_context.h"
32 #include "content/browser/permissions/permission_service_context.h"
33 #include "content/browser/permissions/permission_service_impl.h"
34 #include "content/browser/presentation/presentation_service_impl.h"
35 #include "content/browser/renderer_host/input/input_router.h"
36 #include "content/browser/renderer_host/input/timeout_monitor.h"
37 #include "content/browser/renderer_host/render_process_host_impl.h"
38 #include "content/browser/renderer_host/render_view_host_delegate.h"
39 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
40 #include "content/browser/renderer_host/render_view_host_impl.h"
41 #include "content/browser/renderer_host/render_widget_host_impl.h"
42 #include "content/browser/renderer_host/render_widget_host_view_base.h"
43 #include "content/common/accessibility_messages.h"
44 #include "content/common/frame_messages.h"
45 #include "content/common/input_messages.h"
46 #include "content/common/inter_process_time_ticks_converter.h"
47 #include "content/common/navigation_params.h"
48 #include "content/common/render_frame_setup.mojom.h"
49 #include "content/common/site_isolation_policy.h"
50 #include "content/common/swapped_out_messages.h"
51 #include "content/public/browser/ax_event_notification_details.h"
52 #include "content/public/browser/browser_accessibility_state.h"
53 #include "content/public/browser/browser_context.h"
54 #include "content/public/browser/browser_plugin_guest_manager.h"
55 #include "content/public/browser/browser_thread.h"
56 #include "content/public/browser/content_browser_client.h"
57 #include "content/public/browser/permission_manager.h"
58 #include "content/public/browser/permission_type.h"
59 #include "content/public/browser/render_process_host.h"
60 #include "content/public/browser/render_widget_host_view.h"
61 #include "content/public/browser/stream_handle.h"
62 #include "content/public/browser/user_metrics.h"
63 #include "content/public/common/content_constants.h"
64 #include "content/public/common/content_switches.h"
65 #include "content/public/common/isolated_world_ids.h"
66 #include "content/public/common/url_constants.h"
67 #include "content/public/common/url_utils.h"
68 #include "ui/accessibility/ax_tree.h"
69 #include "ui/accessibility/ax_tree_update.h"
70 #include "url/gurl.h"
72 #if defined(OS_ANDROID)
73 #include "content/browser/mojo/service_registrar_android.h"
74 #endif
76 #if defined(OS_MACOSX)
77 #include "content/browser/frame_host/popup_menu_helper_mac.h"
78 #endif
80 #if defined(ENABLE_WEBVR)
81 #include "content/browser/vr/vr_device_manager.h"
82 #endif
84 using base::TimeDelta;
86 namespace content {
88 namespace {
90 // The next value to use for the accessibility reset token.
91 int g_next_accessibility_reset_token = 1;
93 // The next value to use for the javascript callback id.
94 int g_next_javascript_callback_id = 1;
96 // Whether to allow injecting javascript into any kind of frame (for Android
97 // WebView).
98 bool g_allow_injecting_javascript = false;
100 // The (process id, routing id) pair that identifies one RenderFrame.
101 typedef std::pair<int32, int32> RenderFrameHostID;
102 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
103 RoutingIDFrameMap;
104 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
105 LAZY_INSTANCE_INITIALIZER;
107 // Translate a WebKit text direction into a base::i18n one.
108 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
109 blink::WebTextDirection dir) {
110 switch (dir) {
111 case blink::WebTextDirectionLeftToRight:
112 return base::i18n::LEFT_TO_RIGHT;
113 case blink::WebTextDirectionRightToLeft:
114 return base::i18n::RIGHT_TO_LEFT;
115 default:
116 NOTREACHED();
117 return base::i18n::UNKNOWN_DIRECTION;
121 } // namespace
123 // static
124 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
125 return rfh_state == STATE_DEFAULT;
128 // static
129 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
130 int render_frame_id) {
131 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
134 // static
135 void RenderFrameHost::AllowInjectingJavaScriptForAndroidWebView() {
136 g_allow_injecting_javascript = true;
139 // static
140 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
141 int routing_id) {
142 DCHECK_CURRENTLY_ON(BrowserThread::UI);
143 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
144 RoutingIDFrameMap::iterator it = frames->find(
145 RenderFrameHostID(process_id, routing_id));
146 return it == frames->end() ? NULL : it->second;
149 RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
150 RenderViewHostImpl* render_view_host,
151 RenderFrameHostDelegate* delegate,
152 RenderWidgetHostDelegate* rwh_delegate,
153 FrameTree* frame_tree,
154 FrameTreeNode* frame_tree_node,
155 int routing_id,
156 int flags)
157 : render_view_host_(render_view_host),
158 delegate_(delegate),
159 site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
160 process_(site_instance->GetProcess()),
161 cross_process_frame_connector_(NULL),
162 render_frame_proxy_host_(NULL),
163 frame_tree_(frame_tree),
164 frame_tree_node_(frame_tree_node),
165 render_widget_host_(nullptr),
166 routing_id_(routing_id),
167 render_frame_created_(false),
168 navigations_suspended_(false),
169 is_waiting_for_beforeunload_ack_(false),
170 unload_ack_is_for_navigation_(false),
171 is_loading_(false),
172 pending_commit_(false),
173 accessibility_reset_token_(0),
174 accessibility_reset_count_(0),
175 no_create_browser_accessibility_manager_for_testing_(false),
176 weak_ptr_factory_(this) {
177 bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
178 bool hidden = !!(flags & CREATE_RF_HIDDEN);
179 frame_tree_->AddRenderViewHostRef(render_view_host_);
180 GetProcess()->AddRoute(routing_id_, this);
181 g_routing_id_frame_map.Get().insert(std::make_pair(
182 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
183 this));
185 if (is_swapped_out) {
186 rfh_state_ = STATE_SWAPPED_OUT;
187 } else {
188 rfh_state_ = STATE_DEFAULT;
189 GetSiteInstance()->increment_active_frame_count();
192 SetUpMojoIfNeeded();
193 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
194 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
196 if (flags & CREATE_RF_NEEDS_RENDER_WIDGET_HOST) {
197 render_widget_host_ = new RenderWidgetHostImpl(rwh_delegate, GetProcess(),
198 MSG_ROUTING_NONE, hidden);
199 render_widget_host_->set_owned_by_render_frame_host(true);
203 RenderFrameHostImpl::~RenderFrameHostImpl() {
204 GetProcess()->RemoveRoute(routing_id_);
205 g_routing_id_frame_map.Get().erase(
206 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
208 if (delegate_ && render_frame_created_)
209 delegate_->RenderFrameDeleted(this);
211 FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this);
213 // If this was swapped out, it already decremented the active frame count of
214 // the SiteInstance it belongs to.
215 if (IsRFHStateActive(rfh_state_))
216 GetSiteInstance()->decrement_active_frame_count();
218 // Notify the FrameTree that this RFH is going away, allowing it to shut down
219 // the corresponding RenderViewHost if it is no longer needed.
220 frame_tree_->ReleaseRenderViewHostRef(render_view_host_);
222 // NULL out the swapout timer; in crash dumps this member will be null only if
223 // the dtor has run.
224 swapout_event_monitor_timeout_.reset();
226 for (const auto& iter: visual_state_callbacks_) {
227 iter.second.Run(false);
230 if (render_widget_host_) {
231 // Shutdown causes the RenderWidgetHost to delete itself.
232 render_widget_host_->Shutdown();
236 int RenderFrameHostImpl::GetRoutingID() {
237 return routing_id_;
240 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
241 return site_instance_.get();
244 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
245 return process_;
248 RenderFrameHost* RenderFrameHostImpl::GetParent() {
249 FrameTreeNode* parent_node = frame_tree_node_->parent();
250 if (!parent_node)
251 return NULL;
252 return parent_node->current_frame_host();
255 const std::string& RenderFrameHostImpl::GetFrameName() {
256 return frame_tree_node_->frame_name();
259 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
260 FrameTreeNode* parent_node = frame_tree_node_->parent();
261 if (!parent_node)
262 return false;
263 return GetSiteInstance() !=
264 parent_node->current_frame_host()->GetSiteInstance();
267 GURL RenderFrameHostImpl::GetLastCommittedURL() {
268 return frame_tree_node_->current_url();
271 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
272 RenderWidgetHostView* view = render_view_host_->GetView();
273 if (!view)
274 return NULL;
275 return view->GetNativeView();
278 void RenderFrameHostImpl::AddMessageToConsole(ConsoleMessageLevel level,
279 const std::string& message) {
280 Send(new FrameMsg_AddMessageToConsole(routing_id_, level, message));
283 void RenderFrameHostImpl::ExecuteJavaScript(
284 const base::string16& javascript) {
285 CHECK(CanExecuteJavaScript());
286 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
287 javascript,
288 0, false));
291 void RenderFrameHostImpl::ExecuteJavaScript(
292 const base::string16& javascript,
293 const JavaScriptResultCallback& callback) {
294 CHECK(CanExecuteJavaScript());
295 int key = g_next_javascript_callback_id++;
296 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
297 javascript,
298 key, true));
299 javascript_callbacks_.insert(std::make_pair(key, callback));
302 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
303 const base::string16& javascript) {
304 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
305 javascript,
306 0, false, false));
309 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
310 const base::string16& javascript,
311 const JavaScriptResultCallback& callback) {
312 int key = g_next_javascript_callback_id++;
313 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_, javascript,
314 key, true, false));
315 javascript_callbacks_.insert(std::make_pair(key, callback));
319 void RenderFrameHostImpl::ExecuteJavaScriptWithUserGestureForTests(
320 const base::string16& javascript) {
321 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
322 javascript,
323 0, false, true));
326 void RenderFrameHostImpl::ExecuteJavaScriptInIsolatedWorld(
327 const base::string16& javascript,
328 const JavaScriptResultCallback& callback,
329 int world_id) {
330 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
331 world_id > ISOLATED_WORLD_ID_MAX) {
332 // Return if the world_id is not valid.
333 NOTREACHED();
334 return;
337 int key = 0;
338 bool request_reply = false;
339 if (!callback.is_null()) {
340 request_reply = true;
341 key = g_next_javascript_callback_id++;
342 javascript_callbacks_.insert(std::make_pair(key, callback));
345 Send(new FrameMsg_JavaScriptExecuteRequestInIsolatedWorld(
346 routing_id_, javascript, key, request_reply, world_id));
349 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
350 return render_view_host_;
353 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
354 return service_registry_.get();
357 blink::WebPageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
358 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
359 // returning nullptr in some cases. See https://crbug.com/455245.
360 blink::WebPageVisibilityState visibility_state =
361 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())->is_hidden()
362 ? blink::WebPageVisibilityStateHidden
363 : blink::WebPageVisibilityStateVisible;
364 GetContentClient()->browser()->OverridePageVisibilityState(this,
365 &visibility_state);
366 return visibility_state;
369 bool RenderFrameHostImpl::Send(IPC::Message* message) {
370 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
371 return render_view_host_->input_router()->SendInput(
372 make_scoped_ptr(message));
375 return GetProcess()->Send(message);
378 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
379 // Filter out most IPC messages if this frame is swapped out.
380 // We still want to handle certain ACKs to keep our state consistent.
381 if (is_swapped_out()) {
382 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
383 // If this is a synchronous message and we decided not to handle it,
384 // we must send an error reply, or else the renderer will be stuck
385 // and won't respond to future requests.
386 if (msg.is_sync()) {
387 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
388 reply->set_reply_error();
389 Send(reply);
391 // Don't continue looking for someone to handle it.
392 return true;
396 if (delegate_->OnMessageReceived(this, msg))
397 return true;
399 RenderFrameProxyHost* proxy =
400 frame_tree_node_->render_manager()->GetProxyToParent();
401 if (proxy && proxy->cross_process_frame_connector() &&
402 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
403 return true;
405 bool handled = true;
406 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
407 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
408 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
409 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
410 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
411 OnDidStartProvisionalLoadForFrame)
412 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
413 OnDidFailProvisionalLoadWithError)
414 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
415 OnDidFailLoadWithError)
416 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
417 OnDidCommitProvisionalLoad(msg))
418 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation)
419 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
420 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
421 OnDocumentOnLoadCompleted)
422 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
423 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
424 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
425 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
426 OnJavaScriptExecuteResponse)
427 IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
428 OnVisualStateResponse)
429 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
430 OnRunJavaScriptMessage)
431 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
432 OnRunBeforeUnloadConfirm)
433 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
434 OnDidAccessInitialDocument)
435 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
436 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeName, OnDidChangeName)
437 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
438 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeSandboxFlags,
439 OnDidChangeSandboxFlags)
440 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
441 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
442 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
443 OnBeginNavigation)
444 IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
445 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
446 OnTextSurroundingSelectionResponse)
447 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
448 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
449 OnAccessibilityLocationChanges)
450 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
451 OnAccessibilityFindInPageResult)
452 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
453 OnAccessibilitySnapshotResponse)
454 IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
455 // The following message is synthetic and doesn't come from RenderFrame, but
456 // from RenderProcessHost.
457 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
458 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
459 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
460 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
461 OnDidChangeLoadProgress)
462 #if defined(OS_MACOSX) || defined(OS_ANDROID)
463 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
464 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
465 #endif
466 IPC_END_MESSAGE_MAP()
468 // No further actions here, since we may have been deleted.
469 return handled;
472 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
473 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
476 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
477 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
480 void RenderFrameHostImpl::AccessibilityShowContextMenu(int acc_obj_id) {
481 Send(new AccessibilityMsg_ShowContextMenu(routing_id_, acc_obj_id));
484 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
485 int acc_obj_id, const gfx::Rect& subfocus) {
486 Send(new AccessibilityMsg_ScrollToMakeVisible(
487 routing_id_, acc_obj_id, subfocus));
490 void RenderFrameHostImpl::AccessibilityScrollToPoint(
491 int acc_obj_id, const gfx::Point& point) {
492 Send(new AccessibilityMsg_ScrollToPoint(
493 routing_id_, acc_obj_id, point));
496 void RenderFrameHostImpl::AccessibilitySetScrollOffset(
497 int acc_obj_id, const gfx::Point& offset) {
498 Send(new AccessibilityMsg_SetScrollOffset(
499 routing_id_, acc_obj_id, offset));
502 void RenderFrameHostImpl::AccessibilitySetTextSelection(
503 int object_id, int start_offset, int end_offset) {
504 Send(new AccessibilityMsg_SetTextSelection(
505 routing_id_, object_id, start_offset, end_offset));
508 void RenderFrameHostImpl::AccessibilitySetValue(
509 int object_id, const base::string16& value) {
510 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
513 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
514 RenderWidgetHostView* view = render_view_host_->GetView();
515 if (view)
516 return view->HasFocus();
517 return false;
520 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
521 RenderWidgetHostView* view = render_view_host_->GetView();
522 if (view)
523 return view->GetViewBounds();
524 return gfx::Rect();
527 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
528 const gfx::Rect& bounds) const {
529 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
530 render_view_host_->GetView());
531 if (view)
532 return view->AccessibilityOriginInScreen(bounds);
533 return gfx::Point();
536 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
537 Send(new AccessibilityMsg_HitTest(routing_id_, point));
540 void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) {
541 Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id));
544 void RenderFrameHostImpl::AccessibilityReset() {
545 accessibility_reset_token_ = g_next_accessibility_reset_token++;
546 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
549 void RenderFrameHostImpl::AccessibilityFatalError() {
550 browser_accessibility_manager_.reset(NULL);
551 if (accessibility_reset_token_)
552 return;
554 accessibility_reset_count_++;
555 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
556 Send(new AccessibilityMsg_FatalError(routing_id_));
557 } else {
558 accessibility_reset_token_ = g_next_accessibility_reset_token++;
559 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
560 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
564 gfx::AcceleratedWidget
565 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
566 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
567 render_view_host_->GetView());
568 if (view)
569 return view->AccessibilityGetAcceleratedWidget();
570 return gfx::kNullAcceleratedWidget;
573 gfx::NativeViewAccessible
574 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
575 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
576 render_view_host_->GetView());
577 if (view)
578 return view->AccessibilityGetNativeViewAccessible();
579 return NULL;
582 BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame(
583 int accessibility_node_id) {
584 RenderFrameHostImpl* child_frame =
585 FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id);
586 if (!child_frame || IsSameSiteInstance(child_frame))
587 return nullptr;
589 return child_frame->GetOrCreateBrowserAccessibilityManager();
592 void RenderFrameHostImpl::AccessibilityGetAllChildFrames(
593 std::vector<BrowserAccessibilityManager*>* child_frames) {
594 std::vector<RenderFrameHostImpl*> child_frame_hosts;
595 FrameAccessibility::GetInstance()->GetAllChildFrames(
596 this, &child_frame_hosts);
597 for (size_t i = 0; i < child_frame_hosts.size(); ++i) {
598 RenderFrameHostImpl* child_frame_host = child_frame_hosts[i];
599 if (!child_frame_host || IsSameSiteInstance(child_frame_host))
600 continue;
602 BrowserAccessibilityManager* manager =
603 child_frame_host->GetOrCreateBrowserAccessibilityManager();
604 if (manager)
605 child_frames->push_back(manager);
609 BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() {
610 RenderFrameHostImpl* parent_frame = NULL;
611 int parent_node_id = 0;
612 if (!FrameAccessibility::GetInstance()->GetParent(
613 this, &parent_frame, &parent_node_id)) {
614 return NULL;
617 // As a sanity check, make sure the frame we're going to return belongs
618 // to the same BrowserContext.
619 if (GetSiteInstance()->GetBrowserContext() !=
620 parent_frame->GetSiteInstance()->GetBrowserContext()) {
621 NOTREACHED();
622 return NULL;
625 BrowserAccessibilityManager* manager =
626 parent_frame->browser_accessibility_manager();
627 if (!manager)
628 return NULL;
630 return manager->GetFromID(parent_node_id);
633 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id,
634 int previous_sibling_routing_id,
635 int proxy_routing_id) {
636 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
637 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
639 // The process may (if we're sharing a process with another host that already
640 // initialized it) or may not (we have our own process or the old process
641 // crashed) have been initialized. Calling Init multiple times will be
642 // ignored, so this is safe.
643 if (!GetProcess()->Init())
644 return false;
646 DCHECK(GetProcess()->HasConnection());
648 FrameMsg_NewFrame_Params params;
649 params.routing_id = routing_id_;
650 params.parent_routing_id = parent_routing_id;
651 params.proxy_routing_id = proxy_routing_id;
652 params.previous_sibling_routing_id = previous_sibling_routing_id;
653 params.replication_state = frame_tree_node()->current_replication_state();
655 if (render_widget_host_) {
656 params.widget_params.routing_id = render_widget_host_->GetRoutingID();
657 params.widget_params.surface_id = render_widget_host_->surface_id();
658 params.widget_params.hidden = render_widget_host_->is_hidden();
659 } else {
660 // MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
661 // the renderer process.
662 params.widget_params.routing_id = MSG_ROUTING_NONE;
663 params.widget_params.surface_id = 0;
664 params.widget_params.hidden = true;
667 Send(new FrameMsg_NewFrame(params));
669 // The RenderWidgetHost takes ownership of its view. It is tied to the
670 // lifetime of the current RenderProcessHost for this RenderFrameHost.
671 if (render_widget_host_) {
672 RenderWidgetHostView* rwhv =
673 new RenderWidgetHostViewChildFrame(render_widget_host_);
674 rwhv->Hide();
677 if (proxy_routing_id != MSG_ROUTING_NONE) {
678 RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
679 GetProcess()->GetID(), proxy_routing_id);
680 // We have also created a RenderFrameProxy in FrameMsg_NewFrame above, so
681 // remember that.
682 proxy->set_render_frame_proxy_created(true);
685 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
686 // this path is only used for out-of-process iframes. Main frame RenderFrames
687 // are created with their RenderView, and same-site iframes are created at the
688 // time of OnCreateChildFrame.
689 SetRenderFrameCreated(true);
691 return true;
694 void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
695 bool was_created = render_frame_created_;
696 render_frame_created_ = created;
698 // If the current status is different than the new status, the delegate
699 // needs to be notified.
700 if (delegate_ && (created != was_created)) {
701 if (created)
702 delegate_->RenderFrameCreated(this);
703 else
704 delegate_->RenderFrameDeleted(this);
707 if (created && render_widget_host_)
708 render_widget_host_->InitForFrame();
711 void RenderFrameHostImpl::Init() {
712 GetProcess()->ResumeRequestsForView(routing_id_);
715 void RenderFrameHostImpl::OnAddMessageToConsole(
716 int32 level,
717 const base::string16& message,
718 int32 line_no,
719 const base::string16& source_id) {
720 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
721 return;
723 // Pass through log level only on WebUI pages to limit console spew.
724 const bool is_web_ui =
725 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL());
726 const int32 resolved_level = is_web_ui ? level : ::logging::LOG_INFO;
728 // LogMessages can be persisted so this shouldn't be logged in incognito mode.
729 // This rule is not applied to WebUI pages, because source code of WebUI is a
730 // part of Chrome source code, and we want to treat messages from WebUI the
731 // same way as we treat log messages from native code.
732 if (::logging::GetMinLogLevel() <= resolved_level &&
733 (is_web_ui ||
734 !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord())) {
735 logging::LogMessage("CONSOLE", line_no, resolved_level).stream()
736 << "\"" << message << "\", source: " << source_id << " (" << line_no
737 << ")";
741 void RenderFrameHostImpl::OnCreateChildFrame(
742 int new_routing_id,
743 blink::WebTreeScopeType scope,
744 const std::string& frame_name,
745 blink::WebSandboxFlags sandbox_flags) {
746 // It is possible that while a new RenderFrameHost was committed, the
747 // RenderFrame corresponding to this host sent an IPC message to create a
748 // frame and it is delivered after this host is swapped out.
749 // Ignore such messages, as we know this RenderFrameHost is going away.
750 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
751 return;
753 RenderFrameHostImpl* new_frame =
754 frame_tree_->AddFrame(frame_tree_node_, GetProcess()->GetID(),
755 new_routing_id, scope, frame_name, sandbox_flags);
756 if (!new_frame)
757 return;
759 // We know that the RenderFrame has been created in this case, immediately
760 // after the CreateChildFrame IPC was sent.
761 new_frame->SetRenderFrameCreated(true);
764 void RenderFrameHostImpl::OnDetach() {
765 frame_tree_->RemoveFrame(frame_tree_node_);
768 void RenderFrameHostImpl::OnFrameFocused() {
769 frame_tree_->SetFocusedFrame(frame_tree_node_);
772 void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
773 OpenURL(params, GetSiteInstance());
776 void RenderFrameHostImpl::OnDocumentOnLoadCompleted(
777 FrameMsg_UILoadMetricsReportType::Value report_type,
778 base::TimeTicks ui_timestamp) {
779 if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
780 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Link",
781 base::TimeTicks::Now() - ui_timestamp,
782 base::TimeDelta::FromMilliseconds(10),
783 base::TimeDelta::FromMinutes(10), 100);
784 } else if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
785 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Intent",
786 base::TimeTicks::Now() - ui_timestamp,
787 base::TimeDelta::FromMilliseconds(10),
788 base::TimeDelta::FromMinutes(10), 100);
790 // This message is only sent for top-level frames. TODO(avi): when frame tree
791 // mirroring works correctly, add a check here to enforce it.
792 delegate_->DocumentOnLoadCompleted(this);
795 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(const GURL& url) {
796 frame_tree_node_->navigator()->DidStartProvisionalLoad(
797 this, url);
800 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
801 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
802 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
805 void RenderFrameHostImpl::OnDidFailLoadWithError(
806 const GURL& url,
807 int error_code,
808 const base::string16& error_description,
809 bool was_ignored_by_handler) {
810 GURL validated_url(url);
811 GetProcess()->FilterURL(false, &validated_url);
813 frame_tree_node_->navigator()->DidFailLoadWithError(
814 this, validated_url, error_code, error_description,
815 was_ignored_by_handler);
818 // Called when the renderer navigates. For every frame loaded, we'll get this
819 // notification containing parameters identifying the navigation.
821 // Subframes are identified by the page transition type. For subframes loaded
822 // as part of a wider page load, the page_id will be the same as for the top
823 // level frame. If the user explicitly requests a subframe navigation, we will
824 // get a new page_id because we need to create a new navigation entry for that
825 // action.
826 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
827 RenderProcessHost* process = GetProcess();
829 // Read the parameters out of the IPC message directly to avoid making another
830 // copy when we filter the URLs.
831 base::PickleIterator iter(msg);
832 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
833 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
834 Read(&msg, &iter, &validated_params)) {
835 bad_message::ReceivedBadMessage(
836 process, bad_message::RFH_COMMIT_DESERIALIZATION_FAILED);
837 return;
839 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
840 "url", validated_params.url.possibly_invalid_spec());
842 // Sanity-check the page transition for frame type.
843 DCHECK_EQ(ui::PageTransitionIsMainFrame(validated_params.transition),
844 !GetParent());
846 // If we're waiting for a cross-site beforeunload ack from this renderer and
847 // we receive a Navigate message from the main frame, then the renderer was
848 // navigating already and sent it before hearing the FrameMsg_Stop message.
849 // Treat this as an implicit beforeunload ack to allow the pending navigation
850 // to continue.
851 if (is_waiting_for_beforeunload_ack_ &&
852 unload_ack_is_for_navigation_ &&
853 !GetParent()) {
854 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
855 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
858 // If we're waiting for an unload ack from this renderer and we receive a
859 // Navigate message, then the renderer was navigating before it received the
860 // unload request. It will either respond to the unload request soon or our
861 // timer will expire. Either way, we should ignore this message, because we
862 // have already committed to closing this renderer.
863 if (IsWaitingForUnloadACK())
864 return;
866 if (validated_params.report_type ==
867 FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
868 UMA_HISTOGRAM_CUSTOM_TIMES(
869 "Navigation.UI_OnCommitProvisionalLoad.Link",
870 base::TimeTicks::Now() - validated_params.ui_timestamp,
871 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
872 100);
873 } else if (validated_params.report_type ==
874 FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
875 UMA_HISTOGRAM_CUSTOM_TIMES(
876 "Navigation.UI_OnCommitProvisionalLoad.Intent",
877 base::TimeTicks::Now() - validated_params.ui_timestamp,
878 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
879 100);
882 // Attempts to commit certain off-limits URL should be caught more strictly
883 // than our FilterURL checks below. If a renderer violates this policy, it
884 // should be killed.
885 if (!CanCommitURL(validated_params.url)) {
886 VLOG(1) << "Blocked URL " << validated_params.url.spec();
887 validated_params.url = GURL(url::kAboutBlankURL);
888 // Kills the process.
889 bad_message::ReceivedBadMessage(process,
890 bad_message::RFH_CAN_COMMIT_URL_BLOCKED);
893 // Without this check, an evil renderer can trick the browser into creating
894 // a navigation entry for a banned URL. If the user clicks the back button
895 // followed by the forward button (or clicks reload, or round-trips through
896 // session restore, etc), we'll think that the browser commanded the
897 // renderer to load the URL and grant the renderer the privileges to request
898 // the URL. To prevent this attack, we block the renderer from inserting
899 // banned URLs into the navigation controller in the first place.
900 process->FilterURL(false, &validated_params.url);
901 process->FilterURL(true, &validated_params.referrer.url);
902 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
903 it != validated_params.redirects.end(); ++it) {
904 process->FilterURL(false, &(*it));
906 process->FilterURL(true, &validated_params.searchable_form_url);
908 // Without this check, the renderer can trick the browser into using
909 // filenames it can't access in a future session restore.
910 if (!render_view_host_->CanAccessFilesOfPageState(
911 validated_params.page_state)) {
912 bad_message::ReceivedBadMessage(
913 GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
914 return;
917 accessibility_reset_count_ = 0;
918 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
920 // PlzNavigate
921 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
922 switches::kEnableBrowserSideNavigation)) {
923 pending_commit_ = false;
927 void RenderFrameHostImpl::OnDidDropNavigation() {
928 // At the end of Navigate(), the FrameTreeNode's DidStartLoading is called to
929 // force the spinner to start, even if the renderer didn't yet begin the load.
930 // If it turns out that the renderer dropped the navigation, the spinner needs
931 // to be turned off.
932 frame_tree_node_->DidStopLoading();
935 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
936 if (render_widget_host_)
937 return render_widget_host_;
939 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
940 // we can remove this fallback. Currently it is only used for the main
941 // frame.
942 if (!GetParent())
943 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
945 return nullptr;
948 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
949 RenderFrameHostImpl* frame = this;
950 while (frame) {
951 if (frame->render_widget_host_)
952 return frame->render_widget_host_->GetView();
953 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
956 return render_view_host_->GetView();
959 int RenderFrameHostImpl::GetEnabledBindings() {
960 return render_view_host_->GetEnabledBindings();
963 void RenderFrameHostImpl::OnCrossSiteResponse(
964 const GlobalRequestID& global_request_id,
965 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
966 const std::vector<GURL>& transfer_url_chain,
967 const Referrer& referrer,
968 ui::PageTransition page_transition,
969 bool should_replace_current_entry) {
970 frame_tree_node_->render_manager()->OnCrossSiteResponse(
971 this, global_request_id, cross_site_transferring_request.Pass(),
972 transfer_url_chain, referrer, page_transition,
973 should_replace_current_entry);
976 void RenderFrameHostImpl::SwapOut(
977 RenderFrameProxyHost* proxy,
978 bool is_loading) {
979 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
980 // the operation and sends back an IPC message.
981 // The trace event may not end properly if the ACK times out. We expect this
982 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
983 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
985 // If this RenderFrameHost is not in the default state, it must have already
986 // gone through this, therefore just return.
987 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
988 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
989 return;
992 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
993 swapout_event_monitor_timeout_->Start(
994 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
996 // There may be no proxy if there are no active views in the process.
997 int proxy_routing_id = MSG_ROUTING_NONE;
998 FrameReplicationState replication_state;
999 if (proxy) {
1000 set_render_frame_proxy_host(proxy);
1001 proxy_routing_id = proxy->GetRoutingID();
1002 replication_state = proxy->frame_tree_node()->current_replication_state();
1005 if (IsRenderFrameLive()) {
1006 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
1007 replication_state));
1010 if (!GetParent())
1011 delegate_->SwappedOut(this);
1014 void RenderFrameHostImpl::OnBeforeUnloadACK(
1015 bool proceed,
1016 const base::TimeTicks& renderer_before_unload_start_time,
1017 const base::TimeTicks& renderer_before_unload_end_time) {
1018 TRACE_EVENT_ASYNC_END0(
1019 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1020 DCHECK(!GetParent());
1021 // If this renderer navigated while the beforeunload request was in flight, we
1022 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
1023 // can ignore this message.
1024 // However renderer might also be swapped out but we still want to proceed
1025 // with navigation, otherwise it would block future navigations. This can
1026 // happen when pending cross-site navigation is canceled by a second one just
1027 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
1028 // but second navigation is started from the beginning.
1029 if (!is_waiting_for_beforeunload_ack_) {
1030 return;
1032 DCHECK(!send_before_unload_start_time_.is_null());
1034 // Sets a default value for before_unload_end_time so that the browser
1035 // survives a hacked renderer.
1036 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
1037 if (!renderer_before_unload_start_time.is_null() &&
1038 !renderer_before_unload_end_time.is_null()) {
1039 // When passing TimeTicks across process boundaries, we need to compensate
1040 // for any skew between the processes. Here we are converting the
1041 // renderer's notion of before_unload_end_time to TimeTicks in the browser
1042 // process. See comments in inter_process_time_ticks_converter.h for more.
1043 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
1044 InterProcessTimeTicksConverter converter(
1045 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
1046 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
1047 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
1048 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1049 LocalTimeTicks browser_before_unload_end_time =
1050 converter.ToLocalTimeTicks(
1051 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1052 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1054 // Collect UMA on the inter-process skew.
1055 bool is_skew_additive = false;
1056 if (converter.IsSkewAdditiveForMetrics()) {
1057 is_skew_additive = true;
1058 base::TimeDelta skew = converter.GetSkewForMetrics();
1059 if (skew >= base::TimeDelta()) {
1060 UMA_HISTOGRAM_TIMES(
1061 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
1062 } else {
1063 UMA_HISTOGRAM_TIMES(
1064 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
1067 UMA_HISTOGRAM_BOOLEAN(
1068 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
1069 is_skew_additive);
1071 base::TimeDelta on_before_unload_overhead_time =
1072 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1073 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1074 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1075 on_before_unload_overhead_time);
1077 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1078 renderer_before_unload_start_time, renderer_before_unload_end_time);
1080 // Resets beforeunload waiting state.
1081 is_waiting_for_beforeunload_ack_ = false;
1082 render_view_host_->decrement_in_flight_event_count();
1083 render_view_host_->StopHangMonitorTimeout();
1084 send_before_unload_start_time_ = base::TimeTicks();
1086 // PlzNavigate: if the ACK is for a navigation, send it to the Navigator to
1087 // have the current navigation stop/proceed. Otherwise, send it to the
1088 // RenderFrameHostManager which handles closing.
1089 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1090 switches::kEnableBrowserSideNavigation) &&
1091 unload_ack_is_for_navigation_) {
1092 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1093 // Navigator.
1094 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1095 frame_tree_node_, proceed);
1096 } else {
1097 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1098 unload_ack_is_for_navigation_, proceed,
1099 before_unload_end_time);
1102 // If canceled, notify the delegate to cancel its pending navigation entry.
1103 if (!proceed)
1104 render_view_host_->GetDelegate()->DidCancelLoading();
1107 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1108 return render_view_host_->is_waiting_for_close_ack_ ||
1109 rfh_state_ == STATE_PENDING_SWAP_OUT;
1112 void RenderFrameHostImpl::OnSwapOutACK() {
1113 OnSwappedOut();
1116 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1117 if (frame_tree_node_->IsMainFrame()) {
1118 // Keep the termination status so we can get at it later when we
1119 // need to know why it died.
1120 render_view_host_->render_view_termination_status_ =
1121 static_cast<base::TerminationStatus>(status);
1124 // Reset frame tree state associated with this process. This must happen
1125 // before RenderViewTerminated because observers expect the subframes of any
1126 // affected frames to be cleared first.
1127 // Note: When a RenderFrameHost is swapped out there is a different one
1128 // which is the current host. In this case, the FrameTreeNode state must
1129 // not be reset.
1130 if (!is_swapped_out())
1131 frame_tree_node_->ResetForNewProcess();
1133 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1134 // reset.
1135 SetRenderFrameCreated(false);
1136 InvalidateMojoConnection();
1138 // Execute any pending AX tree snapshot callbacks with an empty response,
1139 // since we're never going to get a response from this renderer.
1140 for (const auto& iter : ax_tree_snapshot_callbacks_)
1141 iter.second.Run(ui::AXTreeUpdate());
1142 ax_tree_snapshot_callbacks_.clear();
1144 // Note: don't add any more code at this point in the function because
1145 // |this| may be deleted. Any additional cleanup should happen before
1146 // the last block of code here.
1149 void RenderFrameHostImpl::OnSwappedOut() {
1150 // Ignore spurious swap out ack.
1151 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1152 return;
1154 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1155 swapout_event_monitor_timeout_->Stop();
1158 // If this is a main frame RFH that's about to be deleted, update its RVH's
1159 // swapped-out state here, since SetState won't be called once this RFH is
1160 // deleted below. https://crbug.com/505887
1161 if (frame_tree_node_->IsMainFrame() &&
1162 frame_tree_node_->render_manager()->IsPendingDeletion(this)) {
1163 render_view_host_->set_is_active(false);
1164 render_view_host_->set_is_swapped_out(true);
1167 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1168 // We are now deleted.
1169 return;
1172 // If this RFH wasn't pending deletion, then it is now swapped out.
1173 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1176 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1177 // Validate the URLs in |params|. If the renderer can't request the URLs
1178 // directly, don't show them in the context menu.
1179 ContextMenuParams validated_params(params);
1180 RenderProcessHost* process = GetProcess();
1182 // We don't validate |unfiltered_link_url| so that this field can be used
1183 // when users want to copy the original link URL.
1184 process->FilterURL(true, &validated_params.link_url);
1185 process->FilterURL(true, &validated_params.src_url);
1186 process->FilterURL(false, &validated_params.page_url);
1187 process->FilterURL(true, &validated_params.frame_url);
1189 delegate_->ShowContextMenu(this, validated_params);
1192 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1193 int id, const base::ListValue& result) {
1194 const base::Value* result_value;
1195 if (!result.Get(0, &result_value)) {
1196 // Programming error or rogue renderer.
1197 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1198 return;
1201 std::map<int, JavaScriptResultCallback>::iterator it =
1202 javascript_callbacks_.find(id);
1203 if (it != javascript_callbacks_.end()) {
1204 it->second.Run(result_value);
1205 javascript_callbacks_.erase(it);
1206 } else {
1207 NOTREACHED() << "Received script response for unknown request";
1211 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1212 auto it = visual_state_callbacks_.find(id);
1213 if (it != visual_state_callbacks_.end()) {
1214 it->second.Run(true);
1215 visual_state_callbacks_.erase(it);
1216 } else {
1217 NOTREACHED() << "Received script response for unknown request";
1221 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1222 const base::string16& message,
1223 const base::string16& default_prompt,
1224 const GURL& frame_url,
1225 JavaScriptMessageType type,
1226 IPC::Message* reply_msg) {
1227 // While a JS message dialog is showing, tabs in the same process shouldn't
1228 // process input events.
1229 GetProcess()->SetIgnoreInputEvents(true);
1230 render_view_host_->StopHangMonitorTimeout();
1231 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1232 frame_url, type, reply_msg);
1235 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1236 const GURL& frame_url,
1237 const base::string16& message,
1238 bool is_reload,
1239 IPC::Message* reply_msg) {
1240 // While a JS beforeunload dialog is showing, tabs in the same process
1241 // shouldn't process input events.
1242 GetProcess()->SetIgnoreInputEvents(true);
1243 render_view_host_->StopHangMonitorTimeout();
1244 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1247 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1248 const base::string16& content,
1249 size_t start_offset,
1250 size_t end_offset) {
1251 render_view_host_->OnTextSurroundingSelectionResponse(
1252 content, start_offset, end_offset);
1255 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1256 delegate_->DidAccessInitialDocument();
1259 void RenderFrameHostImpl::OnDidDisownOpener() {
1260 // This message is only sent for top-level frames for now.
1261 // TODO(alexmos): This should eventually support subframe openers as well,
1262 // and it should allow openers to be updated to another frame (which can
1263 // happen via window.open('','framename')) in addition to being disowned.
1265 // No action is necessary if the opener has already been cleared.
1266 if (!frame_tree_node_->opener())
1267 return;
1269 // Clear our opener so that future cross-process navigations don't have an
1270 // opener assigned.
1271 frame_tree_node_->SetOpener(nullptr);
1273 // Notify all other RenderFrameHosts and RenderFrameProxies for this frame.
1274 // This is important in case we go back to them, or if another window in
1275 // those processes tries to access window.opener.
1276 frame_tree_node_->render_manager()->DidDisownOpener(this);
1279 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1280 std::string old_name = frame_tree_node()->frame_name();
1281 frame_tree_node()->SetFrameName(name);
1282 if (old_name.empty() && !name.empty())
1283 frame_tree_node_->render_manager()->CreateProxiesForNewNamedFrame();
1284 delegate_->DidChangeName(this, name);
1287 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1288 // Update the RVH's current page ID so that future IPCs from the renderer
1289 // correspond to the new page.
1290 render_view_host_->page_id_ = page_id;
1293 void RenderFrameHostImpl::OnDidChangeSandboxFlags(
1294 int32 frame_routing_id,
1295 blink::WebSandboxFlags flags) {
1296 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1297 FrameTreeNode* child =
1298 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1299 if (!child)
1300 return;
1302 // Ensure that a frame can only update sandbox flags for its immediate
1303 // children. If this is not the case, the renderer is considered malicious
1304 // and is killed.
1305 if (child->parent() != frame_tree_node()) {
1306 bad_message::ReceivedBadMessage(GetProcess(),
1307 bad_message::RFH_SANDBOX_FLAGS);
1308 return;
1311 child->set_sandbox_flags(flags);
1313 // Notify the RenderFrame if it lives in a different process from its
1314 // parent. The frame's proxies in other processes also need to learn about
1315 // the updated sandbox flags, but these notifications are sent later in
1316 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1317 // navigates and the new sandbox flags take effect.
1318 RenderFrameHost* child_rfh = child->current_frame_host();
1319 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1320 child_rfh->Send(
1321 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1325 void RenderFrameHostImpl::OnUpdateTitle(
1326 const base::string16& title,
1327 blink::WebTextDirection title_direction) {
1328 // This message is only sent for top-level frames. TODO(avi): when frame tree
1329 // mirroring works correctly, add a check here to enforce it.
1330 if (title.length() > kMaxTitleChars) {
1331 NOTREACHED() << "Renderer sent too many characters in title.";
1332 return;
1335 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1336 WebTextDirectionToChromeTextDirection(
1337 title_direction));
1340 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1341 // This message is only sent for top-level frames. TODO(avi): when frame tree
1342 // mirroring works correctly, add a check here to enforce it.
1343 delegate_->UpdateEncoding(this, encoding_name);
1346 void RenderFrameHostImpl::OnBeginNavigation(
1347 const CommonNavigationParams& common_params,
1348 const BeginNavigationParams& begin_params,
1349 scoped_refptr<ResourceRequestBody> body) {
1350 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1351 switches::kEnableBrowserSideNavigation));
1352 frame_tree_node()->navigator()->OnBeginNavigation(
1353 frame_tree_node(), common_params, begin_params, body);
1356 void RenderFrameHostImpl::OnDispatchLoad() {
1357 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
1358 // Only frames with an out-of-process parent frame should be sending this
1359 // message.
1360 RenderFrameProxyHost* proxy =
1361 frame_tree_node()->render_manager()->GetProxyToParent();
1362 if (!proxy) {
1363 bad_message::ReceivedBadMessage(GetProcess(),
1364 bad_message::RFH_NO_PROXY_TO_PARENT);
1365 return;
1368 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1371 void RenderFrameHostImpl::OnAccessibilityEvents(
1372 const std::vector<AccessibilityHostMsg_EventParams>& params,
1373 int reset_token) {
1374 // Don't process this IPC if either we're waiting on a reset and this
1375 // IPC doesn't have the matching token ID, or if we're not waiting on a
1376 // reset but this message includes a reset token.
1377 if (accessibility_reset_token_ != reset_token) {
1378 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1379 return;
1381 accessibility_reset_token_ = 0;
1383 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1384 render_view_host_->GetView());
1386 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1387 if ((accessibility_mode != AccessibilityModeOff) && view &&
1388 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1389 if (browser_accessibility_manager_) {
1390 // Get the frame routing ids from out-of-process iframes and
1391 // browser plugin instance ids from guests and update the mappings in
1392 // FrameAccessibility.
1393 for (size_t i = 0; i < params.size(); ++i) {
1394 const AccessibilityHostMsg_EventParams& param = params[i];
1395 UpdateCrossProcessIframeAccessibility(
1396 param.node_to_frame_routing_id_map);
1397 UpdateGuestFrameAccessibility(
1398 param.node_to_browser_plugin_instance_id_map);
1402 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1403 GetOrCreateBrowserAccessibilityManager();
1404 if (browser_accessibility_manager_)
1405 browser_accessibility_manager_->OnAccessibilityEvents(params);
1408 // Send the updates to the automation extension API.
1409 std::vector<AXEventNotificationDetails> details;
1410 details.reserve(params.size());
1411 for (size_t i = 0; i < params.size(); ++i) {
1412 const AccessibilityHostMsg_EventParams& param = params[i];
1413 AXEventNotificationDetails detail(
1414 param.update.node_id_to_clear,
1415 param.update.nodes,
1416 param.event_type,
1417 param.id,
1418 param.node_to_browser_plugin_instance_id_map,
1419 GetProcess()->GetID(),
1420 routing_id_);
1421 details.push_back(detail);
1424 delegate_->AccessibilityEventReceived(details);
1427 // Always send an ACK or the renderer can be in a bad state.
1428 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1430 // The rest of this code is just for testing; bail out if we're not
1431 // in that mode.
1432 if (accessibility_testing_callback_.is_null())
1433 return;
1435 for (size_t i = 0; i < params.size(); i++) {
1436 const AccessibilityHostMsg_EventParams& param = params[i];
1437 if (static_cast<int>(param.event_type) < 0)
1438 continue;
1440 if (!ax_tree_for_testing_) {
1441 if (browser_accessibility_manager_) {
1442 ax_tree_for_testing_.reset(new ui::AXTree(
1443 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1444 } else {
1445 ax_tree_for_testing_.reset(new ui::AXTree());
1446 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1447 << ax_tree_for_testing_->error();
1449 } else {
1450 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1451 << ax_tree_for_testing_->error();
1453 accessibility_testing_callback_.Run(param.event_type, param.id);
1457 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1458 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1459 if (accessibility_reset_token_)
1460 return;
1462 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1463 render_view_host_->GetView());
1464 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1465 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1466 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1467 BrowserAccessibilityManager* manager =
1468 GetOrCreateBrowserAccessibilityManager();
1469 if (manager)
1470 manager->OnLocationChanges(params);
1472 // TODO(aboxhall): send location change events to web contents observers too
1476 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1477 const AccessibilityHostMsg_FindInPageResultParams& params) {
1478 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1479 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1480 BrowserAccessibilityManager* manager =
1481 GetOrCreateBrowserAccessibilityManager();
1482 if (manager) {
1483 manager->OnFindInPageResult(
1484 params.request_id, params.match_index, params.start_id,
1485 params.start_offset, params.end_id, params.end_offset);
1490 void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
1491 int callback_id,
1492 const ui::AXTreeUpdate& snapshot) {
1493 const auto& it = ax_tree_snapshot_callbacks_.find(callback_id);
1494 if (it != ax_tree_snapshot_callbacks_.end()) {
1495 it->second.Run(snapshot);
1496 ax_tree_snapshot_callbacks_.erase(it);
1497 } else {
1498 NOTREACHED() << "Received AX tree snapshot response for unknown id";
1502 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1503 if (enter_fullscreen)
1504 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1505 else
1506 delegate_->ExitFullscreenMode();
1508 // The previous call might change the fullscreen state. We need to make sure
1509 // the renderer is aware of that, which is done via the resize message.
1510 render_view_host_->WasResized();
1513 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
1514 // Any main frame load to a new document should reset the load since it will
1515 // replace the current page and any frames.
1516 if (to_different_document && !GetParent())
1517 is_loading_ = false;
1519 // This method should never be called when the frame is loading.
1520 // Unfortunately, it can happen if a history navigation happens during a
1521 // BeforeUnload or Unload event.
1522 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1523 // refactored in Blink. See crbug.com/466089
1524 if (is_loading_) {
1525 LOG(WARNING) << "OnDidStartLoading was called twice.";
1526 return;
1529 frame_tree_node_->DidStartLoading(to_different_document);
1530 is_loading_ = true;
1533 void RenderFrameHostImpl::OnDidStopLoading() {
1534 // This method should never be called when the frame is not loading.
1535 // Unfortunately, it can happen if a history navigation happens during a
1536 // BeforeUnload or Unload event.
1537 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1538 // refactored in Blink. See crbug.com/466089
1539 if (!is_loading_) {
1540 LOG(WARNING) << "OnDidStopLoading was called twice.";
1541 return;
1544 is_loading_ = false;
1545 frame_tree_node_->DidStopLoading();
1548 void RenderFrameHostImpl::OnDidChangeLoadProgress(double load_progress) {
1549 frame_tree_node_->DidChangeLoadProgress(load_progress);
1552 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1553 void RenderFrameHostImpl::OnShowPopup(
1554 const FrameHostMsg_ShowPopup_Params& params) {
1555 RenderViewHostDelegateView* view =
1556 render_view_host_->delegate_->GetDelegateView();
1557 if (view) {
1558 view->ShowPopupMenu(this,
1559 params.bounds,
1560 params.item_height,
1561 params.item_font_size,
1562 params.selected_item,
1563 params.popup_items,
1564 params.right_aligned,
1565 params.allow_multiple_selection);
1569 void RenderFrameHostImpl::OnHidePopup() {
1570 RenderViewHostDelegateView* view =
1571 render_view_host_->delegate_->GetDelegateView();
1572 if (view)
1573 view->HidePopupMenu();
1575 #endif
1577 void RenderFrameHostImpl::RegisterMojoServices() {
1578 GeolocationServiceContext* geolocation_service_context =
1579 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1580 if (geolocation_service_context) {
1581 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1582 // can perform permissions checks once site isolation is complete.
1583 // crbug.com/426384
1584 GetServiceRegistry()->AddService<GeolocationService>(
1585 base::Bind(&GeolocationServiceContext::CreateService,
1586 base::Unretained(geolocation_service_context),
1587 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1588 base::Unretained(this))));
1591 if (!permission_service_context_)
1592 permission_service_context_.reset(new PermissionServiceContext(this));
1594 GetServiceRegistry()->AddService<PermissionService>(
1595 base::Bind(&PermissionServiceContext::CreateService,
1596 base::Unretained(permission_service_context_.get())));
1598 GetServiceRegistry()->AddService<presentation::PresentationService>(
1599 base::Bind(&PresentationServiceImpl::CreateMojoService,
1600 base::Unretained(this)));
1602 if (!frame_mojo_shell_)
1603 frame_mojo_shell_.reset(new FrameMojoShell(this));
1605 GetServiceRegistry()->AddService<mojo::Shell>(base::Bind(
1606 &FrameMojoShell::BindRequest, base::Unretained(frame_mojo_shell_.get())));
1608 #if defined(ENABLE_WEBVR)
1609 const base::CommandLine& browser_command_line =
1610 *base::CommandLine::ForCurrentProcess();
1612 if (browser_command_line.HasSwitch(switches::kEnableWebVR)) {
1613 GetServiceRegistry()->AddService<VRService>(
1614 base::Bind(&VRDeviceManager::BindRequest));
1616 #endif
1619 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1620 // Only main frames should be swapped out and retained inside a proxy host.
1621 if (rfh_state == STATE_SWAPPED_OUT)
1622 CHECK(!GetParent());
1624 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1625 // out status of a RenderFrameHost gets flipped to/from active.
1626 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1627 GetSiteInstance()->increment_active_frame_count();
1628 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1629 GetSiteInstance()->decrement_active_frame_count();
1631 // The active and swapped out state of the RVH is determined by its main
1632 // frame, since subframes should have their own widgets.
1633 if (frame_tree_node_->IsMainFrame()) {
1634 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1635 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1638 // Whenever we change the RFH state to and from active or swapped out state,
1639 // we should not be waiting for beforeunload or close acks. We clear them
1640 // here to be safe, since they can cause navigations to be ignored in
1641 // OnDidCommitProvisionalLoad.
1642 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1643 if (rfh_state == STATE_DEFAULT ||
1644 rfh_state == STATE_SWAPPED_OUT ||
1645 rfh_state_ == STATE_DEFAULT ||
1646 rfh_state_ == STATE_SWAPPED_OUT) {
1647 if (is_waiting_for_beforeunload_ack_) {
1648 is_waiting_for_beforeunload_ack_ = false;
1649 render_view_host_->decrement_in_flight_event_count();
1650 render_view_host_->StopHangMonitorTimeout();
1652 send_before_unload_start_time_ = base::TimeTicks();
1653 render_view_host_->is_waiting_for_close_ack_ = false;
1655 rfh_state_ = rfh_state;
1658 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1659 // TODO(creis): We should also check for WebUI pages here. Also, when the
1660 // out-of-process iframes implementation is ready, we should check for
1661 // cross-site URLs that are not allowed to commit in this process.
1663 // Give the client a chance to disallow URLs from committing.
1664 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1667 void RenderFrameHostImpl::Navigate(
1668 const CommonNavigationParams& common_params,
1669 const StartNavigationParams& start_params,
1670 const RequestNavigationParams& request_params) {
1671 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1673 UpdatePermissionsForNavigation(common_params, request_params);
1675 // Only send the message if we aren't suspended at the start of a cross-site
1676 // request.
1677 if (navigations_suspended_) {
1678 // Shouldn't be possible to have a second navigation while suspended, since
1679 // navigations will only be suspended during a cross-site request. If a
1680 // second navigation occurs, RenderFrameHostManager will cancel this pending
1681 // RFH and create a new pending RFH.
1682 DCHECK(!suspended_nav_params_.get());
1683 suspended_nav_params_.reset(
1684 new NavigationParams(common_params, start_params, request_params));
1685 } else {
1686 // Get back to a clean state, in case we start a new navigation without
1687 // completing a RFH swap or unload handler.
1688 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1690 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1691 request_params));
1694 // Force the throbber to start. This is done because Blink's "started loading"
1695 // message will be received asynchronously from the UI of the browser. But the
1696 // throbber needs to be kept in sync with what's happening in the UI. For
1697 // example, the throbber will start immediately when the user navigates even
1698 // if the renderer is delayed. There is also an issue with the throbber
1699 // starting because the WebUI (which controls whether the favicon is
1700 // displayed) happens synchronously. If the start loading messages was
1701 // asynchronous, then the default favicon would flash in.
1703 // Blink doesn't send throb notifications for JavaScript URLs, so it is not
1704 // done here either.
1705 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1706 frame_tree_node_->DidStartLoading(true);
1709 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1710 CommonNavigationParams common_params(
1711 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::NORMAL,
1712 true, false, base::TimeTicks::Now(),
1713 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
1714 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1717 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1718 SiteInstance* source_site_instance) {
1719 GURL validated_url(params.url);
1720 GetProcess()->FilterURL(false, &validated_url);
1722 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1723 validated_url.possibly_invalid_spec());
1724 frame_tree_node_->navigator()->RequestOpenURL(
1725 this, validated_url, source_site_instance, params.referrer,
1726 params.disposition, params.should_replace_current_entry,
1727 params.user_gesture);
1730 void RenderFrameHostImpl::Stop() {
1731 Send(new FrameMsg_Stop(routing_id_));
1734 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1735 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1736 // the handler ran and allowed the navigation to proceed.
1737 if (!ShouldDispatchBeforeUnload()) {
1738 DCHECK(!(base::CommandLine::ForCurrentProcess()->HasSwitch(
1739 switches::kEnableBrowserSideNavigation) &&
1740 for_navigation));
1741 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1742 for_navigation, true, base::TimeTicks::Now());
1743 return;
1745 TRACE_EVENT_ASYNC_BEGIN0(
1746 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1748 // This may be called more than once (if the user clicks the tab close button
1749 // several times, or if she clicks the tab close button then the browser close
1750 // button), and we only send the message once.
1751 if (is_waiting_for_beforeunload_ack_) {
1752 // Some of our close messages could be for the tab, others for cross-site
1753 // transitions. We always want to think it's for closing the tab if any
1754 // of the messages were, since otherwise it might be impossible to close
1755 // (if there was a cross-site "close" request pending when the user clicked
1756 // the close button). We want to keep the "for cross site" flag only if
1757 // both the old and the new ones are also for cross site.
1758 unload_ack_is_for_navigation_ =
1759 unload_ack_is_for_navigation_ && for_navigation;
1760 } else {
1761 // Start the hang monitor in case the renderer hangs in the beforeunload
1762 // handler.
1763 is_waiting_for_beforeunload_ack_ = true;
1764 unload_ack_is_for_navigation_ = for_navigation;
1765 // Increment the in-flight event count, to ensure that input events won't
1766 // cancel the timeout timer.
1767 render_view_host_->increment_in_flight_event_count();
1768 render_view_host_->StartHangMonitorTimeout(
1769 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1770 send_before_unload_start_time_ = base::TimeTicks::Now();
1771 Send(new FrameMsg_BeforeUnload(routing_id_));
1775 bool RenderFrameHostImpl::ShouldDispatchBeforeUnload() {
1776 // TODO(creis): Support beforeunload on subframes.
1777 return !GetParent() && IsRenderFrameLive();
1780 void RenderFrameHostImpl::DisownOpener() {
1781 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1784 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1785 size_t after) {
1786 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1789 void RenderFrameHostImpl::JavaScriptDialogClosed(
1790 IPC::Message* reply_msg,
1791 bool success,
1792 const base::string16& user_input,
1793 bool dialog_was_suppressed) {
1794 GetProcess()->SetIgnoreInputEvents(false);
1795 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1797 // If we are executing as part of (before)unload event handling, we don't
1798 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1799 // leave the current page. In this case, use the regular timeout value used
1800 // during the (before)unload handling.
1801 if (is_waiting) {
1802 render_view_host_->StartHangMonitorTimeout(
1803 success
1804 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1805 : render_view_host_->hung_renderer_delay_);
1808 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1809 success, user_input);
1810 Send(reply_msg);
1812 // If we are waiting for an unload or beforeunload ack and the user has
1813 // suppressed messages, kill the tab immediately; a page that's spamming
1814 // alerts in onbeforeunload is presumably malicious, so there's no point in
1815 // continuing to run its script and dragging out the process.
1816 // This must be done after sending the reply since RenderView can't close
1817 // correctly while waiting for a response.
1818 if (is_waiting && dialog_was_suppressed)
1819 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1822 // PlzNavigate
1823 void RenderFrameHostImpl::CommitNavigation(
1824 ResourceResponse* response,
1825 scoped_ptr<StreamHandle> body,
1826 const CommonNavigationParams& common_params,
1827 const RequestNavigationParams& request_params) {
1828 DCHECK((response && body.get()) ||
1829 !ShouldMakeNetworkRequestForURL(common_params.url));
1830 UpdatePermissionsForNavigation(common_params, request_params);
1832 // Get back to a clean state, in case we start a new navigation without
1833 // completing a RFH swap or unload handler.
1834 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1836 const GURL body_url = body.get() ? body->GetURL() : GURL();
1837 const ResourceResponseHead head = response ?
1838 response->head : ResourceResponseHead();
1839 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1840 request_params));
1841 // TODO(clamy): Check if we should start the throbber for non javascript urls
1842 // here.
1844 // TODO(clamy): Release the stream handle once the renderer has finished
1845 // reading it.
1846 stream_handle_ = body.Pass();
1848 // When navigating to a Javascript url, no commit is expected from the
1849 // RenderFrameHost, nor should the throbber start.
1850 if (!common_params.url.SchemeIs(url::kJavaScriptScheme)) {
1851 pending_commit_ = true;
1852 is_loading_ = true;
1854 frame_tree_node_->ResetNavigationRequest(true);
1857 void RenderFrameHostImpl::FailedNavigation(
1858 const CommonNavigationParams& common_params,
1859 const RequestNavigationParams& request_params,
1860 bool has_stale_copy_in_cache,
1861 int error_code) {
1862 // Get back to a clean state, in case a new navigation started without
1863 // completing a RFH swap or unload handler.
1864 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1866 Send(new FrameMsg_FailedNavigation(routing_id_, common_params, request_params,
1867 has_stale_copy_in_cache, error_code));
1869 // An error page is expected to commit, hence why is_loading_ is set to true.
1870 is_loading_ = true;
1871 frame_tree_node_->ResetNavigationRequest(true);
1874 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1875 if (service_registry_.get())
1876 return;
1878 service_registry_.reset(new ServiceRegistryImpl());
1879 if (!GetProcess()->GetServiceRegistry())
1880 return;
1882 RegisterMojoServices();
1883 RenderFrameSetupPtr setup;
1884 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(
1885 mojo::GetProxy(&setup));
1887 mojo::ServiceProviderPtr exposed_services;
1888 service_registry_->Bind(GetProxy(&exposed_services));
1890 mojo::ServiceProviderPtr services;
1891 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1892 exposed_services.Pass());
1893 service_registry_->BindRemoteServiceProvider(services.Pass());
1895 #if defined(OS_ANDROID)
1896 service_registry_android_.reset(
1897 new ServiceRegistryAndroid(service_registry_.get()));
1898 ServiceRegistrarAndroid::RegisterFrameHostServices(
1899 service_registry_android_.get());
1900 #endif
1903 void RenderFrameHostImpl::InvalidateMojoConnection() {
1904 #if defined(OS_ANDROID)
1905 // The Android-specific service registry has a reference to
1906 // |service_registry_| and thus must be torn down first.
1907 service_registry_android_.reset();
1908 #endif
1910 service_registry_.reset();
1912 // Disconnect with ImageDownloader Mojo service in RenderFrame.
1913 mojo_image_downloader_.reset();
1916 bool RenderFrameHostImpl::IsFocused() {
1917 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1918 // returning nullptr in some cases. See https://crbug.com/455245.
1919 return RenderWidgetHostImpl::From(
1920 GetView()->GetRenderWidgetHost())->is_focused() &&
1921 frame_tree_->GetFocusedFrame() &&
1922 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1923 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1926 const image_downloader::ImageDownloaderPtr&
1927 RenderFrameHostImpl::GetMojoImageDownloader() {
1928 if (!mojo_image_downloader_.get()) {
1929 GetServiceRegistry()->ConnectToRemoteService(
1930 mojo::GetProxy(&mojo_image_downloader_));
1932 return mojo_image_downloader_;
1935 void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility(
1936 const std::map<int32, int>& node_to_frame_routing_id_map) {
1937 for (const auto& iter : node_to_frame_routing_id_map) {
1938 // This is the id of the accessibility node that has a child frame.
1939 int32 node_id = iter.first;
1940 // The routing id from either a RenderFrame or a RenderFrameProxy.
1941 int frame_routing_id = iter.second;
1943 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1944 FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID(
1945 GetProcess()->GetID(), frame_routing_id);
1947 if (child_frame_tree_node) {
1948 FrameAccessibility::GetInstance()->AddChildFrame(
1949 this, node_id, child_frame_tree_node->frame_tree_node_id());
1954 void RenderFrameHostImpl::UpdateGuestFrameAccessibility(
1955 const std::map<int32, int>& node_to_browser_plugin_instance_id_map) {
1956 for (const auto& iter : node_to_browser_plugin_instance_id_map) {
1957 // This is the id of the accessibility node that hosts a plugin.
1958 int32 node_id = iter.first;
1959 // The id of the browser plugin.
1960 int browser_plugin_instance_id = iter.second;
1961 FrameAccessibility::GetInstance()->AddGuestWebContents(
1962 this, node_id, browser_plugin_instance_id);
1966 bool RenderFrameHostImpl::IsSameSiteInstance(
1967 RenderFrameHostImpl* other_render_frame_host) {
1968 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1969 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1970 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1971 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1974 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1975 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1978 void RenderFrameHostImpl::RequestAXTreeSnapshot(
1979 AXTreeSnapshotCallback callback) {
1980 static int next_id = 1;
1981 int callback_id = next_id++;
1982 Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
1983 ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
1986 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1987 const base::Callback<void(ui::AXEvent, int)>& callback) {
1988 accessibility_testing_callback_ = callback;
1991 void RenderFrameHostImpl::SetTextTrackSettings(
1992 const FrameMsg_TextTrackSettings_Params& params) {
1993 DCHECK(!GetParent());
1994 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
1997 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1998 return ax_tree_for_testing_.get();
2001 BrowserAccessibilityManager*
2002 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
2003 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2004 render_view_host_->GetView());
2005 if (view &&
2006 !browser_accessibility_manager_ &&
2007 !no_create_browser_accessibility_manager_for_testing_) {
2008 browser_accessibility_manager_.reset(
2009 view->CreateBrowserAccessibilityManager(this));
2010 if (browser_accessibility_manager_)
2011 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
2012 else
2013 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
2015 return browser_accessibility_manager_.get();
2018 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
2019 int request_id) {
2020 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
2021 if (accessibility_mode & AccessibilityModeFlagPlatform) {
2022 BrowserAccessibilityManager* manager =
2023 GetOrCreateBrowserAccessibilityManager();
2024 if (manager)
2025 manager->ActivateFindInPageResult(request_id);
2029 void RenderFrameHostImpl::InsertVisualStateCallback(
2030 const VisualStateCallback& callback) {
2031 static uint64 next_id = 1;
2032 uint64 key = next_id++;
2033 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
2034 visual_state_callbacks_.insert(std::make_pair(key, callback));
2037 bool RenderFrameHostImpl::IsRenderFrameLive() {
2038 bool is_live = GetProcess()->HasConnection() && render_frame_created_;
2040 // Sanity check: the RenderView should always be live if the RenderFrame is.
2041 DCHECK_IMPLIES(is_live, render_view_host_->IsRenderViewLive());
2043 return is_live;
2046 #if defined(OS_WIN)
2048 void RenderFrameHostImpl::SetParentNativeViewAccessible(
2049 gfx::NativeViewAccessible accessible_parent) {
2050 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2051 render_view_host_->GetView());
2052 if (view)
2053 view->SetParentNativeViewAccessible(accessible_parent);
2056 gfx::NativeViewAccessible
2057 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
2058 return delegate_->GetParentNativeViewAccessible();
2061 #elif defined(OS_MACOSX)
2063 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
2064 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
2067 void RenderFrameHostImpl::DidCancelPopupMenu() {
2068 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
2071 #elif defined(OS_ANDROID)
2073 void RenderFrameHostImpl::DidSelectPopupMenuItems(
2074 const std::vector<int>& selected_indices) {
2075 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
2078 void RenderFrameHostImpl::DidCancelPopupMenu() {
2079 Send(new FrameMsg_SelectPopupMenuItems(
2080 routing_id_, true, std::vector<int>()));
2083 #endif
2085 void RenderFrameHostImpl::SetNavigationsSuspended(
2086 bool suspend,
2087 const base::TimeTicks& proceed_time) {
2088 // This should only be called to toggle the state.
2089 DCHECK(navigations_suspended_ != suspend);
2091 navigations_suspended_ = suspend;
2092 if (navigations_suspended_) {
2093 TRACE_EVENT_ASYNC_BEGIN0("navigation",
2094 "RenderFrameHostImpl navigation suspended", this);
2095 } else {
2096 TRACE_EVENT_ASYNC_END0("navigation",
2097 "RenderFrameHostImpl navigation suspended", this);
2100 if (!suspend && suspended_nav_params_) {
2101 // There's navigation message params waiting to be sent. Now that we're not
2102 // suspended anymore, resume navigation by sending them. If we were swapped
2103 // out, we should also stop filtering out the IPC messages now.
2104 SetState(RenderFrameHostImpl::STATE_DEFAULT);
2106 DCHECK(!proceed_time.is_null());
2107 suspended_nav_params_->request_params.browser_navigation_start =
2108 proceed_time;
2109 Send(new FrameMsg_Navigate(routing_id_,
2110 suspended_nav_params_->common_params,
2111 suspended_nav_params_->start_params,
2112 suspended_nav_params_->request_params));
2113 suspended_nav_params_.reset();
2117 void RenderFrameHostImpl::CancelSuspendedNavigations() {
2118 // Clear any state if a pending navigation is canceled or preempted.
2119 if (suspended_nav_params_)
2120 suspended_nav_params_.reset();
2122 TRACE_EVENT_ASYNC_END0("navigation",
2123 "RenderFrameHostImpl navigation suspended", this);
2124 navigations_suspended_ = false;
2127 void RenderFrameHostImpl::DidUseGeolocationPermission() {
2128 PermissionManager* permission_manager =
2129 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
2130 if (!permission_manager)
2131 return;
2133 permission_manager->RegisterPermissionUsage(
2134 PermissionType::GEOLOCATION,
2135 GetLastCommittedURL().GetOrigin(),
2136 frame_tree_node()->frame_tree()->GetMainFrame()
2137 ->GetLastCommittedURL().GetOrigin());
2140 void RenderFrameHostImpl::UpdatePermissionsForNavigation(
2141 const CommonNavigationParams& common_params,
2142 const RequestNavigationParams& request_params) {
2143 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
2144 // so do not grant them the ability to request additional URLs.
2145 if (!GetProcess()->IsForGuestsOnly()) {
2146 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2147 GetProcess()->GetID(), common_params.url);
2148 if (common_params.url.SchemeIs(url::kDataScheme) &&
2149 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
2150 // If 'data:' is used, and we have a 'file:' base url, grant access to
2151 // local files.
2152 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2153 GetProcess()->GetID(), common_params.base_url_for_data_url);
2157 // We may be returning to an existing NavigationEntry that had been granted
2158 // file access. If this is a different process, we will need to grant the
2159 // access again. The files listed in the page state are validated when they
2160 // are received from the renderer to prevent abuse.
2161 if (request_params.page_state.IsValid()) {
2162 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
2166 bool RenderFrameHostImpl::CanExecuteJavaScript() {
2167 return g_allow_injecting_javascript ||
2168 !frame_tree_node_->current_url().is_valid() ||
2169 frame_tree_node_->current_url().SchemeIs(kChromeDevToolsScheme) ||
2170 ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2171 GetProcess()->GetID()) ||
2172 // It's possible to load about:blank in a Web UI renderer.
2173 // See http://crbug.com/42547
2174 (frame_tree_node_->current_url().spec() == url::kAboutBlankURL) ||
2175 // InterstitialPageImpl should be the only case matching this.
2176 (delegate_->GetAsWebContents() == nullptr);
2179 } // namespace content