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