Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blob57ba8e25e3fd7eb743d7353b2d3916aae34a1f5e
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_tree.h"
23 #include "content/browser/frame_host/frame_tree_node.h"
24 #include "content/browser/frame_host/navigation_request.h"
25 #include "content/browser/frame_host/navigator.h"
26 #include "content/browser/frame_host/navigator_impl.h"
27 #include "content/browser/frame_host/render_frame_host_delegate.h"
28 #include "content/browser/frame_host/render_frame_proxy_host.h"
29 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
30 #include "content/browser/geolocation/geolocation_service_context.h"
31 #include "content/browser/permissions/permission_service_context.h"
32 #include "content/browser/permissions/permission_service_impl.h"
33 #include "content/browser/presentation/presentation_service_impl.h"
34 #include "content/browser/renderer_host/input/input_router.h"
35 #include "content/browser/renderer_host/input/timeout_monitor.h"
36 #include "content/browser/renderer_host/render_process_host_impl.h"
37 #include "content/browser/renderer_host/render_view_host_delegate.h"
38 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
39 #include "content/browser/renderer_host/render_view_host_impl.h"
40 #include "content/browser/renderer_host/render_widget_host_impl.h"
41 #include "content/browser/renderer_host/render_widget_host_view_base.h"
42 #include "content/browser/transition_request_manager.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/swapped_out_messages.h"
50 #include "content/public/browser/ax_event_notification_details.h"
51 #include "content/public/browser/browser_accessibility_state.h"
52 #include "content/public/browser/browser_context.h"
53 #include "content/public/browser/browser_plugin_guest_manager.h"
54 #include "content/public/browser/browser_thread.h"
55 #include "content/public/browser/content_browser_client.h"
56 #include "content/public/browser/permission_manager.h"
57 #include "content/public/browser/permission_type.h"
58 #include "content/public/browser/render_process_host.h"
59 #include "content/public/browser/render_widget_host_view.h"
60 #include "content/public/browser/stream_handle.h"
61 #include "content/public/browser/user_metrics.h"
62 #include "content/public/common/content_constants.h"
63 #include "content/public/common/content_switches.h"
64 #include "content/public/common/url_constants.h"
65 #include "content/public/common/url_utils.h"
66 #include "ui/accessibility/ax_tree.h"
67 #include "ui/accessibility/ax_tree_update.h"
68 #include "url/gurl.h"
70 #if defined(OS_ANDROID)
71 #include "content/browser/mojo/service_registrar_android.h"
72 #endif
74 #if defined(OS_MACOSX)
75 #include "content/browser/frame_host/popup_menu_helper_mac.h"
76 #endif
78 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
79 #include "media/mojo/interfaces/media_renderer.mojom.h"
80 #include "media/mojo/services/mojo_renderer_service.h"
81 #endif
83 using base::TimeDelta;
85 namespace content {
87 namespace {
89 // The next value to use for the accessibility reset token.
90 int g_next_accessibility_reset_token = 1;
92 // The (process id, routing id) pair that identifies one RenderFrame.
93 typedef std::pair<int32, int32> RenderFrameHostID;
94 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
95 RoutingIDFrameMap;
96 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
97 LAZY_INSTANCE_INITIALIZER;
99 // Translate a WebKit text direction into a base::i18n one.
100 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
101 blink::WebTextDirection dir) {
102 switch (dir) {
103 case blink::WebTextDirectionLeftToRight:
104 return base::i18n::LEFT_TO_RIGHT;
105 case blink::WebTextDirectionRightToLeft:
106 return base::i18n::RIGHT_TO_LEFT;
107 default:
108 NOTREACHED();
109 return base::i18n::UNKNOWN_DIRECTION;
113 } // namespace
115 // static
116 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
117 return rfh_state == STATE_DEFAULT;
120 // static
121 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
122 int render_frame_id) {
123 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
126 // static
127 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
128 int routing_id) {
129 DCHECK_CURRENTLY_ON(BrowserThread::UI);
130 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
131 RoutingIDFrameMap::iterator it = frames->find(
132 RenderFrameHostID(process_id, routing_id));
133 return it == frames->end() ? NULL : it->second;
136 RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
137 RenderViewHostImpl* render_view_host,
138 RenderFrameHostDelegate* delegate,
139 RenderWidgetHostDelegate* rwh_delegate,
140 FrameTree* frame_tree,
141 FrameTreeNode* frame_tree_node,
142 int routing_id,
143 int flags)
144 : render_view_host_(render_view_host),
145 delegate_(delegate),
146 site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
147 process_(site_instance->GetProcess()),
148 cross_process_frame_connector_(NULL),
149 render_frame_proxy_host_(NULL),
150 frame_tree_(frame_tree),
151 frame_tree_node_(frame_tree_node),
152 routing_id_(routing_id),
153 render_frame_created_(false),
154 navigations_suspended_(false),
155 is_waiting_for_beforeunload_ack_(false),
156 unload_ack_is_for_navigation_(false),
157 is_loading_(false),
158 pending_commit_(false),
159 accessibility_reset_token_(0),
160 accessibility_reset_count_(0),
161 no_create_browser_accessibility_manager_for_testing_(false),
162 weak_ptr_factory_(this) {
163 bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
164 bool hidden = !!(flags & CREATE_RF_HIDDEN);
165 frame_tree_->RegisterRenderFrameHost(this);
166 GetProcess()->AddRoute(routing_id_, this);
167 g_routing_id_frame_map.Get().insert(std::make_pair(
168 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
169 this));
171 if (is_swapped_out) {
172 rfh_state_ = STATE_SWAPPED_OUT;
173 } else {
174 rfh_state_ = STATE_DEFAULT;
175 GetSiteInstance()->increment_active_frame_count();
178 SetUpMojoIfNeeded();
179 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
180 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
182 if (flags & CREATE_RF_NEEDS_RENDER_WIDGET_HOST) {
183 render_widget_host_.reset(new RenderWidgetHostImpl(
184 rwh_delegate, GetProcess(), MSG_ROUTING_NONE, hidden));
185 render_widget_host_->set_owned_by_render_frame_host(true);
189 RenderFrameHostImpl::~RenderFrameHostImpl() {
190 GetProcess()->RemoveRoute(routing_id_);
191 g_routing_id_frame_map.Get().erase(
192 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
194 if (delegate_ && render_frame_created_)
195 delegate_->RenderFrameDeleted(this);
197 FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this);
199 // If this was swapped out, it already decremented the active frame count of
200 // the SiteInstance it belongs to.
201 if (IsRFHStateActive(rfh_state_))
202 GetSiteInstance()->decrement_active_frame_count();
204 // Notify the FrameTree that this RFH is going away, allowing it to shut down
205 // the corresponding RenderViewHost if it is no longer needed.
206 frame_tree_->UnregisterRenderFrameHost(this);
208 // NULL out the swapout timer; in crash dumps this member will be null only if
209 // the dtor has run.
210 swapout_event_monitor_timeout_.reset();
212 for (const auto& iter: visual_state_callbacks_) {
213 iter.second.Run(false);
216 if (render_widget_host_)
217 render_widget_host_->Cleanup();
220 int RenderFrameHostImpl::GetRoutingID() {
221 return routing_id_;
224 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
225 return site_instance_.get();
228 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
229 return process_;
232 RenderFrameHost* RenderFrameHostImpl::GetParent() {
233 FrameTreeNode* parent_node = frame_tree_node_->parent();
234 if (!parent_node)
235 return NULL;
236 return parent_node->current_frame_host();
239 const std::string& RenderFrameHostImpl::GetFrameName() {
240 return frame_tree_node_->frame_name();
243 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
244 FrameTreeNode* parent_node = frame_tree_node_->parent();
245 if (!parent_node)
246 return false;
247 return GetSiteInstance() !=
248 parent_node->current_frame_host()->GetSiteInstance();
251 GURL RenderFrameHostImpl::GetLastCommittedURL() {
252 return frame_tree_node_->current_url();
255 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
256 RenderWidgetHostView* view = render_view_host_->GetView();
257 if (!view)
258 return NULL;
259 return view->GetNativeView();
262 void RenderFrameHostImpl::ExecuteJavaScript(
263 const base::string16& javascript) {
264 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
265 javascript,
266 0, false));
269 void RenderFrameHostImpl::ExecuteJavaScript(
270 const base::string16& javascript,
271 const JavaScriptResultCallback& callback) {
272 static int next_id = 1;
273 int key = next_id++;
274 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
275 javascript,
276 key, true));
277 javascript_callbacks_.insert(std::make_pair(key, callback));
280 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
281 const base::string16& javascript) {
282 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
283 javascript,
284 0, false));
287 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
288 return render_view_host_;
291 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
292 return service_registry_.get();
295 blink::WebPageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
296 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
297 // returning nullptr in some cases. See https://crbug.com/455245.
298 blink::WebPageVisibilityState visibility_state =
299 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())->is_hidden()
300 ? blink::WebPageVisibilityStateHidden
301 : blink::WebPageVisibilityStateVisible;
302 GetContentClient()->browser()->OverridePageVisibilityState(this,
303 &visibility_state);
304 return visibility_state;
307 bool RenderFrameHostImpl::Send(IPC::Message* message) {
308 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
309 return render_view_host_->input_router()->SendInput(
310 make_scoped_ptr(message));
313 return GetProcess()->Send(message);
316 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
317 // Filter out most IPC messages if this frame is swapped out.
318 // We still want to handle certain ACKs to keep our state consistent.
319 if (is_swapped_out()) {
320 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
321 // If this is a synchronous message and we decided not to handle it,
322 // we must send an error reply, or else the renderer will be stuck
323 // and won't respond to future requests.
324 if (msg.is_sync()) {
325 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
326 reply->set_reply_error();
327 Send(reply);
329 // Don't continue looking for someone to handle it.
330 return true;
334 if (delegate_->OnMessageReceived(this, msg))
335 return true;
337 RenderFrameProxyHost* proxy =
338 frame_tree_node_->render_manager()->GetProxyToParent();
339 if (proxy && proxy->cross_process_frame_connector() &&
340 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
341 return true;
343 bool handled = true;
344 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
345 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
346 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
347 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
348 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
349 OnDidStartProvisionalLoadForFrame)
350 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
351 OnDidFailProvisionalLoadWithError)
352 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
353 OnDidFailLoadWithError)
354 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
355 OnDidCommitProvisionalLoad(msg))
356 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation)
357 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
358 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
359 OnDocumentOnLoadCompleted)
360 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
361 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
362 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
363 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
364 OnJavaScriptExecuteResponse)
365 IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
366 OnVisualStateResponse)
367 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
368 OnRunJavaScriptMessage)
369 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
370 OnRunBeforeUnloadConfirm)
371 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
372 OnDidAccessInitialDocument)
373 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
374 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeName, OnDidChangeName)
375 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
376 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeSandboxFlags,
377 OnDidChangeSandboxFlags)
378 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
379 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
380 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
381 OnBeginNavigation)
382 IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
383 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
384 OnTextSurroundingSelectionResponse)
385 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
386 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
387 OnAccessibilityLocationChanges)
388 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
389 OnAccessibilityFindInPageResult)
390 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
391 OnAccessibilitySnapshotResponse)
392 IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
393 // The following message is synthetic and doesn't come from RenderFrame, but
394 // from RenderProcessHost.
395 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
396 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
397 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
398 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
399 OnDidChangeLoadProgress)
400 #if defined(OS_MACOSX) || defined(OS_ANDROID)
401 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
402 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
403 #endif
404 IPC_END_MESSAGE_MAP()
406 // No further actions here, since we may have been deleted.
407 return handled;
410 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
411 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
414 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
415 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
418 void RenderFrameHostImpl::AccessibilityShowMenu(
419 const gfx::Point& global_point) {
420 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
421 render_view_host_->GetView());
422 if (view)
423 view->AccessibilityShowMenu(global_point);
426 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
427 int acc_obj_id, const gfx::Rect& subfocus) {
428 Send(new AccessibilityMsg_ScrollToMakeVisible(
429 routing_id_, acc_obj_id, subfocus));
432 void RenderFrameHostImpl::AccessibilityScrollToPoint(
433 int acc_obj_id, const gfx::Point& point) {
434 Send(new AccessibilityMsg_ScrollToPoint(
435 routing_id_, acc_obj_id, point));
438 void RenderFrameHostImpl::AccessibilitySetTextSelection(
439 int object_id, int start_offset, int end_offset) {
440 Send(new AccessibilityMsg_SetTextSelection(
441 routing_id_, object_id, start_offset, end_offset));
444 void RenderFrameHostImpl::AccessibilitySetValue(
445 int object_id, const base::string16& value) {
446 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
449 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
450 RenderWidgetHostView* view = render_view_host_->GetView();
451 if (view)
452 return view->HasFocus();
453 return false;
456 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
457 RenderWidgetHostView* view = render_view_host_->GetView();
458 if (view)
459 return view->GetViewBounds();
460 return gfx::Rect();
463 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
464 const gfx::Rect& bounds) const {
465 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
466 render_view_host_->GetView());
467 if (view)
468 return view->AccessibilityOriginInScreen(bounds);
469 return gfx::Point();
472 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
473 Send(new AccessibilityMsg_HitTest(routing_id_, point));
476 void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) {
477 Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id));
480 void RenderFrameHostImpl::AccessibilityFatalError() {
481 browser_accessibility_manager_.reset(NULL);
482 if (accessibility_reset_token_)
483 return;
485 accessibility_reset_count_++;
486 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
487 Send(new AccessibilityMsg_FatalError(routing_id_));
488 } else {
489 accessibility_reset_token_ = g_next_accessibility_reset_token++;
490 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
491 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
495 gfx::AcceleratedWidget
496 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
497 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
498 render_view_host_->GetView());
499 if (view)
500 return view->AccessibilityGetAcceleratedWidget();
501 return gfx::kNullAcceleratedWidget;
504 gfx::NativeViewAccessible
505 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
506 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
507 render_view_host_->GetView());
508 if (view)
509 return view->AccessibilityGetNativeViewAccessible();
510 return NULL;
513 BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame(
514 int accessibility_node_id) {
515 RenderFrameHostImpl* child_frame =
516 FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id);
517 if (!child_frame || IsSameSiteInstance(child_frame))
518 return nullptr;
520 return child_frame->GetOrCreateBrowserAccessibilityManager();
523 void RenderFrameHostImpl::AccessibilityGetAllChildFrames(
524 std::vector<BrowserAccessibilityManager*>* child_frames) {
525 std::vector<RenderFrameHostImpl*> child_frame_hosts;
526 FrameAccessibility::GetInstance()->GetAllChildFrames(
527 this, &child_frame_hosts);
528 for (size_t i = 0; i < child_frame_hosts.size(); ++i) {
529 RenderFrameHostImpl* child_frame_host = child_frame_hosts[i];
530 if (!child_frame_host || IsSameSiteInstance(child_frame_host))
531 continue;
533 BrowserAccessibilityManager* manager =
534 child_frame_host->GetOrCreateBrowserAccessibilityManager();
535 if (manager)
536 child_frames->push_back(manager);
540 BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() {
541 RenderFrameHostImpl* parent_frame = NULL;
542 int parent_node_id = 0;
543 if (!FrameAccessibility::GetInstance()->GetParent(
544 this, &parent_frame, &parent_node_id)) {
545 return NULL;
548 // As a sanity check, make sure the frame we're going to return belongs
549 // to the same BrowserContext.
550 if (GetSiteInstance()->GetBrowserContext() !=
551 parent_frame->GetSiteInstance()->GetBrowserContext()) {
552 NOTREACHED();
553 return NULL;
556 BrowserAccessibilityManager* manager =
557 parent_frame->browser_accessibility_manager();
558 if (!manager)
559 return NULL;
561 return manager->GetFromID(parent_node_id);
564 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id,
565 int proxy_routing_id) {
566 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
567 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
569 // The process may (if we're sharing a process with another host that already
570 // initialized it) or may not (we have our own process or the old process
571 // crashed) have been initialized. Calling Init multiple times will be
572 // ignored, so this is safe.
573 if (!GetProcess()->Init())
574 return false;
576 DCHECK(GetProcess()->HasConnection());
578 FrameMsg_NewFrame_WidgetParams widget_params;
579 if (render_widget_host_) {
580 widget_params.routing_id = render_widget_host_->GetRoutingID();
581 widget_params.surface_id = render_widget_host_->surface_id();
582 widget_params.hidden = render_widget_host_->is_hidden();
583 } else {
584 // MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
585 // the renderer process.
586 widget_params.routing_id = MSG_ROUTING_NONE;
587 widget_params.surface_id = 0;
588 widget_params.hidden = true;
591 Send(new FrameMsg_NewFrame(routing_id_, parent_routing_id, proxy_routing_id,
592 frame_tree_node()->current_replication_state(),
593 widget_params));
595 // The RenderWidgetHost takes ownership of its view. It is tied to the
596 // lifetime of the current RenderProcessHost for this RenderFrameHost.
597 if (render_widget_host_) {
598 RenderWidgetHostView* rwhv =
599 new RenderWidgetHostViewChildFrame(render_widget_host_.get());
600 rwhv->Hide();
603 if (proxy_routing_id != MSG_ROUTING_NONE) {
604 RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
605 GetProcess()->GetID(), proxy_routing_id);
606 // We have also created a RenderFrameProxy in FrameMsg_NewFrame above, so
607 // remember that.
608 proxy->set_render_frame_proxy_created(true);
611 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
612 // this path is only used for out-of-process iframes. Main frame RenderFrames
613 // are created with their RenderView, and same-site iframes are created at the
614 // time of OnCreateChildFrame.
615 SetRenderFrameCreated(true);
617 return true;
620 bool RenderFrameHostImpl::IsRenderFrameLive() {
621 // RenderFrames are created for main frames at the same time as RenderViews,
622 // so we rely on IsRenderViewLive. For subframes, we keep track of each
623 // RenderFrame individually with render_frame_created_.
624 bool is_live = !GetParent() ?
625 render_view_host_->IsRenderViewLive() :
626 GetProcess()->HasConnection() && render_frame_created_;
628 // Sanity check: the RenderView should always be live if the RenderFrame is.
629 DCHECK(!is_live || render_view_host_->IsRenderViewLive());
631 return is_live;
634 void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
635 bool was_created = render_frame_created_;
636 render_frame_created_ = created;
638 // If the current status is different than the new status, the delegate
639 // needs to be notified.
640 if (delegate_ && (created != was_created)) {
641 if (created)
642 delegate_->RenderFrameCreated(this);
643 else
644 delegate_->RenderFrameDeleted(this);
647 if (created && render_widget_host_)
648 render_widget_host_->InitForFrame();
651 void RenderFrameHostImpl::Init() {
652 GetProcess()->ResumeRequestsForView(routing_id_);
655 void RenderFrameHostImpl::OnAddMessageToConsole(
656 int32 level,
657 const base::string16& message,
658 int32 line_no,
659 const base::string16& source_id) {
660 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
661 return;
663 // Pass through log level only on WebUI pages to limit console spew.
664 const bool is_web_ui =
665 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL());
666 const int32 resolved_level = is_web_ui ? level : ::logging::LOG_INFO;
668 // LogMessages can be persisted so this shouldn't be logged in incognito mode.
669 // This rule is not applied to WebUI pages, because source code of WebUI is a
670 // part of Chrome source code, and we want to treat messages from WebUI the
671 // same way as we treat log messages from native code.
672 if (::logging::GetMinLogLevel() <= resolved_level &&
673 (is_web_ui ||
674 !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord())) {
675 logging::LogMessage("CONSOLE", line_no, resolved_level).stream()
676 << "\"" << message << "\", source: " << source_id << " (" << line_no
677 << ")";
681 void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id,
682 const std::string& frame_name,
683 SandboxFlags sandbox_flags) {
684 // It is possible that while a new RenderFrameHost was committed, the
685 // RenderFrame corresponding to this host sent an IPC message to create a
686 // frame and it is delivered after this host is swapped out.
687 // Ignore such messages, as we know this RenderFrameHost is going away.
688 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
689 return;
691 RenderFrameHostImpl* new_frame = frame_tree_->AddFrame(
692 frame_tree_node_, GetProcess()->GetID(), new_routing_id, frame_name);
693 if (!new_frame)
694 return;
696 // Set sandbox flags for the new frame. The flags are committed immediately,
697 // since they should apply to the initial empty document in the frame.
698 new_frame->frame_tree_node()->set_sandbox_flags(sandbox_flags);
699 new_frame->frame_tree_node()->CommitPendingSandboxFlags();
701 // We know that the RenderFrame has been created in this case, immediately
702 // after the CreateChildFrame IPC was sent.
703 new_frame->SetRenderFrameCreated(true);
706 void RenderFrameHostImpl::OnDetach() {
707 frame_tree_->RemoveFrame(frame_tree_node_);
710 void RenderFrameHostImpl::OnFrameFocused() {
711 frame_tree_->SetFocusedFrame(frame_tree_node_);
714 void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
715 OpenURL(params, GetSiteInstance());
718 void RenderFrameHostImpl::OnDocumentOnLoadCompleted(
719 FrameMsg_UILoadMetricsReportType::Value report_type,
720 base::TimeTicks ui_timestamp) {
721 if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
722 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Link",
723 base::TimeTicks::Now() - ui_timestamp,
724 base::TimeDelta::FromMilliseconds(10),
725 base::TimeDelta::FromMinutes(10), 100);
726 } else if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
727 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Intent",
728 base::TimeTicks::Now() - ui_timestamp,
729 base::TimeDelta::FromMilliseconds(10),
730 base::TimeDelta::FromMinutes(10), 100);
732 // This message is only sent for top-level frames. TODO(avi): when frame tree
733 // mirroring works correctly, add a check here to enforce it.
734 delegate_->DocumentOnLoadCompleted(this);
737 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(
738 const GURL& url,
739 bool is_transition_navigation) {
740 frame_tree_node_->navigator()->DidStartProvisionalLoad(
741 this, url, is_transition_navigation);
744 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
745 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
746 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
749 void RenderFrameHostImpl::OnDidFailLoadWithError(
750 const GURL& url,
751 int error_code,
752 const base::string16& error_description) {
753 GURL validated_url(url);
754 GetProcess()->FilterURL(false, &validated_url);
756 frame_tree_node_->navigator()->DidFailLoadWithError(
757 this, validated_url, error_code, error_description);
760 // Called when the renderer navigates. For every frame loaded, we'll get this
761 // notification containing parameters identifying the navigation.
763 // Subframes are identified by the page transition type. For subframes loaded
764 // as part of a wider page load, the page_id will be the same as for the top
765 // level frame. If the user explicitly requests a subframe navigation, we will
766 // get a new page_id because we need to create a new navigation entry for that
767 // action.
768 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
769 // Read the parameters out of the IPC message directly to avoid making another
770 // copy when we filter the URLs.
771 PickleIterator iter(msg);
772 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
773 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
774 Read(&msg, &iter, &validated_params))
775 return;
776 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
777 "url", validated_params.url.possibly_invalid_spec());
779 // If we're waiting for a cross-site beforeunload ack from this renderer and
780 // we receive a Navigate message from the main frame, then the renderer was
781 // navigating already and sent it before hearing the FrameMsg_Stop message.
782 // We do not want to cancel the pending navigation in this case, since the
783 // old page will soon be stopped. Instead, treat this as a beforeunload ack
784 // to allow the pending navigation to continue.
785 if (is_waiting_for_beforeunload_ack_ &&
786 unload_ack_is_for_navigation_ &&
787 ui::PageTransitionIsMainFrame(validated_params.transition)) {
788 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
789 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
790 return;
793 // If we're waiting for an unload ack from this renderer and we receive a
794 // Navigate message, then the renderer was navigating before it received the
795 // unload request. It will either respond to the unload request soon or our
796 // timer will expire. Either way, we should ignore this message, because we
797 // have already committed to closing this renderer.
798 if (IsWaitingForUnloadACK())
799 return;
801 if (validated_params.report_type ==
802 FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
803 UMA_HISTOGRAM_CUSTOM_TIMES(
804 "Navigation.UI_OnCommitProvisionalLoad.Link",
805 base::TimeTicks::Now() - validated_params.ui_timestamp,
806 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
807 100);
808 } else if (validated_params.report_type ==
809 FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
810 UMA_HISTOGRAM_CUSTOM_TIMES(
811 "Navigation.UI_OnCommitProvisionalLoad.Intent",
812 base::TimeTicks::Now() - validated_params.ui_timestamp,
813 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
814 100);
817 RenderProcessHost* process = GetProcess();
819 // Attempts to commit certain off-limits URL should be caught more strictly
820 // than our FilterURL checks below. If a renderer violates this policy, it
821 // should be killed.
822 if (!CanCommitURL(validated_params.url)) {
823 VLOG(1) << "Blocked URL " << validated_params.url.spec();
824 validated_params.url = GURL(url::kAboutBlankURL);
825 // Kills the process.
826 bad_message::ReceivedBadMessage(process,
827 bad_message::RFH_CAN_COMMIT_URL_BLOCKED);
830 // Without this check, an evil renderer can trick the browser into creating
831 // a navigation entry for a banned URL. If the user clicks the back button
832 // followed by the forward button (or clicks reload, or round-trips through
833 // session restore, etc), we'll think that the browser commanded the
834 // renderer to load the URL and grant the renderer the privileges to request
835 // the URL. To prevent this attack, we block the renderer from inserting
836 // banned URLs into the navigation controller in the first place.
837 process->FilterURL(false, &validated_params.url);
838 process->FilterURL(true, &validated_params.referrer.url);
839 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
840 it != validated_params.redirects.end(); ++it) {
841 process->FilterURL(false, &(*it));
843 process->FilterURL(true, &validated_params.searchable_form_url);
845 // Without this check, the renderer can trick the browser into using
846 // filenames it can't access in a future session restore.
847 if (!render_view_host_->CanAccessFilesOfPageState(
848 validated_params.page_state)) {
849 bad_message::ReceivedBadMessage(
850 GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
851 return;
854 accessibility_reset_count_ = 0;
855 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
857 // PlzNavigate
858 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
859 switches::kEnableBrowserSideNavigation)) {
860 pending_commit_ = false;
864 void RenderFrameHostImpl::OnDidDropNavigation() {
865 // At the end of Navigate(), the FrameTreeNode's DidStartLoading is called to
866 // force the spinner to start, even if the renderer didn't yet begin the load.
867 // If it turns out that the renderer dropped the navigation, the spinner needs
868 // to be turned off.
869 frame_tree_node_->DidStopLoading();
872 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
873 if (render_widget_host_)
874 return render_widget_host_.get();
876 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
877 // we can remove this fallback. Currently it is only used for the main
878 // frame.
879 if (!GetParent())
880 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
882 return nullptr;
885 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
886 RenderFrameHostImpl* frame = this;
887 while (frame) {
888 if (frame->render_widget_host_)
889 return frame->render_widget_host_->GetView();
890 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
893 return render_view_host_->GetView();
896 int RenderFrameHostImpl::GetEnabledBindings() {
897 return render_view_host_->GetEnabledBindings();
900 void RenderFrameHostImpl::OnCrossSiteResponse(
901 const GlobalRequestID& global_request_id,
902 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
903 const std::vector<GURL>& transfer_url_chain,
904 const Referrer& referrer,
905 ui::PageTransition page_transition,
906 bool should_replace_current_entry) {
907 frame_tree_node_->render_manager()->OnCrossSiteResponse(
908 this, global_request_id, cross_site_transferring_request.Pass(),
909 transfer_url_chain, referrer, page_transition,
910 should_replace_current_entry);
913 void RenderFrameHostImpl::OnDeferredAfterResponseStarted(
914 const GlobalRequestID& global_request_id,
915 const TransitionLayerData& transition_data) {
916 frame_tree_node_->render_manager()->OnDeferredAfterResponseStarted(
917 global_request_id, this);
919 if (GetParent() || !delegate_->WillHandleDeferAfterResponseStarted())
920 frame_tree_node_->render_manager()->ResumeResponseDeferredAtStart();
921 else
922 delegate_->DidDeferAfterResponseStarted(transition_data);
925 void RenderFrameHostImpl::SwapOut(
926 RenderFrameProxyHost* proxy,
927 bool is_loading) {
928 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
929 // the operation and sends back an IPC message.
930 // The trace event may not end properly if the ACK times out. We expect this
931 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
932 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
934 // If this RenderFrameHost is not in the default state, it must have already
935 // gone through this, therefore just return.
936 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
937 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
938 return;
941 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
942 swapout_event_monitor_timeout_->Start(
943 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
945 // There may be no proxy if there are no active views in the process.
946 int proxy_routing_id = MSG_ROUTING_NONE;
947 FrameReplicationState replication_state;
948 if (proxy) {
949 set_render_frame_proxy_host(proxy);
950 proxy_routing_id = proxy->GetRoutingID();
951 replication_state = proxy->frame_tree_node()->current_replication_state();
954 if (IsRenderFrameLive()) {
955 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
956 replication_state));
959 if (!GetParent())
960 delegate_->SwappedOut(this);
963 void RenderFrameHostImpl::OnBeforeUnloadACK(
964 bool proceed,
965 const base::TimeTicks& renderer_before_unload_start_time,
966 const base::TimeTicks& renderer_before_unload_end_time) {
967 TRACE_EVENT_ASYNC_END0(
968 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
969 DCHECK(!GetParent());
970 // If this renderer navigated while the beforeunload request was in flight, we
971 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
972 // can ignore this message.
973 // However renderer might also be swapped out but we still want to proceed
974 // with navigation, otherwise it would block future navigations. This can
975 // happen when pending cross-site navigation is canceled by a second one just
976 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
977 // but second navigation is started from the beginning.
978 if (!is_waiting_for_beforeunload_ack_) {
979 return;
981 DCHECK(!send_before_unload_start_time_.is_null());
983 // Sets a default value for before_unload_end_time so that the browser
984 // survives a hacked renderer.
985 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
986 if (!renderer_before_unload_start_time.is_null() &&
987 !renderer_before_unload_end_time.is_null()) {
988 // When passing TimeTicks across process boundaries, we need to compensate
989 // for any skew between the processes. Here we are converting the
990 // renderer's notion of before_unload_end_time to TimeTicks in the browser
991 // process. See comments in inter_process_time_ticks_converter.h for more.
992 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
993 InterProcessTimeTicksConverter converter(
994 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
995 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
996 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
997 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
998 LocalTimeTicks browser_before_unload_end_time =
999 converter.ToLocalTimeTicks(
1000 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1001 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1003 // Collect UMA on the inter-process skew.
1004 bool is_skew_additive = false;
1005 if (converter.IsSkewAdditiveForMetrics()) {
1006 is_skew_additive = true;
1007 base::TimeDelta skew = converter.GetSkewForMetrics();
1008 if (skew >= base::TimeDelta()) {
1009 UMA_HISTOGRAM_TIMES(
1010 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
1011 } else {
1012 UMA_HISTOGRAM_TIMES(
1013 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
1016 UMA_HISTOGRAM_BOOLEAN(
1017 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
1018 is_skew_additive);
1020 base::TimeDelta on_before_unload_overhead_time =
1021 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1022 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1023 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1024 on_before_unload_overhead_time);
1026 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1027 renderer_before_unload_start_time, renderer_before_unload_end_time);
1029 // Resets beforeunload waiting state.
1030 is_waiting_for_beforeunload_ack_ = false;
1031 render_view_host_->decrement_in_flight_event_count();
1032 render_view_host_->StopHangMonitorTimeout();
1033 send_before_unload_start_time_ = base::TimeTicks();
1035 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1036 switches::kEnableBrowserSideNavigation)) {
1037 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1038 // Navigator.
1039 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1040 frame_tree_node_, proceed);
1041 } else {
1042 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1043 unload_ack_is_for_navigation_, proceed,
1044 before_unload_end_time);
1047 // If canceled, notify the delegate to cancel its pending navigation entry.
1048 if (!proceed)
1049 render_view_host_->GetDelegate()->DidCancelLoading();
1052 bool RenderFrameHostImpl::IsWaitingForBeforeUnloadACK() const {
1053 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1054 switches::kEnableBrowserSideNavigation)) {
1055 return is_waiting_for_beforeunload_ack_;
1057 return frame_tree_node_->navigator()->IsWaitingForBeforeUnloadACK(
1058 frame_tree_node_);
1061 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1062 return render_view_host_->is_waiting_for_close_ack_ ||
1063 rfh_state_ == STATE_PENDING_SWAP_OUT;
1066 void RenderFrameHostImpl::OnSwapOutACK() {
1067 OnSwappedOut();
1070 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1071 if (frame_tree_node_->IsMainFrame()) {
1072 // Keep the termination status so we can get at it later when we
1073 // need to know why it died.
1074 render_view_host_->render_view_termination_status_ =
1075 static_cast<base::TerminationStatus>(status);
1078 // Reset frame tree state associated with this process. This must happen
1079 // before RenderViewTerminated because observers expect the subframes of any
1080 // affected frames to be cleared first.
1081 // Note: When a RenderFrameHost is swapped out there is a different one
1082 // which is the current host. In this case, the FrameTreeNode state must
1083 // not be reset.
1084 if (!is_swapped_out())
1085 frame_tree_node_->ResetForNewProcess();
1087 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1088 // reset.
1089 SetRenderFrameCreated(false);
1090 InvalidateMojoConnection();
1092 // Execute any pending AX tree snapshot callbacks with an empty response,
1093 // since we're never going to get a response from this renderer.
1094 for (const auto& iter : ax_tree_snapshot_callbacks_)
1095 iter.second.Run(ui::AXTreeUpdate());
1096 ax_tree_snapshot_callbacks_.clear();
1098 if (frame_tree_node_->IsMainFrame()) {
1099 // RenderViewHost/RenderWidgetHost needs to reset some stuff.
1100 render_view_host_->RendererExited(
1101 render_view_host_->render_view_termination_status_, exit_code);
1103 render_view_host_->delegate_->RenderViewTerminated(
1104 render_view_host_, static_cast<base::TerminationStatus>(status),
1105 exit_code);
1108 // Note: don't add any more code at this point in the function because
1109 // |this| may be deleted. Any additional cleanup should happen before
1110 // the last block of code here.
1113 void RenderFrameHostImpl::OnSwappedOut() {
1114 // Ignore spurious swap out ack.
1115 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1116 return;
1118 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1119 swapout_event_monitor_timeout_->Stop();
1121 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1122 // We are now deleted.
1123 return;
1126 // If this RFH wasn't pending deletion, then it is now swapped out.
1127 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1130 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1131 // Validate the URLs in |params|. If the renderer can't request the URLs
1132 // directly, don't show them in the context menu.
1133 ContextMenuParams validated_params(params);
1134 RenderProcessHost* process = GetProcess();
1136 // We don't validate |unfiltered_link_url| so that this field can be used
1137 // when users want to copy the original link URL.
1138 process->FilterURL(true, &validated_params.link_url);
1139 process->FilterURL(true, &validated_params.src_url);
1140 process->FilterURL(false, &validated_params.page_url);
1141 process->FilterURL(true, &validated_params.frame_url);
1143 delegate_->ShowContextMenu(this, validated_params);
1146 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1147 int id, const base::ListValue& result) {
1148 const base::Value* result_value;
1149 if (!result.Get(0, &result_value)) {
1150 // Programming error or rogue renderer.
1151 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1152 return;
1155 std::map<int, JavaScriptResultCallback>::iterator it =
1156 javascript_callbacks_.find(id);
1157 if (it != javascript_callbacks_.end()) {
1158 it->second.Run(result_value);
1159 javascript_callbacks_.erase(it);
1160 } else {
1161 NOTREACHED() << "Received script response for unknown request";
1165 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1166 auto it = visual_state_callbacks_.find(id);
1167 if (it != visual_state_callbacks_.end()) {
1168 it->second.Run(true);
1169 visual_state_callbacks_.erase(it);
1170 } else {
1171 NOTREACHED() << "Received script response for unknown request";
1175 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1176 const base::string16& message,
1177 const base::string16& default_prompt,
1178 const GURL& frame_url,
1179 JavaScriptMessageType type,
1180 IPC::Message* reply_msg) {
1181 // While a JS message dialog is showing, tabs in the same process shouldn't
1182 // process input events.
1183 GetProcess()->SetIgnoreInputEvents(true);
1184 render_view_host_->StopHangMonitorTimeout();
1185 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1186 frame_url, type, reply_msg);
1189 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1190 const GURL& frame_url,
1191 const base::string16& message,
1192 bool is_reload,
1193 IPC::Message* reply_msg) {
1194 // While a JS beforeunload dialog is showing, tabs in the same process
1195 // shouldn't process input events.
1196 GetProcess()->SetIgnoreInputEvents(true);
1197 render_view_host_->StopHangMonitorTimeout();
1198 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1201 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1202 const base::string16& content,
1203 size_t start_offset,
1204 size_t end_offset) {
1205 render_view_host_->OnTextSurroundingSelectionResponse(
1206 content, start_offset, end_offset);
1209 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1210 delegate_->DidAccessInitialDocument();
1213 void RenderFrameHostImpl::OnDidDisownOpener() {
1214 // This message is only sent for top-level frames. TODO(avi): when frame tree
1215 // mirroring works correctly, add a check here to enforce it.
1216 delegate_->DidDisownOpener(this);
1219 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1220 frame_tree_node()->SetFrameName(name);
1221 delegate_->DidChangeName(this, name);
1224 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1225 // Update the RVH's current page ID so that future IPCs from the renderer
1226 // correspond to the new page.
1227 render_view_host_->page_id_ = page_id;
1230 void RenderFrameHostImpl::OnDidChangeSandboxFlags(int32 frame_routing_id,
1231 SandboxFlags flags) {
1232 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1233 FrameTreeNode* child =
1234 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1235 if (!child)
1236 return;
1238 // Ensure that a frame can only update sandbox flags for its immediate
1239 // children. If this is not the case, the renderer is considered malicious
1240 // and is killed.
1241 if (child->parent() != frame_tree_node()) {
1242 bad_message::ReceivedBadMessage(GetProcess(),
1243 bad_message::RFH_SANDBOX_FLAGS);
1244 return;
1247 child->set_sandbox_flags(flags);
1249 // Notify the RenderFrame if it lives in a different process from its
1250 // parent. The frame's proxies in other processes also need to learn about
1251 // the updated sandbox flags, but these notifications are sent later in
1252 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1253 // navigates and the new sandbox flags take effect.
1254 RenderFrameHost* child_rfh = child->current_frame_host();
1255 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1256 child_rfh->Send(
1257 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1261 void RenderFrameHostImpl::OnUpdateTitle(
1262 const base::string16& title,
1263 blink::WebTextDirection title_direction) {
1264 // This message is only sent for top-level frames. TODO(avi): when frame tree
1265 // mirroring works correctly, add a check here to enforce it.
1266 if (title.length() > kMaxTitleChars) {
1267 NOTREACHED() << "Renderer sent too many characters in title.";
1268 return;
1271 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1272 WebTextDirectionToChromeTextDirection(
1273 title_direction));
1276 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1277 // This message is only sent for top-level frames. TODO(avi): when frame tree
1278 // mirroring works correctly, add a check here to enforce it.
1279 delegate_->UpdateEncoding(this, encoding_name);
1282 void RenderFrameHostImpl::OnBeginNavigation(
1283 const CommonNavigationParams& common_params,
1284 const BeginNavigationParams& begin_params,
1285 scoped_refptr<ResourceRequestBody> body) {
1286 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1287 switches::kEnableBrowserSideNavigation));
1288 frame_tree_node()->navigator()->OnBeginNavigation(
1289 frame_tree_node(), common_params, begin_params, body);
1292 void RenderFrameHostImpl::OnDispatchLoad() {
1293 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1294 switches::kSitePerProcess));
1295 // Only frames with an out-of-process parent frame should be sending this
1296 // message.
1297 RenderFrameProxyHost* proxy =
1298 frame_tree_node()->render_manager()->GetProxyToParent();
1299 if (!proxy) {
1300 bad_message::ReceivedBadMessage(GetProcess(),
1301 bad_message::RFH_NO_PROXY_TO_PARENT);
1302 return;
1305 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1308 void RenderFrameHostImpl::OnAccessibilityEvents(
1309 const std::vector<AccessibilityHostMsg_EventParams>& params,
1310 int reset_token) {
1311 // Don't process this IPC if either we're waiting on a reset and this
1312 // IPC doesn't have the matching token ID, or if we're not waiting on a
1313 // reset but this message includes a reset token.
1314 if (accessibility_reset_token_ != reset_token) {
1315 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1316 return;
1318 accessibility_reset_token_ = 0;
1320 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1321 render_view_host_->GetView());
1323 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1324 if ((accessibility_mode != AccessibilityModeOff) && view &&
1325 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1326 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1327 GetOrCreateBrowserAccessibilityManager();
1328 if (browser_accessibility_manager_)
1329 browser_accessibility_manager_->OnAccessibilityEvents(params);
1332 if (browser_accessibility_manager_) {
1333 // Get the frame routing ids from out-of-process iframes and
1334 // browser plugin instance ids from guests and update the mappings in
1335 // FrameAccessibility.
1336 for (size_t i = 0; i < params.size(); ++i) {
1337 const AccessibilityHostMsg_EventParams& param = params[i];
1338 UpdateCrossProcessIframeAccessibility(
1339 param.node_to_frame_routing_id_map);
1340 UpdateGuestFrameAccessibility(
1341 param.node_to_browser_plugin_instance_id_map);
1345 // Send the updates to the automation extension API.
1346 std::vector<AXEventNotificationDetails> details;
1347 details.reserve(params.size());
1348 for (size_t i = 0; i < params.size(); ++i) {
1349 const AccessibilityHostMsg_EventParams& param = params[i];
1350 AXEventNotificationDetails detail(param.update.node_id_to_clear,
1351 param.update.nodes,
1352 param.event_type,
1353 param.id,
1354 GetProcess()->GetID(),
1355 routing_id_);
1356 details.push_back(detail);
1359 delegate_->AccessibilityEventReceived(details);
1362 // Always send an ACK or the renderer can be in a bad state.
1363 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1365 // The rest of this code is just for testing; bail out if we're not
1366 // in that mode.
1367 if (accessibility_testing_callback_.is_null())
1368 return;
1370 for (size_t i = 0; i < params.size(); i++) {
1371 const AccessibilityHostMsg_EventParams& param = params[i];
1372 if (static_cast<int>(param.event_type) < 0)
1373 continue;
1375 if (!ax_tree_for_testing_) {
1376 if (browser_accessibility_manager_) {
1377 ax_tree_for_testing_.reset(new ui::AXTree(
1378 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1379 } else {
1380 ax_tree_for_testing_.reset(new ui::AXTree());
1381 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1382 << ax_tree_for_testing_->error();
1384 } else {
1385 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1386 << ax_tree_for_testing_->error();
1388 accessibility_testing_callback_.Run(param.event_type, param.id);
1392 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1393 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1394 if (accessibility_reset_token_)
1395 return;
1397 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1398 render_view_host_->GetView());
1399 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1400 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1401 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1402 BrowserAccessibilityManager* manager =
1403 GetOrCreateBrowserAccessibilityManager();
1404 if (manager)
1405 manager->OnLocationChanges(params);
1407 // TODO(aboxhall): send location change events to web contents observers too
1411 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1412 const AccessibilityHostMsg_FindInPageResultParams& params) {
1413 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1414 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1415 BrowserAccessibilityManager* manager =
1416 GetOrCreateBrowserAccessibilityManager();
1417 if (manager) {
1418 manager->OnFindInPageResult(
1419 params.request_id, params.match_index, params.start_id,
1420 params.start_offset, params.end_id, params.end_offset);
1425 void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
1426 int callback_id,
1427 const ui::AXTreeUpdate& snapshot) {
1428 const auto& it = ax_tree_snapshot_callbacks_.find(callback_id);
1429 if (it != ax_tree_snapshot_callbacks_.end()) {
1430 it->second.Run(snapshot);
1431 ax_tree_snapshot_callbacks_.erase(it);
1432 } else {
1433 NOTREACHED() << "Received AX tree snapshot response for unknown id";
1437 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1438 if (enter_fullscreen)
1439 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1440 else
1441 delegate_->ExitFullscreenMode();
1443 // The previous call might change the fullscreen state. We need to make sure
1444 // the renderer is aware of that, which is done via the resize message.
1445 render_view_host_->WasResized();
1448 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
1449 // Any main frame load to a new document should reset the load since it will
1450 // replace the current page and any frames.
1451 if (to_different_document && !GetParent())
1452 is_loading_ = false;
1454 // This method should never be called when the frame is loading.
1455 // Unfortunately, it can happen if a history navigation happens during a
1456 // BeforeUnload or Unload event.
1457 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1458 // refactored in Blink. See crbug.com/466089
1459 if (is_loading_) {
1460 LOG(WARNING) << "OnDidStartLoading was called twice.";
1461 return;
1464 frame_tree_node_->DidStartLoading(to_different_document);
1465 is_loading_ = true;
1468 void RenderFrameHostImpl::OnDidStopLoading() {
1469 // This method should never be called when the frame is not loading.
1470 // Unfortunately, it can happen if a history navigation happens during a
1471 // BeforeUnload or Unload event.
1472 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1473 // refactored in Blink. See crbug.com/466089
1474 if (!is_loading_) {
1475 LOG(WARNING) << "OnDidStopLoading was called twice.";
1476 return;
1479 is_loading_ = false;
1480 frame_tree_node_->DidStopLoading();
1483 void RenderFrameHostImpl::OnDidChangeLoadProgress(double load_progress) {
1484 frame_tree_node_->DidChangeLoadProgress(load_progress);
1487 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1488 void RenderFrameHostImpl::OnShowPopup(
1489 const FrameHostMsg_ShowPopup_Params& params) {
1490 RenderViewHostDelegateView* view =
1491 render_view_host_->delegate_->GetDelegateView();
1492 if (view) {
1493 view->ShowPopupMenu(this,
1494 params.bounds,
1495 params.item_height,
1496 params.item_font_size,
1497 params.selected_item,
1498 params.popup_items,
1499 params.right_aligned,
1500 params.allow_multiple_selection);
1504 void RenderFrameHostImpl::OnHidePopup() {
1505 RenderViewHostDelegateView* view =
1506 render_view_host_->delegate_->GetDelegateView();
1507 if (view)
1508 view->HidePopupMenu();
1510 #endif
1512 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1513 static void CreateMediaRendererService(
1514 mojo::InterfaceRequest<mojo::MediaRenderer> request) {
1515 media::MojoRendererService* service = new media::MojoRendererService();
1516 mojo::BindToRequest(service, &request);
1518 #endif
1520 void RenderFrameHostImpl::RegisterMojoServices() {
1521 GeolocationServiceContext* geolocation_service_context =
1522 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1523 if (geolocation_service_context) {
1524 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1525 // can perform permissions checks once site isolation is complete.
1526 // crbug.com/426384
1527 GetServiceRegistry()->AddService<GeolocationService>(
1528 base::Bind(&GeolocationServiceContext::CreateService,
1529 base::Unretained(geolocation_service_context),
1530 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1531 base::Unretained(this))));
1534 if (!permission_service_context_)
1535 permission_service_context_.reset(new PermissionServiceContext(this));
1537 GetServiceRegistry()->AddService<PermissionService>(
1538 base::Bind(&PermissionServiceContext::CreateService,
1539 base::Unretained(permission_service_context_.get())));
1541 GetServiceRegistry()->AddService<presentation::PresentationService>(
1542 base::Bind(&PresentationServiceImpl::CreateMojoService,
1543 base::Unretained(this)));
1545 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1546 GetServiceRegistry()->AddService<mojo::MediaRenderer>(
1547 base::Bind(&CreateMediaRendererService));
1548 #endif
1551 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1552 // Only main frames should be swapped out and retained inside a proxy host.
1553 if (rfh_state == STATE_SWAPPED_OUT)
1554 CHECK(!GetParent());
1556 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1557 // out status of a RenderFrameHost gets flipped to/from active.
1558 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1559 GetSiteInstance()->increment_active_frame_count();
1560 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1561 GetSiteInstance()->decrement_active_frame_count();
1563 // The active and swapped out state of the RVH is determined by its main
1564 // frame, since subframes should have their own widgets.
1565 if (frame_tree_node_->IsMainFrame()) {
1566 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1567 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1570 // Whenever we change the RFH state to and from active or swapped out state,
1571 // we should not be waiting for beforeunload or close acks. We clear them
1572 // here to be safe, since they can cause navigations to be ignored in
1573 // OnDidCommitProvisionalLoad.
1574 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1575 if (rfh_state == STATE_DEFAULT ||
1576 rfh_state == STATE_SWAPPED_OUT ||
1577 rfh_state_ == STATE_DEFAULT ||
1578 rfh_state_ == STATE_SWAPPED_OUT) {
1579 if (is_waiting_for_beforeunload_ack_) {
1580 is_waiting_for_beforeunload_ack_ = false;
1581 render_view_host_->decrement_in_flight_event_count();
1582 render_view_host_->StopHangMonitorTimeout();
1584 send_before_unload_start_time_ = base::TimeTicks();
1585 render_view_host_->is_waiting_for_close_ack_ = false;
1587 rfh_state_ = rfh_state;
1590 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1591 // TODO(creis): We should also check for WebUI pages here. Also, when the
1592 // out-of-process iframes implementation is ready, we should check for
1593 // cross-site URLs that are not allowed to commit in this process.
1595 // Give the client a chance to disallow URLs from committing.
1596 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1599 void RenderFrameHostImpl::Navigate(
1600 const CommonNavigationParams& common_params,
1601 const StartNavigationParams& start_params,
1602 const RequestNavigationParams& request_params) {
1603 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1604 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
1605 // so do not grant them the ability to request additional URLs.
1606 if (!GetProcess()->IsIsolatedGuest()) {
1607 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1608 GetProcess()->GetID(), common_params.url);
1609 if (common_params.url.SchemeIs(url::kDataScheme) &&
1610 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
1611 // If 'data:' is used, and we have a 'file:' base url, grant access to
1612 // local files.
1613 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1614 GetProcess()->GetID(), common_params.base_url_for_data_url);
1618 // We may be returning to an existing NavigationEntry that had been granted
1619 // file access. If this is a different process, we will need to grant the
1620 // access again. The files listed in the page state are validated when they
1621 // are received from the renderer to prevent abuse.
1622 if (request_params.page_state.IsValid()) {
1623 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
1626 // Only send the message if we aren't suspended at the start of a cross-site
1627 // request.
1628 if (navigations_suspended_) {
1629 // Shouldn't be possible to have a second navigation while suspended, since
1630 // navigations will only be suspended during a cross-site request. If a
1631 // second navigation occurs, RenderFrameHostManager will cancel this pending
1632 // RFH and create a new pending RFH.
1633 DCHECK(!suspended_nav_params_.get());
1634 suspended_nav_params_.reset(
1635 new NavigationParams(common_params, start_params, request_params));
1636 } else {
1637 // Get back to a clean state, in case we start a new navigation without
1638 // completing a RFH swap or unload handler.
1639 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1641 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1642 request_params));
1645 // Force the throbber to start. This is done because Blink's "started loading"
1646 // message will be received asynchronously from the UI of the browser. But the
1647 // throbber needs to be kept in sync with what's happening in the UI. For
1648 // example, the throbber will start immediately when the user navigates even
1649 // if the renderer is delayed. There is also an issue with the throbber
1650 // starting because the WebUI (which controls whether the favicon is
1651 // displayed) happens synchronously. If the start loading messages was
1652 // asynchronous, then the default favicon would flash in.
1654 // Blink doesn't send throb notifications for JavaScript URLs, so it is not
1655 // done here either.
1656 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1657 frame_tree_node_->DidStartLoading(true);
1660 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1661 CommonNavigationParams common_params(
1662 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::NORMAL,
1663 true, base::TimeTicks::Now(), FrameMsg_UILoadMetricsReportType::NO_REPORT,
1664 GURL(), GURL());
1665 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1668 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1669 SiteInstance* source_site_instance) {
1670 GURL validated_url(params.url);
1671 GetProcess()->FilterURL(false, &validated_url);
1673 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1674 validated_url.possibly_invalid_spec());
1675 ui::PageTransition transition = ui::PAGE_TRANSITION_LINK;
1676 if (frame_tree_node_->parent()) {
1677 transition = params.should_replace_current_entry
1678 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1679 : ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
1681 frame_tree_node_->navigator()->RequestOpenURL(
1682 this, validated_url, source_site_instance, params.referrer, transition,
1683 params.disposition, params.should_replace_current_entry,
1684 params.user_gesture);
1687 void RenderFrameHostImpl::Stop() {
1688 Send(new FrameMsg_Stop(routing_id_));
1691 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1692 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1693 // the handler ran and allowed the navigation to proceed.
1694 if (GetParent() || !IsRenderFrameLive()) {
1695 // We don't have a live renderer, so just skip running beforeunload.
1696 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1697 switches::kEnableBrowserSideNavigation)) {
1698 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1699 frame_tree_node_, true);
1700 } else {
1701 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1702 for_navigation, true, base::TimeTicks::Now());
1704 return;
1706 TRACE_EVENT_ASYNC_BEGIN0(
1707 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1709 // This may be called more than once (if the user clicks the tab close button
1710 // several times, or if she clicks the tab close button then the browser close
1711 // button), and we only send the message once.
1712 if (is_waiting_for_beforeunload_ack_) {
1713 // Some of our close messages could be for the tab, others for cross-site
1714 // transitions. We always want to think it's for closing the tab if any
1715 // of the messages were, since otherwise it might be impossible to close
1716 // (if there was a cross-site "close" request pending when the user clicked
1717 // the close button). We want to keep the "for cross site" flag only if
1718 // both the old and the new ones are also for cross site.
1719 unload_ack_is_for_navigation_ =
1720 unload_ack_is_for_navigation_ && for_navigation;
1721 } else {
1722 // Start the hang monitor in case the renderer hangs in the beforeunload
1723 // handler.
1724 is_waiting_for_beforeunload_ack_ = true;
1725 unload_ack_is_for_navigation_ = for_navigation;
1726 // Increment the in-flight event count, to ensure that input events won't
1727 // cancel the timeout timer.
1728 render_view_host_->increment_in_flight_event_count();
1729 render_view_host_->StartHangMonitorTimeout(
1730 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1731 send_before_unload_start_time_ = base::TimeTicks::Now();
1732 Send(new FrameMsg_BeforeUnload(routing_id_));
1736 void RenderFrameHostImpl::DisownOpener() {
1737 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1740 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1741 size_t after) {
1742 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1745 void RenderFrameHostImpl::JavaScriptDialogClosed(
1746 IPC::Message* reply_msg,
1747 bool success,
1748 const base::string16& user_input,
1749 bool dialog_was_suppressed) {
1750 GetProcess()->SetIgnoreInputEvents(false);
1751 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1753 // If we are executing as part of (before)unload event handling, we don't
1754 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1755 // leave the current page. In this case, use the regular timeout value used
1756 // during the (before)unload handling.
1757 if (is_waiting) {
1758 render_view_host_->StartHangMonitorTimeout(
1759 success
1760 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1761 : render_view_host_->hung_renderer_delay_);
1764 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1765 success, user_input);
1766 Send(reply_msg);
1768 // If we are waiting for an unload or beforeunload ack and the user has
1769 // suppressed messages, kill the tab immediately; a page that's spamming
1770 // alerts in onbeforeunload is presumably malicious, so there's no point in
1771 // continuing to run its script and dragging out the process.
1772 // This must be done after sending the reply since RenderView can't close
1773 // correctly while waiting for a response.
1774 if (is_waiting && dialog_was_suppressed)
1775 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1778 // PlzNavigate
1779 void RenderFrameHostImpl::CommitNavigation(
1780 ResourceResponse* response,
1781 scoped_ptr<StreamHandle> body,
1782 const CommonNavigationParams& common_params,
1783 const RequestNavigationParams& request_params) {
1784 DCHECK((response && body.get()) ||
1785 !NavigationRequest::ShouldMakeNetworkRequest(common_params.url));
1786 // TODO(clamy): Check if we have to add security checks for the browser plugin
1787 // guests.
1789 // Get back to a clean state, in case we start a new navigation without
1790 // completing a RFH swap or unload handler.
1791 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1793 const GURL body_url = body.get() ? body->GetURL() : GURL();
1794 const ResourceResponseHead head = response ?
1795 response->head : ResourceResponseHead();
1796 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1797 request_params));
1798 // TODO(clamy): Check if we should start the throbber for non javascript urls
1799 // here.
1801 // TODO(clamy): Release the stream handle once the renderer has finished
1802 // reading it.
1803 stream_handle_ = body.Pass();
1804 pending_commit_ = true;
1807 void RenderFrameHostImpl::FailedNavigation(
1808 const CommonNavigationParams& common_params,
1809 const RequestNavigationParams& request_params,
1810 bool has_stale_copy_in_cache,
1811 int error_code) {
1812 // Get back to a clean state, in case a new navigation started without
1813 // completing a RFH swap or unload handler.
1814 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1816 Send(new FrameMsg_FailedNavigation(routing_id_, common_params, request_params,
1817 has_stale_copy_in_cache, error_code));
1820 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1821 if (service_registry_.get())
1822 return;
1824 service_registry_.reset(new ServiceRegistryImpl());
1825 if (!GetProcess()->GetServiceRegistry())
1826 return;
1828 RegisterMojoServices();
1829 RenderFrameSetupPtr setup;
1830 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(&setup);
1832 mojo::ServiceProviderPtr exposed_services;
1833 service_registry_->Bind(GetProxy(&exposed_services));
1835 mojo::ServiceProviderPtr services;
1836 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1837 exposed_services.Pass());
1838 service_registry_->BindRemoteServiceProvider(services.Pass());
1840 #if defined(OS_ANDROID)
1841 service_registry_android_.reset(
1842 new ServiceRegistryAndroid(service_registry_.get()));
1843 ServiceRegistrarAndroid::RegisterFrameHostServices(
1844 service_registry_android_.get());
1845 #endif
1848 void RenderFrameHostImpl::InvalidateMojoConnection() {
1849 #if defined(OS_ANDROID)
1850 // The Android-specific service registry has a reference to
1851 // |service_registry_| and thus must be torn down first.
1852 service_registry_android_.reset();
1853 #endif
1855 service_registry_.reset();
1858 bool RenderFrameHostImpl::IsFocused() {
1859 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1860 // returning nullptr in some cases. See https://crbug.com/455245.
1861 return RenderWidgetHostImpl::From(
1862 GetView()->GetRenderWidgetHost())->is_focused() &&
1863 frame_tree_->GetFocusedFrame() &&
1864 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1865 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1868 void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility(
1869 const std::map<int32, int>& node_to_frame_routing_id_map) {
1870 for (const auto& iter : node_to_frame_routing_id_map) {
1871 // This is the id of the accessibility node that has a child frame.
1872 int32 node_id = iter.first;
1873 // The routing id from either a RenderFrame or a RenderFrameProxy.
1874 int frame_routing_id = iter.second;
1876 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1877 FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID(
1878 GetProcess()->GetID(), frame_routing_id);
1880 if (child_frame_tree_node) {
1881 FrameAccessibility::GetInstance()->AddChildFrame(
1882 this, node_id, child_frame_tree_node->frame_tree_node_id());
1887 void RenderFrameHostImpl::UpdateGuestFrameAccessibility(
1888 const std::map<int32, int>& node_to_browser_plugin_instance_id_map) {
1889 for (const auto& iter : node_to_browser_plugin_instance_id_map) {
1890 // This is the id of the accessibility node that hosts a plugin.
1891 int32 node_id = iter.first;
1892 // The id of the browser plugin.
1893 int browser_plugin_instance_id = iter.second;
1894 FrameAccessibility::GetInstance()->AddGuestWebContents(
1895 this, node_id, browser_plugin_instance_id);
1899 bool RenderFrameHostImpl::IsSameSiteInstance(
1900 RenderFrameHostImpl* other_render_frame_host) {
1901 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1902 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1903 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1904 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1907 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1908 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1911 void RenderFrameHostImpl::RequestAXTreeSnapshot(
1912 AXTreeSnapshotCallback callback) {
1913 static int next_id = 1;
1914 int callback_id = next_id++;
1915 Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
1916 ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
1919 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1920 const base::Callback<void(ui::AXEvent, int)>& callback) {
1921 accessibility_testing_callback_ = callback;
1924 void RenderFrameHostImpl::SetTextTrackSettings(
1925 const FrameMsg_TextTrackSettings_Params& params) {
1926 DCHECK(!GetParent());
1927 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
1930 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1931 return ax_tree_for_testing_.get();
1934 BrowserAccessibilityManager*
1935 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1936 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1937 render_view_host_->GetView());
1938 if (view &&
1939 !browser_accessibility_manager_ &&
1940 !no_create_browser_accessibility_manager_for_testing_) {
1941 browser_accessibility_manager_.reset(
1942 view->CreateBrowserAccessibilityManager(this));
1943 if (browser_accessibility_manager_)
1944 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
1945 else
1946 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
1948 return browser_accessibility_manager_.get();
1951 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
1952 int request_id) {
1953 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1954 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1955 BrowserAccessibilityManager* manager =
1956 GetOrCreateBrowserAccessibilityManager();
1957 if (manager)
1958 manager->ActivateFindInPageResult(request_id);
1962 void RenderFrameHostImpl::InsertVisualStateCallback(
1963 const VisualStateCallback& callback) {
1964 static uint64 next_id = 1;
1965 uint64 key = next_id++;
1966 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
1967 visual_state_callbacks_.insert(std::make_pair(key, callback));
1970 #if defined(OS_WIN)
1972 void RenderFrameHostImpl::SetParentNativeViewAccessible(
1973 gfx::NativeViewAccessible accessible_parent) {
1974 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1975 render_view_host_->GetView());
1976 if (view)
1977 view->SetParentNativeViewAccessible(accessible_parent);
1980 gfx::NativeViewAccessible
1981 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
1982 return delegate_->GetParentNativeViewAccessible();
1985 #elif defined(OS_MACOSX)
1987 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
1988 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
1991 void RenderFrameHostImpl::DidCancelPopupMenu() {
1992 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
1995 #elif defined(OS_ANDROID)
1997 void RenderFrameHostImpl::DidSelectPopupMenuItems(
1998 const std::vector<int>& selected_indices) {
1999 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
2002 void RenderFrameHostImpl::DidCancelPopupMenu() {
2003 Send(new FrameMsg_SelectPopupMenuItems(
2004 routing_id_, true, std::vector<int>()));
2007 #endif
2009 void RenderFrameHostImpl::ClearPendingTransitionRequestData() {
2010 BrowserThread::PostTask(
2011 BrowserThread::IO,
2012 FROM_HERE,
2013 base::Bind(
2014 &TransitionRequestManager::ClearPendingTransitionRequestData,
2015 base::Unretained(TransitionRequestManager::GetInstance()),
2016 GetProcess()->GetID(),
2017 routing_id_));
2020 void RenderFrameHostImpl::SetNavigationsSuspended(
2021 bool suspend,
2022 const base::TimeTicks& proceed_time) {
2023 // This should only be called to toggle the state.
2024 DCHECK(navigations_suspended_ != suspend);
2026 navigations_suspended_ = suspend;
2027 if (navigations_suspended_) {
2028 TRACE_EVENT_ASYNC_BEGIN0("navigation",
2029 "RenderFrameHostImpl navigation suspended", this);
2030 } else {
2031 TRACE_EVENT_ASYNC_END0("navigation",
2032 "RenderFrameHostImpl navigation suspended", this);
2035 if (!suspend && suspended_nav_params_) {
2036 // There's navigation message params waiting to be sent. Now that we're not
2037 // suspended anymore, resume navigation by sending them. If we were swapped
2038 // out, we should also stop filtering out the IPC messages now.
2039 SetState(RenderFrameHostImpl::STATE_DEFAULT);
2041 DCHECK(!proceed_time.is_null());
2042 suspended_nav_params_->request_params.browser_navigation_start =
2043 proceed_time;
2044 Send(new FrameMsg_Navigate(routing_id_,
2045 suspended_nav_params_->common_params,
2046 suspended_nav_params_->start_params,
2047 suspended_nav_params_->request_params));
2048 suspended_nav_params_.reset();
2052 void RenderFrameHostImpl::CancelSuspendedNavigations() {
2053 // Clear any state if a pending navigation is canceled or preempted.
2054 if (suspended_nav_params_)
2055 suspended_nav_params_.reset();
2057 TRACE_EVENT_ASYNC_END0("navigation",
2058 "RenderFrameHostImpl navigation suspended", this);
2059 navigations_suspended_ = false;
2062 void RenderFrameHostImpl::DidUseGeolocationPermission() {
2063 PermissionManager* permission_manager =
2064 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
2065 if (!permission_manager)
2066 return;
2068 permission_manager->RegisterPermissionUsage(
2069 PermissionType::GEOLOCATION,
2070 GetLastCommittedURL().GetOrigin(),
2071 frame_tree_node()->frame_tree()->GetMainFrame()
2072 ->GetLastCommittedURL().GetOrigin());
2075 } // namespace content