Use multiline attribute to check for IA2_STATE_MULTILINE.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blobd4cc6f50c5f352ef7c908d8f5601785b97335ec6
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/frame_host/render_frame_host_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/containers/hash_tables.h"
10 #include "base/lazy_instance.h"
11 #include "base/metrics/histogram.h"
12 #include "base/process/kill.h"
13 #include "base/time/time.h"
14 #include "content/browser/accessibility/accessibility_mode_helper.h"
15 #include "content/browser/accessibility/browser_accessibility_manager.h"
16 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
17 #include "content/browser/bad_message.h"
18 #include "content/browser/child_process_security_policy_impl.h"
19 #include "content/browser/frame_host/cross_process_frame_connector.h"
20 #include "content/browser/frame_host/cross_site_transferring_request.h"
21 #include "content/browser/frame_host/frame_accessibility.h"
22 #include "content/browser/frame_host/frame_tree.h"
23 #include "content/browser/frame_host/frame_tree_node.h"
24 #include "content/browser/frame_host/navigation_request.h"
25 #include "content/browser/frame_host/navigator.h"
26 #include "content/browser/frame_host/navigator_impl.h"
27 #include "content/browser/frame_host/render_frame_host_delegate.h"
28 #include "content/browser/frame_host/render_frame_proxy_host.h"
29 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
30 #include "content/browser/geolocation/geolocation_service_context.h"
31 #include "content/browser/permissions/permission_service_context.h"
32 #include "content/browser/permissions/permission_service_impl.h"
33 #include "content/browser/presentation/presentation_service_impl.h"
34 #include "content/browser/renderer_host/input/input_router.h"
35 #include "content/browser/renderer_host/input/timeout_monitor.h"
36 #include "content/browser/renderer_host/render_process_host_impl.h"
37 #include "content/browser/renderer_host/render_view_host_delegate.h"
38 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
39 #include "content/browser/renderer_host/render_view_host_impl.h"
40 #include "content/browser/renderer_host/render_widget_host_impl.h"
41 #include "content/browser/renderer_host/render_widget_host_view_base.h"
42 #include "content/browser/transition_request_manager.h"
43 #include "content/common/accessibility_messages.h"
44 #include "content/common/frame_messages.h"
45 #include "content/common/input_messages.h"
46 #include "content/common/inter_process_time_ticks_converter.h"
47 #include "content/common/navigation_params.h"
48 #include "content/common/render_frame_setup.mojom.h"
49 #include "content/common/swapped_out_messages.h"
50 #include "content/public/browser/ax_event_notification_details.h"
51 #include "content/public/browser/browser_accessibility_state.h"
52 #include "content/public/browser/browser_context.h"
53 #include "content/public/browser/browser_plugin_guest_manager.h"
54 #include "content/public/browser/browser_thread.h"
55 #include "content/public/browser/content_browser_client.h"
56 #include "content/public/browser/permission_manager.h"
57 #include "content/public/browser/permission_type.h"
58 #include "content/public/browser/render_process_host.h"
59 #include "content/public/browser/render_widget_host_view.h"
60 #include "content/public/browser/stream_handle.h"
61 #include "content/public/browser/user_metrics.h"
62 #include "content/public/common/content_constants.h"
63 #include "content/public/common/content_switches.h"
64 #include "content/public/common/url_constants.h"
65 #include "content/public/common/url_utils.h"
66 #include "ui/accessibility/ax_tree.h"
67 #include "url/gurl.h"
69 #if defined(OS_MACOSX)
70 #include "content/browser/frame_host/popup_menu_helper_mac.h"
71 #endif
73 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
74 #include "media/mojo/interfaces/media_renderer.mojom.h"
75 #include "media/mojo/services/mojo_renderer_service.h"
76 #endif
78 using base::TimeDelta;
80 namespace content {
82 namespace {
84 // The next value to use for the accessibility reset token.
85 int g_next_accessibility_reset_token = 1;
87 // The (process id, routing id) pair that identifies one RenderFrame.
88 typedef std::pair<int32, int32> RenderFrameHostID;
89 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
90 RoutingIDFrameMap;
91 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
92 LAZY_INSTANCE_INITIALIZER;
94 // Translate a WebKit text direction into a base::i18n one.
95 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
96 blink::WebTextDirection dir) {
97 switch (dir) {
98 case blink::WebTextDirectionLeftToRight:
99 return base::i18n::LEFT_TO_RIGHT;
100 case blink::WebTextDirectionRightToLeft:
101 return base::i18n::RIGHT_TO_LEFT;
102 default:
103 NOTREACHED();
104 return base::i18n::UNKNOWN_DIRECTION;
108 } // namespace
110 // static
111 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
112 return rfh_state == STATE_DEFAULT;
115 // static
116 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
117 int render_frame_id) {
118 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
121 // static
122 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
123 int routing_id) {
124 DCHECK_CURRENTLY_ON(BrowserThread::UI);
125 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
126 RoutingIDFrameMap::iterator it = frames->find(
127 RenderFrameHostID(process_id, routing_id));
128 return it == frames->end() ? NULL : it->second;
131 RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
132 RenderViewHostImpl* render_view_host,
133 RenderFrameHostDelegate* delegate,
134 RenderWidgetHostDelegate* rwh_delegate,
135 FrameTree* frame_tree,
136 FrameTreeNode* frame_tree_node,
137 int routing_id,
138 int flags)
139 : render_view_host_(render_view_host),
140 delegate_(delegate),
141 site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
142 process_(site_instance->GetProcess()),
143 cross_process_frame_connector_(NULL),
144 render_frame_proxy_host_(NULL),
145 frame_tree_(frame_tree),
146 frame_tree_node_(frame_tree_node),
147 routing_id_(routing_id),
148 render_frame_created_(false),
149 navigations_suspended_(false),
150 is_waiting_for_beforeunload_ack_(false),
151 unload_ack_is_for_navigation_(false),
152 is_loading_(false),
153 accessibility_reset_token_(0),
154 accessibility_reset_count_(0),
155 no_create_browser_accessibility_manager_for_testing_(false),
156 weak_ptr_factory_(this) {
157 bool is_swapped_out = !!(flags & CREATE_RF_SWAPPED_OUT);
158 bool hidden = !!(flags & CREATE_RF_HIDDEN);
159 frame_tree_->RegisterRenderFrameHost(this);
160 GetProcess()->AddRoute(routing_id_, this);
161 g_routing_id_frame_map.Get().insert(std::make_pair(
162 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
163 this));
165 if (is_swapped_out) {
166 rfh_state_ = STATE_SWAPPED_OUT;
167 } else {
168 rfh_state_ = STATE_DEFAULT;
169 GetSiteInstance()->increment_active_frame_count();
172 SetUpMojoIfNeeded();
173 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
174 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
176 if (flags & CREATE_RF_NEEDS_RENDER_WIDGET_HOST) {
177 render_widget_host_.reset(new RenderWidgetHostImpl(
178 rwh_delegate, GetProcess(), MSG_ROUTING_NONE, hidden));
179 render_widget_host_->set_owned_by_render_frame_host(true);
183 RenderFrameHostImpl::~RenderFrameHostImpl() {
184 GetProcess()->RemoveRoute(routing_id_);
185 g_routing_id_frame_map.Get().erase(
186 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
188 if (delegate_ && render_frame_created_)
189 delegate_->RenderFrameDeleted(this);
191 FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this);
193 // If this was swapped out, it already decremented the active frame count of
194 // the SiteInstance it belongs to.
195 if (IsRFHStateActive(rfh_state_))
196 GetSiteInstance()->decrement_active_frame_count();
198 // Notify the FrameTree that this RFH is going away, allowing it to shut down
199 // the corresponding RenderViewHost if it is no longer needed.
200 frame_tree_->UnregisterRenderFrameHost(this);
202 // NULL out the swapout timer; in crash dumps this member will be null only if
203 // the dtor has run.
204 swapout_event_monitor_timeout_.reset();
206 for (const auto& iter: visual_state_callbacks_) {
207 iter.second.Run(false);
210 if (render_widget_host_)
211 render_widget_host_->Cleanup();
214 int RenderFrameHostImpl::GetRoutingID() {
215 return routing_id_;
218 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
219 return site_instance_.get();
222 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
223 return process_;
226 RenderFrameHost* RenderFrameHostImpl::GetParent() {
227 FrameTreeNode* parent_node = frame_tree_node_->parent();
228 if (!parent_node)
229 return NULL;
230 return parent_node->current_frame_host();
233 const std::string& RenderFrameHostImpl::GetFrameName() {
234 return frame_tree_node_->frame_name();
237 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
238 FrameTreeNode* parent_node = frame_tree_node_->parent();
239 if (!parent_node)
240 return false;
241 return GetSiteInstance() !=
242 parent_node->current_frame_host()->GetSiteInstance();
245 GURL RenderFrameHostImpl::GetLastCommittedURL() {
246 return frame_tree_node_->current_url();
249 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
250 RenderWidgetHostView* view = render_view_host_->GetView();
251 if (!view)
252 return NULL;
253 return view->GetNativeView();
256 void RenderFrameHostImpl::ExecuteJavaScript(
257 const base::string16& javascript) {
258 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
259 javascript,
260 0, false));
263 void RenderFrameHostImpl::ExecuteJavaScript(
264 const base::string16& javascript,
265 const JavaScriptResultCallback& callback) {
266 static int next_id = 1;
267 int key = next_id++;
268 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
269 javascript,
270 key, true));
271 javascript_callbacks_.insert(std::make_pair(key, callback));
274 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
275 const base::string16& javascript) {
276 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
277 javascript,
278 0, false));
281 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
282 return render_view_host_;
285 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
286 return service_registry_.get();
289 blink::WebPageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
290 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
291 // returning nullptr in some cases. See https://crbug.com/455245.
292 blink::WebPageVisibilityState visibility_state =
293 RenderWidgetHostImpl::From(GetView()->GetRenderWidgetHost())->is_hidden()
294 ? blink::WebPageVisibilityStateHidden
295 : blink::WebPageVisibilityStateVisible;
296 GetContentClient()->browser()->OverridePageVisibilityState(this,
297 &visibility_state);
298 return visibility_state;
301 bool RenderFrameHostImpl::Send(IPC::Message* message) {
302 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
303 return render_view_host_->input_router()->SendInput(
304 make_scoped_ptr(message));
307 return GetProcess()->Send(message);
310 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
311 // Filter out most IPC messages if this frame is swapped out.
312 // We still want to handle certain ACKs to keep our state consistent.
313 if (is_swapped_out()) {
314 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
315 // If this is a synchronous message and we decided not to handle it,
316 // we must send an error reply, or else the renderer will be stuck
317 // and won't respond to future requests.
318 if (msg.is_sync()) {
319 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
320 reply->set_reply_error();
321 Send(reply);
323 // Don't continue looking for someone to handle it.
324 return true;
328 if (delegate_->OnMessageReceived(this, msg))
329 return true;
331 RenderFrameProxyHost* proxy =
332 frame_tree_node_->render_manager()->GetProxyToParent();
333 if (proxy && proxy->cross_process_frame_connector() &&
334 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
335 return true;
337 bool handled = true;
338 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
339 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
340 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
341 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
342 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
343 OnDidStartProvisionalLoadForFrame)
344 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
345 OnDidFailProvisionalLoadWithError)
346 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
347 OnDidFailLoadWithError)
348 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
349 OnDidCommitProvisionalLoad(msg))
350 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDropNavigation, OnDidDropNavigation)
351 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
352 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
353 OnDocumentOnLoadCompleted)
354 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
355 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
356 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
357 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
358 OnJavaScriptExecuteResponse)
359 IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
360 OnVisualStateResponse)
361 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
362 OnRunJavaScriptMessage)
363 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
364 OnRunBeforeUnloadConfirm)
365 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
366 OnDidAccessInitialDocument)
367 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
368 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeName, OnDidChangeName)
369 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
370 IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeSandboxFlags,
371 OnDidChangeSandboxFlags)
372 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
373 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
374 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
375 OnBeginNavigation)
376 IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
377 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
378 OnTextSurroundingSelectionResponse)
379 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
380 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
381 OnAccessibilityLocationChanges)
382 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
383 OnAccessibilityFindInPageResult)
384 IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
385 // The following message is synthetic and doesn't come from RenderFrame, but
386 // from RenderProcessHost.
387 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
388 #if defined(OS_MACOSX) || defined(OS_ANDROID)
389 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
390 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
391 #endif
392 IPC_END_MESSAGE_MAP()
394 // No further actions here, since we may have been deleted.
395 return handled;
398 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
399 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
402 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
403 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
406 void RenderFrameHostImpl::AccessibilityShowMenu(
407 const gfx::Point& global_point) {
408 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
409 render_view_host_->GetView());
410 if (view)
411 view->AccessibilityShowMenu(global_point);
414 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
415 int acc_obj_id, const gfx::Rect& subfocus) {
416 Send(new AccessibilityMsg_ScrollToMakeVisible(
417 routing_id_, acc_obj_id, subfocus));
420 void RenderFrameHostImpl::AccessibilityScrollToPoint(
421 int acc_obj_id, const gfx::Point& point) {
422 Send(new AccessibilityMsg_ScrollToPoint(
423 routing_id_, acc_obj_id, point));
426 void RenderFrameHostImpl::AccessibilitySetTextSelection(
427 int object_id, int start_offset, int end_offset) {
428 Send(new AccessibilityMsg_SetTextSelection(
429 routing_id_, object_id, start_offset, end_offset));
432 void RenderFrameHostImpl::AccessibilitySetValue(
433 int object_id, const base::string16& value) {
434 Send(new AccessibilityMsg_SetValue(routing_id_, object_id, value));
437 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
438 RenderWidgetHostView* view = render_view_host_->GetView();
439 if (view)
440 return view->HasFocus();
441 return false;
444 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
445 RenderWidgetHostView* view = render_view_host_->GetView();
446 if (view)
447 return view->GetViewBounds();
448 return gfx::Rect();
451 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
452 const gfx::Rect& bounds) const {
453 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
454 render_view_host_->GetView());
455 if (view)
456 return view->AccessibilityOriginInScreen(bounds);
457 return gfx::Point();
460 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
461 Send(new AccessibilityMsg_HitTest(routing_id_, point));
464 void RenderFrameHostImpl::AccessibilitySetAccessibilityFocus(int acc_obj_id) {
465 Send(new AccessibilityMsg_SetAccessibilityFocus(routing_id_, acc_obj_id));
468 void RenderFrameHostImpl::AccessibilityFatalError() {
469 browser_accessibility_manager_.reset(NULL);
470 if (accessibility_reset_token_)
471 return;
473 accessibility_reset_count_++;
474 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
475 Send(new AccessibilityMsg_FatalError(routing_id_));
476 } else {
477 accessibility_reset_token_ = g_next_accessibility_reset_token++;
478 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
479 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
483 gfx::AcceleratedWidget
484 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
485 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
486 render_view_host_->GetView());
487 if (view)
488 return view->AccessibilityGetAcceleratedWidget();
489 return gfx::kNullAcceleratedWidget;
492 gfx::NativeViewAccessible
493 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
494 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
495 render_view_host_->GetView());
496 if (view)
497 return view->AccessibilityGetNativeViewAccessible();
498 return NULL;
501 BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame(
502 int accessibility_node_id) {
503 RenderFrameHostImpl* child_frame =
504 FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id);
505 if (!child_frame || IsSameSiteInstance(child_frame))
506 return nullptr;
508 return child_frame->GetOrCreateBrowserAccessibilityManager();
511 void RenderFrameHostImpl::AccessibilityGetAllChildFrames(
512 std::vector<BrowserAccessibilityManager*>* child_frames) {
513 std::vector<RenderFrameHostImpl*> child_frame_hosts;
514 FrameAccessibility::GetInstance()->GetAllChildFrames(
515 this, &child_frame_hosts);
516 for (size_t i = 0; i < child_frame_hosts.size(); ++i) {
517 RenderFrameHostImpl* child_frame_host = child_frame_hosts[i];
518 if (!child_frame_host || IsSameSiteInstance(child_frame_host))
519 continue;
521 BrowserAccessibilityManager* manager =
522 child_frame_host->GetOrCreateBrowserAccessibilityManager();
523 if (manager)
524 child_frames->push_back(manager);
528 BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() {
529 RenderFrameHostImpl* parent_frame = NULL;
530 int parent_node_id = 0;
531 if (!FrameAccessibility::GetInstance()->GetParent(
532 this, &parent_frame, &parent_node_id)) {
533 return NULL;
536 // As a sanity check, make sure the frame we're going to return belongs
537 // to the same BrowserContext.
538 if (GetSiteInstance()->GetBrowserContext() !=
539 parent_frame->GetSiteInstance()->GetBrowserContext()) {
540 NOTREACHED();
541 return NULL;
544 BrowserAccessibilityManager* manager =
545 parent_frame->browser_accessibility_manager();
546 if (!manager)
547 return NULL;
549 return manager->GetFromID(parent_node_id);
552 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id,
553 int proxy_routing_id) {
554 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
555 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
557 // The process may (if we're sharing a process with another host that already
558 // initialized it) or may not (we have our own process or the old process
559 // crashed) have been initialized. Calling Init multiple times will be
560 // ignored, so this is safe.
561 if (!GetProcess()->Init())
562 return false;
564 DCHECK(GetProcess()->HasConnection());
566 FrameMsg_NewFrame_WidgetParams widget_params;
567 if (render_widget_host_) {
568 widget_params.routing_id = render_widget_host_->GetRoutingID();
569 widget_params.surface_id = render_widget_host_->surface_id();
570 widget_params.hidden = render_widget_host_->is_hidden();
571 } else {
572 // MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
573 // the renderer process.
574 widget_params.routing_id = MSG_ROUTING_NONE;
575 widget_params.surface_id = 0;
576 widget_params.hidden = true;
579 Send(new FrameMsg_NewFrame(routing_id_, parent_routing_id, proxy_routing_id,
580 frame_tree_node()->current_replication_state(),
581 widget_params));
583 // The RenderWidgetHost takes ownership of its view. It is tied to the
584 // lifetime of the current RenderProcessHost for this RenderFrameHost.
585 if (render_widget_host_) {
586 RenderWidgetHostView* rwhv =
587 new RenderWidgetHostViewChildFrame(render_widget_host_.get());
588 rwhv->Hide();
591 if (proxy_routing_id != MSG_ROUTING_NONE) {
592 RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
593 GetProcess()->GetID(), proxy_routing_id);
594 // We have also created a RenderFrameProxy in FrameMsg_NewFrame above, so
595 // remember that.
596 proxy->set_render_frame_proxy_created(true);
599 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
600 // this path is only used for out-of-process iframes. Main frame RenderFrames
601 // are created with their RenderView, and same-site iframes are created at the
602 // time of OnCreateChildFrame.
603 SetRenderFrameCreated(true);
605 return true;
608 bool RenderFrameHostImpl::IsRenderFrameLive() {
609 // RenderFrames are created for main frames at the same time as RenderViews,
610 // so we rely on IsRenderViewLive. For subframes, we keep track of each
611 // RenderFrame individually with render_frame_created_.
612 bool is_live = !GetParent() ?
613 render_view_host_->IsRenderViewLive() :
614 GetProcess()->HasConnection() && render_frame_created_;
616 // Sanity check: the RenderView should always be live if the RenderFrame is.
617 DCHECK(!is_live || render_view_host_->IsRenderViewLive());
619 return is_live;
622 void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
623 // If the current status is different than the new status, the delegate
624 // needs to be notified.
625 if (delegate_ && (created != render_frame_created_)) {
626 if (created)
627 delegate_->RenderFrameCreated(this);
628 else
629 delegate_->RenderFrameDeleted(this);
632 render_frame_created_ = created;
633 if (created && render_widget_host_)
634 render_widget_host_->InitForFrame();
637 void RenderFrameHostImpl::Init() {
638 GetProcess()->ResumeRequestsForView(routing_id_);
641 void RenderFrameHostImpl::OnAddMessageToConsole(
642 int32 level,
643 const base::string16& message,
644 int32 line_no,
645 const base::string16& source_id) {
646 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
647 return;
649 // Pass through log level only on WebUI pages to limit console spew.
650 const bool is_web_ui =
651 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL());
652 const int32 resolved_level = is_web_ui ? level : ::logging::LOG_INFO;
654 // LogMessages can be persisted so this shouldn't be logged in incognito mode.
655 // This rule is not applied to WebUI pages, because source code of WebUI is a
656 // part of Chrome source code, and we want to treat messages from WebUI the
657 // same way as we treat log messages from native code.
658 if (::logging::GetMinLogLevel() <= resolved_level &&
659 (is_web_ui ||
660 !GetSiteInstance()->GetBrowserContext()->IsOffTheRecord())) {
661 logging::LogMessage("CONSOLE", line_no, resolved_level).stream()
662 << "\"" << message << "\", source: " << source_id << " (" << line_no
663 << ")";
667 void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id,
668 const std::string& frame_name,
669 SandboxFlags sandbox_flags) {
670 // It is possible that while a new RenderFrameHost was committed, the
671 // RenderFrame corresponding to this host sent an IPC message to create a
672 // frame and it is delivered after this host is swapped out.
673 // Ignore such messages, as we know this RenderFrameHost is going away.
674 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
675 return;
677 RenderFrameHostImpl* new_frame = frame_tree_->AddFrame(
678 frame_tree_node_, GetProcess()->GetID(), new_routing_id, frame_name);
679 if (!new_frame)
680 return;
682 // Set sandbox flags for the new frame. The flags are committed immediately,
683 // since they should apply to the initial empty document in the frame.
684 new_frame->frame_tree_node()->set_sandbox_flags(sandbox_flags);
685 new_frame->frame_tree_node()->CommitPendingSandboxFlags();
687 // We know that the RenderFrame has been created in this case, immediately
688 // after the CreateChildFrame IPC was sent.
689 new_frame->SetRenderFrameCreated(true);
692 void RenderFrameHostImpl::OnDetach() {
693 frame_tree_->RemoveFrame(frame_tree_node_);
696 void RenderFrameHostImpl::OnFrameFocused() {
697 frame_tree_->SetFocusedFrame(frame_tree_node_);
700 void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
701 OpenURL(params, GetSiteInstance());
704 void RenderFrameHostImpl::OnDocumentOnLoadCompleted(
705 FrameMsg_UILoadMetricsReportType::Value report_type,
706 base::TimeTicks ui_timestamp) {
707 if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
708 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Link",
709 base::TimeTicks::Now() - ui_timestamp,
710 base::TimeDelta::FromMilliseconds(10),
711 base::TimeDelta::FromMinutes(10), 100);
712 } else if (report_type == FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
713 UMA_HISTOGRAM_CUSTOM_TIMES("Navigation.UI_OnLoadComplete.Intent",
714 base::TimeTicks::Now() - ui_timestamp,
715 base::TimeDelta::FromMilliseconds(10),
716 base::TimeDelta::FromMinutes(10), 100);
718 // This message is only sent for top-level frames. TODO(avi): when frame tree
719 // mirroring works correctly, add a check here to enforce it.
720 delegate_->DocumentOnLoadCompleted(this);
723 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(
724 const GURL& url,
725 bool is_transition_navigation) {
726 frame_tree_node_->navigator()->DidStartProvisionalLoad(
727 this, url, is_transition_navigation);
730 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
731 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
732 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
735 void RenderFrameHostImpl::OnDidFailLoadWithError(
736 const GURL& url,
737 int error_code,
738 const base::string16& error_description) {
739 GURL validated_url(url);
740 GetProcess()->FilterURL(false, &validated_url);
742 frame_tree_node_->navigator()->DidFailLoadWithError(
743 this, validated_url, error_code, error_description);
746 // Called when the renderer navigates. For every frame loaded, we'll get this
747 // notification containing parameters identifying the navigation.
749 // Subframes are identified by the page transition type. For subframes loaded
750 // as part of a wider page load, the page_id will be the same as for the top
751 // level frame. If the user explicitly requests a subframe navigation, we will
752 // get a new page_id because we need to create a new navigation entry for that
753 // action.
754 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
755 // Read the parameters out of the IPC message directly to avoid making another
756 // copy when we filter the URLs.
757 PickleIterator iter(msg);
758 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
759 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
760 Read(&msg, &iter, &validated_params))
761 return;
762 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
763 "url", validated_params.url.possibly_invalid_spec());
765 // If we're waiting for a cross-site beforeunload ack from this renderer and
766 // we receive a Navigate message from the main frame, then the renderer was
767 // navigating already and sent it before hearing the FrameMsg_Stop message.
768 // We do not want to cancel the pending navigation in this case, since the
769 // old page will soon be stopped. Instead, treat this as a beforeunload ack
770 // to allow the pending navigation to continue.
771 if (is_waiting_for_beforeunload_ack_ &&
772 unload_ack_is_for_navigation_ &&
773 ui::PageTransitionIsMainFrame(validated_params.transition)) {
774 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
775 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
776 return;
779 // If we're waiting for an unload ack from this renderer and we receive a
780 // Navigate message, then the renderer was navigating before it received the
781 // unload request. It will either respond to the unload request soon or our
782 // timer will expire. Either way, we should ignore this message, because we
783 // have already committed to closing this renderer.
784 if (IsWaitingForUnloadACK())
785 return;
787 if (validated_params.report_type ==
788 FrameMsg_UILoadMetricsReportType::REPORT_LINK) {
789 UMA_HISTOGRAM_CUSTOM_TIMES(
790 "Navigation.UI_OnCommitProvisionalLoad.Link",
791 base::TimeTicks::Now() - validated_params.ui_timestamp,
792 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
793 100);
794 } else if (validated_params.report_type ==
795 FrameMsg_UILoadMetricsReportType::REPORT_INTENT) {
796 UMA_HISTOGRAM_CUSTOM_TIMES(
797 "Navigation.UI_OnCommitProvisionalLoad.Intent",
798 base::TimeTicks::Now() - validated_params.ui_timestamp,
799 base::TimeDelta::FromMilliseconds(10), base::TimeDelta::FromMinutes(10),
800 100);
803 RenderProcessHost* process = GetProcess();
805 // Attempts to commit certain off-limits URL should be caught more strictly
806 // than our FilterURL checks below. If a renderer violates this policy, it
807 // should be killed.
808 if (!CanCommitURL(validated_params.url)) {
809 VLOG(1) << "Blocked URL " << validated_params.url.spec();
810 validated_params.url = GURL(url::kAboutBlankURL);
811 // Kills the process.
812 bad_message::ReceivedBadMessage(process,
813 bad_message::RFH_CAN_COMMIT_URL_BLOCKED);
816 // Without this check, an evil renderer can trick the browser into creating
817 // a navigation entry for a banned URL. If the user clicks the back button
818 // followed by the forward button (or clicks reload, or round-trips through
819 // session restore, etc), we'll think that the browser commanded the
820 // renderer to load the URL and grant the renderer the privileges to request
821 // the URL. To prevent this attack, we block the renderer from inserting
822 // banned URLs into the navigation controller in the first place.
823 process->FilterURL(false, &validated_params.url);
824 process->FilterURL(true, &validated_params.referrer.url);
825 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
826 it != validated_params.redirects.end(); ++it) {
827 process->FilterURL(false, &(*it));
829 process->FilterURL(true, &validated_params.searchable_form_url);
831 // Without this check, the renderer can trick the browser into using
832 // filenames it can't access in a future session restore.
833 if (!render_view_host_->CanAccessFilesOfPageState(
834 validated_params.page_state)) {
835 bad_message::ReceivedBadMessage(
836 GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
837 return;
840 accessibility_reset_count_ = 0;
841 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
844 void RenderFrameHostImpl::OnDidDropNavigation() {
845 // At the end of Navigate(), the delegate's DidStartLoading is called to force
846 // the spinner to start, even if the renderer didn't yet begin the load. If it
847 // turns out that the renderer dropped the navigation, we need to turn off the
848 // spinner.
849 delegate_->DidStopLoading();
852 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
853 if (render_widget_host_)
854 return render_widget_host_.get();
856 // TODO(kenrb): When RenderViewHost no longer inherits RenderWidgetHost,
857 // we can remove this fallback. Currently it is only used for the main
858 // frame.
859 if (!GetParent())
860 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
862 return nullptr;
865 RenderWidgetHostView* RenderFrameHostImpl::GetView() {
866 RenderFrameHostImpl* frame = this;
867 while (frame) {
868 if (frame->render_widget_host_)
869 return frame->render_widget_host_->GetView();
870 frame = static_cast<RenderFrameHostImpl*>(frame->GetParent());
873 return render_view_host_->GetView();
876 int RenderFrameHostImpl::GetEnabledBindings() {
877 return render_view_host_->GetEnabledBindings();
880 void RenderFrameHostImpl::OnCrossSiteResponse(
881 const GlobalRequestID& global_request_id,
882 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
883 const std::vector<GURL>& transfer_url_chain,
884 const Referrer& referrer,
885 ui::PageTransition page_transition,
886 bool should_replace_current_entry) {
887 frame_tree_node_->render_manager()->OnCrossSiteResponse(
888 this, global_request_id, cross_site_transferring_request.Pass(),
889 transfer_url_chain, referrer, page_transition,
890 should_replace_current_entry);
893 void RenderFrameHostImpl::OnDeferredAfterResponseStarted(
894 const GlobalRequestID& global_request_id,
895 const TransitionLayerData& transition_data) {
896 frame_tree_node_->render_manager()->OnDeferredAfterResponseStarted(
897 global_request_id, this);
899 if (GetParent() || !delegate_->WillHandleDeferAfterResponseStarted())
900 frame_tree_node_->render_manager()->ResumeResponseDeferredAtStart();
901 else
902 delegate_->DidDeferAfterResponseStarted(transition_data);
905 void RenderFrameHostImpl::SwapOut(
906 RenderFrameProxyHost* proxy,
907 bool is_loading) {
908 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
909 // the operation and sends back an IPC message.
910 // The trace event may not end properly if the ACK times out. We expect this
911 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
912 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
914 // If this RenderFrameHost is not in the default state, it must have already
915 // gone through this, therefore just return.
916 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
917 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
918 return;
921 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
922 swapout_event_monitor_timeout_->Start(
923 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
925 // There may be no proxy if there are no active views in the process.
926 int proxy_routing_id = MSG_ROUTING_NONE;
927 FrameReplicationState replication_state;
928 if (proxy) {
929 set_render_frame_proxy_host(proxy);
930 proxy_routing_id = proxy->GetRoutingID();
931 replication_state = proxy->frame_tree_node()->current_replication_state();
934 if (IsRenderFrameLive()) {
935 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id, is_loading,
936 replication_state));
939 if (!GetParent())
940 delegate_->SwappedOut(this);
943 void RenderFrameHostImpl::OnBeforeUnloadACK(
944 bool proceed,
945 const base::TimeTicks& renderer_before_unload_start_time,
946 const base::TimeTicks& renderer_before_unload_end_time) {
947 TRACE_EVENT_ASYNC_END0(
948 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
949 DCHECK(!GetParent());
950 // If this renderer navigated while the beforeunload request was in flight, we
951 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
952 // can ignore this message.
953 // However renderer might also be swapped out but we still want to proceed
954 // with navigation, otherwise it would block future navigations. This can
955 // happen when pending cross-site navigation is canceled by a second one just
956 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
957 // but second navigation is started from the beginning.
958 if (!is_waiting_for_beforeunload_ack_) {
959 return;
961 DCHECK(!send_before_unload_start_time_.is_null());
963 // Sets a default value for before_unload_end_time so that the browser
964 // survives a hacked renderer.
965 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
966 if (!renderer_before_unload_start_time.is_null() &&
967 !renderer_before_unload_end_time.is_null()) {
968 // When passing TimeTicks across process boundaries, we need to compensate
969 // for any skew between the processes. Here we are converting the
970 // renderer's notion of before_unload_end_time to TimeTicks in the browser
971 // process. See comments in inter_process_time_ticks_converter.h for more.
972 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
973 InterProcessTimeTicksConverter converter(
974 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
975 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
976 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
977 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
978 LocalTimeTicks browser_before_unload_end_time =
979 converter.ToLocalTimeTicks(
980 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
981 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
983 // Collect UMA on the inter-process skew.
984 bool is_skew_additive = false;
985 if (converter.IsSkewAdditiveForMetrics()) {
986 is_skew_additive = true;
987 base::TimeDelta skew = converter.GetSkewForMetrics();
988 if (skew >= base::TimeDelta()) {
989 UMA_HISTOGRAM_TIMES(
990 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
991 } else {
992 UMA_HISTOGRAM_TIMES(
993 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
996 UMA_HISTOGRAM_BOOLEAN(
997 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
998 is_skew_additive);
1000 base::TimeDelta on_before_unload_overhead_time =
1001 (receive_before_unload_ack_time - send_before_unload_start_time_) -
1002 (renderer_before_unload_end_time - renderer_before_unload_start_time);
1003 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
1004 on_before_unload_overhead_time);
1006 frame_tree_node_->navigator()->LogBeforeUnloadTime(
1007 renderer_before_unload_start_time, renderer_before_unload_end_time);
1009 // Resets beforeunload waiting state.
1010 is_waiting_for_beforeunload_ack_ = false;
1011 render_view_host_->decrement_in_flight_event_count();
1012 render_view_host_->StopHangMonitorTimeout();
1013 send_before_unload_start_time_ = base::TimeTicks();
1015 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1016 switches::kEnableBrowserSideNavigation)) {
1017 // TODO(clamy): see if before_unload_end_time should be transmitted to the
1018 // Navigator.
1019 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1020 frame_tree_node_, proceed);
1021 } else {
1022 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1023 unload_ack_is_for_navigation_, proceed,
1024 before_unload_end_time);
1027 // If canceled, notify the delegate to cancel its pending navigation entry.
1028 if (!proceed)
1029 render_view_host_->GetDelegate()->DidCancelLoading();
1032 bool RenderFrameHostImpl::IsWaitingForBeforeUnloadACK() const {
1033 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1034 switches::kEnableBrowserSideNavigation)) {
1035 return is_waiting_for_beforeunload_ack_;
1037 return frame_tree_node_->navigator()->IsWaitingForBeforeUnloadACK(
1038 frame_tree_node_);
1041 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
1042 return render_view_host_->is_waiting_for_close_ack_ ||
1043 rfh_state_ == STATE_PENDING_SWAP_OUT;
1046 void RenderFrameHostImpl::OnSwapOutACK() {
1047 OnSwappedOut();
1050 void RenderFrameHostImpl::OnRenderProcessGone(int status, int exit_code) {
1051 if (frame_tree_node_->IsMainFrame()) {
1052 // Keep the termination status so we can get at it later when we
1053 // need to know why it died.
1054 render_view_host_->render_view_termination_status_ =
1055 static_cast<base::TerminationStatus>(status);
1058 // Reset frame tree state associated with this process. This must happen
1059 // before RenderViewTerminated because observers expect the subframes of any
1060 // affected frames to be cleared first.
1061 // Note: When a RenderFrameHost is swapped out there is a different one
1062 // which is the current host. In this case, the FrameTreeNode state must
1063 // not be reset.
1064 if (!is_swapped_out())
1065 frame_tree_node_->ResetForNewProcess();
1067 // Reset state for the current RenderFrameHost once the FrameTreeNode has been
1068 // reset.
1069 SetRenderFrameCreated(false);
1070 InvalidateMojoConnection();
1072 if (frame_tree_node_->IsMainFrame()) {
1073 // RenderViewHost/RenderWidgetHost needs to reset some stuff.
1074 render_view_host_->RendererExited(
1075 render_view_host_->render_view_termination_status_, exit_code);
1077 render_view_host_->delegate_->RenderViewTerminated(
1078 render_view_host_, static_cast<base::TerminationStatus>(status),
1079 exit_code);
1083 void RenderFrameHostImpl::OnSwappedOut() {
1084 // Ignore spurious swap out ack.
1085 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
1086 return;
1088 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
1089 swapout_event_monitor_timeout_->Stop();
1091 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
1092 // We are now deleted.
1093 return;
1096 // If this RFH wasn't pending deletion, then it is now swapped out.
1097 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
1100 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
1101 // Validate the URLs in |params|. If the renderer can't request the URLs
1102 // directly, don't show them in the context menu.
1103 ContextMenuParams validated_params(params);
1104 RenderProcessHost* process = GetProcess();
1106 // We don't validate |unfiltered_link_url| so that this field can be used
1107 // when users want to copy the original link URL.
1108 process->FilterURL(true, &validated_params.link_url);
1109 process->FilterURL(true, &validated_params.src_url);
1110 process->FilterURL(false, &validated_params.page_url);
1111 process->FilterURL(true, &validated_params.frame_url);
1113 delegate_->ShowContextMenu(this, validated_params);
1116 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
1117 int id, const base::ListValue& result) {
1118 const base::Value* result_value;
1119 if (!result.Get(0, &result_value)) {
1120 // Programming error or rogue renderer.
1121 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
1122 return;
1125 std::map<int, JavaScriptResultCallback>::iterator it =
1126 javascript_callbacks_.find(id);
1127 if (it != javascript_callbacks_.end()) {
1128 it->second.Run(result_value);
1129 javascript_callbacks_.erase(it);
1130 } else {
1131 NOTREACHED() << "Received script response for unknown request";
1135 void RenderFrameHostImpl::OnVisualStateResponse(uint64 id) {
1136 auto it = visual_state_callbacks_.find(id);
1137 if (it != visual_state_callbacks_.end()) {
1138 it->second.Run(true);
1139 visual_state_callbacks_.erase(it);
1140 } else {
1141 NOTREACHED() << "Received script response for unknown request";
1145 void RenderFrameHostImpl::OnRunJavaScriptMessage(
1146 const base::string16& message,
1147 const base::string16& default_prompt,
1148 const GURL& frame_url,
1149 JavaScriptMessageType type,
1150 IPC::Message* reply_msg) {
1151 // While a JS message dialog is showing, tabs in the same process shouldn't
1152 // process input events.
1153 GetProcess()->SetIgnoreInputEvents(true);
1154 render_view_host_->StopHangMonitorTimeout();
1155 delegate_->RunJavaScriptMessage(this, message, default_prompt,
1156 frame_url, type, reply_msg);
1159 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
1160 const GURL& frame_url,
1161 const base::string16& message,
1162 bool is_reload,
1163 IPC::Message* reply_msg) {
1164 // While a JS beforeunload dialog is showing, tabs in the same process
1165 // shouldn't process input events.
1166 GetProcess()->SetIgnoreInputEvents(true);
1167 render_view_host_->StopHangMonitorTimeout();
1168 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1171 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1172 const base::string16& content,
1173 size_t start_offset,
1174 size_t end_offset) {
1175 render_view_host_->OnTextSurroundingSelectionResponse(
1176 content, start_offset, end_offset);
1179 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1180 delegate_->DidAccessInitialDocument();
1183 void RenderFrameHostImpl::OnDidDisownOpener() {
1184 // This message is only sent for top-level frames. TODO(avi): when frame tree
1185 // mirroring works correctly, add a check here to enforce it.
1186 delegate_->DidDisownOpener(this);
1189 void RenderFrameHostImpl::OnDidChangeName(const std::string& name) {
1190 frame_tree_node()->SetFrameName(name);
1191 delegate_->DidChangeName(this, name);
1194 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1195 // Update the RVH's current page ID so that future IPCs from the renderer
1196 // correspond to the new page.
1197 render_view_host_->page_id_ = page_id;
1200 void RenderFrameHostImpl::OnDidChangeSandboxFlags(int32 frame_routing_id,
1201 SandboxFlags flags) {
1202 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1203 FrameTreeNode* child =
1204 frame_tree->FindByRoutingID(GetProcess()->GetID(), frame_routing_id);
1205 if (!child)
1206 return;
1208 // Ensure that a frame can only update sandbox flags for its immediate
1209 // children. If this is not the case, the renderer is considered malicious
1210 // and is killed.
1211 if (child->parent() != frame_tree_node()) {
1212 bad_message::ReceivedBadMessage(GetProcess(),
1213 bad_message::RFH_SANDBOX_FLAGS);
1214 return;
1217 child->set_sandbox_flags(flags);
1219 // Notify the RenderFrame if it lives in a different process from its
1220 // parent. The frame's proxies in other processes also need to learn about
1221 // the updated sandbox flags, but these notifications are sent later in
1222 // RenderFrameHostManager::CommitPendingSandboxFlags(), when the frame
1223 // navigates and the new sandbox flags take effect.
1224 RenderFrameHost* child_rfh = child->current_frame_host();
1225 if (child_rfh->GetSiteInstance() != GetSiteInstance()) {
1226 child_rfh->Send(
1227 new FrameMsg_DidUpdateSandboxFlags(child_rfh->GetRoutingID(), flags));
1231 void RenderFrameHostImpl::OnUpdateTitle(
1232 const base::string16& title,
1233 blink::WebTextDirection title_direction) {
1234 // This message is only sent for top-level frames. TODO(avi): when frame tree
1235 // mirroring works correctly, add a check here to enforce it.
1236 if (title.length() > kMaxTitleChars) {
1237 NOTREACHED() << "Renderer sent too many characters in title.";
1238 return;
1241 delegate_->UpdateTitle(this, render_view_host_->page_id_, title,
1242 WebTextDirectionToChromeTextDirection(
1243 title_direction));
1246 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1247 // This message is only sent for top-level frames. TODO(avi): when frame tree
1248 // mirroring works correctly, add a check here to enforce it.
1249 delegate_->UpdateEncoding(this, encoding_name);
1252 void RenderFrameHostImpl::OnBeginNavigation(
1253 const CommonNavigationParams& common_params,
1254 const BeginNavigationParams& begin_params,
1255 scoped_refptr<ResourceRequestBody> body) {
1256 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1257 switches::kEnableBrowserSideNavigation));
1258 frame_tree_node()->navigator()->OnBeginNavigation(
1259 frame_tree_node(), common_params, begin_params, body);
1262 void RenderFrameHostImpl::OnDispatchLoad() {
1263 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
1264 switches::kSitePerProcess));
1265 // Only frames with an out-of-process parent frame should be sending this
1266 // message.
1267 RenderFrameProxyHost* proxy =
1268 frame_tree_node()->render_manager()->GetProxyToParent();
1269 if (!proxy) {
1270 bad_message::ReceivedBadMessage(GetProcess(),
1271 bad_message::RFH_NO_PROXY_TO_PARENT);
1272 return;
1275 proxy->Send(new FrameMsg_DispatchLoad(proxy->GetRoutingID()));
1278 void RenderFrameHostImpl::OnAccessibilityEvents(
1279 const std::vector<AccessibilityHostMsg_EventParams>& params,
1280 int reset_token) {
1281 // Don't process this IPC if either we're waiting on a reset and this
1282 // IPC doesn't have the matching token ID, or if we're not waiting on a
1283 // reset but this message includes a reset token.
1284 if (accessibility_reset_token_ != reset_token) {
1285 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1286 return;
1288 accessibility_reset_token_ = 0;
1290 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1291 render_view_host_->GetView());
1293 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1294 if ((accessibility_mode != AccessibilityModeOff) && view &&
1295 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1296 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1297 GetOrCreateBrowserAccessibilityManager();
1298 if (browser_accessibility_manager_)
1299 browser_accessibility_manager_->OnAccessibilityEvents(params);
1302 if (browser_accessibility_manager_) {
1303 // Get the frame routing ids from out-of-process iframes and
1304 // browser plugin instance ids from guests and update the mappings in
1305 // FrameAccessibility.
1306 for (size_t i = 0; i < params.size(); ++i) {
1307 const AccessibilityHostMsg_EventParams& param = params[i];
1308 UpdateCrossProcessIframeAccessibility(
1309 param.node_to_frame_routing_id_map);
1310 UpdateGuestFrameAccessibility(
1311 param.node_to_browser_plugin_instance_id_map);
1315 // Send the updates to the automation extension API.
1316 std::vector<AXEventNotificationDetails> details;
1317 details.reserve(params.size());
1318 for (size_t i = 0; i < params.size(); ++i) {
1319 const AccessibilityHostMsg_EventParams& param = params[i];
1320 AXEventNotificationDetails detail(param.update.node_id_to_clear,
1321 param.update.nodes,
1322 param.event_type,
1323 param.id,
1324 GetProcess()->GetID(),
1325 routing_id_);
1326 details.push_back(detail);
1329 delegate_->AccessibilityEventReceived(details);
1332 // Always send an ACK or the renderer can be in a bad state.
1333 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1335 // The rest of this code is just for testing; bail out if we're not
1336 // in that mode.
1337 if (accessibility_testing_callback_.is_null())
1338 return;
1340 for (size_t i = 0; i < params.size(); i++) {
1341 const AccessibilityHostMsg_EventParams& param = params[i];
1342 if (static_cast<int>(param.event_type) < 0)
1343 continue;
1345 if (!ax_tree_for_testing_) {
1346 if (browser_accessibility_manager_) {
1347 ax_tree_for_testing_.reset(new ui::AXTree(
1348 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1349 } else {
1350 ax_tree_for_testing_.reset(new ui::AXTree());
1351 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1352 << ax_tree_for_testing_->error();
1354 } else {
1355 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1356 << ax_tree_for_testing_->error();
1358 accessibility_testing_callback_.Run(param.event_type, param.id);
1362 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1363 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1364 if (accessibility_reset_token_)
1365 return;
1367 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1368 render_view_host_->GetView());
1369 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1370 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1371 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1372 BrowserAccessibilityManager* manager =
1373 GetOrCreateBrowserAccessibilityManager();
1374 if (manager)
1375 manager->OnLocationChanges(params);
1377 // TODO(aboxhall): send location change events to web contents observers too
1381 void RenderFrameHostImpl::OnAccessibilityFindInPageResult(
1382 const AccessibilityHostMsg_FindInPageResultParams& params) {
1383 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1384 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1385 BrowserAccessibilityManager* manager =
1386 GetOrCreateBrowserAccessibilityManager();
1387 if (manager) {
1388 manager->OnFindInPageResult(
1389 params.request_id, params.match_index, params.start_id,
1390 params.start_offset, params.end_id, params.end_offset);
1395 void RenderFrameHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1396 if (enter_fullscreen)
1397 delegate_->EnterFullscreenMode(GetLastCommittedURL().GetOrigin());
1398 else
1399 delegate_->ExitFullscreenMode();
1401 // The previous call might change the fullscreen state. We need to make sure
1402 // the renderer is aware of that, which is done via the resize message.
1403 render_view_host_->WasResized();
1406 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1407 void RenderFrameHostImpl::OnShowPopup(
1408 const FrameHostMsg_ShowPopup_Params& params) {
1409 RenderViewHostDelegateView* view =
1410 render_view_host_->delegate_->GetDelegateView();
1411 if (view) {
1412 view->ShowPopupMenu(this,
1413 params.bounds,
1414 params.item_height,
1415 params.item_font_size,
1416 params.selected_item,
1417 params.popup_items,
1418 params.right_aligned,
1419 params.allow_multiple_selection);
1423 void RenderFrameHostImpl::OnHidePopup() {
1424 RenderViewHostDelegateView* view =
1425 render_view_host_->delegate_->GetDelegateView();
1426 if (view)
1427 view->HidePopupMenu();
1429 #endif
1431 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1432 static void CreateMediaRendererService(
1433 mojo::InterfaceRequest<mojo::MediaRenderer> request) {
1434 media::MojoRendererService* service = new media::MojoRendererService();
1435 mojo::BindToRequest(service, &request);
1437 #endif
1439 void RenderFrameHostImpl::RegisterMojoServices() {
1440 GeolocationServiceContext* geolocation_service_context =
1441 delegate_ ? delegate_->GetGeolocationServiceContext() : NULL;
1442 if (geolocation_service_context) {
1443 // TODO(creis): Bind process ID here so that GeolocationServiceImpl
1444 // can perform permissions checks once site isolation is complete.
1445 // crbug.com/426384
1446 GetServiceRegistry()->AddService<GeolocationService>(
1447 base::Bind(&GeolocationServiceContext::CreateService,
1448 base::Unretained(geolocation_service_context),
1449 base::Bind(&RenderFrameHostImpl::DidUseGeolocationPermission,
1450 base::Unretained(this))));
1453 if (!permission_service_context_)
1454 permission_service_context_.reset(new PermissionServiceContext(this));
1456 GetServiceRegistry()->AddService<PermissionService>(
1457 base::Bind(&PermissionServiceContext::CreateService,
1458 base::Unretained(permission_service_context_.get())));
1460 GetServiceRegistry()->AddService<presentation::PresentationService>(
1461 base::Bind(&PresentationServiceImpl::CreateMojoService,
1462 base::Unretained(this)));
1464 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1465 GetServiceRegistry()->AddService<mojo::MediaRenderer>(
1466 base::Bind(&CreateMediaRendererService));
1467 #endif
1470 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1471 // Only main frames should be swapped out and retained inside a proxy host.
1472 if (rfh_state == STATE_SWAPPED_OUT)
1473 CHECK(!GetParent());
1475 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1476 // out status of a RenderFrameHost gets flipped to/from active.
1477 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1478 GetSiteInstance()->increment_active_frame_count();
1479 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1480 GetSiteInstance()->decrement_active_frame_count();
1482 // The active and swapped out state of the RVH is determined by its main
1483 // frame, since subframes should have their own widgets.
1484 if (frame_tree_node_->IsMainFrame()) {
1485 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1486 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1489 // Whenever we change the RFH state to and from active or swapped out state,
1490 // we should not be waiting for beforeunload or close acks. We clear them
1491 // here to be safe, since they can cause navigations to be ignored in
1492 // OnDidCommitProvisionalLoad.
1493 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1494 if (rfh_state == STATE_DEFAULT ||
1495 rfh_state == STATE_SWAPPED_OUT ||
1496 rfh_state_ == STATE_DEFAULT ||
1497 rfh_state_ == STATE_SWAPPED_OUT) {
1498 if (is_waiting_for_beforeunload_ack_) {
1499 is_waiting_for_beforeunload_ack_ = false;
1500 render_view_host_->decrement_in_flight_event_count();
1501 render_view_host_->StopHangMonitorTimeout();
1503 send_before_unload_start_time_ = base::TimeTicks();
1504 render_view_host_->is_waiting_for_close_ack_ = false;
1506 rfh_state_ = rfh_state;
1509 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1510 // TODO(creis): We should also check for WebUI pages here. Also, when the
1511 // out-of-process iframes implementation is ready, we should check for
1512 // cross-site URLs that are not allowed to commit in this process.
1514 // Give the client a chance to disallow URLs from committing.
1515 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1518 void RenderFrameHostImpl::Navigate(
1519 const CommonNavigationParams& common_params,
1520 const StartNavigationParams& start_params,
1521 const RequestNavigationParams& request_params) {
1522 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1523 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
1524 // so do not grant them the ability to request additional URLs.
1525 if (!GetProcess()->IsIsolatedGuest()) {
1526 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1527 GetProcess()->GetID(), common_params.url);
1528 if (common_params.url.SchemeIs(url::kDataScheme) &&
1529 common_params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
1530 // If 'data:' is used, and we have a 'file:' base url, grant access to
1531 // local files.
1532 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1533 GetProcess()->GetID(), common_params.base_url_for_data_url);
1537 // We may be returning to an existing NavigationEntry that had been granted
1538 // file access. If this is a different process, we will need to grant the
1539 // access again. The files listed in the page state are validated when they
1540 // are received from the renderer to prevent abuse.
1541 if (request_params.page_state.IsValid()) {
1542 render_view_host_->GrantFileAccessFromPageState(request_params.page_state);
1545 // Only send the message if we aren't suspended at the start of a cross-site
1546 // request.
1547 if (navigations_suspended_) {
1548 // Shouldn't be possible to have a second navigation while suspended, since
1549 // navigations will only be suspended during a cross-site request. If a
1550 // second navigation occurs, RenderFrameHostManager will cancel this pending
1551 // RFH and create a new pending RFH.
1552 DCHECK(!suspended_nav_params_.get());
1553 suspended_nav_params_.reset(
1554 new NavigationParams(common_params, start_params, request_params));
1555 } else {
1556 // Get back to a clean state, in case we start a new navigation without
1557 // completing a RFH swap or unload handler.
1558 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1560 Send(new FrameMsg_Navigate(routing_id_, common_params, start_params,
1561 request_params));
1564 // Force the throbber to start. We do this because Blink's "started
1565 // loading" message will be received asynchronously from the UI of the
1566 // browser. But we want to keep the throbber in sync with what's happening
1567 // in the UI. For example, we want to start throbbing immediately when the
1568 // user navigates even if the renderer is delayed. There is also an issue
1569 // with the throbber starting because the WebUI (which controls whether the
1570 // favicon is displayed) happens synchronously. If the start loading
1571 // messages was asynchronous, then the default favicon would flash in.
1573 // Blink doesn't send throb notifications for JavaScript URLs, so we
1574 // don't want to either.
1575 if (!common_params.url.SchemeIs(url::kJavaScriptScheme))
1576 delegate_->DidStartLoading(this, true);
1579 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1580 CommonNavigationParams common_params(
1581 url, Referrer(), ui::PAGE_TRANSITION_LINK, FrameMsg_Navigate_Type::NORMAL,
1582 true, base::TimeTicks::Now(), FrameMsg_UILoadMetricsReportType::NO_REPORT,
1583 GURL(), GURL());
1584 Navigate(common_params, StartNavigationParams(), RequestNavigationParams());
1587 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params,
1588 SiteInstance* source_site_instance) {
1589 GURL validated_url(params.url);
1590 GetProcess()->FilterURL(false, &validated_url);
1592 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
1593 validated_url.possibly_invalid_spec());
1594 frame_tree_node_->navigator()->RequestOpenURL(
1595 this, validated_url, source_site_instance, params.referrer,
1596 params.disposition, params.should_replace_current_entry,
1597 params.user_gesture);
1600 void RenderFrameHostImpl::Stop() {
1601 Send(new FrameMsg_Stop(routing_id_));
1604 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_navigation) {
1605 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1606 // the handler ran and allowed the navigation to proceed.
1607 if (GetParent() || !IsRenderFrameLive()) {
1608 // We don't have a live renderer, so just skip running beforeunload.
1609 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1610 switches::kEnableBrowserSideNavigation)) {
1611 frame_tree_node_->navigator()->OnBeforeUnloadACK(
1612 frame_tree_node_, true);
1613 } else {
1614 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1615 for_navigation, true, base::TimeTicks::Now());
1617 return;
1619 TRACE_EVENT_ASYNC_BEGIN0(
1620 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1622 // This may be called more than once (if the user clicks the tab close button
1623 // several times, or if she clicks the tab close button then the browser close
1624 // button), and we only send the message once.
1625 if (is_waiting_for_beforeunload_ack_) {
1626 // Some of our close messages could be for the tab, others for cross-site
1627 // transitions. We always want to think it's for closing the tab if any
1628 // of the messages were, since otherwise it might be impossible to close
1629 // (if there was a cross-site "close" request pending when the user clicked
1630 // the close button). We want to keep the "for cross site" flag only if
1631 // both the old and the new ones are also for cross site.
1632 unload_ack_is_for_navigation_ =
1633 unload_ack_is_for_navigation_ && for_navigation;
1634 } else {
1635 // Start the hang monitor in case the renderer hangs in the beforeunload
1636 // handler.
1637 is_waiting_for_beforeunload_ack_ = true;
1638 unload_ack_is_for_navigation_ = for_navigation;
1639 // Increment the in-flight event count, to ensure that input events won't
1640 // cancel the timeout timer.
1641 render_view_host_->increment_in_flight_event_count();
1642 render_view_host_->StartHangMonitorTimeout(
1643 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1644 send_before_unload_start_time_ = base::TimeTicks::Now();
1645 Send(new FrameMsg_BeforeUnload(routing_id_));
1649 void RenderFrameHostImpl::DisownOpener() {
1650 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1653 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1654 size_t after) {
1655 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1658 void RenderFrameHostImpl::JavaScriptDialogClosed(
1659 IPC::Message* reply_msg,
1660 bool success,
1661 const base::string16& user_input,
1662 bool dialog_was_suppressed) {
1663 GetProcess()->SetIgnoreInputEvents(false);
1664 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1666 // If we are executing as part of (before)unload event handling, we don't
1667 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1668 // leave the current page. In this case, use the regular timeout value used
1669 // during the (before)unload handling.
1670 if (is_waiting) {
1671 render_view_host_->StartHangMonitorTimeout(
1672 success
1673 ? TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS)
1674 : render_view_host_->hung_renderer_delay_);
1677 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1678 success, user_input);
1679 Send(reply_msg);
1681 // If we are waiting for an unload or beforeunload ack and the user has
1682 // suppressed messages, kill the tab immediately; a page that's spamming
1683 // alerts in onbeforeunload is presumably malicious, so there's no point in
1684 // continuing to run its script and dragging out the process.
1685 // This must be done after sending the reply since RenderView can't close
1686 // correctly while waiting for a response.
1687 if (is_waiting && dialog_was_suppressed)
1688 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1691 // PlzNavigate
1692 void RenderFrameHostImpl::CommitNavigation(
1693 ResourceResponse* response,
1694 scoped_ptr<StreamHandle> body,
1695 const CommonNavigationParams& common_params,
1696 const RequestNavigationParams& request_params) {
1697 DCHECK((response && body.get()) ||
1698 !NavigationRequest::ShouldMakeNetworkRequest(common_params.url));
1699 // TODO(clamy): Check if we have to add security checks for the browser plugin
1700 // guests.
1702 // Get back to a clean state, in case we start a new navigation without
1703 // completing a RFH swap or unload handler.
1704 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1706 const GURL body_url = body.get() ? body->GetURL() : GURL();
1707 const ResourceResponseHead head = response ?
1708 response->head : ResourceResponseHead();
1709 Send(new FrameMsg_CommitNavigation(routing_id_, head, body_url, common_params,
1710 request_params));
1711 // TODO(clamy): Check if we should start the throbber for non javascript urls
1712 // here.
1714 // TODO(clamy): Release the stream handle once the renderer has finished
1715 // reading it.
1716 stream_handle_ = body.Pass();
1719 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1720 if (service_registry_.get())
1721 return;
1723 service_registry_.reset(new ServiceRegistryImpl());
1724 if (!GetProcess()->GetServiceRegistry())
1725 return;
1727 RegisterMojoServices();
1728 RenderFrameSetupPtr setup;
1729 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(&setup);
1731 mojo::ServiceProviderPtr exposed_services;
1732 service_registry_->Bind(GetProxy(&exposed_services));
1734 mojo::ServiceProviderPtr services;
1735 setup->ExchangeServiceProviders(routing_id_, GetProxy(&services),
1736 exposed_services.Pass());
1737 service_registry_->BindRemoteServiceProvider(services.Pass());
1739 #if defined(OS_ANDROID)
1740 service_registry_android_.reset(
1741 new ServiceRegistryAndroid(service_registry_.get()));
1742 #endif
1745 void RenderFrameHostImpl::InvalidateMojoConnection() {
1746 #if defined(OS_ANDROID)
1747 // The Android-specific service registry has a reference to
1748 // |service_registry_| and thus must be torn down first.
1749 service_registry_android_.reset();
1750 #endif
1752 service_registry_.reset();
1755 bool RenderFrameHostImpl::IsFocused() {
1756 // TODO(mlamouri,kenrb): call GetRenderWidgetHost() directly when it stops
1757 // returning nullptr in some cases. See https://crbug.com/455245.
1758 return RenderWidgetHostImpl::From(
1759 GetView()->GetRenderWidgetHost())->is_focused() &&
1760 frame_tree_->GetFocusedFrame() &&
1761 (frame_tree_->GetFocusedFrame() == frame_tree_node() ||
1762 frame_tree_->GetFocusedFrame()->IsDescendantOf(frame_tree_node()));
1765 void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility(
1766 const std::map<int32, int>& node_to_frame_routing_id_map) {
1767 for (const auto& iter : node_to_frame_routing_id_map) {
1768 // This is the id of the accessibility node that has a child frame.
1769 int32 node_id = iter.first;
1770 // The routing id from either a RenderFrame or a RenderFrameProxy.
1771 int frame_routing_id = iter.second;
1773 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1774 FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID(
1775 GetProcess()->GetID(), frame_routing_id);
1777 if (child_frame_tree_node) {
1778 FrameAccessibility::GetInstance()->AddChildFrame(
1779 this, node_id, child_frame_tree_node->frame_tree_node_id());
1784 void RenderFrameHostImpl::UpdateGuestFrameAccessibility(
1785 const std::map<int32, int>& node_to_browser_plugin_instance_id_map) {
1786 for (const auto& iter : node_to_browser_plugin_instance_id_map) {
1787 // This is the id of the accessibility node that hosts a plugin.
1788 int32 node_id = iter.first;
1789 // The id of the browser plugin.
1790 int browser_plugin_instance_id = iter.second;
1791 FrameAccessibility::GetInstance()->AddGuestWebContents(
1792 this, node_id, browser_plugin_instance_id);
1796 bool RenderFrameHostImpl::IsSameSiteInstance(
1797 RenderFrameHostImpl* other_render_frame_host) {
1798 // As a sanity check, make sure the frame belongs to the same BrowserContext.
1799 CHECK_EQ(GetSiteInstance()->GetBrowserContext(),
1800 other_render_frame_host->GetSiteInstance()->GetBrowserContext());
1801 return GetSiteInstance() == other_render_frame_host->GetSiteInstance();
1804 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1805 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1808 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1809 const base::Callback<void(ui::AXEvent, int)>& callback) {
1810 accessibility_testing_callback_ = callback;
1813 void RenderFrameHostImpl::SetTextTrackSettings(
1814 const FrameMsg_TextTrackSettings_Params& params) {
1815 DCHECK(!GetParent());
1816 Send(new FrameMsg_SetTextTrackSettings(routing_id_, params));
1819 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1820 return ax_tree_for_testing_.get();
1823 BrowserAccessibilityManager*
1824 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1825 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1826 render_view_host_->GetView());
1827 if (view &&
1828 !browser_accessibility_manager_ &&
1829 !no_create_browser_accessibility_manager_for_testing_) {
1830 browser_accessibility_manager_.reset(
1831 view->CreateBrowserAccessibilityManager(this));
1832 if (browser_accessibility_manager_)
1833 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
1834 else
1835 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
1837 return browser_accessibility_manager_.get();
1840 void RenderFrameHostImpl::ActivateFindInPageResultForAccessibility(
1841 int request_id) {
1842 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1843 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1844 BrowserAccessibilityManager* manager =
1845 GetOrCreateBrowserAccessibilityManager();
1846 if (manager)
1847 manager->ActivateFindInPageResult(request_id);
1851 void RenderFrameHostImpl::InsertVisualStateCallback(
1852 const VisualStateCallback& callback) {
1853 static uint64 next_id = 1;
1854 uint64 key = next_id++;
1855 Send(new FrameMsg_VisualStateRequest(routing_id_, key));
1856 visual_state_callbacks_.insert(std::make_pair(key, callback));
1859 #if defined(OS_WIN)
1861 void RenderFrameHostImpl::SetParentNativeViewAccessible(
1862 gfx::NativeViewAccessible accessible_parent) {
1863 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1864 render_view_host_->GetView());
1865 if (view)
1866 view->SetParentNativeViewAccessible(accessible_parent);
1869 gfx::NativeViewAccessible
1870 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
1871 return delegate_->GetParentNativeViewAccessible();
1874 #elif defined(OS_MACOSX)
1876 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
1877 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
1880 void RenderFrameHostImpl::DidCancelPopupMenu() {
1881 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
1884 #elif defined(OS_ANDROID)
1886 void RenderFrameHostImpl::DidSelectPopupMenuItems(
1887 const std::vector<int>& selected_indices) {
1888 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
1891 void RenderFrameHostImpl::DidCancelPopupMenu() {
1892 Send(new FrameMsg_SelectPopupMenuItems(
1893 routing_id_, true, std::vector<int>()));
1896 #endif
1898 void RenderFrameHostImpl::ClearPendingTransitionRequestData() {
1899 BrowserThread::PostTask(
1900 BrowserThread::IO,
1901 FROM_HERE,
1902 base::Bind(
1903 &TransitionRequestManager::ClearPendingTransitionRequestData,
1904 base::Unretained(TransitionRequestManager::GetInstance()),
1905 GetProcess()->GetID(),
1906 routing_id_));
1909 void RenderFrameHostImpl::SetNavigationsSuspended(
1910 bool suspend,
1911 const base::TimeTicks& proceed_time) {
1912 // This should only be called to toggle the state.
1913 DCHECK(navigations_suspended_ != suspend);
1915 navigations_suspended_ = suspend;
1916 if (navigations_suspended_) {
1917 TRACE_EVENT_ASYNC_BEGIN0("navigation",
1918 "RenderFrameHostImpl navigation suspended", this);
1919 } else {
1920 TRACE_EVENT_ASYNC_END0("navigation",
1921 "RenderFrameHostImpl navigation suspended", this);
1924 if (!suspend && suspended_nav_params_) {
1925 // There's navigation message params waiting to be sent. Now that we're not
1926 // suspended anymore, resume navigation by sending them. If we were swapped
1927 // out, we should also stop filtering out the IPC messages now.
1928 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1930 DCHECK(!proceed_time.is_null());
1931 suspended_nav_params_->request_params.browser_navigation_start =
1932 proceed_time;
1933 Send(new FrameMsg_Navigate(routing_id_,
1934 suspended_nav_params_->common_params,
1935 suspended_nav_params_->start_params,
1936 suspended_nav_params_->request_params));
1937 suspended_nav_params_.reset();
1941 void RenderFrameHostImpl::CancelSuspendedNavigations() {
1942 // Clear any state if a pending navigation is canceled or preempted.
1943 if (suspended_nav_params_)
1944 suspended_nav_params_.reset();
1946 TRACE_EVENT_ASYNC_END0("navigation",
1947 "RenderFrameHostImpl navigation suspended", this);
1948 navigations_suspended_ = false;
1951 void RenderFrameHostImpl::DidUseGeolocationPermission() {
1952 PermissionManager* permission_manager =
1953 GetSiteInstance()->GetBrowserContext()->GetPermissionManager();
1954 if (!permission_manager)
1955 return;
1957 permission_manager->RegisterPermissionUsage(
1958 PermissionType::GEOLOCATION,
1959 GetLastCommittedURL().GetOrigin(),
1960 frame_tree_node()->frame_tree()->GetMainFrame()
1961 ->GetLastCommittedURL().GetOrigin());
1964 } // namespace content