Revert "Refactor sudden termination"
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
bloba40518fd7de3d4b3cb9df4934887840db25902ad
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/render_process_host.h"
57 #include "content/public/browser/render_widget_host_view.h"
58 #include "content/public/browser/stream_handle.h"
59 #include "content/public/browser/user_metrics.h"
60 #include "content/public/common/content_constants.h"
61 #include "content/public/common/content_switches.h"
62 #include "content/public/common/url_constants.h"
63 #include "content/public/common/url_utils.h"
64 #include "ui/accessibility/ax_tree.h"
65 #include "url/gurl.h"
67 #if defined(OS_MACOSX)
68 #include "content/browser/frame_host/popup_menu_helper_mac.h"
69 #endif
71 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
72 #include "media/mojo/interfaces/media_renderer.mojom.h"
73 #include "media/mojo/services/mojo_renderer_service.h"
74 #endif
76 using base::TimeDelta;
78 namespace content {
80 namespace {
82 // The next value to use for the accessibility reset token.
83 int g_next_accessibility_reset_token = 1;
85 // The (process id, routing id) pair that identifies one RenderFrame.
86 typedef std::pair<int32, int32> RenderFrameHostID;
87 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
88 RoutingIDFrameMap;
89 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
90 LAZY_INSTANCE_INITIALIZER;
92 // Translate a WebKit text direction into a base::i18n one.
93 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
94 blink::WebTextDirection dir) {
95 switch (dir) {
96 case blink::WebTextDirectionLeftToRight:
97 return base::i18n::LEFT_TO_RIGHT;
98 case blink::WebTextDirectionRightToLeft:
99 return base::i18n::RIGHT_TO_LEFT;
100 default:
101 NOTREACHED();
102 return base::i18n::UNKNOWN_DIRECTION;
106 } // namespace
108 const double RenderFrameHostImpl::kLoadingProgressNotStarted = 0.0;
109 const double RenderFrameHostImpl::kLoadingProgressMinimum = 0.1;
110 const double RenderFrameHostImpl::kLoadingProgressDone = 1.0;
112 // static
113 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
114 return rfh_state == STATE_DEFAULT;
117 // static
118 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
119 int render_frame_id) {
120 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
123 // static
124 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
125 int routing_id) {
126 DCHECK_CURRENTLY_ON(BrowserThread::UI);
127 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
128 RoutingIDFrameMap::iterator it = frames->find(
129 RenderFrameHostID(process_id, routing_id));
130 return it == frames->end() ? NULL : it->second;
133 RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
134 RenderViewHostImpl* render_view_host,
135 RenderFrameHostDelegate* delegate,
136 RenderWidgetHostDelegate* rwh_delegate,
137 FrameTree* frame_tree,
138 FrameTreeNode* frame_tree_node,
139 int routing_id,
140 int flags)
141 : render_view_host_(render_view_host),
142 delegate_(delegate),
143 site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
144 process_(site_instance->GetProcess()),
145 cross_process_frame_connector_(NULL),
146 render_frame_proxy_host_(NULL),
147 frame_tree_(frame_tree),
148 frame_tree_node_(frame_tree_node),
149 routing_id_(routing_id),
150 render_frame_created_(false),
151 navigations_suspended_(false),
152 is_waiting_for_beforeunload_ack_(false),
153 unload_ack_is_for_navigation_(false),
154 is_loading_(false),
155 loading_progress_(kLoadingProgressNotStarted),
156 accessibility_reset_token_(0),
157 accessibility_reset_count_(0),
158 no_create_browser_accessibility_manager_for_testing_(false),
159 weak_ptr_factory_(this) {
160 bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
161 bool hidden = !!(flags & CREATE_RF_HIDDEN);
162 frame_tree_->RegisterRenderFrameHost(this);
163 GetProcess()->AddRoute(routing_id_, this);
164 g_routing_id_frame_map.Get().insert(std::make_pair(
165 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
166 this));
168 if (is_swapped_out) {
169 rfh_state_ = STATE_SWAPPED_OUT;
170 } else {
171 rfh_state_ = STATE_DEFAULT;
172 GetSiteInstance()->increment_active_frame_count();
175 SetUpMojoIfNeeded();
176 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
177 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
179 if (flags & CREATE_RF_NEEDS_RENDER_WIDGET_HOST) {
180 render_widget_host_.reset(new RenderWidgetHostImpl(
181 rwh_delegate, GetProcess(), MSG_ROUTING_NONE, hidden));
182 render_widget_host_->set_owned_by_render_frame_host(true);
186 RenderFrameHostImpl::~RenderFrameHostImpl() {
187 GetProcess()->RemoveRoute(routing_id_);
188 g_routing_id_frame_map.Get().erase(
189 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
191 if (delegate_ && render_frame_created_)
192 delegate_->RenderFrameDeleted(this);
194 FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this);
196 // If this was swapped out, it already decremented the active frame count of
197 // the SiteInstance it belongs to.
198 if (IsRFHStateActive(rfh_state_))
199 GetSiteInstance()->decrement_active_frame_count();
201 // Notify the FrameTree that this RFH is going away, allowing it to shut down
202 // the corresponding RenderViewHost if it is no longer needed.
203 frame_tree_->UnregisterRenderFrameHost(this);
205 // NULL out the swapout timer; in crash dumps this member will be null only if
206 // the dtor has run.
207 swapout_event_monitor_timeout_.reset();
209 for (const auto& iter: visual_state_callbacks_) {
210 iter.second.Run(false);
213 if (render_widget_host_)
214 render_widget_host_->Cleanup();
217 int RenderFrameHostImpl::GetRoutingID() {
218 return routing_id_;
221 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
222 return site_instance_.get();
225 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
226 return process_;
229 RenderFrameHost* RenderFrameHostImpl::GetParent() {
230 FrameTreeNode* parent_node = frame_tree_node_->parent();
231 if (!parent_node)
232 return NULL;
233 return parent_node->current_frame_host();
236 const std::string& RenderFrameHostImpl::GetFrameName() {
237 return frame_tree_node_->frame_name();
240 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
241 FrameTreeNode* parent_node = frame_tree_node_->parent();
242 if (!parent_node)
243 return false;
244 return GetSiteInstance() !=
245 parent_node->current_frame_host()->GetSiteInstance();
248 GURL RenderFrameHostImpl::GetLastCommittedURL() {
249 return frame_tree_node_->current_url();
252 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
253 RenderWidgetHostView* view = render_view_host_->GetView();
254 if (!view)
255 return NULL;
256 return view->GetNativeView();
259 void RenderFrameHostImpl::ExecuteJavaScript(
260 const base::string16& javascript) {
261 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
262 javascript,
263 0, false));
266 void RenderFrameHostImpl::ExecuteJavaScript(
267 const base::string16& javascript,
268 const JavaScriptResultCallback& callback) {
269 static int next_id = 1;
270 int key = next_id++;
271 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
272 javascript,
273 key, true));
274 javascript_callbacks_.insert(std::make_pair(key, callback));
277 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
278 const base::string16& javascript) {
279 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
280 javascript,
281 0, false));
284 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
285 return render_view_host_;
288 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
289 return service_registry_.get();
292 blink::WebPageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
293 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
294 // returning nullptr in some cases. See https://crbug.com/455245.
295 blink::WebPageVisibilityState visibility_state =
296 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())->is_hidden()
297 ? blink::WebPageVisibilityStateHidden
298 : blink::WebPageVisibilityStateVisible;
299 GetContentClient()->browser()->OverridePageVisibilityState(this,
300 &visibility_state);
301 return visibility_state;
304 bool RenderFrameHostImpl::Send(IPC::Message* message) {
305 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
306 return render_view_host_->input_router()->SendInput(
307 make_scoped_ptr(message));
310 return GetProcess()->Send(message);
313 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
314 // Filter out most IPC messages if this frame is swapped out.
315 // We still want to handle certain ACKs to keep our state consistent.
316 if (is_swapped_out()) {
317 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
318 // If this is a synchronous message and we decided not to handle it,
319 // we must send an error reply, or else the renderer will be stuck
320 // and won't respond to future requests.
321 if (msg.is_sync()) {
322 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
323 reply->set_reply_error();
324 Send(reply);
326 // Don't continue looking for someone to handle it.
327 return true;
331 if (delegate_->OnMessageReceived(this, msg))
332 return true;
334 RenderFrameProxyHost* proxy =
335 frame_tree_node_->render_manager()->GetProxyToParent();
336 if (proxy && proxy->cross_process_frame_connector() &&
337 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
338 return true;
340 bool handled = true;
341 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
342 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
343 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
344 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
345 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
346 OnDidStartProvisionalLoadForFrame)
347 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
348 OnDidFailProvisionalLoadWithError)
349 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
350 OnDidFailLoadWithError)
351 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
352 OnDidCommitProvisionalLoad(msg))
353 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation)
354 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
355 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
356 OnDocumentOnLoadCompleted)
357 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
358 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
359 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
360 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
361 OnJavaScriptExecuteResponse)
362 IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
363 OnVisualStateResponse)
364 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
365 OnRunJavaScriptMessage)
366 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
367 OnRunBeforeUnloadConfirm)
368 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
369 OnDidAccessInitialDocument)
370 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
371 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeName, OnDidChangeName)
372 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
373 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeSandboxFlags,
374 OnDidChangeSandboxFlags)
375 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
376 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
377 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
378 OnBeginNavigation)
379 IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
380 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
381 OnTextSurroundingSelectionResponse)
382 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
383 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
384 OnAccessibilityLocationChanges)
385 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
386 OnAccessibilityFindInPageResult)
387 IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
388 // The following message is synthetic and doesn't come from RenderFrame, but
389 // from RenderProcessHost.
390 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
391 #if defined(OS_MACOSX) || defined(OS_ANDROID)
392 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
393 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
394 #endif
395 IPC_END_MESSAGE_MAP()
397 // No further actions here, since we may have been deleted.
398 return handled;
401 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
402 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
405 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
406 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
409 void RenderFrameHostImpl::AccessibilityShowMenu(
410 const gfx::Point& global_point) {
411 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
412 render_view_host_->GetView());
413 if (view)
414 view->AccessibilityShowMenu(global_point);
417 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
418 int acc_obj_id, const gfx::Rect& subfocus) {
419 Send(new AccessibilityMsg_ScrollToMakeVisible(
420 routing_id_, acc_obj_id, subfocus));
423 void RenderFrameHostImpl::AccessibilityScrollToPoint(
424 int acc_obj_id, const gfx::Point& point) {
425 Send(new AccessibilityMsg_ScrollToPoint(
426 routing_id_, acc_obj_id, point));
429 void RenderFrameHostImpl::AccessibilitySetTextSelection(
430 int object_id, int start_offset, int end_offset) {
431 Send(new AccessibilityMsg_SetTextSelection(
432 routing_id_, object_id, start_offset, end_offset));
435 void RenderFrameHostImpl::AccessibilitySetValue(
436 int object_id, const base::string16& value) {
437 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
440 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
441 RenderWidgetHostView* view = render_view_host_->GetView();
442 if (view)
443 return view->HasFocus();
444 return false;
447 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
448 RenderWidgetHostView* view = render_view_host_->GetView();
449 if (view)
450 return view->GetViewBounds();
451 return gfx::Rect();
454 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
455 const gfx::Rect& bounds) const {
456 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
457 render_view_host_->GetView());
458 if (view)
459 return view->AccessibilityOriginInScreen(bounds);
460 return gfx::Point();
463 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
464 Send(new AccessibilityMsg_HitTest(routing_id_, point));
467 void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) {
468 Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id));
471 void RenderFrameHostImpl::AccessibilityFatalError() {
472 browser_accessibility_manager_.reset(NULL);
473 if (accessibility_reset_token_)
474 return;
476 accessibility_reset_count_++;
477 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
478 Send(new AccessibilityMsg_FatalError(routing_id_));
479 } else {
480 accessibility_reset_token_ = g_next_accessibility_reset_token++;
481 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
482 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
486 gfx::AcceleratedWidget
487 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
488 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
489 render_view_host_->GetView());
490 if (view)
491 return view->AccessibilityGetAcceleratedWidget();
492 return gfx::kNullAcceleratedWidget;
495 gfx::NativeViewAccessible
496 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
497 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
498 render_view_host_->GetView());
499 if (view)
500 return view->AccessibilityGetNativeViewAccessible();
501 return NULL;
504 BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame(
505 int accessibility_node_id) {
506 RenderFrameHostImpl* child_frame =
507 FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id);
508 if (!child_frame || IsSameSiteInstance(child_frame))
509 return nullptr;
511 return child_frame->GetOrCreateBrowserAccessibilityManager();
514 void RenderFrameHostImpl::AccessibilityGetAllChildFrames(
515 std::vector<BrowserAccessibilityManager*>* child_frames) {
516 std::vector<RenderFrameHostImpl*> child_frame_hosts;
517 FrameAccessibility::GetInstance()->GetAllChildFrames(
518 this, &child_frame_hosts);
519 for (size_t i = 0; i < child_frame_hosts.size(); ++i) {
520 RenderFrameHostImpl* child_frame_host = child_frame_hosts[i];
521 if (!child_frame_host || IsSameSiteInstance(child_frame_host))
522 continue;
524 BrowserAccessibilityManager* manager =
525 child_frame_host->GetOrCreateBrowserAccessibilityManager();
526 if (manager)
527 child_frames->push_back(manager);
531 BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() {
532 RenderFrameHostImpl* parent_frame = NULL;
533 int parent_node_id = 0;
534 if (!FrameAccessibility::GetInstance()->GetParent(
535 this, &parent_frame, &parent_node_id)) {
536 return NULL;
539 // As a sanity check, make sure the frame we're going to return belongs
540 // to the same BrowserContext.
541 if (GetSiteInstance()->GetBrowserContext() !=
542 parent_frame->GetSiteInstance()->GetBrowserContext()) {
543 NOTREACHED();
544 return NULL;
547 BrowserAccessibilityManager* manager =
548 parent_frame->browser_accessibility_manager();
549 if (!manager)
550 return NULL;
552 return manager->GetFromID(parent_node_id);
555 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id,
556 int proxy_routing_id) {
557 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
558 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
560 // The process may (if we're sharing a process with another host that already
561 // initialized it) or may not (we have our own process or the old process
562 // crashed) have been initialized. Calling Init multiple times will be
563 // ignored, so this is safe.
564 if (!GetProcess()->Init())
565 return false;
567 DCHECK(GetProcess()->HasConnection());
569 FrameMsg_NewFrame_WidgetParams widget_params;
570 if (render_widget_host_) {
571 widget_params.routing_id = render_widget_host_->GetRoutingID();
572 widget_params.surface_id = render_widget_host_->surface_id();
573 widget_params.hidden = render_widget_host_->is_hidden();
574 } else {
575 // MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
576 // the renderer process.
577 widget_params.routing_id = MSG_ROUTING_NONE;
578 widget_params.surface_id = 0;
579 widget_params.hidden = true;
582 Send(new FrameMsg_NewFrame(routing_id_, parent_routing_id, proxy_routing_id,
583 frame_tree_node()->current_replication_state(),
584 widget_params));
586 // The RenderWidgetHost takes ownership of its view. It is tied to the
587 // lifetime of the current RenderProcessHost for this RenderFrameHost.
588 if (render_widget_host_) {
589 RenderWidgetHostView* rwhv =
590 new RenderWidgetHostViewChildFrame(render_widget_host_.get());
591 rwhv->Hide();
594 if (proxy_routing_id != MSG_ROUTING_NONE) {
595 RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
596 GetProcess()->GetID(), proxy_routing_id);
597 // We have also created a RenderFrameProxy in FrameMsg_NewFrame above, so
598 // remember that.
599 proxy->set_render_frame_proxy_created(true);
602 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
603 // this path is only used for out-of-process iframes. Main frame RenderFrames
604 // are created with their RenderView, and same-site iframes are created at the
605 // time of OnCreateChildFrame.
606 SetRenderFrameCreated(true);
608 return true;
611 bool RenderFrameHostImpl::IsRenderFrameLive() {
612 // RenderFrames are created for main frames at the same time as RenderViews,
613 // so we rely on IsRenderViewLive. For subframes, we keep track of each
614 // RenderFrame individually with render_frame_created_.
615 bool is_live = !GetParent() ?
616 render_view_host_->IsRenderViewLive() :
617 GetProcess()->HasConnection() && render_frame_created_;
619 // Sanity check: the RenderView should always be live if the RenderFrame is.
620 DCHECK(!is_live || render_view_host_->IsRenderViewLive());
622 return is_live;
625 void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
626 // If the current status is different than the new status, the delegate
627 // needs to be notified.
628 if (delegate_ && (created != render_frame_created_)) {
629 if (created)
630 delegate_->RenderFrameCreated(this);
631 else
632 delegate_->RenderFrameDeleted(this);
635 render_frame_created_ = created;
636 if (created && render_widget_host_)
637 render_widget_host_->InitForFrame();
640 void RenderFrameHostImpl::Init() {
641 GetProcess()->ResumeRequestsForView(routing_id_);
644 void RenderFrameHostImpl::OnAddMessageToConsole(
645 int32 level,
646 const base::string16& message,
647 int32 line_no,
648 const base::string16& source_id) {
649 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
650 return;
652 // Pass through log level only on WebUI pages to limit console spew.
653 const bool is_web_ui =
654 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL());
655 const int32 resolved_level = is_web_ui ? level : ::logging::LOG_INFO;
657 // LogMessages can be persisted so this shouldn't be logged in incognito mode.
658 // This rule is not applied to WebUI pages, because source code of WebUI is a
659 // part of Chrome source code, and we want to treat messages from WebUI the
660 // same way as we treat log messages from native code.
661 if (::logging::GetMinLogLevel() <= resolved_level &&
662 (is_web_ui ||
663 !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord())) {
664 logging::LogMessage("CONSOLE", line_no, resolved_level).stream()
665 << "\"" << message << "\", source: " << source_id << " (" << line_no
666 << ")";
670 void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id,
671 const std::string& frame_name,
672 SandboxFlags sandbox_flags) {
673 // It is possible that while a new RenderFrameHost was committed, the
674 // RenderFrame corresponding to this host sent an IPC message to create a
675 // frame and it is delivered after this host is swapped out.
676 // Ignore such messages, as we know this RenderFrameHost is going away.
677 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
678 return;
680 RenderFrameHostImpl* new_frame = frame_tree_->AddFrame(
681 frame_tree_node_, GetProcess()->GetID(), new_routing_id, frame_name);
682 if (!new_frame)
683 return;
685 // Set sandbox flags for the new frame. The flags are committed immediately,
686 // since they should apply to the initial empty document in the frame.
687 new_frame->frame_tree_node()->set_sandbox_flags(sandbox_flags);
688 new_frame->frame_tree_node()->CommitPendingSandboxFlags();
690 // We know that the RenderFrame has been created in this case, immediately
691 // after the CreateChildFrame IPC was sent.
692 new_frame->SetRenderFrameCreated(true);
695 void RenderFrameHostImpl::OnDetach() {
696 frame_tree_->RemoveFrame(frame_tree_node_);
699 void RenderFrameHostImpl::OnFrameFocused() {
700 frame_tree_->SetFocusedFrame(frame_tree_node_);
703 void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
704 OpenURL(params, GetSiteInstance());
707 void RenderFrameHostImpl::OnDocumentOnLoadCompleted(
708 FrameMsg_UILoadMetricsReportType::Value report_type,
709 base::TimeTicks ui_timestamp) {
710 if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
711 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Link",
712 base::TimeTicks::Now() - ui_timestamp,
713 base::TimeDelta::FromMilliseconds(10),
714 base::TimeDelta::FromMinutes(10), 100);
715 } else if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
716 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Intent",
717 base::TimeTicks::Now() - ui_timestamp,
718 base::TimeDelta::FromMilliseconds(10),
719 base::TimeDelta::FromMinutes(10), 100);
721 // This message is only sent for top-level frames. TODO(avi): when frame tree
722 // mirroring works correctly, add a check here to enforce it.
723 delegate_->DocumentOnLoadCompleted(this);
726 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(
727 const GURL& url,
728 bool is_transition_navigation) {
729 frame_tree_node_->navigator()->DidStartProvisionalLoad(
730 this, url, is_transition_navigation);
733 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
734 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
735 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
738 void RenderFrameHostImpl::OnDidFailLoadWithError(
739 const GURL& url,
740 int error_code,
741 const base::string16& error_description) {
742 GURL validated_url(url);
743 GetProcess()->FilterURL(false, &validated_url);
745 frame_tree_node_->navigator()->DidFailLoadWithError(
746 this, validated_url, error_code, error_description);
749 // Called when the renderer navigates. For every frame loaded, we'll get this
750 // notification containing parameters identifying the navigation.
752 // Subframes are identified by the page transition type. For subframes loaded
753 // as part of a wider page load, the page_id will be the same as for the top
754 // level frame. If the user explicitly requests a subframe navigation, we will
755 // get a new page_id because we need to create a new navigation entry for that
756 // action.
757 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
758 // Read the parameters out of the IPC message directly to avoid making another
759 // copy when we filter the URLs.
760 PickleIterator iter(msg);
761 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
762 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
763 Read(&msg, &iter, &validated_params))
764 return;
765 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
766 "url", validated_params.url.possibly_invalid_spec());
768 // If we're waiting for a cross-site beforeunload ack from this renderer and
769 // we receive a Navigate message from the main frame, then the renderer was
770 // navigating already and sent it before hearing the FrameMsg_Stop message.
771 // We do not want to cancel the pending navigation in this case, since the
772 // old page will soon be stopped. Instead, treat this as a beforeunload ack
773 // to allow the pending navigation to continue.
774 if (is_waiting_for_beforeunload_ack_ &&
775 unload_ack_is_for_navigation_ &&
776 ui::PageTransitionIsMainFrame(validated_params.transition)) {
777 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
778 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
779 return;
782 // If we're waiting for an unload ack from this renderer and we receive a
783 // Navigate message, then the renderer was navigating before it received the
784 // unload request. It will either respond to the unload request soon or our
785 // timer will expire. Either way, we should ignore this message, because we
786 // have already committed to closing this renderer.
787 if (IsWaitingForUnloadACK())
788 return;
790 if (validated_params.report_type ==
791 FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
792 UMA_HISTOGRAM_CUSTOM_TIMES(
793 "Navigation.UI_OnCommitProvisionalLoad.Link",
794 base::TimeTicks::Now() - validated_params.ui_timestamp,
795 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
796 100);
797 } else if (validated_params.report_type ==
798 FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
799 UMA_HISTOGRAM_CUSTOM_TIMES(
800 "Navigation.UI_OnCommitProvisionalLoad.Intent",
801 base::TimeTicks::Now() - validated_params.ui_timestamp,
802 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
803 100);
806 RenderProcessHost* process = GetProcess();
808 // Attempts to commit certain off-limits URL should be caught more strictly
809 // than our FilterURL checks below. If a renderer violates this policy, it
810 // should be killed.
811 if (!CanCommitURL(validated_params.url)) {
812 VLOG(1) << "Blocked URL " << validated_params.url.spec();
813 validated_params.url = GURL(url::kAboutBlankURL);
814 // Kills the process.
815 bad_message::ReceivedBadMessage(process,
816 bad_message::RFH_CAN_COMMIT_URL_BLOCKED);
819 // Without this check, an evil renderer can trick the browser into creating
820 // a navigation entry for a banned URL. If the user clicks the back button
821 // followed by the forward button (or clicks reload, or round-trips through
822 // session restore, etc), we'll think that the browser commanded the
823 // renderer to load the URL and grant the renderer the privileges to request
824 // the URL. To prevent this attack, we block the renderer from inserting
825 // banned URLs into the navigation controller in the first place.
826 process->FilterURL(false, &validated_params.url);
827 process->FilterURL(true, &validated_params.referrer.url);
828 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
829 it != validated_params.redirects.end(); ++it) {
830 process->FilterURL(false, &(*it));
832 process->FilterURL(true, &validated_params.searchable_form_url);
834 // Without this check, the renderer can trick the browser into using
835 // filenames it can't access in a future session restore.
836 if (!render_view_host_->CanAccessFilesOfPageState(
837 validated_params.page_state)) {
838 bad_message::ReceivedBadMessage(
839 GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
840 return;
843 accessibility_reset_count_ = 0;
844 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
847 void RenderFrameHostImpl::OnDidDropNavigation() {
848 // At the end of Navigate(), the delegate's DidStartLoading is called to force
849 // the spinner to start, even if the renderer didn't yet begin the load. If it
850 // turns out that the renderer dropped the navigation, we need to turn off the
851 // spinner.
852 delegate_->DidStopLoading();
855 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
856 if (render_widget_host_)
857 return render_widget_host_.get();
859 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
860 // we can remove this fallback. Currently it is only used for the main
861 // frame.
862 if (!GetParent())
863 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
865 return nullptr;
868 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
869 RenderFrameHostImpl* frame = this;
870 while (frame) {
871 if (frame->render_widget_host_)
872 return frame->render_widget_host_->GetView();
873 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
876 return render_view_host_->GetView();
879 int RenderFrameHostImpl::GetEnabledBindings() {
880 return render_view_host_->GetEnabledBindings();
883 void RenderFrameHostImpl::OnCrossSiteResponse(
884 const GlobalRequestID& global_request_id,
885 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
886 const std::vector<GURL>& transfer_url_chain,
887 const Referrer& referrer,
888 ui::PageTransition page_transition,
889 bool should_replace_current_entry) {
890 frame_tree_node_->render_manager()->OnCrossSiteResponse(
891 this, global_request_id, cross_site_transferring_request.Pass(),
892 transfer_url_chain, referrer, page_transition,
893 should_replace_current_entry);
896 void RenderFrameHostImpl::OnDeferredAfterResponseStarted(
897 const GlobalRequestID& global_request_id,
898 const TransitionLayerData& transition_data) {
899 frame_tree_node_->render_manager()->OnDeferredAfterResponseStarted(
900 global_request_id, this);
902 if (GetParent() || !delegate_->WillHandleDeferAfterResponseStarted())
903 frame_tree_node_->render_manager()->ResumeResponseDeferredAtStart();
904 else
905 delegate_->DidDeferAfterResponseStarted(transition_data);
908 void RenderFrameHostImpl::SwapOut(
909 RenderFrameProxyHost* proxy,
910 bool is_loading) {
911 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
912 // the operation and sends back an IPC message.
913 // The trace event may not end properly if the ACK times out. We expect this
914 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
915 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
917 // If this RenderFrameHost is not in the default state, it must have already
918 // gone through this, therefore just return.
919 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
920 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
921 return;
924 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
925 swapout_event_monitor_timeout_->Start(
926 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
928 // There may be no proxy if there are no active views in the process.
929 int proxy_routing_id = MSG_ROUTING_NONE;
930 FrameReplicationState replication_state;
931 if (proxy) {
932 set_render_frame_proxy_host(proxy);
933 proxy_routing_id = proxy->GetRoutingID();
934 replication_state = proxy->frame_tree_node()->current_replication_state();
937 if (IsRenderFrameLive()) {
938 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
939 replication_state));
942 if (!GetParent())
943 delegate_->SwappedOut(this);
946 void RenderFrameHostImpl::OnBeforeUnloadACK(
947 bool proceed,
948 const base::TimeTicks& renderer_before_unload_start_time,
949 const base::TimeTicks& renderer_before_unload_end_time) {
950 TRACE_EVENT_ASYNC_END0(
951 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
952 DCHECK(!GetParent());
953 // If this renderer navigated while the beforeunload request was in flight, we
954 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
955 // can ignore this message.
956 // However renderer might also be swapped out but we still want to proceed
957 // with navigation, otherwise it would block future navigations. This can
958 // happen when pending cross-site navigation is canceled by a second one just
959 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
960 // but second navigation is started from the beginning.
961 if (!is_waiting_for_beforeunload_ack_) {
962 return;
964 DCHECK(!send_before_unload_start_time_.is_null());
966 // Sets a default value for before_unload_end_time so that the browser
967 // survives a hacked renderer.
968 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
969 if (!renderer_before_unload_start_time.is_null() &&
970 !renderer_before_unload_end_time.is_null()) {
971 // When passing TimeTicks across process boundaries, we need to compensate
972 // for any skew between the processes. Here we are converting the
973 // renderer's notion of before_unload_end_time to TimeTicks in the browser
974 // process. See comments in inter_process_time_ticks_converter.h for more.
975 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
976 InterProcessTimeTicksConverter converter(
977 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
978 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
979 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
980 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
981 LocalTimeTicks browser_before_unload_end_time =
982 converter.ToLocalTimeTicks(
983 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
984 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
986 // Collect UMA on the inter-process skew.
987 bool is_skew_additive = false;
988 if (converter.IsSkewAdditiveForMetrics()) {
989 is_skew_additive = true;
990 base::TimeDelta skew = converter.GetSkewForMetrics();
991 if (skew >= base::TimeDelta()) {
992 UMA_HISTOGRAM_TIMES(
993 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
994 } else {
995 UMA_HISTOGRAM_TIMES(
996 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
999 UMA_HISTOGRAM_BOOLEAN(
1000 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
1001 is_skew_additive);
1003 base::TimeDelta on_before_unload_overhead_time =
1004 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1005 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1006 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1007 on_before_unload_overhead_time);
1009 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1010 renderer_before_unload_start_time, renderer_before_unload_end_time);
1012 // Resets beforeunload waiting state.
1013 is_waiting_for_beforeunload_ack_ = false;
1014 render_view_host_->decrement_in_flight_event_count();
1015 render_view_host_->StopHangMonitorTimeout();
1016 send_before_unload_start_time_ = base::TimeTicks();
1018 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1019 switches::kEnableBrowserSideNavigation)) {
1020 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1021 // Navigator.
1022 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1023 frame_tree_node_, proceed);
1024 } else {
1025 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1026 unload_ack_is_for_navigation_, proceed,
1027 before_unload_end_time);
1030 // If canceled, notify the delegate to cancel its pending navigation entry.
1031 if (!proceed)
1032 render_view_host_->GetDelegate()->DidCancelLoading();
1035 bool RenderFrameHostImpl::IsWaitingForBeforeUnloadACK() const {
1036 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1037 switches::kEnableBrowserSideNavigation)) {
1038 return is_waiting_for_beforeunload_ack_;
1040 return frame_tree_node_->navigator()->IsWaitingForBeforeUnloadACK(
1041 frame_tree_node_);
1044 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1045 return render_view_host_->is_waiting_for_close_ack_ ||
1046 rfh_state_ == STATE_PENDING_SWAP_OUT;
1049 void RenderFrameHostImpl::OnSwapOutACK() {
1050 OnSwappedOut();
1053 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1054 if (frame_tree_node_->IsMainFrame()) {
1055 // Keep the termination status so we can get at it later when we
1056 // need to know why it died.
1057 render_view_host_->render_view_termination_status_ =
1058 static_cast<base::TerminationStatus>(status);
1061 // Reset frame tree state associated with this process. This must happen
1062 // before RenderViewTerminated because observers expect the subframes of any
1063 // affected frames to be cleared first.
1064 // Note: When a RenderFrameHost is swapped out there is a different one
1065 // which is the current host. In this case, the FrameTreeNode state must
1066 // not be reset.
1067 if (!is_swapped_out())
1068 frame_tree_node_->ResetForNewProcess();
1070 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1071 // reset.
1072 SetRenderFrameCreated(false);
1073 InvalidateMojoConnection();
1075 if (frame_tree_node_->IsMainFrame()) {
1076 // RenderViewHost/RenderWidgetHost needs to reset some stuff.
1077 render_view_host_->RendererExited(
1078 render_view_host_->render_view_termination_status_, exit_code);
1080 render_view_host_->delegate_->RenderViewTerminated(
1081 render_view_host_, static_cast<base::TerminationStatus>(status),
1082 exit_code);
1086 void RenderFrameHostImpl::OnSwappedOut() {
1087 // Ignore spurious swap out ack.
1088 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1089 return;
1091 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1092 swapout_event_monitor_timeout_->Stop();
1094 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1095 // We are now deleted.
1096 return;
1099 // If this RFH wasn't pending deletion, then it is now swapped out.
1100 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1103 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1104 // Validate the URLs in |params|. If the renderer can't request the URLs
1105 // directly, don't show them in the context menu.
1106 ContextMenuParams validated_params(params);
1107 RenderProcessHost* process = GetProcess();
1109 // We don't validate |unfiltered_link_url| so that this field can be used
1110 // when users want to copy the original link URL.
1111 process->FilterURL(true, &validated_params.link_url);
1112 process->FilterURL(true, &validated_params.src_url);
1113 process->FilterURL(false, &validated_params.page_url);
1114 process->FilterURL(true, &validated_params.frame_url);
1116 delegate_->ShowContextMenu(this, validated_params);
1119 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1120 int id, const base::ListValue& result) {
1121 const base::Value* result_value;
1122 if (!result.Get(0, &result_value)) {
1123 // Programming error or rogue renderer.
1124 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1125 return;
1128 std::map<int, JavaScriptResultCallback>::iterator it =
1129 javascript_callbacks_.find(id);
1130 if (it != javascript_callbacks_.end()) {
1131 it->second.Run(result_value);
1132 javascript_callbacks_.erase(it);
1133 } else {
1134 NOTREACHED() << "Received script response for unknown request";
1138 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1139 auto it = visual_state_callbacks_.find(id);
1140 if (it != visual_state_callbacks_.end()) {
1141 it->second.Run(true);
1142 visual_state_callbacks_.erase(it);
1143 } else {
1144 NOTREACHED() << "Received script response for unknown request";
1148 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1149 const base::string16& message,
1150 const base::string16& default_prompt,
1151 const GURL& frame_url,
1152 JavaScriptMessageType type,
1153 IPC::Message* reply_msg) {
1154 // While a JS message dialog is showing, tabs in the same process shouldn't
1155 // process input events.
1156 GetProcess()->SetIgnoreInputEvents(true);
1157 render_view_host_->StopHangMonitorTimeout();
1158 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1159 frame_url, type, reply_msg);
1162 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1163 const GURL& frame_url,
1164 const base::string16& message,
1165 bool is_reload,
1166 IPC::Message* reply_msg) {
1167 // While a JS beforeunload dialog is showing, tabs in the same process
1168 // shouldn't process input events.
1169 GetProcess()->SetIgnoreInputEvents(true);
1170 render_view_host_->StopHangMonitorTimeout();
1171 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1174 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1175 const base::string16& content,
1176 size_t start_offset,
1177 size_t end_offset) {
1178 render_view_host_->OnTextSurroundingSelectionResponse(
1179 content, start_offset, end_offset);
1182 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1183 delegate_->DidAccessInitialDocument();
1186 void RenderFrameHostImpl::OnDidDisownOpener() {
1187 // This message is only sent for top-level frames. TODO(avi): when frame tree
1188 // mirroring works correctly, add a check here to enforce it.
1189 delegate_->DidDisownOpener(this);
1192 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1193 frame_tree_node()->SetFrameName(name);
1194 delegate_->DidChangeName(this, name);
1197 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1198 // Update the RVH's current page ID so that future IPCs from the renderer
1199 // correspond to the new page.
1200 render_view_host_->page_id_ = page_id;
1203 void RenderFrameHostImpl::OnDidChangeSandboxFlags(int32 frame_routing_id,
1204 SandboxFlags flags) {
1205 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1206 FrameTreeNode* child =
1207 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1208 if (!child)
1209 return;
1211 // Ensure that a frame can only update sandbox flags for its immediate
1212 // children. If this is not the case, the renderer is considered malicious
1213 // and is killed.
1214 if (child->parent() != frame_tree_node()) {
1215 bad_message::ReceivedBadMessage(GetProcess(),
1216 bad_message::RFH_SANDBOX_FLAGS);
1217 return;
1220 child->set_sandbox_flags(flags);
1222 // Notify the RenderFrame if it lives in a different process from its
1223 // parent. The frame's proxies in other processes also need to learn about
1224 // the updated sandbox flags, but these notifications are sent later in
1225 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1226 // navigates and the new sandbox flags take effect.
1227 RenderFrameHost* child_rfh = child->current_frame_host();
1228 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1229 child_rfh->Send(
1230 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1234 void RenderFrameHostImpl::OnUpdateTitle(
1235 const base::string16& title,
1236 blink::WebTextDirection title_direction) {
1237 // This message is only sent for top-level frames. TODO(avi): when frame tree
1238 // mirroring works correctly, add a check here to enforce it.
1239 if (title.length() > kMaxTitleChars) {
1240 NOTREACHED() << "Renderer sent too many characters in title.";
1241 return;
1244 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1245 WebTextDirectionToChromeTextDirection(
1246 title_direction));
1249 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1250 // This message is only sent for top-level frames. TODO(avi): when frame tree
1251 // mirroring works correctly, add a check here to enforce it.
1252 delegate_->UpdateEncoding(this, encoding_name);
1255 void RenderFrameHostImpl::OnBeginNavigation(
1256 const CommonNavigationParams& common_params,
1257 const BeginNavigationParams& begin_params,
1258 scoped_refptr<ResourceRequestBody> body) {
1259 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1260 switches::kEnableBrowserSideNavigation));
1261 frame_tree_node()->navigator()->OnBeginNavigation(
1262 frame_tree_node(), common_params, begin_params, body);
1265 void RenderFrameHostImpl::OnDispatchLoad() {
1266 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1267 switches::kSitePerProcess));
1268 // Only frames with an out-of-process parent frame should be sending this
1269 // message.
1270 RenderFrameProxyHost* proxy =
1271 frame_tree_node()->render_manager()->GetProxyToParent();
1272 if (!proxy) {
1273 bad_message::ReceivedBadMessage(GetProcess(),
1274 bad_message::RFH_NO_PROXY_TO_PARENT);
1275 return;
1278 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1281 void RenderFrameHostImpl::OnAccessibilityEvents(
1282 const std::vector<AccessibilityHostMsg_EventParams>& params,
1283 int reset_token) {
1284 // Don't process this IPC if either we're waiting on a reset and this
1285 // IPC doesn't have the matching token ID, or if we're not waiting on a
1286 // reset but this message includes a reset token.
1287 if (accessibility_reset_token_ != reset_token) {
1288 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1289 return;
1291 accessibility_reset_token_ = 0;
1293 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1294 render_view_host_->GetView());
1296 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1297 if ((accessibility_mode != AccessibilityModeOff) && view &&
1298 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1299 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1300 GetOrCreateBrowserAccessibilityManager();
1301 if (browser_accessibility_manager_)
1302 browser_accessibility_manager_->OnAccessibilityEvents(params);
1305 if (browser_accessibility_manager_) {
1306 // Get the frame routing ids from out-of-process iframes and
1307 // browser plugin instance ids from guests and update the mappings in
1308 // FrameAccessibility.
1309 for (size_t i = 0; i < params.size(); ++i) {
1310 const AccessibilityHostMsg_EventParams& param = params[i];
1311 UpdateCrossProcessIframeAccessibility(
1312 param.node_to_frame_routing_id_map);
1313 UpdateGuestFrameAccessibility(
1314 param.node_to_browser_plugin_instance_id_map);
1318 // Send the updates to the automation extension API.
1319 std::vector<AXEventNotificationDetails> details;
1320 details.reserve(params.size());
1321 for (size_t i = 0; i < params.size(); ++i) {
1322 const AccessibilityHostMsg_EventParams& param = params[i];
1323 AXEventNotificationDetails detail(param.update.node_id_to_clear,
1324 param.update.nodes,
1325 param.event_type,
1326 param.id,
1327 GetProcess()->GetID(),
1328 routing_id_);
1329 details.push_back(detail);
1332 delegate_->AccessibilityEventReceived(details);
1335 // Always send an ACK or the renderer can be in a bad state.
1336 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1338 // The rest of this code is just for testing; bail out if we're not
1339 // in that mode.
1340 if (accessibility_testing_callback_.is_null())
1341 return;
1343 for (size_t i = 0; i < params.size(); i++) {
1344 const AccessibilityHostMsg_EventParams& param = params[i];
1345 if (static_cast<int>(param.event_type) < 0)
1346 continue;
1348 if (!ax_tree_for_testing_) {
1349 if (browser_accessibility_manager_) {
1350 ax_tree_for_testing_.reset(new ui::AXTree(
1351 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1352 } else {
1353 ax_tree_for_testing_.reset(new ui::AXTree());
1354 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1355 << ax_tree_for_testing_->error();
1357 } else {
1358 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1359 << ax_tree_for_testing_->error();
1361 accessibility_testing_callback_.Run(param.event_type, param.id);
1365 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1366 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1367 if (accessibility_reset_token_)
1368 return;
1370 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1371 render_view_host_->GetView());
1372 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1373 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1374 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1375 BrowserAccessibilityManager* manager =
1376 GetOrCreateBrowserAccessibilityManager();
1377 if (manager)
1378 manager->OnLocationChanges(params);
1380 // TODO(aboxhall): send location change events to web contents observers too
1384 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1385 const AccessibilityHostMsg_FindInPageResultParams& params) {
1386 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1387 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1388 BrowserAccessibilityManager* manager =
1389 GetOrCreateBrowserAccessibilityManager();
1390 if (manager) {
1391 manager->OnFindInPageResult(
1392 params.request_id, params.match_index, params.start_id,
1393 params.start_offset, params.end_id, params.end_offset);
1398 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1399 if (enter_fullscreen)
1400 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1401 else
1402 delegate_->ExitFullscreenMode();
1404 // The previous call might change the fullscreen state. We need to make sure
1405 // the renderer is aware of that, which is done via the resize message.
1406 render_view_host_->WasResized();
1409 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1410 void RenderFrameHostImpl::OnShowPopup(
1411 const FrameHostMsg_ShowPopup_Params& params) {
1412 RenderViewHostDelegateView* view =
1413 render_view_host_->delegate_->GetDelegateView();
1414 if (view) {
1415 view->ShowPopupMenu(this,
1416 params.bounds,
1417 params.item_height,
1418 params.item_font_size,
1419 params.selected_item,
1420 params.popup_items,
1421 params.right_aligned,
1422 params.allow_multiple_selection);
1426 void RenderFrameHostImpl::OnHidePopup() {
1427 RenderViewHostDelegateView* view =
1428 render_view_host_->delegate_->GetDelegateView();
1429 if (view)
1430 view->HidePopupMenu();
1432 #endif
1434 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1435 static void CreateMediaRendererService(
1436 mojo::InterfaceRequest<mojo::MediaRenderer> request) {
1437 media::MojoRendererService* service = new media::MojoRendererService();
1438 mojo::BindToRequest(service, &request);
1440 #endif
1442 void RenderFrameHostImpl::RegisterMojoServices() {
1443 GeolocationServiceContext* geolocation_service_context =
1444 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1445 if (geolocation_service_context) {
1446 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1447 // can perform permissions checks once site isolation is complete.
1448 // crbug.com/426384
1449 GetServiceRegistry()->AddService<GeolocationService>(
1450 base::Bind(&GeolocationServiceContext::CreateService,
1451 base::Unretained(geolocation_service_context),
1452 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1453 base::Unretained(this))));
1456 if (!permission_service_context_)
1457 permission_service_context_.reset(new PermissionServiceContext(this));
1459 GetServiceRegistry()->AddService<PermissionService>(
1460 base::Bind(&PermissionServiceContext::CreateService,
1461 base::Unretained(permission_service_context_.get())));
1463 GetServiceRegistry()->AddService<presentation::PresentationService>(
1464 base::Bind(&PresentationServiceImpl::CreateMojoService,
1465 base::Unretained(this)));
1467 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1468 GetServiceRegistry()->AddService<mojo::MediaRenderer>(
1469 base::Bind(&CreateMediaRendererService));
1470 #endif
1473 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1474 // Only main frames should be swapped out and retained inside a proxy host.
1475 if (rfh_state == STATE_SWAPPED_OUT)
1476 CHECK(!GetParent());
1478 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1479 // out status of a RenderFrameHost gets flipped to/from active.
1480 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1481 GetSiteInstance()->increment_active_frame_count();
1482 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1483 GetSiteInstance()->decrement_active_frame_count();
1485 // The active and swapped out state of the RVH is determined by its main
1486 // frame, since subframes should have their own widgets.
1487 if (frame_tree_node_->IsMainFrame()) {
1488 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1489 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1492 // Whenever we change the RFH state to and from active or swapped out state,
1493 // we should not be waiting for beforeunload or close acks. We clear them
1494 // here to be safe, since they can cause navigations to be ignored in
1495 // OnDidCommitProvisionalLoad.
1496 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1497 if (rfh_state == STATE_DEFAULT ||
1498 rfh_state == STATE_SWAPPED_OUT ||
1499 rfh_state_ == STATE_DEFAULT ||
1500 rfh_state_ == STATE_SWAPPED_OUT) {
1501 if (is_waiting_for_beforeunload_ack_) {
1502 is_waiting_for_beforeunload_ack_ = false;
1503 render_view_host_->decrement_in_flight_event_count();
1504 render_view_host_->StopHangMonitorTimeout();
1506 send_before_unload_start_time_ = base::TimeTicks();
1507 render_view_host_->is_waiting_for_close_ack_ = false;
1509 rfh_state_ = rfh_state;
1512 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1513 // TODO(creis): We should also check for WebUI pages here. Also, when the
1514 // out-of-process iframes implementation is ready, we should check for
1515 // cross-site URLs that are not allowed to commit in this process.
1517 // Give the client a chance to disallow URLs from committing.
1518 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1521 void RenderFrameHostImpl::Navigate(
1522 const CommonNavigationParams& common_params,
1523 const StartNavigationParams& start_params,
1524 const RequestNavigationParams& request_params) {
1525 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1526 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
1527 // so do not grant them the ability to request additional URLs.
1528 if (!GetProcess()->IsIsolatedGuest()) {
1529 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1530 GetProcess()->GetID(), common_params.url);
1531 if (common_params.url.SchemeIs(url::kDataScheme) &&
1532 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
1533 // If 'data:' is used, and we have a 'file:' base url, grant access to
1534 // local files.
1535 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1536 GetProcess()->GetID(), common_params.base_url_for_data_url);
1540 // We may be returning to an existing NavigationEntry that had been granted
1541 // file access. If this is a different process, we will need to grant the
1542 // access again. The files listed in the page state are validated when they
1543 // are received from the renderer to prevent abuse.
1544 if (request_params.page_state.IsValid()) {
1545 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
1548 // Only send the message if we aren't suspended at the start of a cross-site
1549 // request.
1550 if (navigations_suspended_) {
1551 // Shouldn't be possible to have a second navigation while suspended, since
1552 // navigations will only be suspended during a cross-site request. If a
1553 // second navigation occurs, RenderFrameHostManager will cancel this pending
1554 // RFH and create a new pending RFH.
1555 DCHECK(!suspended_nav_params_.get());
1556 suspended_nav_params_.reset(
1557 new NavigationParams(common_params, start_params, request_params));
1558 } else {
1559 // Get back to a clean state, in case we start a new navigation without
1560 // completing a RFH swap or unload handler.
1561 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1563 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1564 request_params));
1567 // Force the throbber to start. We do this because Blink's "started
1568 // loading" message will be received asynchronously from the UI of the
1569 // browser. But we want to keep the throbber in sync with what's happening
1570 // in the UI. For example, we want to start throbbing immediately when the
1571 // user navigates even if the renderer is delayed. There is also an issue
1572 // with the throbber starting because the WebUI (which controls whether the
1573 // favicon is displayed) happens synchronously. If the start loading
1574 // messages was asynchronous, then the default favicon would flash in.
1576 // Blink doesn't send throb notifications for JavaScript URLs, so we
1577 // don't want to either.
1578 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1579 delegate_->DidStartLoading(this, true);
1582 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1583 CommonNavigationParams common_params(
1584 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::NORMAL,
1585 true, base::TimeTicks::Now(), FrameMsg_UILoadMetricsReportType::NO_REPORT,
1586 GURL(), GURL());
1587 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1590 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1591 SiteInstance* source_site_instance) {
1592 GURL validated_url(params.url);
1593 GetProcess()->FilterURL(false, &validated_url);
1595 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1596 validated_url.possibly_invalid_spec());
1597 frame_tree_node_->navigator()->RequestOpenURL(
1598 this, validated_url, source_site_instance, params.referrer,
1599 params.disposition, params.should_replace_current_entry,
1600 params.user_gesture);
1603 void RenderFrameHostImpl::Stop() {
1604 Send(new FrameMsg_Stop(routing_id_));
1607 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1608 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1609 // the handler ran and allowed the navigation to proceed.
1610 if (GetParent() || !IsRenderFrameLive()) {
1611 // We don't have a live renderer, so just skip running beforeunload.
1612 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1613 switches::kEnableBrowserSideNavigation)) {
1614 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1615 frame_tree_node_, true);
1616 } else {
1617 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1618 for_navigation, true, base::TimeTicks::Now());
1620 return;
1622 TRACE_EVENT_ASYNC_BEGIN0(
1623 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1625 // This may be called more than once (if the user clicks the tab close button
1626 // several times, or if she clicks the tab close button then the browser close
1627 // button), and we only send the message once.
1628 if (is_waiting_for_beforeunload_ack_) {
1629 // Some of our close messages could be for the tab, others for cross-site
1630 // transitions. We always want to think it's for closing the tab if any
1631 // of the messages were, since otherwise it might be impossible to close
1632 // (if there was a cross-site "close" request pending when the user clicked
1633 // the close button). We want to keep the "for cross site" flag only if
1634 // both the old and the new ones are also for cross site.
1635 unload_ack_is_for_navigation_ =
1636 unload_ack_is_for_navigation_ && for_navigation;
1637 } else {
1638 // Start the hang monitor in case the renderer hangs in the beforeunload
1639 // handler.
1640 is_waiting_for_beforeunload_ack_ = true;
1641 unload_ack_is_for_navigation_ = for_navigation;
1642 // Increment the in-flight event count, to ensure that input events won't
1643 // cancel the timeout timer.
1644 render_view_host_->increment_in_flight_event_count();
1645 render_view_host_->StartHangMonitorTimeout(
1646 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1647 send_before_unload_start_time_ = base::TimeTicks::Now();
1648 Send(new FrameMsg_BeforeUnload(routing_id_));
1652 void RenderFrameHostImpl::DisownOpener() {
1653 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1656 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1657 size_t after) {
1658 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1661 void RenderFrameHostImpl::JavaScriptDialogClosed(
1662 IPC::Message* reply_msg,
1663 bool success,
1664 const base::string16& user_input,
1665 bool dialog_was_suppressed) {
1666 GetProcess()->SetIgnoreInputEvents(false);
1667 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1669 // If we are executing as part of (before)unload event handling, we don't
1670 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1671 // leave the current page. In this case, use the regular timeout value used
1672 // during the (before)unload handling.
1673 if (is_waiting) {
1674 render_view_host_->StartHangMonitorTimeout(
1675 success
1676 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1677 : render_view_host_->hung_renderer_delay_);
1680 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1681 success, user_input);
1682 Send(reply_msg);
1684 // If we are waiting for an unload or beforeunload ack and the user has
1685 // suppressed messages, kill the tab immediately; a page that's spamming
1686 // alerts in onbeforeunload is presumably malicious, so there's no point in
1687 // continuing to run its script and dragging out the process.
1688 // This must be done after sending the reply since RenderView can't close
1689 // correctly while waiting for a response.
1690 if (is_waiting && dialog_was_suppressed)
1691 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1694 // PlzNavigate
1695 void RenderFrameHostImpl::CommitNavigation(
1696 ResourceResponse* response,
1697 scoped_ptr<StreamHandle> body,
1698 const CommonNavigationParams& common_params,
1699 const RequestNavigationParams& request_params) {
1700 DCHECK((response && body.get()) ||
1701 !NavigationRequest::ShouldMakeNetworkRequest(common_params.url));
1702 // TODO(clamy): Check if we have to add security checks for the browser plugin
1703 // guests.
1705 // Get back to a clean state, in case we start a new navigation without
1706 // completing a RFH swap or unload handler.
1707 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1709 const GURL body_url = body.get() ? body->GetURL() : GURL();
1710 const ResourceResponseHead head = response ?
1711 response->head : ResourceResponseHead();
1712 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1713 request_params));
1714 // TODO(clamy): Check if we should start the throbber for non javascript urls
1715 // here.
1717 // TODO(clamy): Release the stream handle once the renderer has finished
1718 // reading it.
1719 stream_handle_ = body.Pass();
1722 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1723 if (service_registry_.get())
1724 return;
1726 service_registry_.reset(new ServiceRegistryImpl());
1727 if (!GetProcess()->GetServiceRegistry())
1728 return;
1730 RegisterMojoServices();
1731 RenderFrameSetupPtr setup;
1732 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(&setup);
1734 mojo::ServiceProviderPtr exposed_services;
1735 service_registry_->Bind(GetProxy(&exposed_services));
1737 mojo::ServiceProviderPtr services;
1738 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1739 exposed_services.Pass());
1740 service_registry_->BindRemoteServiceProvider(services.Pass());
1742 #if defined(OS_ANDROID)
1743 service_registry_android_.reset(
1744 new ServiceRegistryAndroid(service_registry_.get()));
1745 #endif
1748 void RenderFrameHostImpl::InvalidateMojoConnection() {
1749 #if defined(OS_ANDROID)
1750 // The Android-specific service registry has a reference to
1751 // |service_registry_| and thus must be torn down first.
1752 service_registry_android_.reset();
1753 #endif
1755 service_registry_.reset();
1758 bool RenderFrameHostImpl::IsFocused() {
1759 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1760 // returning nullptr in some cases. See https://crbug.com/455245.
1761 return RenderWidgetHostImpl::From(
1762 GetView()->GetRenderWidgetHost())->is_focused() &&
1763 frame_tree_->GetFocusedFrame() &&
1764 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1765 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1768 void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility(
1769 const std::map<int32, int>& node_to_frame_routing_id_map) {
1770 for (const auto& iter : node_to_frame_routing_id_map) {
1771 // This is the id of the accessibility node that has a child frame.
1772 int32 node_id = iter.first;
1773 // The routing id from either a RenderFrame or a RenderFrameProxy.
1774 int frame_routing_id = iter.second;
1776 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1777 FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID(
1778 GetProcess()->GetID(), frame_routing_id);
1780 if (child_frame_tree_node) {
1781 FrameAccessibility::GetInstance()->AddChildFrame(
1782 this, node_id, child_frame_tree_node->frame_tree_node_id());
1787 void RenderFrameHostImpl::UpdateGuestFrameAccessibility(
1788 const std::map<int32, int>& node_to_browser_plugin_instance_id_map) {
1789 for (const auto& iter : node_to_browser_plugin_instance_id_map) {
1790 // This is the id of the accessibility node that hosts a plugin.
1791 int32 node_id = iter.first;
1792 // The id of the browser plugin.
1793 int browser_plugin_instance_id = iter.second;
1794 FrameAccessibility::GetInstance()->AddGuestWebContents(
1795 this, node_id, browser_plugin_instance_id);
1799 bool RenderFrameHostImpl::IsSameSiteInstance(
1800 RenderFrameHostImpl* other_render_frame_host) {
1801 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1802 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1803 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1804 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1807 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1808 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1811 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1812 const base::Callback<void(ui::AXEvent, int)>& callback) {
1813 accessibility_testing_callback_ = callback;
1816 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1817 return ax_tree_for_testing_.get();
1820 BrowserAccessibilityManager*
1821 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1822 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1823 render_view_host_->GetView());
1824 if (view &&
1825 !browser_accessibility_manager_ &&
1826 !no_create_browser_accessibility_manager_for_testing_) {
1827 browser_accessibility_manager_.reset(
1828 view->CreateBrowserAccessibilityManager(this));
1829 if (browser_accessibility_manager_)
1830 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
1831 else
1832 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
1834 return browser_accessibility_manager_.get();
1837 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
1838 int request_id) {
1839 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1840 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1841 BrowserAccessibilityManager* manager =
1842 GetOrCreateBrowserAccessibilityManager();
1843 if (manager)
1844 manager->ActivateFindInPageResult(request_id);
1848 void RenderFrameHostImpl::InsertVisualStateCallback(
1849 const VisualStateCallback& callback) {
1850 static uint64 next_id = 1;
1851 uint64 key = next_id++;
1852 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
1853 visual_state_callbacks_.insert(std::make_pair(key, callback));
1856 #if defined(OS_WIN)
1858 void RenderFrameHostImpl::SetParentNativeViewAccessible(
1859 gfx::NativeViewAccessible accessible_parent) {
1860 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1861 render_view_host_->GetView());
1862 if (view)
1863 view->SetParentNativeViewAccessible(accessible_parent);
1866 gfx::NativeViewAccessible
1867 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
1868 return delegate_->GetParentNativeViewAccessible();
1871 #elif defined(OS_MACOSX)
1873 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
1874 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
1877 void RenderFrameHostImpl::DidCancelPopupMenu() {
1878 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
1881 #elif defined(OS_ANDROID)
1883 void RenderFrameHostImpl::DidSelectPopupMenuItems(
1884 const std::vector<int>& selected_indices) {
1885 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
1888 void RenderFrameHostImpl::DidCancelPopupMenu() {
1889 Send(new FrameMsg_SelectPopupMenuItems(
1890 routing_id_, true, std::vector<int>()));
1893 #endif
1895 void RenderFrameHostImpl::ClearPendingTransitionRequestData() {
1896 BrowserThread::PostTask(
1897 BrowserThread::IO,
1898 FROM_HERE,
1899 base::Bind(
1900 &TransitionRequestManager::ClearPendingTransitionRequestData,
1901 base::Unretained(TransitionRequestManager::GetInstance()),
1902 GetProcess()->GetID(),
1903 routing_id_));
1906 void RenderFrameHostImpl::SetNavigationsSuspended(
1907 bool suspend,
1908 const base::TimeTicks& proceed_time) {
1909 // This should only be called to toggle the state.
1910 DCHECK(navigations_suspended_ != suspend);
1912 navigations_suspended_ = suspend;
1913 if (navigations_suspended_) {
1914 TRACE_EVENT_ASYNC_BEGIN0("navigation",
1915 "RenderFrameHostImpl navigation suspended", this);
1916 } else {
1917 TRACE_EVENT_ASYNC_END0("navigation",
1918 "RenderFrameHostImpl navigation suspended", this);
1921 if (!suspend && suspended_nav_params_) {
1922 // There's navigation message params waiting to be sent. Now that we're not
1923 // suspended anymore, resume navigation by sending them. If we were swapped
1924 // out, we should also stop filtering out the IPC messages now.
1925 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1927 DCHECK(!proceed_time.is_null());
1928 suspended_nav_params_->request_params.browser_navigation_start =
1929 proceed_time;
1930 Send(new FrameMsg_Navigate(routing_id_,
1931 suspended_nav_params_->common_params,
1932 suspended_nav_params_->start_params,
1933 suspended_nav_params_->request_params));
1934 suspended_nav_params_.reset();
1938 void RenderFrameHostImpl::CancelSuspendedNavigations() {
1939 // Clear any state if a pending navigation is canceled or preempted.
1940 if (suspended_nav_params_)
1941 suspended_nav_params_.reset();
1943 TRACE_EVENT_ASYNC_END0("navigation",
1944 "RenderFrameHostImpl navigation suspended", this);
1945 navigations_suspended_ = false;
1948 void RenderFrameHostImpl::DidUseGeolocationPermission() {
1949 RenderFrameHost* top_frame = frame_tree_node()->frame_tree()->GetMainFrame();
1950 GetContentClient()->browser()->RegisterPermissionUsage(
1951 PERMISSION_GEOLOCATION,
1952 delegate_->GetAsWebContents(),
1953 GetLastCommittedURL().GetOrigin(),
1954 top_frame->GetLastCommittedURL().GetOrigin());
1957 } // namespace content