Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
bloba25fc594cd3861f74bc23bc863bab09ffe8255a5
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/render_frame_host_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/containers/hash_tables.h"
10 #include "base/lazy_instance.h"
11 #include "base/metrics/histogram.h"
12 #include "base/process/kill.h"
13 #include "base/time/time.h"
14 #include "content/browser/accessibility/accessibility_mode_helper.h"
15 #include "content/browser/accessibility/ax_tree_id_registry.h"
16 #include "content/browser/accessibility/browser_accessibility_manager.h"
17 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
18 #include "content/browser/bad_message.h"
19 #include "content/browser/child_process_security_policy_impl.h"
20 #include "content/browser/frame_host/cross_process_frame_connector.h"
21 #include "content/browser/frame_host/cross_site_transferring_request.h"
22 #include "content/browser/frame_host/frame_mojo_shell.h"
23 #include "content/browser/frame_host/frame_tree.h"
24 #include "content/browser/frame_host/frame_tree_node.h"
25 #include "content/browser/frame_host/navigation_handle_impl.h"
26 #include "content/browser/frame_host/navigation_request.h"
27 #include "content/browser/frame_host/navigator.h"
28 #include "content/browser/frame_host/navigator_impl.h"
29 #include "content/browser/frame_host/render_frame_host_delegate.h"
30 #include "content/browser/frame_host/render_frame_proxy_host.h"
31 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
32 #include "content/browser/geolocation/geolocation_service_context.h"
33 #include "content/browser/permissions/permission_service_context.h"
34 #include "content/browser/permissions/permission_service_impl.h"
35 #include "content/browser/presentation/presentation_service_impl.h"
36 #include "content/browser/renderer_host/input/input_router.h"
37 #include "content/browser/renderer_host/input/timeout_monitor.h"
38 #include "content/browser/renderer_host/render_process_host_impl.h"
39 #include "content/browser/renderer_host/render_view_host_delegate.h"
40 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
41 #include "content/browser/renderer_host/render_view_host_impl.h"
42 #include "content/browser/renderer_host/render_widget_host_impl.h"
43 #include "content/browser/renderer_host/render_widget_host_view_base.h"
44 #include "content/common/accessibility_messages.h"
45 #include "content/common/frame_messages.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/inter_process_time_ticks_converter.h"
48 #include "content/common/navigation_params.h"
49 #include "content/common/render_frame_setup.mojom.h"
50 #include "content/common/site_isolation_policy.h"
51 #include "content/common/swapped_out_messages.h"
52 #include "content/public/browser/ax_event_notification_details.h"
53 #include "content/public/browser/browser_accessibility_state.h"
54 #include "content/public/browser/browser_context.h"
55 #include "content/public/browser/browser_plugin_guest_manager.h"
56 #include "content/public/browser/browser_thread.h"
57 #include "content/public/browser/content_browser_client.h"
58 #include "content/public/browser/permission_manager.h"
59 #include "content/public/browser/permission_type.h"
60 #include "content/public/browser/render_process_host.h"
61 #include "content/public/browser/render_widget_host_view.h"
62 #include "content/public/browser/stream_handle.h"
63 #include "content/public/browser/user_metrics.h"
64 #include "content/public/common/content_constants.h"
65 #include "content/public/common/content_switches.h"
66 #include "content/public/common/isolated_world_ids.h"
67 #include "content/public/common/url_constants.h"
68 #include "content/public/common/url_utils.h"
69 #include "ui/accessibility/ax_tree.h"
70 #include "ui/accessibility/ax_tree_update.h"
71 #include "url/gurl.h"
73 #if defined(OS_ANDROID)
74 #include "content/browser/mojo/service_registrar_android.h"
75 #endif
77 #if defined(OS_MACOSX)
78 #include "content/browser/frame_host/popup_menu_helper_mac.h"
79 #endif
81 #if defined(ENABLE_WEBVR)
82 #include "content/browser/vr/vr_device_manager.h"
83 #endif
85 using base::TimeDelta;
87 namespace content {
89 namespace {
91 // The next value to use for the accessibility reset token.
92 int g_next_accessibility_reset_token = 1;
94 // The next value to use for the javascript callback id.
95 int g_next_javascript_callback_id = 1;
97 // Whether to allow injecting javascript into any kind of frame (for Android
98 // WebView).
99 bool g_allow_injecting_javascript = false;
101 // The (process id, routing id) pair that identifies one RenderFrame.
102 typedef std::pair<int32, int32> RenderFrameHostID;
103 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
104 RoutingIDFrameMap;
105 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
106 LAZY_INSTANCE_INITIALIZER;
108 // Translate a WebKit text direction into a base::i18n one.
109 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
110 blink::WebTextDirection dir) {
111 switch (dir) {
112 case blink::WebTextDirectionLeftToRight:
113 return base::i18n::LEFT_TO_RIGHT;
114 case blink::WebTextDirectionRightToLeft:
115 return base::i18n::RIGHT_TO_LEFT;
116 default:
117 NOTREACHED();
118 return base::i18n::UNKNOWN_DIRECTION;
122 } // namespace
124 // static
125 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
126 return rfh_state == STATE_DEFAULT;
129 // static
130 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
131 int render_frame_id) {
132 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
135 // static
136 void RenderFrameHost::AllowInjectingJavaScriptForAndroidWebView() {
137 g_allow_injecting_javascript = true;
140 // static
141 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
142 int routing_id) {
143 DCHECK_CURRENTLY_ON(BrowserThread::UI);
144 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
145 RoutingIDFrameMap::iterator it = frames->find(
146 RenderFrameHostID(process_id, routing_id));
147 return it == frames->end() ? NULL : it->second;
150 // static
151 RenderFrameHost* RenderFrameHost::FromAXTreeID(
152 int ax_tree_id) {
153 return RenderFrameHostImpl::FromAXTreeID(ax_tree_id);
156 // static
157 RenderFrameHostImpl* RenderFrameHostImpl::FromAXTreeID(
158 AXTreeIDRegistry::AXTreeID ax_tree_id) {
159 DCHECK_CURRENTLY_ON(BrowserThread::UI);
160 AXTreeIDRegistry::FrameID frame_id =
161 AXTreeIDRegistry::GetInstance()->GetFrameID(ax_tree_id);
162 return RenderFrameHostImpl::FromID(frame_id.first, frame_id.second);
165 RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
166 RenderViewHostImpl* render_view_host,
167 RenderFrameHostDelegate* delegate,
168 RenderWidgetHostDelegate* rwh_delegate,
169 FrameTree* frame_tree,
170 FrameTreeNode* frame_tree_node,
171 int routing_id,
172 int flags)
173 : render_view_host_(render_view_host),
174 delegate_(delegate),
175 site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
176 process_(site_instance->GetProcess()),
177 cross_process_frame_connector_(NULL),
178 render_frame_proxy_host_(NULL),
179 frame_tree_(frame_tree),
180 frame_tree_node_(frame_tree_node),
181 render_widget_host_(nullptr),
182 routing_id_(routing_id),
183 render_frame_created_(false),
184 navigations_suspended_(false),
185 is_waiting_for_beforeunload_ack_(false),
186 unload_ack_is_for_navigation_(false),
187 is_loading_(false),
188 pending_commit_(false),
189 accessibility_reset_token_(0),
190 accessibility_reset_count_(0),
191 no_create_browser_accessibility_manager_for_testing_(false),
192 weak_ptr_factory_(this) {
193 bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
194 bool hidden = !!(flags & CREATE_RF_HIDDEN);
195 frame_tree_->AddRenderViewHostRef(render_view_host_);
196 GetProcess()->AddRoute(routing_id_, this);
197 g_routing_id_frame_map.Get().insert(std::make_pair(
198 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
199 this));
201 if (is_swapped_out) {
202 rfh_state_ = STATE_SWAPPED_OUT;
203 } else {
204 rfh_state_ = STATE_DEFAULT;
205 GetSiteInstance()->increment_active_frame_count();
208 SetUpMojoIfNeeded();
209 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
210 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
212 if (flags & CREATE_RF_NEEDS_RENDER_WIDGET_HOST) {
213 render_widget_host_ = new RenderWidgetHostImpl(rwh_delegate, GetProcess(),
214 MSG_ROUTING_NONE, hidden);
215 render_widget_host_->set_owned_by_render_frame_host(true);
219 RenderFrameHostImpl::~RenderFrameHostImpl() {
220 GetProcess()->RemoveRoute(routing_id_);
221 g_routing_id_frame_map.Get().erase(
222 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
224 if (delegate_ && render_frame_created_)
225 delegate_->RenderFrameDeleted(this);
227 // If this was swapped out, it already decremented the active frame count of
228 // the SiteInstance it belongs to.
229 if (IsRFHStateActive(rfh_state_))
230 GetSiteInstance()->decrement_active_frame_count();
232 // Notify the FrameTree that this RFH is going away, allowing it to shut down
233 // the corresponding RenderViewHost if it is no longer needed.
234 frame_tree_->ReleaseRenderViewHostRef(render_view_host_);
236 // NULL out the swapout timer; in crash dumps this member will be null only if
237 // the dtor has run.
238 swapout_event_monitor_timeout_.reset();
240 for (const auto& iter: visual_state_callbacks_) {
241 iter.second.Run(false);
244 if (render_widget_host_) {
245 // Shutdown causes the RenderWidgetHost to delete itself.
246 render_widget_host_->Shutdown();
250 int RenderFrameHostImpl::GetRoutingID() {
251 return routing_id_;
254 AXTreeIDRegistry::AXTreeID RenderFrameHostImpl::GetAXTreeID() {
255 return AXTreeIDRegistry::GetInstance()->GetOrCreateAXTreeID(
256 GetProcess()->GetID(), routing_id_);
259 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
260 return site_instance_.get();
263 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
264 return process_;
267 RenderFrameHost* RenderFrameHostImpl::GetParent() {
268 FrameTreeNode* parent_node = frame_tree_node_->parent();
269 if (!parent_node)
270 return NULL;
271 return parent_node->current_frame_host();
274 const std::string& RenderFrameHostImpl::GetFrameName() {
275 return frame_tree_node_->frame_name();
278 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
279 FrameTreeNode* parent_node = frame_tree_node_->parent();
280 if (!parent_node)
281 return false;
282 return GetSiteInstance() !=
283 parent_node->current_frame_host()->GetSiteInstance();
286 GURL RenderFrameHostImpl::GetLastCommittedURL() {
287 return frame_tree_node_->current_url();
290 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
291 RenderWidgetHostView* view = render_view_host_->GetView();
292 if (!view)
293 return NULL;
294 return view->GetNativeView();
297 void RenderFrameHostImpl::AddMessageToConsole(ConsoleMessageLevel level,
298 const std::string& message) {
299 Send(new FrameMsg_AddMessageToConsole(routing_id_, level, message));
302 void RenderFrameHostImpl::ExecuteJavaScript(
303 const base::string16& javascript) {
304 CHECK(CanExecuteJavaScript());
305 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
306 javascript,
307 0, false));
310 void RenderFrameHostImpl::ExecuteJavaScript(
311 const base::string16& javascript,
312 const JavaScriptResultCallback& callback) {
313 CHECK(CanExecuteJavaScript());
314 int key = g_next_javascript_callback_id++;
315 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
316 javascript,
317 key, true));
318 javascript_callbacks_.insert(std::make_pair(key, callback));
321 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
322 const base::string16& javascript) {
323 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
324 javascript,
325 0, false, false));
328 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
329 const base::string16& javascript,
330 const JavaScriptResultCallback& callback) {
331 int key = g_next_javascript_callback_id++;
332 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_, javascript,
333 key, true, false));
334 javascript_callbacks_.insert(std::make_pair(key, callback));
338 void RenderFrameHostImpl::ExecuteJavaScriptWithUserGestureForTests(
339 const base::string16& javascript) {
340 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
341 javascript,
342 0, false, true));
345 void RenderFrameHostImpl::ExecuteJavaScriptInIsolatedWorld(
346 const base::string16& javascript,
347 const JavaScriptResultCallback& callback,
348 int world_id) {
349 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
350 world_id > ISOLATED_WORLD_ID_MAX) {
351 // Return if the world_id is not valid.
352 NOTREACHED();
353 return;
356 int key = 0;
357 bool request_reply = false;
358 if (!callback.is_null()) {
359 request_reply = true;
360 key = g_next_javascript_callback_id++;
361 javascript_callbacks_.insert(std::make_pair(key, callback));
364 Send(new FrameMsg_JavaScriptExecuteRequestInIsolatedWorld(
365 routing_id_, javascript, key, request_reply, world_id));
368 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
369 return render_view_host_;
372 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
373 return service_registry_.get();
376 blink::WebPageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
377 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
378 // returning nullptr in some cases. See https://crbug.com/455245.
379 blink::WebPageVisibilityState visibility_state =
380 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())->is_hidden()
381 ? blink::WebPageVisibilityStateHidden
382 : blink::WebPageVisibilityStateVisible;
383 GetContentClient()->browser()->OverridePageVisibilityState(this,
384 &visibility_state);
385 return visibility_state;
388 bool RenderFrameHostImpl::Send(IPC::Message* message) {
389 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
390 return render_view_host_->input_router()->SendInput(
391 make_scoped_ptr(message));
394 return GetProcess()->Send(message);
397 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
398 // Filter out most IPC messages if this frame is swapped out.
399 // We still want to handle certain ACKs to keep our state consistent.
400 if (is_swapped_out()) {
401 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
402 // If this is a synchronous message and we decided not to handle it,
403 // we must send an error reply, or else the renderer will be stuck
404 // and won't respond to future requests.
405 if (msg.is_sync()) {
406 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
407 reply->set_reply_error();
408 Send(reply);
410 // Don't continue looking for someone to handle it.
411 return true;
415 if (delegate_->OnMessageReceived(this, msg))
416 return true;
418 RenderFrameProxyHost* proxy =
419 frame_tree_node_->render_manager()->GetProxyToParent();
420 if (proxy && proxy->cross_process_frame_connector() &&
421 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
422 return true;
424 bool handled = true;
425 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
426 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
427 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
428 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
429 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
430 OnDidStartProvisionalLoadForFrame)
431 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
432 OnDidFailProvisionalLoadWithError)
433 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
434 OnDidFailLoadWithError)
435 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
436 OnDidCommitProvisionalLoad(msg))
437 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation)
438 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
439 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
440 OnDocumentOnLoadCompleted)
441 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
442 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
443 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
444 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
445 OnJavaScriptExecuteResponse)
446 IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
447 OnVisualStateResponse)
448 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
449 OnRunJavaScriptMessage)
450 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
451 OnRunBeforeUnloadConfirm)
452 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
453 OnDidAccessInitialDocument)
454 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
455 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeName, OnDidChangeName)
456 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
457 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeSandboxFlags,
458 OnDidChangeSandboxFlags)
459 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
460 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
461 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
462 OnBeginNavigation)
463 IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
464 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
465 OnTextSurroundingSelectionResponse)
466 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
467 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
468 OnAccessibilityLocationChanges)
469 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
470 OnAccessibilityFindInPageResult)
471 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
472 OnAccessibilitySnapshotResponse)
473 IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
474 // The following message is synthetic and doesn't come from RenderFrame, but
475 // from RenderProcessHost.
476 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
477 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
478 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
479 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
480 OnDidChangeLoadProgress)
481 #if defined(OS_MACOSX) || defined(OS_ANDROID)
482 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
483 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
484 #endif
485 IPC_END_MESSAGE_MAP()
487 // No further actions here, since we may have been deleted.
488 return handled;
491 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
492 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
495 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
496 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
499 void RenderFrameHostImpl::AccessibilityShowContextMenu(int acc_obj_id) {
500 Send(new AccessibilityMsg_ShowContextMenu(routing_id_, acc_obj_id));
503 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
504 int acc_obj_id, const gfx::Rect& subfocus) {
505 Send(new AccessibilityMsg_ScrollToMakeVisible(
506 routing_id_, acc_obj_id, subfocus));
509 void RenderFrameHostImpl::AccessibilityScrollToPoint(
510 int acc_obj_id, const gfx::Point& point) {
511 Send(new AccessibilityMsg_ScrollToPoint(
512 routing_id_, acc_obj_id, point));
515 void RenderFrameHostImpl::AccessibilitySetScrollOffset(
516 int acc_obj_id, const gfx::Point& offset) {
517 Send(new AccessibilityMsg_SetScrollOffset(
518 routing_id_, acc_obj_id, offset));
521 void RenderFrameHostImpl::AccessibilitySetTextSelection(
522 int object_id, int start_offset, int end_offset) {
523 Send(new AccessibilityMsg_SetTextSelection(
524 routing_id_, object_id, start_offset, end_offset));
527 void RenderFrameHostImpl::AccessibilitySetValue(
528 int object_id, const base::string16& value) {
529 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
532 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
533 RenderWidgetHostView* view = render_view_host_->GetView();
534 if (view)
535 return view->HasFocus();
536 return false;
539 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
540 RenderWidgetHostView* view = render_view_host_->GetView();
541 if (view)
542 return view->GetViewBounds();
543 return gfx::Rect();
546 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
547 const gfx::Rect& bounds) const {
548 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
549 render_view_host_->GetView());
550 if (view)
551 return view->AccessibilityOriginInScreen(bounds);
552 return gfx::Point();
555 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
556 Send(new AccessibilityMsg_HitTest(routing_id_, point));
559 void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) {
560 Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id));
563 void RenderFrameHostImpl::AccessibilityReset() {
564 accessibility_reset_token_ = g_next_accessibility_reset_token++;
565 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
568 void RenderFrameHostImpl::AccessibilityFatalError() {
569 browser_accessibility_manager_.reset(NULL);
570 if (accessibility_reset_token_)
571 return;
573 accessibility_reset_count_++;
574 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
575 Send(new AccessibilityMsg_FatalError(routing_id_));
576 } else {
577 accessibility_reset_token_ = g_next_accessibility_reset_token++;
578 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
579 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
583 gfx::AcceleratedWidget
584 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
585 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
586 render_view_host_->GetView());
587 if (view)
588 return view->AccessibilityGetAcceleratedWidget();
589 return gfx::kNullAcceleratedWidget;
592 gfx::NativeViewAccessible
593 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
594 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
595 render_view_host_->GetView());
596 if (view)
597 return view->AccessibilityGetNativeViewAccessible();
598 return NULL;
601 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id,
602 int previous_sibling_routing_id,
603 int proxy_routing_id) {
604 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
605 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
607 // The process may (if we're sharing a process with another host that already
608 // initialized it) or may not (we have our own process or the old process
609 // crashed) have been initialized. Calling Init multiple times will be
610 // ignored, so this is safe.
611 if (!GetProcess()->Init())
612 return false;
614 DCHECK(GetProcess()->HasConnection());
616 FrameMsg_NewFrame_Params params;
617 params.routing_id = routing_id_;
618 params.parent_routing_id = parent_routing_id;
619 params.proxy_routing_id = proxy_routing_id;
620 params.previous_sibling_routing_id = previous_sibling_routing_id;
621 params.replication_state = frame_tree_node()->current_replication_state();
623 if (render_widget_host_) {
624 params.widget_params.routing_id = render_widget_host_->GetRoutingID();
625 params.widget_params.surface_id = render_widget_host_->surface_id();
626 params.widget_params.hidden = render_widget_host_->is_hidden();
627 } else {
628 // MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
629 // the renderer process.
630 params.widget_params.routing_id = MSG_ROUTING_NONE;
631 params.widget_params.surface_id = 0;
632 params.widget_params.hidden = true;
635 Send(new FrameMsg_NewFrame(params));
637 // The RenderWidgetHost takes ownership of its view. It is tied to the
638 // lifetime of the current RenderProcessHost for this RenderFrameHost.
639 if (render_widget_host_) {
640 RenderWidgetHostView* rwhv =
641 new RenderWidgetHostViewChildFrame(render_widget_host_);
642 rwhv->Hide();
645 if (proxy_routing_id != MSG_ROUTING_NONE) {
646 RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
647 GetProcess()->GetID(), proxy_routing_id);
648 // We have also created a RenderFrameProxy in FrameMsg_NewFrame above, so
649 // remember that.
650 proxy->set_render_frame_proxy_created(true);
653 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
654 // this path is only used for out-of-process iframes. Main frame RenderFrames
655 // are created with their RenderView, and same-site iframes are created at the
656 // time of OnCreateChildFrame.
657 SetRenderFrameCreated(true);
659 return true;
662 void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
663 bool was_created = render_frame_created_;
664 render_frame_created_ = created;
666 // If the current status is different than the new status, the delegate
667 // needs to be notified.
668 if (delegate_ && (created != was_created)) {
669 if (created)
670 delegate_->RenderFrameCreated(this);
671 else
672 delegate_->RenderFrameDeleted(this);
675 if (created && render_widget_host_)
676 render_widget_host_->InitForFrame();
679 void RenderFrameHostImpl::Init() {
680 GetProcess()->ResumeRequestsForView(routing_id_);
683 void RenderFrameHostImpl::OnAddMessageToConsole(
684 int32 level,
685 const base::string16& message,
686 int32 line_no,
687 const base::string16& source_id) {
688 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
689 return;
691 // Pass through log level only on WebUI pages to limit console spew.
692 const bool is_web_ui =
693 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL());
694 const int32 resolved_level = is_web_ui ? level : ::logging::LOG_INFO;
696 // LogMessages can be persisted so this shouldn't be logged in incognito mode.
697 // This rule is not applied to WebUI pages, because source code of WebUI is a
698 // part of Chrome source code, and we want to treat messages from WebUI the
699 // same way as we treat log messages from native code.
700 if (::logging::GetMinLogLevel() <= resolved_level &&
701 (is_web_ui ||
702 !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord())) {
703 logging::LogMessage("CONSOLE", line_no, resolved_level).stream()
704 << "\"" << message << "\", source: " << source_id << " (" << line_no
705 << ")";
709 void RenderFrameHostImpl::OnCreateChildFrame(
710 int new_routing_id,
711 blink::WebTreeScopeType scope,
712 const std::string& frame_name,
713 blink::WebSandboxFlags sandbox_flags) {
714 // It is possible that while a new RenderFrameHost was committed, the
715 // RenderFrame corresponding to this host sent an IPC message to create a
716 // frame and it is delivered after this host is swapped out.
717 // Ignore such messages, as we know this RenderFrameHost is going away.
718 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
719 return;
721 RenderFrameHostImpl* new_frame =
722 frame_tree_->AddFrame(frame_tree_node_, GetProcess()->GetID(),
723 new_routing_id, scope, frame_name, sandbox_flags);
724 if (!new_frame)
725 return;
727 // We know that the RenderFrame has been created in this case, immediately
728 // after the CreateChildFrame IPC was sent.
729 new_frame->SetRenderFrameCreated(true);
732 void RenderFrameHostImpl::OnDetach() {
733 frame_tree_->RemoveFrame(frame_tree_node_);
736 void RenderFrameHostImpl::OnFrameFocused() {
737 frame_tree_->SetFocusedFrame(frame_tree_node_);
740 void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
741 OpenURL(params, GetSiteInstance());
744 void RenderFrameHostImpl::OnDocumentOnLoadCompleted(
745 FrameMsg_UILoadMetricsReportType::Value report_type,
746 base::TimeTicks ui_timestamp) {
747 if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
748 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Link",
749 base::TimeTicks::Now() - ui_timestamp,
750 base::TimeDelta::FromMilliseconds(10),
751 base::TimeDelta::FromMinutes(10), 100);
752 } else if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
753 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Intent",
754 base::TimeTicks::Now() - ui_timestamp,
755 base::TimeDelta::FromMilliseconds(10),
756 base::TimeDelta::FromMinutes(10), 100);
758 // This message is only sent for top-level frames. TODO(avi): when frame tree
759 // mirroring works correctly, add a check here to enforce it.
760 delegate_->DocumentOnLoadCompleted(this);
763 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(const GURL& url) {
764 frame_tree_node_->navigator()->DidStartProvisionalLoad(
765 this, url);
768 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
769 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
770 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
771 switches::kEnableBrowserSideNavigation) &&
772 navigation_handle_) {
773 navigation_handle_->set_net_error_code(
774 static_cast<net::Error>(params.error_code));
776 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
779 void RenderFrameHostImpl::OnDidFailLoadWithError(
780 const GURL& url,
781 int error_code,
782 const base::string16& error_description,
783 bool was_ignored_by_handler) {
784 GURL validated_url(url);
785 GetProcess()->FilterURL(false, &validated_url);
787 frame_tree_node_->navigator()->DidFailLoadWithError(
788 this, validated_url, error_code, error_description,
789 was_ignored_by_handler);
792 // Called when the renderer navigates. For every frame loaded, we'll get this
793 // notification containing parameters identifying the navigation.
795 // Subframes are identified by the page transition type. For subframes loaded
796 // as part of a wider page load, the page_id will be the same as for the top
797 // level frame. If the user explicitly requests a subframe navigation, we will
798 // get a new page_id because we need to create a new navigation entry for that
799 // action.
800 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
801 RenderProcessHost* process = GetProcess();
803 // Read the parameters out of the IPC message directly to avoid making another
804 // copy when we filter the URLs.
805 base::PickleIterator iter(msg);
806 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
807 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
808 Read(&msg, &iter, &validated_params)) {
809 bad_message::ReceivedBadMessage(
810 process, bad_message::RFH_COMMIT_DESERIALIZATION_FAILED);
811 return;
813 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
814 "url", validated_params.url.possibly_invalid_spec());
816 // Sanity-check the page transition for frame type.
817 DCHECK_EQ(ui::PageTransitionIsMainFrame(validated_params.transition),
818 !GetParent());
820 // If we're waiting for a cross-site beforeunload ack from this renderer and
821 // we receive a Navigate message from the main frame, then the renderer was
822 // navigating already and sent it before hearing the FrameMsg_Stop message.
823 // Treat this as an implicit beforeunload ack to allow the pending navigation
824 // to continue.
825 if (is_waiting_for_beforeunload_ack_ &&
826 unload_ack_is_for_navigation_ &&
827 !GetParent()) {
828 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
829 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
832 // If we're waiting for an unload ack from this renderer and we receive a
833 // Navigate message, then the renderer was navigating before it received the
834 // unload request. It will either respond to the unload request soon or our
835 // timer will expire. Either way, we should ignore this message, because we
836 // have already committed to closing this renderer.
837 if (IsWaitingForUnloadACK())
838 return;
840 if (validated_params.report_type ==
841 FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
842 UMA_HISTOGRAM_CUSTOM_TIMES(
843 "Navigation.UI_OnCommitProvisionalLoad.Link",
844 base::TimeTicks::Now() - validated_params.ui_timestamp,
845 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
846 100);
847 } else if (validated_params.report_type ==
848 FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
849 UMA_HISTOGRAM_CUSTOM_TIMES(
850 "Navigation.UI_OnCommitProvisionalLoad.Intent",
851 base::TimeTicks::Now() - validated_params.ui_timestamp,
852 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
853 100);
856 // Attempts to commit certain off-limits URL should be caught more strictly
857 // than our FilterURL checks below. If a renderer violates this policy, it
858 // should be killed.
859 if (!CanCommitURL(validated_params.url)) {
860 VLOG(1) << "Blocked URL " << validated_params.url.spec();
861 validated_params.url = GURL(url::kAboutBlankURL);
862 // Kills the process.
863 bad_message::ReceivedBadMessage(process,
864 bad_message::RFH_CAN_COMMIT_URL_BLOCKED);
867 // Without this check, an evil renderer can trick the browser into creating
868 // a navigation entry for a banned URL. If the user clicks the back button
869 // followed by the forward button (or clicks reload, or round-trips through
870 // session restore, etc), we'll think that the browser commanded the
871 // renderer to load the URL and grant the renderer the privileges to request
872 // the URL. To prevent this attack, we block the renderer from inserting
873 // banned URLs into the navigation controller in the first place.
874 process->FilterURL(false, &validated_params.url);
875 process->FilterURL(true, &validated_params.referrer.url);
876 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
877 it != validated_params.redirects.end(); ++it) {
878 process->FilterURL(false, &(*it));
880 process->FilterURL(true, &validated_params.searchable_form_url);
882 // Without this check, the renderer can trick the browser into using
883 // filenames it can't access in a future session restore.
884 if (!render_view_host_->CanAccessFilesOfPageState(
885 validated_params.page_state)) {
886 bad_message::ReceivedBadMessage(
887 GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
888 return;
891 // If the URL does not match what the NavigationHandle expects, treat the
892 // commit as a new navigation. This can happen if an ongoing slow
893 // same-process navigation is interrupted by a synchronous renderer-initiated
894 // navigation.
895 if (navigation_handle_ &&
896 navigation_handle_->GetURL() != validated_params.url) {
897 navigation_handle_.reset();
900 // Synchronous renderer-initiated navigations will send a
901 // DidCommitProvisionalLoad IPC without a prior DidStartProvisionalLoad
902 // message.
903 if (!navigation_handle_) {
904 navigation_handle_ = NavigationHandleImpl::Create(
905 validated_params.url, frame_tree_node_->IsMainFrame(),
906 frame_tree_node_->navigator()->GetDelegate());
909 accessibility_reset_count_ = 0;
910 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
912 // PlzNavigate
913 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
914 switches::kEnableBrowserSideNavigation)) {
915 pending_commit_ = false;
919 void RenderFrameHostImpl::OnDidDropNavigation() {
920 // At the end of Navigate(), the FrameTreeNode's DidStartLoading is called to
921 // force the spinner to start, even if the renderer didn't yet begin the load.
922 // If it turns out that the renderer dropped the navigation, the spinner needs
923 // to be turned off.
924 frame_tree_node_->DidStopLoading();
925 navigation_handle_.reset();
928 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
929 if (render_widget_host_)
930 return render_widget_host_;
932 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
933 // we can remove this fallback. Currently it is only used for the main
934 // frame.
935 if (!GetParent())
936 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
938 return nullptr;
941 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
942 RenderFrameHostImpl* frame = this;
943 while (frame) {
944 if (frame->render_widget_host_)
945 return frame->render_widget_host_->GetView();
946 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
949 return render_view_host_->GetView();
952 int RenderFrameHostImpl::GetEnabledBindings() {
953 return render_view_host_->GetEnabledBindings();
956 void RenderFrameHostImpl::SetNavigationHandle(
957 scoped_ptr<NavigationHandleImpl> navigation_handle) {
958 navigation_handle_ = navigation_handle.Pass();
961 scoped_ptr<NavigationHandleImpl>
962 RenderFrameHostImpl::PassNavigationHandleOwnership() {
963 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
964 switches::kEnableBrowserSideNavigation));
965 navigation_handle_->set_is_transferring(true);
966 return navigation_handle_.Pass();
969 void RenderFrameHostImpl::OnCrossSiteResponse(
970 const GlobalRequestID& global_request_id,
971 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
972 const std::vector<GURL>& transfer_url_chain,
973 const Referrer& referrer,
974 ui::PageTransition page_transition,
975 bool should_replace_current_entry) {
976 frame_tree_node_->render_manager()->OnCrossSiteResponse(
977 this, global_request_id, cross_site_transferring_request.Pass(),
978 transfer_url_chain, referrer, page_transition,
979 should_replace_current_entry);
982 void RenderFrameHostImpl::SwapOut(
983 RenderFrameProxyHost* proxy,
984 bool is_loading) {
985 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
986 // the operation and sends back an IPC message.
987 // The trace event may not end properly if the ACK times out. We expect this
988 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
989 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
991 // If this RenderFrameHost is not in the default state, it must have already
992 // gone through this, therefore just return.
993 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
994 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
995 return;
998 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
999 swapout_event_monitor_timeout_->Start(
1000 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1002 // There may be no proxy if there are no active views in the process.
1003 int proxy_routing_id = MSG_ROUTING_NONE;
1004 FrameReplicationState replication_state;
1005 if (proxy) {
1006 set_render_frame_proxy_host(proxy);
1007 proxy_routing_id = proxy->GetRoutingID();
1008 replication_state = proxy->frame_tree_node()->current_replication_state();
1011 if (IsRenderFrameLive()) {
1012 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
1013 replication_state));
1016 if (!GetParent())
1017 delegate_->SwappedOut(this);
1020 void RenderFrameHostImpl::OnBeforeUnloadACK(
1021 bool proceed,
1022 const base::TimeTicks& renderer_before_unload_start_time,
1023 const base::TimeTicks& renderer_before_unload_end_time) {
1024 TRACE_EVENT_ASYNC_END0(
1025 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1026 DCHECK(!GetParent());
1027 // If this renderer navigated while the beforeunload request was in flight, we
1028 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
1029 // can ignore this message.
1030 // However renderer might also be swapped out but we still want to proceed
1031 // with navigation, otherwise it would block future navigations. This can
1032 // happen when pending cross-site navigation is canceled by a second one just
1033 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
1034 // but second navigation is started from the beginning.
1035 if (!is_waiting_for_beforeunload_ack_) {
1036 return;
1038 DCHECK(!send_before_unload_start_time_.is_null());
1040 // Sets a default value for before_unload_end_time so that the browser
1041 // survives a hacked renderer.
1042 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
1043 if (!renderer_before_unload_start_time.is_null() &&
1044 !renderer_before_unload_end_time.is_null()) {
1045 // When passing TimeTicks across process boundaries, we need to compensate
1046 // for any skew between the processes. Here we are converting the
1047 // renderer's notion of before_unload_end_time to TimeTicks in the browser
1048 // process. See comments in inter_process_time_ticks_converter.h for more.
1049 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
1050 InterProcessTimeTicksConverter converter(
1051 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
1052 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
1053 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
1054 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1055 LocalTimeTicks browser_before_unload_end_time =
1056 converter.ToLocalTimeTicks(
1057 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1058 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1060 // Collect UMA on the inter-process skew.
1061 bool is_skew_additive = false;
1062 if (converter.IsSkewAdditiveForMetrics()) {
1063 is_skew_additive = true;
1064 base::TimeDelta skew = converter.GetSkewForMetrics();
1065 if (skew >= base::TimeDelta()) {
1066 UMA_HISTOGRAM_TIMES(
1067 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
1068 } else {
1069 UMA_HISTOGRAM_TIMES(
1070 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
1073 UMA_HISTOGRAM_BOOLEAN(
1074 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
1075 is_skew_additive);
1077 base::TimeDelta on_before_unload_overhead_time =
1078 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1079 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1080 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1081 on_before_unload_overhead_time);
1083 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1084 renderer_before_unload_start_time, renderer_before_unload_end_time);
1086 // Resets beforeunload waiting state.
1087 is_waiting_for_beforeunload_ack_ = false;
1088 render_view_host_->decrement_in_flight_event_count();
1089 render_view_host_->StopHangMonitorTimeout();
1090 send_before_unload_start_time_ = base::TimeTicks();
1092 // PlzNavigate: if the ACK is for a navigation, send it to the Navigator to
1093 // have the current navigation stop/proceed. Otherwise, send it to the
1094 // RenderFrameHostManager which handles closing.
1095 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1096 switches::kEnableBrowserSideNavigation) &&
1097 unload_ack_is_for_navigation_) {
1098 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1099 // Navigator.
1100 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1101 frame_tree_node_, proceed);
1102 } else {
1103 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1104 unload_ack_is_for_navigation_, proceed,
1105 before_unload_end_time);
1108 // If canceled, notify the delegate to cancel its pending navigation entry.
1109 if (!proceed)
1110 render_view_host_->GetDelegate()->DidCancelLoading();
1113 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1114 return render_view_host_->is_waiting_for_close_ack_ ||
1115 rfh_state_ == STATE_PENDING_SWAP_OUT;
1118 void RenderFrameHostImpl::OnSwapOutACK() {
1119 OnSwappedOut();
1122 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1123 if (frame_tree_node_->IsMainFrame()) {
1124 // Keep the termination status so we can get at it later when we
1125 // need to know why it died.
1126 render_view_host_->render_view_termination_status_ =
1127 static_cast<base::TerminationStatus>(status);
1130 // Reset frame tree state associated with this process. This must happen
1131 // before RenderViewTerminated because observers expect the subframes of any
1132 // affected frames to be cleared first.
1133 // Note: When a RenderFrameHost is swapped out there is a different one
1134 // which is the current host. In this case, the FrameTreeNode state must
1135 // not be reset.
1136 if (!is_swapped_out())
1137 frame_tree_node_->ResetForNewProcess();
1139 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1140 // reset.
1141 SetRenderFrameCreated(false);
1142 InvalidateMojoConnection();
1144 // Execute any pending AX tree snapshot callbacks with an empty response,
1145 // since we're never going to get a response from this renderer.
1146 for (const auto& iter : ax_tree_snapshot_callbacks_)
1147 iter.second.Run(ui::AXTreeUpdate<ui::AXNodeData>());
1148 ax_tree_snapshot_callbacks_.clear();
1150 // Note: don't add any more code at this point in the function because
1151 // |this| may be deleted. Any additional cleanup should happen before
1152 // the last block of code here.
1155 void RenderFrameHostImpl::OnSwappedOut() {
1156 // Ignore spurious swap out ack.
1157 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1158 return;
1160 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1161 swapout_event_monitor_timeout_->Stop();
1164 // If this is a main frame RFH that's about to be deleted, update its RVH's
1165 // swapped-out state here, since SetState won't be called once this RFH is
1166 // deleted below. https://crbug.com/505887
1167 if (frame_tree_node_->IsMainFrame() &&
1168 frame_tree_node_->render_manager()->IsPendingDeletion(this)) {
1169 render_view_host_->set_is_active(false);
1170 render_view_host_->set_is_swapped_out(true);
1173 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1174 // We are now deleted.
1175 return;
1178 // If this RFH wasn't pending deletion, then it is now swapped out.
1179 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1182 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1183 // Validate the URLs in |params|. If the renderer can't request the URLs
1184 // directly, don't show them in the context menu.
1185 ContextMenuParams validated_params(params);
1186 RenderProcessHost* process = GetProcess();
1188 // We don't validate |unfiltered_link_url| so that this field can be used
1189 // when users want to copy the original link URL.
1190 process->FilterURL(true, &validated_params.link_url);
1191 process->FilterURL(true, &validated_params.src_url);
1192 process->FilterURL(false, &validated_params.page_url);
1193 process->FilterURL(true, &validated_params.frame_url);
1195 delegate_->ShowContextMenu(this, validated_params);
1198 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1199 int id, const base::ListValue& result) {
1200 const base::Value* result_value;
1201 if (!result.Get(0, &result_value)) {
1202 // Programming error or rogue renderer.
1203 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1204 return;
1207 std::map<int, JavaScriptResultCallback>::iterator it =
1208 javascript_callbacks_.find(id);
1209 if (it != javascript_callbacks_.end()) {
1210 it->second.Run(result_value);
1211 javascript_callbacks_.erase(it);
1212 } else {
1213 NOTREACHED() << "Received script response for unknown request";
1217 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1218 auto it = visual_state_callbacks_.find(id);
1219 if (it != visual_state_callbacks_.end()) {
1220 it->second.Run(true);
1221 visual_state_callbacks_.erase(it);
1222 } else {
1223 NOTREACHED() << "Received script response for unknown request";
1227 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1228 const base::string16& message,
1229 const base::string16& default_prompt,
1230 const GURL& frame_url,
1231 JavaScriptMessageType type,
1232 IPC::Message* reply_msg) {
1233 // While a JS message dialog is showing, tabs in the same process shouldn't
1234 // process input events.
1235 GetProcess()->SetIgnoreInputEvents(true);
1236 render_view_host_->StopHangMonitorTimeout();
1237 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1238 frame_url, type, reply_msg);
1241 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1242 const GURL& frame_url,
1243 const base::string16& message,
1244 bool is_reload,
1245 IPC::Message* reply_msg) {
1246 // While a JS beforeunload dialog is showing, tabs in the same process
1247 // shouldn't process input events.
1248 GetProcess()->SetIgnoreInputEvents(true);
1249 render_view_host_->StopHangMonitorTimeout();
1250 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1253 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1254 const base::string16& content,
1255 size_t start_offset,
1256 size_t end_offset) {
1257 render_view_host_->OnTextSurroundingSelectionResponse(
1258 content, start_offset, end_offset);
1261 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1262 delegate_->DidAccessInitialDocument();
1265 void RenderFrameHostImpl::OnDidDisownOpener() {
1266 // This message is only sent for top-level frames for now.
1267 // TODO(alexmos): This should eventually support subframe openers as well,
1268 // and it should allow openers to be updated to another frame (which can
1269 // happen via window.open('','framename')) in addition to being disowned.
1271 // No action is necessary if the opener has already been cleared.
1272 if (!frame_tree_node_->opener())
1273 return;
1275 // Clear our opener so that future cross-process navigations don't have an
1276 // opener assigned.
1277 frame_tree_node_->SetOpener(nullptr);
1279 // Notify all other RenderFrameHosts and RenderFrameProxies for this frame.
1280 // This is important in case we go back to them, or if another window in
1281 // those processes tries to access window.opener.
1282 frame_tree_node_->render_manager()->DidDisownOpener(this);
1285 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1286 std::string old_name = frame_tree_node()->frame_name();
1287 frame_tree_node()->SetFrameName(name);
1288 if (old_name.empty() && !name.empty())
1289 frame_tree_node_->render_manager()->CreateProxiesForNewNamedFrame();
1290 delegate_->DidChangeName(this, name);
1293 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1294 // Update the RVH's current page ID so that future IPCs from the renderer
1295 // correspond to the new page.
1296 render_view_host_->page_id_ = page_id;
1299 void RenderFrameHostImpl::OnDidChangeSandboxFlags(
1300 int32 frame_routing_id,
1301 blink::WebSandboxFlags flags) {
1302 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1303 FrameTreeNode* child =
1304 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1305 if (!child)
1306 return;
1308 // Ensure that a frame can only update sandbox flags for its immediate
1309 // children. If this is not the case, the renderer is considered malicious
1310 // and is killed.
1311 if (child->parent() != frame_tree_node()) {
1312 bad_message::ReceivedBadMessage(GetProcess(),
1313 bad_message::RFH_SANDBOX_FLAGS);
1314 return;
1317 child->set_sandbox_flags(flags);
1319 // Notify the RenderFrame if it lives in a different process from its
1320 // parent. The frame's proxies in other processes also need to learn about
1321 // the updated sandbox flags, but these notifications are sent later in
1322 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1323 // navigates and the new sandbox flags take effect.
1324 RenderFrameHost* child_rfh = child->current_frame_host();
1325 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1326 child_rfh->Send(
1327 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1331 void RenderFrameHostImpl::OnUpdateTitle(
1332 const base::string16& title,
1333 blink::WebTextDirection title_direction) {
1334 // This message is only sent for top-level frames. TODO(avi): when frame tree
1335 // mirroring works correctly, add a check here to enforce it.
1336 if (title.length() > kMaxTitleChars) {
1337 NOTREACHED() << "Renderer sent too many characters in title.";
1338 return;
1341 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1342 WebTextDirectionToChromeTextDirection(
1343 title_direction));
1346 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1347 // This message is only sent for top-level frames. TODO(avi): when frame tree
1348 // mirroring works correctly, add a check here to enforce it.
1349 delegate_->UpdateEncoding(this, encoding_name);
1352 void RenderFrameHostImpl::OnBeginNavigation(
1353 const CommonNavigationParams& common_params,
1354 const BeginNavigationParams& begin_params,
1355 scoped_refptr<ResourceRequestBody> body) {
1356 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1357 switches::kEnableBrowserSideNavigation));
1358 frame_tree_node()->navigator()->OnBeginNavigation(
1359 frame_tree_node(), common_params, begin_params, body);
1362 void RenderFrameHostImpl::OnDispatchLoad() {
1363 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
1364 // Only frames with an out-of-process parent frame should be sending this
1365 // message.
1366 RenderFrameProxyHost* proxy =
1367 frame_tree_node()->render_manager()->GetProxyToParent();
1368 if (!proxy) {
1369 bad_message::ReceivedBadMessage(GetProcess(),
1370 bad_message::RFH_NO_PROXY_TO_PARENT);
1371 return;
1374 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1377 void RenderFrameHostImpl::OnAccessibilityEvents(
1378 const std::vector<AccessibilityHostMsg_EventParams>& params,
1379 int reset_token) {
1380 // Don't process this IPC if either we're waiting on a reset and this
1381 // IPC doesn't have the matching token ID, or if we're not waiting on a
1382 // reset but this message includes a reset token.
1383 if (accessibility_reset_token_ != reset_token) {
1384 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1385 return;
1387 accessibility_reset_token_ = 0;
1389 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1390 render_view_host_->GetView());
1392 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1393 if ((accessibility_mode != AccessibilityModeOff) && view &&
1394 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1395 if (accessibility_mode & AccessibilityModeFlagPlatform)
1396 GetOrCreateBrowserAccessibilityManager();
1398 std::vector<AXEventNotificationDetails> details;
1399 details.reserve(params.size());
1400 for (size_t i = 0; i < params.size(); ++i) {
1401 const AccessibilityHostMsg_EventParams& param = params[i];
1402 AXEventNotificationDetails detail;
1403 detail.event_type = param.event_type;
1404 detail.id = param.id;
1405 detail.ax_tree_id = GetAXTreeID();
1406 detail.update.node_id_to_clear = param.update.node_id_to_clear;
1407 detail.update.nodes.resize(param.update.nodes.size());
1408 for (size_t i = 0; i < param.update.nodes.size(); ++i) {
1409 AXContentNodeDataToAXNodeData(param.update.nodes[i],
1410 &detail.update.nodes[i]);
1412 details.push_back(detail);
1415 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1416 if (browser_accessibility_manager_)
1417 browser_accessibility_manager_->OnAccessibilityEvents(details);
1420 // Send the updates to the automation extension API.
1421 delegate_->AccessibilityEventReceived(details);
1423 // For testing only.
1424 if (!accessibility_testing_callback_.is_null()) {
1425 for (size_t i = 0; i < details.size(); i++) {
1426 const AXEventNotificationDetails& detail = details[i];
1427 if (static_cast<int>(detail.event_type) < 0)
1428 continue;
1430 if (!ax_tree_for_testing_) {
1431 if (browser_accessibility_manager_) {
1432 ax_tree_for_testing_.reset(new ui::AXTree(
1433 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1434 } else {
1435 ax_tree_for_testing_.reset(new ui::AXTree());
1436 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1437 << ax_tree_for_testing_->error();
1439 } else {
1440 CHECK(ax_tree_for_testing_->Unserialize(detail.update))
1441 << ax_tree_for_testing_->error();
1443 accessibility_testing_callback_.Run(detail.event_type, detail.id);
1448 // Always send an ACK or the renderer can be in a bad state.
1449 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1452 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1453 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1454 if (accessibility_reset_token_)
1455 return;
1457 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1458 render_view_host_->GetView());
1459 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1460 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1461 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1462 BrowserAccessibilityManager* manager =
1463 GetOrCreateBrowserAccessibilityManager();
1464 if (manager)
1465 manager->OnLocationChanges(params);
1467 // TODO(aboxhall): send location change events to web contents observers too
1471 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1472 const AccessibilityHostMsg_FindInPageResultParams& params) {
1473 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1474 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1475 BrowserAccessibilityManager* manager =
1476 GetOrCreateBrowserAccessibilityManager();
1477 if (manager) {
1478 manager->OnFindInPageResult(
1479 params.request_id, params.match_index, params.start_id,
1480 params.start_offset, params.end_id, params.end_offset);
1485 void RenderFrameHostImpl::OnAccessibilitySnapshotResponse(
1486 int callback_id,
1487 const ui::AXTreeUpdate<AXContentNodeData>& snapshot) {
1488 const auto& it = ax_tree_snapshot_callbacks_.find(callback_id);
1489 if (it != ax_tree_snapshot_callbacks_.end()) {
1490 ui::AXTreeUpdate<ui::AXNodeData> dst_snapshot;
1491 dst_snapshot.nodes.resize(snapshot.nodes.size());
1492 for (size_t i = 0; i < snapshot.nodes.size(); ++i) {
1493 AXContentNodeDataToAXNodeData(snapshot.nodes[i],
1494 &dst_snapshot.nodes[i]);
1496 it->second.Run(dst_snapshot);
1497 ax_tree_snapshot_callbacks_.erase(it);
1498 } else {
1499 NOTREACHED() << "Received AX tree snapshot response for unknown id";
1503 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1504 if (enter_fullscreen)
1505 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1506 else
1507 delegate_->ExitFullscreenMode();
1509 // The previous call might change the fullscreen state. We need to make sure
1510 // the renderer is aware of that, which is done via the resize message.
1511 render_view_host_->WasResized();
1514 void RenderFrameHostImpl::OnDidStartLoading(bool to_different_document) {
1515 // Any main frame load to a new document should reset the load since it will
1516 // replace the current page and any frames.
1517 if (to_different_document && !GetParent())
1518 is_loading_ = false;
1520 // This method should never be called when the frame is loading.
1521 // Unfortunately, it can happen if a history navigation happens during a
1522 // BeforeUnload or Unload event.
1523 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1524 // refactored in Blink. See crbug.com/466089
1525 if (is_loading_) {
1526 LOG(WARNING) << "OnDidStartLoading was called twice.";
1527 return;
1530 frame_tree_node_->DidStartLoading(to_different_document);
1531 is_loading_ = true;
1534 void RenderFrameHostImpl::OnDidStopLoading() {
1535 // This method should never be called when the frame is not loading.
1536 // Unfortunately, it can happen if a history navigation happens during a
1537 // BeforeUnload or Unload event.
1538 // TODO(fdegans): Change this to a DCHECK after LoadEventProgress has been
1539 // refactored in Blink. See crbug.com/466089
1540 if (!is_loading_) {
1541 LOG(WARNING) << "OnDidStopLoading was called twice.";
1542 return;
1545 is_loading_ = false;
1546 frame_tree_node_->DidStopLoading();
1547 navigation_handle_.reset();
1550 void RenderFrameHostImpl::OnDidChangeLoadProgress(double load_progress) {
1551 frame_tree_node_->DidChangeLoadProgress(load_progress);
1554 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1555 void RenderFrameHostImpl::OnShowPopup(
1556 const FrameHostMsg_ShowPopup_Params& params) {
1557 RenderViewHostDelegateView* view =
1558 render_view_host_->delegate_->GetDelegateView();
1559 if (view) {
1560 view->ShowPopupMenu(this,
1561 params.bounds,
1562 params.item_height,
1563 params.item_font_size,
1564 params.selected_item,
1565 params.popup_items,
1566 params.right_aligned,
1567 params.allow_multiple_selection);
1571 void RenderFrameHostImpl::OnHidePopup() {
1572 RenderViewHostDelegateView* view =
1573 render_view_host_->delegate_->GetDelegateView();
1574 if (view)
1575 view->HidePopupMenu();
1577 #endif
1579 void RenderFrameHostImpl::RegisterMojoServices() {
1580 GeolocationServiceContext* geolocation_service_context =
1581 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1582 if (geolocation_service_context) {
1583 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1584 // can perform permissions checks once site isolation is complete.
1585 // crbug.com/426384
1586 GetServiceRegistry()->AddService<GeolocationService>(
1587 base::Bind(&GeolocationServiceContext::CreateService,
1588 base::Unretained(geolocation_service_context),
1589 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1590 base::Unretained(this))));
1593 if (!permission_service_context_)
1594 permission_service_context_.reset(new PermissionServiceContext(this));
1596 GetServiceRegistry()->AddService<PermissionService>(
1597 base::Bind(&PermissionServiceContext::CreateService,
1598 base::Unretained(permission_service_context_.get())));
1600 GetServiceRegistry()->AddService<presentation::PresentationService>(
1601 base::Bind(&PresentationServiceImpl::CreateMojoService,
1602 base::Unretained(this)));
1604 if (!frame_mojo_shell_)
1605 frame_mojo_shell_.reset(new FrameMojoShell(this));
1607 GetServiceRegistry()->AddService<mojo::Shell>(base::Bind(
1608 &FrameMojoShell::BindRequest, base::Unretained(frame_mojo_shell_.get())));
1610 #if defined(ENABLE_WEBVR)
1611 const base::CommandLine& browser_command_line =
1612 *base::CommandLine::ForCurrentProcess();
1614 if (browser_command_line.HasSwitch(switches::kEnableWebVR)) {
1615 GetServiceRegistry()->AddService<VRService>(
1616 base::Bind(&VRDeviceManager::BindRequest));
1618 #endif
1621 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1622 // Only main frames should be swapped out and retained inside a proxy host.
1623 if (rfh_state == STATE_SWAPPED_OUT)
1624 CHECK(!GetParent());
1626 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1627 // out status of a RenderFrameHost gets flipped to/from active.
1628 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1629 GetSiteInstance()->increment_active_frame_count();
1630 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1631 GetSiteInstance()->decrement_active_frame_count();
1633 // The active and swapped out state of the RVH is determined by its main
1634 // frame, since subframes should have their own widgets.
1635 if (frame_tree_node_->IsMainFrame()) {
1636 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1637 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1640 // Whenever we change the RFH state to and from active or swapped out state,
1641 // we should not be waiting for beforeunload or close acks. We clear them
1642 // here to be safe, since they can cause navigations to be ignored in
1643 // OnDidCommitProvisionalLoad.
1644 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1645 if (rfh_state == STATE_DEFAULT ||
1646 rfh_state == STATE_SWAPPED_OUT ||
1647 rfh_state_ == STATE_DEFAULT ||
1648 rfh_state_ == STATE_SWAPPED_OUT) {
1649 if (is_waiting_for_beforeunload_ack_) {
1650 is_waiting_for_beforeunload_ack_ = false;
1651 render_view_host_->decrement_in_flight_event_count();
1652 render_view_host_->StopHangMonitorTimeout();
1654 send_before_unload_start_time_ = base::TimeTicks();
1655 render_view_host_->is_waiting_for_close_ack_ = false;
1657 rfh_state_ = rfh_state;
1660 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1661 // TODO(creis): We should also check for WebUI pages here. Also, when the
1662 // out-of-process iframes implementation is ready, we should check for
1663 // cross-site URLs that are not allowed to commit in this process.
1665 // Give the client a chance to disallow URLs from committing.
1666 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1669 void RenderFrameHostImpl::Navigate(
1670 const CommonNavigationParams& common_params,
1671 const StartNavigationParams& start_params,
1672 const RequestNavigationParams& request_params) {
1673 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1675 UpdatePermissionsForNavigation(common_params, request_params);
1677 // Only send the message if we aren't suspended at the start of a cross-site
1678 // request.
1679 if (navigations_suspended_) {
1680 // Shouldn't be possible to have a second navigation while suspended, since
1681 // navigations will only be suspended during a cross-site request. If a
1682 // second navigation occurs, RenderFrameHostManager will cancel this pending
1683 // RFH and create a new pending RFH.
1684 DCHECK(!suspended_nav_params_.get());
1685 suspended_nav_params_.reset(
1686 new NavigationParams(common_params, start_params, request_params));
1687 } else {
1688 // Get back to a clean state, in case we start a new navigation without
1689 // completing a RFH swap or unload handler.
1690 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1692 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1693 request_params));
1696 // Force the throbber to start. This is done because Blink's "started loading"
1697 // message will be received asynchronously from the UI of the browser. But the
1698 // throbber needs to be kept in sync with what's happening in the UI. For
1699 // example, the throbber will start immediately when the user navigates even
1700 // if the renderer is delayed. There is also an issue with the throbber
1701 // starting because the WebUI (which controls whether the favicon is
1702 // displayed) happens synchronously. If the start loading messages was
1703 // asynchronous, then the default favicon would flash in.
1705 // Blink doesn't send throb notifications for JavaScript URLs, so it is not
1706 // done here either.
1707 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1708 frame_tree_node_->DidStartLoading(true);
1711 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1712 CommonNavigationParams common_params(
1713 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::NORMAL,
1714 true, false, base::TimeTicks::Now(),
1715 FrameMsg_UILoadMetricsReportType::NO_REPORT, GURL(), GURL());
1716 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1719 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1720 SiteInstance* source_site_instance) {
1721 GURL validated_url(params.url);
1722 GetProcess()->FilterURL(false, &validated_url);
1724 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1725 validated_url.possibly_invalid_spec());
1726 frame_tree_node_->navigator()->RequestOpenURL(
1727 this, validated_url, source_site_instance, params.referrer,
1728 params.disposition, params.should_replace_current_entry,
1729 params.user_gesture);
1732 void RenderFrameHostImpl::Stop() {
1733 Send(new FrameMsg_Stop(routing_id_));
1736 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1737 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1738 // the handler ran and allowed the navigation to proceed.
1739 if (!ShouldDispatchBeforeUnload()) {
1740 DCHECK(!(base::CommandLine::ForCurrentProcess()->HasSwitch(
1741 switches::kEnableBrowserSideNavigation) &&
1742 for_navigation));
1743 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1744 for_navigation, true, base::TimeTicks::Now());
1745 return;
1747 TRACE_EVENT_ASYNC_BEGIN0(
1748 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1750 // This may be called more than once (if the user clicks the tab close button
1751 // several times, or if she clicks the tab close button then the browser close
1752 // button), and we only send the message once.
1753 if (is_waiting_for_beforeunload_ack_) {
1754 // Some of our close messages could be for the tab, others for cross-site
1755 // transitions. We always want to think it's for closing the tab if any
1756 // of the messages were, since otherwise it might be impossible to close
1757 // (if there was a cross-site "close" request pending when the user clicked
1758 // the close button). We want to keep the "for cross site" flag only if
1759 // both the old and the new ones are also for cross site.
1760 unload_ack_is_for_navigation_ =
1761 unload_ack_is_for_navigation_ && for_navigation;
1762 } else {
1763 // Start the hang monitor in case the renderer hangs in the beforeunload
1764 // handler.
1765 is_waiting_for_beforeunload_ack_ = true;
1766 unload_ack_is_for_navigation_ = for_navigation;
1767 // Increment the in-flight event count, to ensure that input events won't
1768 // cancel the timeout timer.
1769 render_view_host_->increment_in_flight_event_count();
1770 render_view_host_->StartHangMonitorTimeout(
1771 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1772 send_before_unload_start_time_ = base::TimeTicks::Now();
1773 Send(new FrameMsg_BeforeUnload(routing_id_));
1777 bool RenderFrameHostImpl::ShouldDispatchBeforeUnload() {
1778 // TODO(creis): Support beforeunload on subframes.
1779 return !GetParent() && IsRenderFrameLive();
1782 void RenderFrameHostImpl::DisownOpener() {
1783 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1786 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1787 size_t after) {
1788 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1791 void RenderFrameHostImpl::JavaScriptDialogClosed(
1792 IPC::Message* reply_msg,
1793 bool success,
1794 const base::string16& user_input,
1795 bool dialog_was_suppressed) {
1796 GetProcess()->SetIgnoreInputEvents(false);
1797 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1799 // If we are executing as part of (before)unload event handling, we don't
1800 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1801 // leave the current page. In this case, use the regular timeout value used
1802 // during the (before)unload handling.
1803 if (is_waiting) {
1804 render_view_host_->StartHangMonitorTimeout(
1805 success
1806 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1807 : render_view_host_->hung_renderer_delay_);
1810 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1811 success, user_input);
1812 Send(reply_msg);
1814 // If we are waiting for an unload or beforeunload ack and the user has
1815 // suppressed messages, kill the tab immediately; a page that's spamming
1816 // alerts in onbeforeunload is presumably malicious, so there's no point in
1817 // continuing to run its script and dragging out the process.
1818 // This must be done after sending the reply since RenderView can't close
1819 // correctly while waiting for a response.
1820 if (is_waiting && dialog_was_suppressed)
1821 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1824 // PlzNavigate
1825 void RenderFrameHostImpl::CommitNavigation(
1826 ResourceResponse* response,
1827 scoped_ptr<StreamHandle> body,
1828 const CommonNavigationParams& common_params,
1829 const RequestNavigationParams& request_params) {
1830 DCHECK((response && body.get()) ||
1831 !ShouldMakeNetworkRequestForURL(common_params.url));
1832 UpdatePermissionsForNavigation(common_params, request_params);
1834 // Get back to a clean state, in case we start a new navigation without
1835 // completing a RFH swap or unload handler.
1836 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1838 const GURL body_url = body.get() ? body->GetURL() : GURL();
1839 const ResourceResponseHead head = response ?
1840 response->head : ResourceResponseHead();
1841 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1842 request_params));
1843 // TODO(clamy): Check if we should start the throbber for non javascript urls
1844 // here.
1846 // TODO(clamy): Release the stream handle once the renderer has finished
1847 // reading it.
1848 stream_handle_ = body.Pass();
1850 // When navigating to a Javascript url, no commit is expected from the
1851 // RenderFrameHost, nor should the throbber start.
1852 if (!common_params.url.SchemeIs(url::kJavaScriptScheme)) {
1853 pending_commit_ = true;
1854 is_loading_ = true;
1856 frame_tree_node_->ResetNavigationRequest(true);
1859 void RenderFrameHostImpl::FailedNavigation(
1860 const CommonNavigationParams& common_params,
1861 const RequestNavigationParams& request_params,
1862 bool has_stale_copy_in_cache,
1863 int error_code) {
1864 // Get back to a clean state, in case a new navigation started without
1865 // completing a RFH swap or unload handler.
1866 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1868 Send(new FrameMsg_FailedNavigation(routing_id_, common_params, request_params,
1869 has_stale_copy_in_cache, error_code));
1871 // An error page is expected to commit, hence why is_loading_ is set to true.
1872 is_loading_ = true;
1873 frame_tree_node_->ResetNavigationRequest(true);
1876 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1877 if (service_registry_.get())
1878 return;
1880 service_registry_.reset(new ServiceRegistryImpl());
1881 if (!GetProcess()->GetServiceRegistry())
1882 return;
1884 RegisterMojoServices();
1885 RenderFrameSetupPtr setup;
1886 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(
1887 mojo::GetProxy(&setup));
1889 mojo::ServiceProviderPtr exposed_services;
1890 service_registry_->Bind(GetProxy(&exposed_services));
1892 mojo::ServiceProviderPtr services;
1893 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1894 exposed_services.Pass());
1895 service_registry_->BindRemoteServiceProvider(services.Pass());
1897 #if defined(OS_ANDROID)
1898 service_registry_android_.reset(
1899 new ServiceRegistryAndroid(service_registry_.get()));
1900 ServiceRegistrarAndroid::RegisterFrameHostServices(
1901 service_registry_android_.get());
1902 #endif
1905 void RenderFrameHostImpl::InvalidateMojoConnection() {
1906 #if defined(OS_ANDROID)
1907 // The Android-specific service registry has a reference to
1908 // |service_registry_| and thus must be torn down first.
1909 service_registry_android_.reset();
1910 #endif
1912 service_registry_.reset();
1914 // Disconnect with ImageDownloader Mojo service in RenderFrame.
1915 mojo_image_downloader_.reset();
1918 bool RenderFrameHostImpl::IsFocused() {
1919 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1920 // returning nullptr in some cases. See https://crbug.com/455245.
1921 return RenderWidgetHostImpl::From(
1922 GetView()->GetRenderWidgetHost())->is_focused() &&
1923 frame_tree_->GetFocusedFrame() &&
1924 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1925 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1928 const image_downloader::ImageDownloaderPtr&
1929 RenderFrameHostImpl::GetMojoImageDownloader() {
1930 if (!mojo_image_downloader_.get() && GetServiceRegistry()) {
1931 GetServiceRegistry()->ConnectToRemoteService(
1932 mojo::GetProxy(&mojo_image_downloader_));
1934 return mojo_image_downloader_;
1937 bool RenderFrameHostImpl::IsSameSiteInstance(
1938 RenderFrameHostImpl* other_render_frame_host) {
1939 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1940 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1941 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1942 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1945 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1946 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1949 void RenderFrameHostImpl::RequestAXTreeSnapshot(
1950 AXTreeSnapshotCallback callback) {
1951 static int next_id = 1;
1952 int callback_id = next_id++;
1953 Send(new AccessibilityMsg_SnapshotTree(routing_id_, callback_id));
1954 ax_tree_snapshot_callbacks_.insert(std::make_pair(callback_id, callback));
1957 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1958 const base::Callback<void(ui::AXEvent, int)>& callback) {
1959 accessibility_testing_callback_ = callback;
1962 void RenderFrameHostImpl::SetTextTrackSettings(
1963 const FrameMsg_TextTrackSettings_Params& params) {
1964 DCHECK(!GetParent());
1965 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
1968 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1969 return ax_tree_for_testing_.get();
1972 BrowserAccessibilityManager*
1973 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1974 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1975 render_view_host_->GetView());
1976 if (view &&
1977 !browser_accessibility_manager_ &&
1978 !no_create_browser_accessibility_manager_for_testing_) {
1979 browser_accessibility_manager_.reset(
1980 view->CreateBrowserAccessibilityManager(this));
1981 if (browser_accessibility_manager_)
1982 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
1983 else
1984 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
1986 return browser_accessibility_manager_.get();
1989 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
1990 int request_id) {
1991 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1992 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1993 BrowserAccessibilityManager* manager =
1994 GetOrCreateBrowserAccessibilityManager();
1995 if (manager)
1996 manager->ActivateFindInPageResult(request_id);
2000 void RenderFrameHostImpl::InsertVisualStateCallback(
2001 const VisualStateCallback& callback) {
2002 static uint64 next_id = 1;
2003 uint64 key = next_id++;
2004 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
2005 visual_state_callbacks_.insert(std::make_pair(key, callback));
2008 bool RenderFrameHostImpl::IsRenderFrameLive() {
2009 bool is_live = GetProcess()->HasConnection() && render_frame_created_;
2011 // Sanity check: the RenderView should always be live if the RenderFrame is.
2012 DCHECK_IMPLIES(is_live, render_view_host_->IsRenderViewLive());
2014 return is_live;
2017 #if defined(OS_WIN)
2019 void RenderFrameHostImpl::SetParentNativeViewAccessible(
2020 gfx::NativeViewAccessible accessible_parent) {
2021 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
2022 render_view_host_->GetView());
2023 if (view)
2024 view->SetParentNativeViewAccessible(accessible_parent);
2027 gfx::NativeViewAccessible
2028 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
2029 return delegate_->GetParentNativeViewAccessible();
2032 #elif defined(OS_MACOSX)
2034 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
2035 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
2038 void RenderFrameHostImpl::DidCancelPopupMenu() {
2039 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
2042 #elif defined(OS_ANDROID)
2044 void RenderFrameHostImpl::DidSelectPopupMenuItems(
2045 const std::vector<int>& selected_indices) {
2046 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
2049 void RenderFrameHostImpl::DidCancelPopupMenu() {
2050 Send(new FrameMsg_SelectPopupMenuItems(
2051 routing_id_, true, std::vector<int>()));
2054 #endif
2056 void RenderFrameHostImpl::SetNavigationsSuspended(
2057 bool suspend,
2058 const base::TimeTicks& proceed_time) {
2059 // This should only be called to toggle the state.
2060 DCHECK(navigations_suspended_ != suspend);
2062 navigations_suspended_ = suspend;
2063 if (navigations_suspended_) {
2064 TRACE_EVENT_ASYNC_BEGIN0("navigation",
2065 "RenderFrameHostImpl navigation suspended", this);
2066 } else {
2067 TRACE_EVENT_ASYNC_END0("navigation",
2068 "RenderFrameHostImpl navigation suspended", this);
2071 if (!suspend && suspended_nav_params_) {
2072 // There's navigation message params waiting to be sent. Now that we're not
2073 // suspended anymore, resume navigation by sending them. If we were swapped
2074 // out, we should also stop filtering out the IPC messages now.
2075 SetState(RenderFrameHostImpl::STATE_DEFAULT);
2077 DCHECK(!proceed_time.is_null());
2078 suspended_nav_params_->request_params.browser_navigation_start =
2079 proceed_time;
2080 Send(new FrameMsg_Navigate(routing_id_,
2081 suspended_nav_params_->common_params,
2082 suspended_nav_params_->start_params,
2083 suspended_nav_params_->request_params));
2084 suspended_nav_params_.reset();
2088 void RenderFrameHostImpl::CancelSuspendedNavigations() {
2089 // Clear any state if a pending navigation is canceled or preempted.
2090 if (suspended_nav_params_)
2091 suspended_nav_params_.reset();
2093 TRACE_EVENT_ASYNC_END0("navigation",
2094 "RenderFrameHostImpl navigation suspended", this);
2095 navigations_suspended_ = false;
2098 void RenderFrameHostImpl::DidUseGeolocationPermission() {
2099 PermissionManager* permission_manager =
2100 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
2101 if (!permission_manager)
2102 return;
2104 permission_manager->RegisterPermissionUsage(
2105 PermissionType::GEOLOCATION,
2106 GetLastCommittedURL().GetOrigin(),
2107 frame_tree_node()->frame_tree()->GetMainFrame()
2108 ->GetLastCommittedURL().GetOrigin());
2111 void RenderFrameHostImpl::UpdatePermissionsForNavigation(
2112 const CommonNavigationParams& common_params,
2113 const RequestNavigationParams& request_params) {
2114 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
2115 // so do not grant them the ability to request additional URLs.
2116 if (!GetProcess()->IsForGuestsOnly()) {
2117 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2118 GetProcess()->GetID(), common_params.url);
2119 if (common_params.url.SchemeIs(url::kDataScheme) &&
2120 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
2121 // If 'data:' is used, and we have a 'file:' base url, grant access to
2122 // local files.
2123 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
2124 GetProcess()->GetID(), common_params.base_url_for_data_url);
2128 // We may be returning to an existing NavigationEntry that had been granted
2129 // file access. If this is a different process, we will need to grant the
2130 // access again. The files listed in the page state are validated when they
2131 // are received from the renderer to prevent abuse.
2132 if (request_params.page_state.IsValid()) {
2133 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
2137 bool RenderFrameHostImpl::CanExecuteJavaScript() {
2138 return g_allow_injecting_javascript ||
2139 !frame_tree_node_->current_url().is_valid() ||
2140 frame_tree_node_->current_url().SchemeIs(kChromeDevToolsScheme) ||
2141 ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2142 GetProcess()->GetID()) ||
2143 // It's possible to load about:blank in a Web UI renderer.
2144 // See http://crbug.com/42547
2145 (frame_tree_node_->current_url().spec() == url::kAboutBlankURL) ||
2146 // InterstitialPageImpl should be the only case matching this.
2147 (delegate_->GetAsWebContents() == nullptr);
2150 AXTreeIDRegistry::AXTreeID RenderFrameHostImpl::RoutingIDToAXTreeID(
2151 int routing_id) {
2152 RenderFrameHostImpl* rfh = nullptr;
2153 RenderFrameProxyHost* rfph = RenderFrameProxyHost::FromID(
2154 GetProcess()->GetID(), routing_id);
2155 if (rfph) {
2156 FrameTree* frame_tree = frame_tree_node()->frame_tree();
2157 FrameTreeNode* frame_tree_node = frame_tree->FindByRoutingID(
2158 GetProcess()->GetID(), routing_id);
2159 rfh = frame_tree_node->render_manager()->current_frame_host();
2160 } else {
2161 rfh = RenderFrameHostImpl::FromID(GetProcess()->GetID(), routing_id);
2164 if (!rfh)
2165 return AXTreeIDRegistry::kNoAXTreeID;
2167 // As a sanity check, make sure we're within the same frame tree and
2168 // crash the renderer if not.
2169 if (rfh->frame_tree_node()->frame_tree() != frame_tree_node()->frame_tree()) {
2170 AccessibilityFatalError();
2171 return AXTreeIDRegistry::kNoAXTreeID;
2174 return rfh->GetAXTreeID();
2177 AXTreeIDRegistry::AXTreeID
2178 RenderFrameHostImpl::BrowserPluginInstanceIDToAXTreeID(
2179 int instance_id) {
2180 RenderFrameHost* guest = delegate()->GetGuestByInstanceID(
2181 this, instance_id);
2182 if (!guest)
2183 return AXTreeIDRegistry::kNoAXTreeID;
2185 return guest->GetAXTreeID();
2188 void RenderFrameHostImpl::AXContentNodeDataToAXNodeData(
2189 const AXContentNodeData& src,
2190 ui::AXNodeData* dst) {
2191 // Copy the common fields.
2192 *dst = src;
2194 // Map content-specific attributes based on routing IDs or browser plugin
2195 // instance IDs to generic attributes with global AXTreeIDs.
2196 for (auto iter : src.content_int_attributes) {
2197 AXContentIntAttribute attr = iter.first;
2198 int32 value = iter.second;
2199 switch (attr) {
2200 case AX_CONTENT_ATTR_ROUTING_ID:
2201 dst->int_attributes.push_back(std::make_pair(
2202 ui::AX_ATTR_TREE_ID, RoutingIDToAXTreeID(value)));
2203 break;
2204 case AX_CONTENT_ATTR_PARENT_ROUTING_ID:
2205 dst->int_attributes.push_back(std::make_pair(
2206 ui::AX_ATTR_PARENT_TREE_ID, RoutingIDToAXTreeID(value)));
2207 break;
2208 case AX_CONTENT_ATTR_CHILD_ROUTING_ID:
2209 dst->int_attributes.push_back(std::make_pair(
2210 ui::AX_ATTR_CHILD_TREE_ID, RoutingIDToAXTreeID(value)));
2211 break;
2212 case AX_CONTENT_ATTR_CHILD_BROWSER_PLUGIN_INSTANCE_ID:
2213 dst->int_attributes.push_back(std::make_pair(
2214 ui::AX_ATTR_CHILD_TREE_ID,
2215 BrowserPluginInstanceIDToAXTreeID(value)));
2216 break;
2217 case AX_CONTENT_INT_ATTRIBUTE_LAST:
2218 NOTREACHED();
2219 break;
2224 } // namespace content