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/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/time/time.h"
22 #include "cc/base/switches.h"
23 #include "components/scheduler/renderer/renderer_scheduler.h"
24 #include "content/child/appcache/appcache_dispatcher.h"
25 #include "content/child/permissions/permission_dispatcher.h"
26 #include "content/child/plugin_messages.h"
27 #include "content/child/quota_dispatcher.h"
28 #include "content/child/request_extra_data.h"
29 #include "content/child/service_worker/service_worker_handle_reference.h"
30 #include "content/child/service_worker/service_worker_network_provider.h"
31 #include "content/child/service_worker/service_worker_provider_context.h"
32 #include "content/child/service_worker/web_service_worker_provider_impl.h"
33 #include "content/child/v8_value_converter_impl.h"
34 #include "content/child/web_url_loader_impl.h"
35 #include "content/child/web_url_request_util.h"
36 #include "content/child/webmessageportchannel_impl.h"
37 #include "content/child/websocket_bridge.h"
38 #include "content/child/weburlresponse_extradata_impl.h"
39 #include "content/common/accessibility_messages.h"
40 #include "content/common/clipboard_messages.h"
41 #include "content/common/frame_messages.h"
42 #include "content/common/frame_replication_state.h"
43 #include "content/common/input_messages.h"
44 #include "content/common/navigation_params.h"
45 #include "content/common/service_worker/service_worker_types.h"
46 #include "content/common/site_isolation_policy.h"
47 #include "content/common/swapped_out_messages.h"
48 #include "content/common/view_messages.h"
49 #include "content/public/common/bindings_policy.h"
50 #include "content/public/common/content_constants.h"
51 #include "content/public/common/content_switches.h"
52 #include "content/public/common/context_menu_params.h"
53 #include "content/public/common/isolated_world_ids.h"
54 #include "content/public/common/page_state.h"
55 #include "content/public/common/resource_response.h"
56 #include "content/public/common/url_constants.h"
57 #include "content/public/common/url_utils.h"
58 #include "content/public/renderer/browser_plugin_delegate.h"
59 #include "content/public/renderer/content_renderer_client.h"
60 #include "content/public/renderer/context_menu_client.h"
61 #include "content/public/renderer/document_state.h"
62 #include "content/public/renderer/navigation_state.h"
63 #include "content/public/renderer/render_frame_observer.h"
64 #include "content/public/renderer/renderer_ppapi_host.h"
65 #include "content/renderer/accessibility/renderer_accessibility.h"
66 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
67 #include "content/renderer/browser_plugin/browser_plugin.h"
68 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
69 #include "content/renderer/child_frame_compositing_helper.h"
70 #include "content/renderer/context_menu_params_builder.h"
71 #include "content/renderer/devtools/devtools_agent.h"
72 #include "content/renderer/dom_automation_controller.h"
73 #include "content/renderer/external_popup_menu.h"
74 #include "content/renderer/geolocation_dispatcher.h"
75 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
76 #include "content/renderer/history_controller.h"
77 #include "content/renderer/history_serialization.h"
78 #include "content/renderer/image_downloader/image_downloader_impl.h"
79 #include "content/renderer/ime_event_guard.h"
80 #include "content/renderer/internal_document_state_data.h"
81 #include "content/renderer/manifest/manifest_manager.h"
82 #include "content/renderer/media/audio_renderer_mixer_manager.h"
83 #include "content/renderer/media/crypto/render_cdm_factory.h"
84 #include "content/renderer/media/media_permission_dispatcher.h"
85 #include "content/renderer/media/media_stream_dispatcher.h"
86 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
87 #include "content/renderer/media/midi_dispatcher.h"
88 #include "content/renderer/media/render_media_log.h"
89 #include "content/renderer/media/user_media_client_impl.h"
90 #include "content/renderer/media/webmediaplayer_ms.h"
91 #include "content/renderer/memory_benchmarking_extension.h"
92 #include "content/renderer/mojo/service_registry_js_wrapper.h"
93 #include "content/renderer/navigation_state_impl.h"
94 #include "content/renderer/notification_permission_dispatcher.h"
95 #include "content/renderer/npapi/plugin_channel_host.h"
96 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
97 #include "content/renderer/presentation/presentation_dispatcher.h"
98 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
99 #include "content/renderer/render_frame_proxy.h"
100 #include "content/renderer/render_process.h"
101 #include "content/renderer/render_thread_impl.h"
102 #include "content/renderer/render_view_impl.h"
103 #include "content/renderer/render_widget_fullscreen_pepper.h"
104 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
105 #include "content/renderer/renderer_webcolorchooser_impl.h"
106 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
107 #include "content/renderer/shared_worker_repository.h"
108 #include "content/renderer/skia_benchmarking_extension.h"
109 #include "content/renderer/stats_collection_controller.h"
110 #include "content/renderer/web_ui_extension.h"
111 #include "content/renderer/websharedworker_proxy.h"
112 #include "gin/modules/module_registry.h"
113 #include "media/base/audio_renderer_mixer_input.h"
114 #include "media/base/media_log.h"
115 #include "media/blink/webencryptedmediaclient_impl.h"
116 #include "media/blink/webmediaplayer_impl.h"
117 #include "media/renderers/gpu_video_accelerator_factories.h"
118 #include "mojo/common/url_type_converters.h"
119 #include "net/base/data_url.h"
120 #include "net/base/net_errors.h"
121 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
122 #include "net/http/http_util.h"
123 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
124 #include "third_party/WebKit/public/platform/WebString.h"
125 #include "third_party/WebKit/public/platform/WebURL.h"
126 #include "third_party/WebKit/public/platform/WebURLError.h"
127 #include "third_party/WebKit/public/platform/WebURLResponse.h"
128 #include "third_party/WebKit/public/platform/WebVector.h"
129 #include "third_party/WebKit/public/platform/modules/webusb/WebUSBClient.h"
130 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
131 #include "third_party/WebKit/public/web/WebDocument.h"
132 #include "third_party/WebKit/public/web/WebFrameWidget.h"
133 #include "third_party/WebKit/public/web/WebGlyphCache.h"
134 #include "third_party/WebKit/public/web/WebKit.h"
135 #include "third_party/WebKit/public/web/WebLocalFrame.h"
136 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
137 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
138 #include "third_party/WebKit/public/web/WebPlugin.h"
139 #include "third_party/WebKit/public/web/WebPluginParams.h"
140 #include "third_party/WebKit/public/web/WebRange.h"
141 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
142 #include "third_party/WebKit/public/web/WebScriptSource.h"
143 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
144 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
145 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
146 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
147 #include "third_party/WebKit/public/web/WebSettings.h"
148 #include "third_party/WebKit/public/web/WebSurroundingText.h"
149 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
150 #include "third_party/WebKit/public/web/WebView.h"
151 #include "third_party/mojo/src/mojo/edk/js/core.h"
152 #include "third_party/mojo/src/mojo/edk/js/support.h"
153 #include "url/url_util.h"
155 #if defined(ENABLE_PLUGINS)
156 #include "content/renderer/npapi/webplugin_impl.h"
157 #include "content/renderer/pepper/pepper_browser_connection.h"
158 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
159 #include "content/renderer/pepper/pepper_webplugin_impl.h"
160 #include "content/renderer/pepper/plugin_module.h"
163 #if defined(ENABLE_WEBRTC)
164 #include "content/renderer/media/rtc_peer_connection_handler.h"
167 #if defined(OS_ANDROID)
168 #include <cpu-features.h>
170 #include "content/common/gpu/client/context_provider_command_buffer.h"
171 #include "content/renderer/android/synchronous_compositor_factory.h"
172 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
173 #include "content/renderer/media/android/renderer_media_player_manager.h"
174 #include "content/renderer/media/android/stream_texture_factory_impl.h"
175 #include "content/renderer/media/android/webmediaplayer_android.h"
177 #include "cc/blink/context_provider_web_context.h"
178 #include "content/renderer/usb/web_usb_client_impl.h"
179 #include "device/devices_app/public/cpp/constants.h"
182 #if defined(ENABLE_PEPPER_CDMS)
183 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
184 #elif defined(ENABLE_BROWSER_CDMS)
185 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
188 #if defined(ENABLE_MOJO_MEDIA)
189 #include "media/mojo/services/mojo_cdm_factory.h"
190 #include "media/mojo/services/mojo_renderer_factory.h"
191 #include "mojo/application/public/cpp/connect.h"
192 #include "mojo/application/public/interfaces/shell.mojom.h"
193 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
195 #include "media/renderers/default_renderer_factory.h"
198 #if defined(ENABLE_WEBVR)
199 #include "content/renderer/vr/vr_dispatcher.h"
202 using blink::WebContentDecryptionModule
;
203 using blink::WebContextMenuData
;
204 using blink::WebData
;
205 using blink::WebDataSource
;
206 using blink::WebDocument
;
207 using blink::WebDOMEvent
;
208 using blink::WebDOMMessageEvent
;
209 using blink::WebElement
;
210 using blink::WebExternalPopupMenu
;
211 using blink::WebExternalPopupMenuClient
;
212 using blink::WebFrame
;
213 using blink::WebHistoryItem
;
214 using blink::WebHTTPBody
;
215 using blink::WebLocalFrame
;
216 using blink::WebMediaPlayer
;
217 using blink::WebMediaPlayerClient
;
218 using blink::WebMediaPlayerEncryptedMediaClient
;
219 using blink::WebNavigationPolicy
;
220 using blink::WebNavigationType
;
221 using blink::WebNode
;
222 using blink::WebPluginParams
;
223 using blink::WebPopupMenuInfo
;
224 using blink::WebRange
;
225 using blink::WebReferrerPolicy
;
226 using blink::WebScriptSource
;
227 using blink::WebSearchableFormData
;
228 using blink::WebSecurityOrigin
;
229 using blink::WebSecurityPolicy
;
230 using blink::WebSerializedScriptValue
;
231 using blink::WebServiceWorkerProvider
;
232 using blink::WebSettings
;
233 using blink::WebStorageQuotaCallbacks
;
234 using blink::WebString
;
236 using blink::WebURLError
;
237 using blink::WebURLRequest
;
238 using blink::WebURLResponse
;
239 using blink::WebUserGestureIndicator
;
240 using blink::WebVector
;
241 using blink::WebView
;
243 using base::TimeDelta
;
249 const char kDefaultAcceptHeader
[] =
250 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
252 const char kAcceptHeader
[] = "Accept";
254 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
256 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
257 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
258 LAZY_INSTANCE_INITIALIZER
;
260 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
261 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
263 int64
ExtractPostId(HistoryEntry
* entry
) {
267 const WebHistoryItem
& item
= entry
->root();
268 if (item
.isNull() || item
.httpBody().isNull())
271 return item
.httpBody().identifier();
274 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
275 const WebURLResponse
& response
) {
276 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
279 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
280 // Replace any occurrences of swappedout:// with about:blank.
281 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
282 WebVector
<WebURL
> urls
;
283 ds
->redirectChain(urls
);
284 result
->reserve(urls
.size());
285 for (size_t i
= 0; i
< urls
.size(); ++i
) {
286 if (urls
[i
] != GURL(kSwappedOutURL
))
287 result
->push_back(urls
[i
]);
289 result
->push_back(blank_url
);
293 // Returns the original request url. If there is no redirect, the original
294 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
295 // frame was loaded by loadData, the original url will be ds->unreachableURL()
296 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
297 // WebDataSource has unreachable URL means that the frame is loaded through
298 // blink::WebFrame::loadData(), and the base URL will be in the redirect
299 // chain. However, we never visited the baseURL. So in this case, we should
300 // use the unreachable URL as the original URL.
301 if (ds
->hasUnreachableURL())
302 return ds
->unreachableURL();
304 std::vector
<GURL
> redirects
;
305 GetRedirectChain(ds
, &redirects
);
306 if (!redirects
.empty())
307 return redirects
.at(0);
309 return ds
->originalRequest().url();
312 NOINLINE
void CrashIntentionally() {
313 // NOTE(shess): Crash directly rather than using NOTREACHED() so
314 // that the signature is easier to triage in crash reports.
315 volatile int* zero
= NULL
;
319 NOINLINE
void BadCastCrashIntentionally() {
332 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
333 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
334 // NOTE(rogerm): We intentionally perform an invalid heap access here in
335 // order to trigger an Address Sanitizer (ASAN) error report.
336 const char kCrashDomain
[] = "crash";
337 const char kHeapOverflow
[] = "/heap-overflow";
338 const char kHeapUnderflow
[] = "/heap-underflow";
339 const char kUseAfterFree
[] = "/use-after-free";
340 #if defined(SYZYASAN)
341 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
342 const char kCorruptHeap
[] = "/corrupt-heap";
345 if (!url
.DomainIs(kCrashDomain
))
351 std::string
crash_type(url
.path());
352 if (crash_type
== kHeapOverflow
) {
353 base::debug::AsanHeapOverflow();
354 } else if (crash_type
== kHeapUnderflow
) {
355 base::debug::AsanHeapUnderflow();
356 } else if (crash_type
== kUseAfterFree
) {
357 base::debug::AsanHeapUseAfterFree();
358 #if defined(SYZYASAN)
359 } else if (crash_type
== kCorruptHeapBlock
) {
360 base::debug::AsanCorruptHeapBlock();
361 } else if (crash_type
== kCorruptHeap
) {
362 base::debug::AsanCorruptHeap();
366 #endif // ADDRESS_SANITIZER || SYZYASAN
368 void MaybeHandleDebugURL(const GURL
& url
) {
369 if (!url
.SchemeIs(kChromeUIScheme
))
371 if (url
== GURL(kChromeUIBadCastCrashURL
)) {
372 BadCastCrashIntentionally();
373 } else if (url
== GURL(kChromeUICrashURL
)) {
374 CrashIntentionally();
375 } else if (url
== GURL(kChromeUIDumpURL
)) {
376 // This URL will only correctly create a crash dump file if content is
377 // hosted in a process that has correctly called
378 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
379 // of base::debug::DumpWithoutCrashing for more details.
380 base::debug::DumpWithoutCrashing();
381 } else if (url
== GURL(kChromeUIKillURL
)) {
382 base::Process::Current().Terminate(1, false);
383 } else if (url
== GURL(kChromeUIHangURL
)) {
385 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
387 } else if (url
== GURL(kChromeUIShorthangURL
)) {
388 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
391 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
392 MaybeTriggerAsanError(url
);
393 #endif // ADDRESS_SANITIZER || SYZYASAN
396 // Returns false unless this is a top-level navigation.
397 bool IsTopLevelNavigation(WebFrame
* frame
) {
398 return frame
->parent() == NULL
;
401 WebURLRequest
CreateURLRequestForNavigation(
402 const CommonNavigationParams
& common_params
,
403 scoped_ptr
<StreamOverrideParameters
> stream_override
,
404 bool is_view_source_mode_enabled
) {
405 WebURLRequest
request(common_params
.url
);
406 if (is_view_source_mode_enabled
)
407 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
409 if (common_params
.referrer
.url
.is_valid()) {
410 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
411 common_params
.referrer
.policy
,
413 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
414 if (!web_referrer
.isEmpty())
415 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
418 RequestExtraData
* extra_data
= new RequestExtraData();
419 extra_data
->set_stream_override(stream_override
.Pass());
420 request
.setExtraData(extra_data
);
422 // Set the ui timestamp for this navigation. Currently the timestamp here is
423 // only non empty when the navigation was triggered by an Android intent. The
424 // timestamp is converted to a double version supported by blink. It will be
425 // passed back to the browser in the DidCommitProvisionalLoad and the
426 // DocumentLoadComplete IPCs.
427 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
428 request
.setUiStartTime(ui_timestamp
.InSecondsF());
429 request
.setInputPerfMetricReportPolicy(
430 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
431 common_params
.report_type
));
435 void UpdateFrameNavigationTiming(WebFrame
* frame
,
436 base::TimeTicks browser_navigation_start
,
437 base::TimeTicks renderer_navigation_start
) {
438 // The browser provides the navigation_start time to bootstrap the
439 // Navigation Timing information for the browser-initiated navigations. In
440 // case of cross-process navigations, this carries over the time of
441 // finishing the onbeforeunload handler of the previous page.
442 DCHECK(!browser_navigation_start
.is_null());
443 if (frame
->provisionalDataSource()) {
444 // |browser_navigation_start| is likely before this process existed, so we
445 // can't use InterProcessTimeTicksConverter. We need at least to ensure
446 // that the browser-side navigation start we set is not later than the one
447 // on the renderer side.
448 base::TimeTicks navigation_start
= std::min(
449 browser_navigation_start
, renderer_navigation_start
);
450 double navigation_start_seconds
=
451 (navigation_start
- base::TimeTicks()).InSecondsF();
452 frame
->provisionalDataSource()->setNavigationStartTime(
453 navigation_start_seconds
);
454 // TODO(clamy): We need to provide additional timing values for the
455 // Navigation Timing API to work with browser-side navigations.
460 CommonNavigationParams
MakeCommonNavigationParams(
461 blink::WebURLRequest
* request
,
462 bool should_replace_current_entry
) {
463 const RequestExtraData kEmptyData
;
464 const RequestExtraData
* extra_data
=
465 static_cast<RequestExtraData
*>(request
->extraData());
467 extra_data
= &kEmptyData
;
469 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
470 request
->referrerPolicy());
472 // Set the ui timestamp for this navigation. Currently the timestamp here is
473 // only non empty when the navigation was triggered by an Android intent, or
474 // by the user clicking on a link. The timestamp is converted from a double
475 // version supported by blink. It will be passed back to the renderer in the
476 // CommitNavigation IPC, and then back to the browser again in the
477 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
478 base::TimeTicks ui_timestamp
=
479 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
480 FrameMsg_UILoadMetricsReportType::Value report_type
=
481 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
482 request
->inputPerfMetricReportPolicy());
483 return CommonNavigationParams(
484 request
->url(), referrer
, extra_data
->transition_type(),
485 FrameMsg_Navigate_Type::NORMAL
, true, should_replace_current_entry
,
486 ui_timestamp
, report_type
, GURL(), GURL());
489 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
490 media::Context3D
GetSharedMainThreadContext3D() {
491 cc::ContextProvider
* provider
=
492 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
494 return media::Context3D();
495 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
499 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
500 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
501 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
502 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
505 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
508 void OnGotContentHandlerID(uint32_t content_handler_id
) {}
513 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
515 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
516 CreateParams
params(render_view
, routing_id
);
518 if (g_create_render_frame_impl
)
519 return g_create_render_frame_impl(params
);
521 return new RenderFrameImpl(params
);
525 RenderFrame
* RenderFrame::FromRoutingID(int routing_id
) {
526 return RenderFrameImpl::FromRoutingID(routing_id
);
530 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int routing_id
) {
531 RoutingIDFrameMap::iterator iter
=
532 g_routing_id_frame_map
.Get().find(routing_id
);
533 if (iter
!= g_routing_id_frame_map
.Get().end())
539 RenderFrameImpl
* RenderFrameImpl::CreateMainFrame(RenderViewImpl
* render_view
,
541 RenderFrameImpl
* render_frame
=
542 RenderFrameImpl::Create(render_view
, routing_id
);
543 WebLocalFrame
* web_frame
=
544 WebLocalFrame::create(blink::WebTreeScopeType::Document
, render_frame
);
545 render_frame
->SetWebFrame(web_frame
);
546 render_view
->webview()->setMainFrame(web_frame
);
551 void RenderFrameImpl::CreateFrame(
553 int proxy_routing_id
,
554 int opener_routing_id
,
555 int parent_routing_id
,
556 int previous_sibling_routing_id
,
557 const FrameReplicationState
& replicated_state
,
558 CompositorDependencies
* compositor_deps
,
559 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
560 blink::WebLocalFrame
* web_frame
;
561 RenderFrameImpl
* render_frame
;
562 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
563 RenderFrameProxy
* parent_proxy
=
564 RenderFrameProxy::FromRoutingID(parent_routing_id
);
565 // If the browser is sending a valid parent routing id, it should already
566 // be created and registered.
568 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
570 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
571 RenderFrameProxy
* previous_sibling_proxy
=
572 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
573 if (previous_sibling_proxy
)
574 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
576 // Create the RenderFrame and WebLocalFrame, linking the two.
578 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
579 web_frame
= parent_web_frame
->createLocalChild(
580 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
581 replicated_state
.sandbox_flags
, render_frame
,
582 previous_sibling_web_frame
);
584 RenderFrameProxy
* proxy
=
585 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
587 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
589 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
590 render_frame
->proxy_routing_id_
= proxy_routing_id
;
591 web_frame
->initializeToReplaceRemoteFrame(
592 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
593 replicated_state
.sandbox_flags
);
595 render_frame
->SetWebFrame(web_frame
);
596 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
598 WebFrame
* opener
= ResolveOpener(opener_routing_id
, nullptr);
599 web_frame
->setOpener(opener
);
601 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
602 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
603 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
604 widget_params
.routing_id
, widget_params
.surface_id
,
605 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
606 compositor_deps
, web_frame
);
607 // TODO(kenrb): Observing shouldn't be necessary when we sort out
608 // WasShown and WasHidden, separating page-level visibility from
609 // frame-level visibility.
610 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
613 render_frame
->Initialize();
617 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
618 return RenderFrameImpl::FromWebFrame(web_frame
);
622 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
623 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
624 if (iter
!= g_frame_map
.Get().end())
630 void RenderFrameImpl::InstallCreateHook(
631 CreateRenderFrameImplFunction create_render_frame_impl
) {
632 CHECK(!g_create_render_frame_impl
);
633 g_create_render_frame_impl
= create_render_frame_impl
;
637 blink::WebFrame
* RenderFrameImpl::ResolveOpener(int opener_frame_routing_id
,
638 int* opener_view_routing_id
) {
639 if (opener_view_routing_id
)
640 *opener_view_routing_id
= MSG_ROUTING_NONE
;
642 if (opener_frame_routing_id
== MSG_ROUTING_NONE
)
645 // Opener routing ID could refer to either a RenderFrameProxy or a
646 // RenderFrame, so need to check both.
647 RenderFrameProxy
* opener_proxy
=
648 RenderFrameProxy::FromRoutingID(opener_frame_routing_id
);
650 if (opener_view_routing_id
)
651 *opener_view_routing_id
= opener_proxy
->render_view()->GetRoutingID();
653 // TODO(nasko,alexmos): This check won't be needed once swappedout:// is
655 if (opener_proxy
->IsMainFrameDetachedFromTree()) {
656 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
657 return opener_proxy
->render_view()->webview()->mainFrame();
659 return opener_proxy
->web_frame();
663 RenderFrameImpl
* opener_frame
=
664 RenderFrameImpl::FromRoutingID(opener_frame_routing_id
);
666 if (opener_view_routing_id
)
667 *opener_view_routing_id
= opener_frame
->render_view()->GetRoutingID();
668 return opener_frame
->GetWebFrame();
674 // RenderFrameImpl ----------------------------------------------------------
675 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
678 is_local_root_(false),
679 render_view_(params
.render_view
->AsWeakPtr()),
680 routing_id_(params
.routing_id
),
681 is_swapped_out_(false),
682 render_frame_proxy_(NULL
),
683 is_detaching_(false),
684 proxy_routing_id_(MSG_ROUTING_NONE
),
685 #if defined(ENABLE_PLUGINS)
686 plugin_power_saver_helper_(nullptr),
689 selection_text_offset_(0),
690 selection_range_(gfx::Range::InvalidRange()),
691 handling_select_range_(false),
692 notification_permission_dispatcher_(NULL
),
693 web_user_media_client_(NULL
),
694 media_permission_dispatcher_(NULL
),
695 midi_dispatcher_(NULL
),
696 #if defined(OS_ANDROID)
697 media_player_manager_(NULL
),
699 #if defined(ENABLE_BROWSER_CDMS)
702 #if defined(VIDEO_HOLE)
703 contains_media_player_(false),
705 has_played_media_(false),
706 devtools_agent_(nullptr),
707 geolocation_dispatcher_(NULL
),
708 push_messaging_dispatcher_(NULL
),
709 presentation_dispatcher_(NULL
),
710 screen_orientation_dispatcher_(NULL
),
711 manifest_manager_(NULL
),
712 accessibility_mode_(AccessibilityModeOff
),
713 renderer_accessibility_(NULL
),
714 weak_factory_(this) {
715 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
716 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
717 CHECK(result
.second
) << "Inserting a duplicate item.";
719 RenderThread::Get()->AddRoute(routing_id_
, this);
721 render_view_
->RegisterRenderFrame(this);
723 // Everything below subclasses RenderFrameObserver and is automatically
724 // deleted when the RenderFrame gets deleted.
725 #if defined(OS_ANDROID)
726 new GinJavaBridgeDispatcher(this);
729 #if defined(ENABLE_PLUGINS)
730 // Manages its own lifetime.
731 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
734 manifest_manager_
= new ManifestManager(this);
736 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_
));
739 RenderFrameImpl::~RenderFrameImpl() {
740 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
741 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
743 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
745 #if defined(VIDEO_HOLE)
746 if (contains_media_player_
)
747 render_view_
->UnregisterVideoHoleFrame(this);
751 // When using swapped out frames, RenderFrameProxy is owned by
752 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
753 // along with this object.
754 if (render_frame_proxy_
&&
755 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
756 // The following method calls back into this object and clears
757 // |render_frame_proxy_|.
758 render_frame_proxy_
->frameDetached(
759 blink::WebRemoteFrameClient::DetachType::Remove
);
762 // Ensure the RenderView doesn't point to this object, once it is destroyed.
763 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
764 // is |this|, once the object is no longer leaked.
765 // See https://crbug.com/464764.
766 render_view_
->main_render_frame_
= nullptr;
769 render_view_
->UnregisterRenderFrame(this);
770 g_routing_id_frame_map
.Get().erase(routing_id_
);
771 RenderThread::Get()->RemoveRoute(routing_id_
);
774 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
777 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
778 std::make_pair(web_frame
, this));
779 CHECK(result
.second
) << "Inserting a duplicate item.";
784 void RenderFrameImpl::Initialize() {
785 is_subframe_
= !!frame_
->parent();
786 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
788 #if defined(ENABLE_PLUGINS)
789 new PepperBrowserConnection(this);
791 new SharedWorkerRepository(this);
793 if (is_local_root_
&& !render_frame_proxy_
) {
794 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
795 // when |this| is deleted.
796 devtools_agent_
= new DevToolsAgent(this);
799 RegisterMojoServices();
801 // We delay calling this until we have the WebFrame so that any observer or
802 // embedder can call GetWebFrame on any RenderFrame.
803 GetContentClient()->renderer()->RenderFrameCreated(this);
806 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
807 return render_view_
.get();
810 #if defined(ENABLE_PLUGINS)
811 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
812 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
813 DidCreatePepperPlugin(host
));
814 if (host
->GetPluginName() == kFlashPluginName
) {
815 RenderThread::Get()->RecordAction(
816 base::UserMetricsAction("FrameLoadWithFlash"));
820 void RenderFrameImpl::PepperDidChangeCursor(
821 PepperPluginInstanceImpl
* instance
,
822 const blink::WebCursorInfo
& cursor
) {
823 // Update the cursor appearance immediately if the requesting plugin is the
824 // one which receives the last mouse event. Otherwise, the new cursor won't be
825 // picked up until the plugin gets the next input event. That is bad if, e.g.,
826 // the plugin would like to set an invisible cursor when there isn't any user
827 // input for a while.
828 if (instance
== render_view_
->pepper_last_mouse_event_target())
829 GetRenderWidget()->didChangeCursor(cursor
);
832 void RenderFrameImpl::PepperDidReceiveMouseEvent(
833 PepperPluginInstanceImpl
* instance
) {
834 render_view_
->set_pepper_last_mouse_event_target(instance
);
837 void RenderFrameImpl::PepperTextInputTypeChanged(
838 PepperPluginInstanceImpl
* instance
) {
839 if (instance
!= render_view_
->focused_pepper_plugin())
842 GetRenderWidget()->UpdateTextInputState(
843 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
845 FocusedNodeChangedForAccessibility(WebNode());
848 void RenderFrameImpl::PepperCaretPositionChanged(
849 PepperPluginInstanceImpl
* instance
) {
850 if (instance
!= render_view_
->focused_pepper_plugin())
852 GetRenderWidget()->UpdateSelectionBounds();
855 void RenderFrameImpl::PepperCancelComposition(
856 PepperPluginInstanceImpl
* instance
) {
857 if (instance
!= render_view_
->focused_pepper_plugin())
859 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
860 #if defined(OS_MACOSX) || defined(USE_AURA)
861 GetRenderWidget()->UpdateCompositionInfo(true);
865 void RenderFrameImpl::PepperSelectionChanged(
866 PepperPluginInstanceImpl
* instance
) {
867 if (instance
!= render_view_
->focused_pepper_plugin())
869 SyncSelectionIfRequired();
872 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
873 PepperPluginInstanceImpl
* plugin
) {
875 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
876 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
877 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
878 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
879 plugin
, active_url
, GetRenderWidget()->screenInfo());
880 widget
->show(blink::WebNavigationPolicyIgnore
);
884 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
885 if (!render_view_
->focused_pepper_plugin())
887 return render_view_
->focused_pepper_plugin()->
888 IsPluginAcceptingCompositionEvents();
891 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
892 base::ProcessId plugin_pid
) {
893 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
894 // routing_id_ as a result.
895 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
898 void RenderFrameImpl::SimulateImeSetComposition(
899 const base::string16
& text
,
900 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
903 render_view_
->OnImeSetComposition(
904 text
, underlines
, selection_start
, selection_end
);
907 void RenderFrameImpl::SimulateImeConfirmComposition(
908 const base::string16
& text
,
909 const gfx::Range
& replacement_range
) {
910 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
913 void RenderFrameImpl::OnImeSetComposition(
914 const base::string16
& text
,
915 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
918 // When a PPAPI plugin has focus, we bypass WebKit.
919 if (!IsPepperAcceptingCompositionEvents()) {
920 pepper_composition_text_
= text
;
922 // TODO(kinaba) currently all composition events are sent directly to
923 // plugins. Use DOM event mechanism after WebKit is made aware about
924 // plugins that support composition.
925 // The code below mimics the behavior of WebCore::Editor::setComposition.
927 // Empty -> nonempty: composition started.
928 if (pepper_composition_text_
.empty() && !text
.empty()) {
929 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
932 // Nonempty -> empty: composition canceled.
933 if (!pepper_composition_text_
.empty() && text
.empty()) {
934 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
937 pepper_composition_text_
= text
;
938 // Nonempty: composition is ongoing.
939 if (!pepper_composition_text_
.empty()) {
940 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
941 pepper_composition_text_
, underlines
, selection_start
,
947 void RenderFrameImpl::OnImeConfirmComposition(
948 const base::string16
& text
,
949 const gfx::Range
& replacement_range
,
950 bool keep_selection
) {
951 // When a PPAPI plugin has focus, we bypass WebKit.
952 // Here, text.empty() has a special meaning. It means to commit the last
953 // update of composition text (see
954 // RenderWidgetHost::ImeConfirmComposition()).
955 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
958 // last_text is empty only when both text and pepper_composition_text_ is.
960 if (last_text
.empty())
963 if (!IsPepperAcceptingCompositionEvents()) {
964 base::i18n::UTF16CharIterator
iterator(&last_text
);
966 while (iterator
.Advance()) {
967 blink::WebKeyboardEvent char_event
;
968 char_event
.type
= blink::WebInputEvent::Char
;
969 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
970 char_event
.modifiers
= 0;
971 char_event
.windowsKeyCode
= last_text
[i
];
972 char_event
.nativeKeyCode
= last_text
[i
];
974 const int32 char_start
= i
;
975 for (; i
< iterator
.array_pos(); ++i
) {
976 char_event
.text
[i
- char_start
] = last_text
[i
];
977 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
980 if (GetRenderWidget()->webwidget())
981 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
984 // Mimics the order of events sent by WebKit.
985 // See WebCore::Editor::setComposition() for the corresponding code.
986 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
987 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
989 pepper_composition_text_
.clear();
991 #endif // defined(ENABLE_PLUGINS)
993 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
994 if (!web_user_media_client_
)
995 InitializeUserMediaClient();
996 return web_user_media_client_
?
997 web_user_media_client_
->media_stream_dispatcher() : NULL
;
1000 bool RenderFrameImpl::Send(IPC::Message
* message
) {
1001 if (is_detaching_
) {
1005 if (is_swapped_out_
) {
1006 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
1012 return RenderThread::Get()->Send(message
);
1015 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1016 void RenderFrameImpl::DidHideExternalPopupMenu() {
1017 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
1018 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
1019 external_popup_menu_
.reset();
1023 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
1024 // We may get here while detaching, when the WebFrame has been deleted. Do
1025 // not process any messages in this state.
1029 // TODO(kenrb): document() should not be null, but as a transitional step
1030 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1031 // to this method. This happens for a top-level remote frame, where a
1032 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1033 // around and is still able to receive messages.
1034 if (!frame_
->document().isNull())
1035 GetContentClient()->SetActiveURL(frame_
->document().url());
1037 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
1038 RenderFrameObserver
* observer
;
1039 while ((observer
= it
.GetNext()) != NULL
) {
1040 if (observer
->OnMessageReceived(msg
))
1044 bool handled
= true;
1045 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1046 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1047 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1048 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1049 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1050 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1051 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1052 OnCustomContextMenuAction
)
1053 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1054 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1055 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1056 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1057 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1058 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1059 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1060 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1061 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1062 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1063 OnAdjustSelectionByCharacterOffset
)
1064 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1065 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1066 OnMoveRangeSelectionExtent
)
1067 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1068 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1069 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1070 OnExtendSelectionAndDelete
)
1071 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1072 OnSetCompositionFromExistingText
)
1073 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1074 OnExecuteNoValueEditCommand
)
1075 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1076 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1077 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1078 OnJavaScriptExecuteRequest
)
1079 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1080 OnJavaScriptExecuteRequestForTests
)
1081 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1082 OnJavaScriptExecuteRequestInIsolatedWorld
)
1083 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1084 OnVisualStateRequest
)
1085 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1086 OnSetEditableSelectionOffsets
)
1087 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1088 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1089 OnTextSurroundingSelectionRequest
)
1090 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1091 OnSetAccessibilityMode
)
1092 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1093 OnSnapshotAccessibilityTree
)
1094 IPC_MESSAGE_HANDLER(FrameMsg_UpdateOpener
, OnUpdateOpener
)
1095 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1096 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1097 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1098 OnTextTrackSettingsChanged
)
1099 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1100 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1101 #if defined(OS_ANDROID)
1102 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1103 #elif defined(OS_MACOSX)
1104 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1105 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1107 IPC_END_MESSAGE_MAP()
1112 void RenderFrameImpl::OnNavigate(
1113 const CommonNavigationParams
& common_params
,
1114 const StartNavigationParams
& start_params
,
1115 const RequestNavigationParams
& request_params
) {
1116 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
1117 // Can be NULL in tests.
1118 if (render_thread_impl
)
1119 render_thread_impl
->GetRendererScheduler()->OnPageLoadStarted();
1120 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1121 switches::kEnableBrowserSideNavigation
));
1122 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1123 "url", common_params
.url
.possibly_invalid_spec());
1124 NavigateInternal(common_params
, start_params
, request_params
,
1125 scoped_ptr
<StreamOverrideParameters
>());
1128 void RenderFrameImpl::NavigateToSwappedOutURL() {
1129 // We use loadRequest instead of loadHTMLString because the former commits
1130 // synchronously. Otherwise a new navigation can interrupt the navigation
1131 // to kSwappedOutURL. If that happens to be to the page we had been
1132 // showing, then WebKit will never send a commit and we'll be left spinning.
1133 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1134 // the navigation to swappedout:// is not announced to the browser side.
1135 is_swapped_out_
= true;
1136 GURL
swappedOutURL(kSwappedOutURL
);
1137 WebURLRequest
request(swappedOutURL
);
1138 frame_
->loadRequest(request
);
1141 void RenderFrameImpl::BindServiceRegistry(
1142 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1143 mojo::ServiceProviderPtr exposed_services
) {
1144 service_registry_
.Bind(services
.Pass());
1145 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1148 ManifestManager
* RenderFrameImpl::manifest_manager() {
1149 return manifest_manager_
;
1152 void RenderFrameImpl::SetPendingNavigationParams(
1153 scoped_ptr
<NavigationParams
> navigation_params
) {
1154 pending_navigation_params_
= navigation_params
.Pass();
1157 void RenderFrameImpl::OnBeforeUnload() {
1158 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1160 // TODO(creis): Right now, this is only called on the main frame. Make the
1161 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1163 CHECK(!frame_
->parent());
1165 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1166 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1167 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1168 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1169 before_unload_start_time
,
1170 before_unload_end_time
));
1173 void RenderFrameImpl::OnSwapOut(
1174 int proxy_routing_id
,
1176 const FrameReplicationState
& replicated_frame_state
) {
1177 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1178 RenderFrameProxy
* proxy
= NULL
;
1179 bool swapped_out_forbidden
=
1180 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1181 bool is_main_frame
= !frame_
->parent();
1183 // This codepath should only be hit for subframes when in --site-per-process.
1184 CHECK_IMPLIES(!is_main_frame
,
1185 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1187 // Only run unload if we're not swapped out yet, but send the ack either way.
1188 if (!is_swapped_out_
) {
1189 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1190 // a different process. This involves running the unload handler and
1191 // clearing the page. We also allow this process to exit if there are no
1192 // other active RenderFrames in it.
1194 // Send an UpdateState message before we get swapped out.
1195 render_view_
->SendUpdateState();
1197 // If we need a proxy to replace this, create it now so its routing id is
1198 // registered for receiving IPC messages.
1199 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1200 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1201 this, proxy_routing_id
, replicated_frame_state
.scope
);
1204 // Synchronously run the unload handler before sending the ACK.
1205 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1206 // unload on subframes as well.
1208 frame_
->dispatchUnloadEvent();
1210 // Swap out and stop sending any IPC messages that are not ACKs.
1212 render_view_
->SetSwappedOut(true);
1213 is_swapped_out_
= true;
1215 // Set the proxy here, since OnStop() below could cause an onload event
1216 // handler to execute, which could trigger code such as
1217 // willCheckAndDispatchMessageEvent() that needs the proxy.
1219 set_render_frame_proxy(proxy
);
1221 // Now that we're swapped out and filtering IPC messages, stop loading to
1222 // ensure that no other in-progress navigation continues. We do this here
1223 // to avoid sending a DidStopLoading message to the browser process.
1224 // TODO(creis): Should we be stopping all frames here and using
1225 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1227 if (!swapped_out_forbidden
)
1230 // Transfer settings such as initial drawing parameters to the remote frame,
1231 // if one is created, that will replace this frame.
1232 if (!is_main_frame
&& proxy
)
1233 proxy
->web_frame()->initializeFromFrame(frame_
);
1235 // Replace the page with a blank dummy URL. The unload handler will not be
1236 // run a second time, thanks to a check in FrameLoader::stopLoading.
1237 // TODO(creis): Need to add a better way to do this that avoids running the
1238 // beforeunload handler. For now, we just run it a second time silently.
1239 if (!swapped_out_forbidden
)
1240 NavigateToSwappedOutURL();
1242 // Let WebKit know that this view is hidden so it can drop resources and
1243 // stop compositing.
1244 // TODO(creis): Support this for subframes as well.
1245 if (is_main_frame
) {
1246 render_view_
->webview()->setVisibilityState(
1247 blink::WebPageVisibilityStateHidden
, false);
1251 // It is now safe to show modal dialogs again.
1252 // TODO(creis): Deal with modal dialogs from subframes.
1254 render_view_
->suppress_dialogs_until_swap_out_
= false;
1256 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1258 RenderViewImpl
* render_view
= render_view_
.get();
1260 // Now that all of the cleanup is complete and the browser side is notified,
1261 // start using the RenderFrameProxy, if one is created.
1262 if (proxy
&& swapped_out_forbidden
) {
1263 frame_
->swap(proxy
->web_frame());
1266 proxy
->OnDidStartLoading();
1269 // In --site-per-process, initialize the WebRemoteFrame with the replication
1270 // state passed by the process that is now rendering the frame.
1271 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1272 // in that case we leave the LocalFrame as the main frame visible to Blink
1273 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1274 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1275 // When we do an unconditional swap for all frames, we can remove
1276 // !is_main_frame below.
1277 if (proxy
&& swapped_out_forbidden
)
1278 proxy
->SetReplicatedState(replicated_frame_state
);
1280 // Safe to exit if no one else is using the process.
1281 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1282 // the process based on the lifetime of this RenderFrameImpl object.
1283 if (is_main_frame
) {
1284 render_view
->WasSwappedOut();
1288 void RenderFrameImpl::OnContextMenuClosed(
1289 const CustomContextMenuContext
& custom_context
) {
1290 if (custom_context
.request_id
) {
1291 // External request, should be in our map.
1292 ContextMenuClient
* client
=
1293 pending_context_menus_
.Lookup(custom_context
.request_id
);
1295 client
->OnMenuClosed(custom_context
.request_id
);
1296 pending_context_menus_
.Remove(custom_context
.request_id
);
1299 if (custom_context
.link_followed
.is_valid())
1300 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1301 // Internal request, forward to WebKit.
1302 context_menu_node_
.reset();
1306 void RenderFrameImpl::OnCustomContextMenuAction(
1307 const CustomContextMenuContext
& custom_context
,
1309 if (custom_context
.request_id
) {
1310 // External context menu request, look in our map.
1311 ContextMenuClient
* client
=
1312 pending_context_menus_
.Lookup(custom_context
.request_id
);
1314 client
->OnMenuAction(custom_context
.request_id
, action
);
1316 // Internal request, forward to WebKit.
1317 render_view_
->webview()->performCustomContextMenuAction(action
);
1321 void RenderFrameImpl::OnUndo() {
1322 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1325 void RenderFrameImpl::OnRedo() {
1326 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1329 void RenderFrameImpl::OnCut() {
1330 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1331 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1334 void RenderFrameImpl::OnCopy() {
1335 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1336 WebNode current_node
= context_menu_node_
.isNull() ?
1337 GetFocusedElement() : context_menu_node_
;
1338 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1341 void RenderFrameImpl::OnPaste() {
1342 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1343 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1346 void RenderFrameImpl::OnPasteAndMatchStyle() {
1347 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1348 frame_
->executeCommand(
1349 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1352 #if defined(OS_MACOSX)
1353 void RenderFrameImpl::OnCopyToFindPboard() {
1354 // Since the find pasteboard supports only plain text, this can be simpler
1355 // than the |OnCopy()| case.
1356 if (frame_
->hasSelection()) {
1357 base::string16 selection
= frame_
->selectionAsText();
1358 RenderThread::Get()->Send(
1359 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1364 void RenderFrameImpl::OnDelete() {
1365 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1368 void RenderFrameImpl::OnSelectAll() {
1369 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1370 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1373 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1374 const gfx::Point
& extent
) {
1375 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1376 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1378 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1379 frame_
->selectRange(base
, extent
);
1382 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1384 size_t start
, length
;
1385 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1390 // Sanity checks to disallow empty and out of range selections.
1391 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1392 || static_cast<int>(start
) + start_adjust
< 0) {
1396 // A negative adjust amount moves the selection towards the beginning of
1397 // the document, a positive amount moves the selection towards the end of
1399 start
+= start_adjust
;
1400 length
+= end_adjust
- start_adjust
;
1402 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1403 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1406 void RenderFrameImpl::OnUnselect() {
1407 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1408 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1411 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1412 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1413 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1414 GetRenderWidget()->routing_id()));
1416 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1417 frame_
->moveRangeSelectionExtent(point
);
1420 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1421 if (!frame_
->hasSelection())
1422 frame_
->selectWordAroundCaret();
1424 frame_
->replaceSelection(text
);
1427 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1428 if (!frame_
->hasSelection())
1431 frame_
->replaceMisspelledRange(text
);
1434 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1435 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1438 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1439 const std::string
& message
) {
1440 AddMessageToConsole(level
, message
);
1443 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1444 const base::string16
& jscript
,
1446 bool notify_result
) {
1447 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1448 TRACE_EVENT_SCOPE_THREAD
);
1450 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1451 v8::Local
<v8::Value
> result
=
1452 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1454 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1457 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1458 const base::string16
& jscript
,
1461 bool has_user_gesture
) {
1462 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1463 TRACE_EVENT_SCOPE_THREAD
);
1465 // A bunch of tests expect to run code in the context of a user gesture, which
1466 // can grant additional privileges (e.g. the ability to create popups).
1467 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1468 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1469 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1470 v8::Local
<v8::Value
> result
=
1471 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1473 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1476 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1477 const base::string16
& jscript
,
1481 TRACE_EVENT_INSTANT0("test_tracing",
1482 "OnJavaScriptExecuteRequestInIsolatedWorld",
1483 TRACE_EVENT_SCOPE_THREAD
);
1485 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1486 world_id
> ISOLATED_WORLD_ID_MAX
) {
1487 // Return if the world_id is not valid. world_id is passed as a plain int
1488 // over IPC and needs to be verified here, in the IPC endpoint.
1493 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1494 WebScriptSource script
= WebScriptSource(jscript
);
1495 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1496 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1497 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1501 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1505 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1507 notify_result_(notify_result
),
1508 routing_id_(routing_id
),
1509 render_frame_impl_(render_frame_impl
) {
1512 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1513 ~JavaScriptIsolatedWorldRequest() {
1516 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1517 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1518 if (!render_frame_impl_
.get()) {
1522 if (notify_result_
) {
1523 base::ListValue list
;
1524 if (!result
.isEmpty()) {
1525 // It's safe to always use the main world context when converting
1526 // here. V8ValueConverterImpl shouldn't actually care about the
1527 // context scope, and it switches to v8::Object's creation context
1528 // when encountered. (from extensions/renderer/script_injection.cc)
1529 v8::Local
<v8::Context
> context
=
1530 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1531 v8::Context::Scope
context_scope(context
);
1532 V8ValueConverterImpl converter
;
1533 converter
.SetDateAllowed(true);
1534 converter
.SetRegExpAllowed(true);
1535 for (const auto& value
: result
) {
1536 scoped_ptr
<base::Value
> result_value(
1537 converter
.FromV8Value(value
, context
));
1538 list
.Append(result_value
? result_value
.Pass()
1539 : base::Value::CreateNullValue());
1542 list
.Set(0, base::Value::CreateNullValue());
1544 render_frame_impl_
.get()->Send(
1545 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1551 void RenderFrameImpl::HandleJavascriptExecutionResult(
1552 const base::string16
& jscript
,
1555 v8::Local
<v8::Value
> result
) {
1556 if (notify_result
) {
1557 base::ListValue list
;
1558 if (!result
.IsEmpty()) {
1559 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1560 v8::Context::Scope
context_scope(context
);
1561 V8ValueConverterImpl converter
;
1562 converter
.SetDateAllowed(true);
1563 converter
.SetRegExpAllowed(true);
1564 scoped_ptr
<base::Value
> result_value(
1565 converter
.FromV8Value(result
, context
));
1566 list
.Set(0, result_value
? result_value
.Pass()
1567 : base::Value::CreateNullValue());
1569 list
.Set(0, base::Value::CreateNullValue());
1571 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1575 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1576 GetRenderWidget()->QueueMessage(
1577 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1578 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1581 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1582 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1583 if (!GetRenderWidget()->ShouldHandleImeEvent())
1585 ImeEventGuard
guard(GetRenderWidget());
1586 frame_
->setEditableSelectionOffsets(start
, end
);
1589 void RenderFrameImpl::OnSetCompositionFromExistingText(
1591 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1592 if (!GetRenderWidget()->ShouldHandleImeEvent())
1594 ImeEventGuard
guard(GetRenderWidget());
1595 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1598 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1599 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1602 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1603 if (!GetRenderWidget()->ShouldHandleImeEvent())
1606 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1608 ImeEventGuard
guard(GetRenderWidget());
1609 blink::WebScopedUserGesture gesture_indicator
;
1610 frame_
->extendSelectionAndDelete(before
, after
);
1613 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1614 if (accessibility_mode_
== new_mode
)
1616 accessibility_mode_
= new_mode
;
1617 if (renderer_accessibility_
) {
1618 // Note: this isn't called automatically by the destructor because
1619 // there'd be no point in calling it in frame teardown, only if there's
1620 // an accessibility mode change but the frame is persisting.
1621 renderer_accessibility_
->DisableAccessibility();
1623 delete renderer_accessibility_
;
1624 renderer_accessibility_
= NULL
;
1626 if (accessibility_mode_
== AccessibilityModeOff
)
1629 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1630 renderer_accessibility_
= new RendererAccessibility(this);
1633 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1634 ui::AXTreeUpdate
<AXContentNodeData
> response
;
1635 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1636 Send(new AccessibilityHostMsg_SnapshotResponse(
1637 routing_id_
, callback_id
, response
));
1640 void RenderFrameImpl::OnUpdateOpener(int opener_routing_id
) {
1641 WebFrame
* opener
= ResolveOpener(opener_routing_id
, nullptr);
1642 frame_
->setOpener(opener
);
1645 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1646 frame_
->setFrameOwnerSandboxFlags(flags
);
1649 void RenderFrameImpl::OnTextTrackSettingsChanged(
1650 const FrameMsg_TextTrackSettings_Params
& params
) {
1651 DCHECK(!frame_
->parent());
1652 if (!render_view_
->webview())
1655 if (params
.text_tracks_enabled
) {
1656 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1657 WebSettings::TextTrackKindUserPreference::Captions
);
1659 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1660 WebSettings::TextTrackKindUserPreference::Default
);
1662 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1663 WebString::fromUTF8(params
.text_track_background_color
));
1664 render_view_
->webview()->settings()->setTextTrackFontFamily(
1665 WebString::fromUTF8(params
.text_track_font_family
));
1666 render_view_
->webview()->settings()->setTextTrackFontStyle(
1667 WebString::fromUTF8(params
.text_track_font_style
));
1668 render_view_
->webview()->settings()->setTextTrackFontVariant(
1669 WebString::fromUTF8(params
.text_track_font_variant
));
1670 render_view_
->webview()->settings()->setTextTrackTextColor(
1671 WebString::fromUTF8(params
.text_track_text_color
));
1672 render_view_
->webview()->settings()->setTextTrackTextShadow(
1673 WebString::fromUTF8(params
.text_track_text_shadow
));
1674 render_view_
->webview()->settings()->setTextTrackTextSize(
1675 WebString::fromUTF8(params
.text_track_text_size
));
1678 void RenderFrameImpl::OnPostMessageEvent(
1679 const FrameMsg_PostMessage_Params
& params
) {
1680 // Find the source frame if it exists.
1681 WebFrame
* source_frame
= NULL
;
1682 if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1683 RenderFrameProxy
* source_proxy
=
1684 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1686 // Currently, navigating a top-level frame cross-process does not swap
1687 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1688 // WebRemoteFrame will not have an associated blink::Frame. If this is
1689 // the case for |source_proxy|, use the corresponding (swapped-out)
1690 // WebLocalFrame instead, so that event.source for this message can be
1691 // set and used properly.
1692 if (source_proxy
->IsMainFrameDetachedFromTree())
1693 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1695 source_frame
= source_proxy
->web_frame();
1699 // If the message contained MessagePorts, create the corresponding endpoints.
1700 blink::WebMessagePortChannelArray channels
=
1701 WebMessagePortChannelImpl::CreatePorts(
1702 params
.message_ports
, params
.new_routing_ids
,
1703 base::ThreadTaskRunnerHandle::Get().get());
1705 WebSerializedScriptValue serialized_script_value
;
1706 if (params
.is_data_raw_string
) {
1707 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1708 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1709 v8::Context::Scope
context_scope(context
);
1710 V8ValueConverterImpl converter
;
1711 converter
.SetDateAllowed(true);
1712 converter
.SetRegExpAllowed(true);
1713 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1714 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1716 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1718 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1721 // Create an event with the message. The next-to-last parameter to
1722 // initMessageEvent is the last event ID, which is not used with postMessage.
1723 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1724 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1725 msg_event
.initMessageEvent("message",
1726 // |canBubble| and |cancellable| are always false
1728 serialized_script_value
,
1729 params
.source_origin
, source_frame
,
1730 frame_
->document(), "", channels
);
1732 // We must pass in the target_origin to do the security check on this side,
1733 // since it may have changed since the original postMessage call was made.
1734 WebSecurityOrigin target_origin
;
1735 if (!params
.target_origin
.empty()) {
1737 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1739 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1742 #if defined(OS_ANDROID)
1743 void RenderFrameImpl::OnSelectPopupMenuItems(
1745 const std::vector
<int>& selected_indices
) {
1746 // It is possible to receive more than one of these calls if the user presses
1747 // a select faster than it takes for the show-select-popup IPC message to make
1748 // it to the browser UI thread. Ignore the extra-messages.
1749 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1750 if (!external_popup_menu_
)
1753 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1754 external_popup_menu_
.reset();
1758 #if defined(OS_MACOSX)
1759 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1760 if (external_popup_menu_
== NULL
)
1762 external_popup_menu_
->DidSelectItem(selected_index
);
1763 external_popup_menu_
.reset();
1767 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1768 frame_
->reload(ignore_cache
);
1771 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1772 blink::WebSurroundingText surroundingText
;
1773 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1775 if (surroundingText
.isNull()) {
1776 // |surroundingText| might not be correctly initialized, for example if
1777 // |frame_->selectionRange().isNull()|, in other words, if there was no
1779 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1780 routing_id_
, base::string16(), 0, 0));
1784 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1786 surroundingText
.textContent(),
1787 surroundingText
.startOffsetInTextContent(),
1788 surroundingText
.endOffsetInTextContent()));
1791 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1792 const base::string16
& message
,
1793 const base::string16
& default_value
,
1794 const GURL
& frame_url
,
1795 base::string16
* result
) {
1796 // Don't allow further dialogs if we are waiting to swap out, since the
1797 // PageGroupLoadDeferrer in our stack prevents it.
1798 if (render_view()->suppress_dialogs_until_swap_out_
)
1801 bool success
= false;
1802 base::string16 result_temp
;
1804 result
= &result_temp
;
1806 render_view()->SendAndRunNestedMessageLoop(
1807 new FrameHostMsg_RunJavaScriptMessage(
1808 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1813 void RenderFrameImpl::LoadNavigationErrorPage(
1814 const WebURLRequest
& failed_request
,
1815 const WebURLError
& error
,
1817 std::string error_html
;
1818 GetContentClient()->renderer()->GetNavigationErrorStrings(
1819 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1821 frame_
->loadHTMLString(error_html
,
1822 GURL(kUnreachableWebDataURL
),
1823 error
.unreachableURL
,
1827 void RenderFrameImpl::DidCommitCompositorFrame() {
1828 if (BrowserPluginManager::Get())
1829 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1831 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1834 RenderView
* RenderFrameImpl::GetRenderView() {
1835 return render_view_
.get();
1838 int RenderFrameImpl::GetRoutingID() {
1842 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1847 WebElement
RenderFrameImpl::GetFocusedElement() const {
1848 WebDocument doc
= frame_
->document();
1850 return doc
.focusedElement();
1852 return WebElement();
1855 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1856 return render_view_
->GetWebkitPreferences();
1859 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1860 const ContextMenuParams
& params
) {
1861 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1862 ContextMenuParams
our_params(params
);
1863 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1864 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1865 return our_params
.custom_context
.request_id
;
1868 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1869 DCHECK(pending_context_menus_
.Lookup(request_id
));
1870 pending_context_menus_
.Remove(request_id
);
1873 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1874 return context_menu_node_
;
1877 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1878 blink::WebFrame
* frame
,
1879 const WebPluginInfo
& info
,
1880 const blink::WebPluginParams
& params
,
1881 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1882 DCHECK_EQ(frame_
, frame
);
1883 #if defined(ENABLE_PLUGINS)
1884 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1885 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1886 this, GetContentClient()
1888 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1893 bool pepper_plugin_was_registered
= false;
1894 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1895 this, info
, &pepper_plugin_was_registered
));
1896 if (pepper_plugin_was_registered
) {
1897 if (pepper_module
.get()) {
1898 return new PepperWebPluginImpl(
1899 pepper_module
.get(), params
, this,
1901 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1904 #if defined(OS_CHROMEOS)
1905 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1907 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1908 // TODO(jam): change to take RenderFrame.
1909 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1916 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1917 const blink::WebURLRequest
& request
,
1918 blink::WebNavigationPolicy policy
) {
1919 DCHECK(!frame_
|| frame_
== frame
);
1920 loadURLExternally(frame
, request
, policy
, WebString());
1923 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1924 OnJavaScriptExecuteRequest(javascript
, 0, false);
1927 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1928 return &service_registry_
;
1931 #if defined(ENABLE_PLUGINS)
1932 void RenderFrameImpl::RegisterPeripheralPlugin(
1933 const url::Origin
& content_origin
,
1934 const base::Closure
& unthrottle_callback
) {
1935 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1936 content_origin
, unthrottle_callback
);
1938 #endif // defined(ENABLE_PLUGINS)
1940 bool RenderFrameImpl::IsFTPDirectoryListing() {
1941 WebURLResponseExtraDataImpl
* extra_data
=
1942 GetExtraDataFromResponse(frame_
->dataSource()->response());
1943 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1946 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1947 BrowserPluginManager::Get()->Attach(element_instance_id
);
1950 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1951 BrowserPluginManager::Get()->Detach(element_instance_id
);
1954 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1956 const gfx::Range
& range
) {
1957 // Use the routing id of Render Widget Host.
1958 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1964 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1965 v8::Isolate
* isolate
,
1966 v8::Local
<v8::Context
> context
) {
1967 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1968 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1971 v8::HandleScope
handle_scope(isolate
);
1972 registry
->AddBuiltinModule(
1973 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1974 registry
->AddBuiltinModule(isolate
,
1975 mojo::js::Support::kModuleName
,
1976 mojo::js::Support::GetModule(isolate
));
1977 registry
->AddBuiltinModule(
1979 ServiceRegistryJsWrapper::kModuleName
,
1980 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1983 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
1984 const std::string
& message
) {
1985 if (devtools_agent_
)
1986 devtools_agent_
->AddMessageToConsole(level
, message
);
1989 // blink::WebFrameClient implementation ----------------------------------------
1991 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1992 blink::WebLocalFrame
* frame
,
1993 const blink::WebPluginParams
& params
) {
1994 DCHECK_EQ(frame_
, frame
);
1995 blink::WebPlugin
* plugin
= NULL
;
1996 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1997 this, frame
, params
, &plugin
)) {
2001 if (base::UTF16ToUTF8(base::StringPiece16(params
.mimeType
)) ==
2002 kBrowserPluginMimeType
) {
2003 return BrowserPluginManager::Get()->CreateBrowserPlugin(
2004 this, GetContentClient()
2006 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
2011 #if defined(ENABLE_PLUGINS)
2013 std::string mime_type
;
2015 WebString top_origin
= frame
->top()->securityOrigin().toString();
2016 Send(new FrameHostMsg_GetPluginInfo(routing_id_
, params
.url
, GURL(top_origin
),
2017 params
.mimeType
.utf8(), &found
, &info
,
2022 WebPluginParams params_to_use
= params
;
2023 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2024 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2027 #endif // defined(ENABLE_PLUGINS)
2030 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2031 blink::WebLocalFrame
* frame
,
2032 const blink::WebURL
& url
,
2033 WebMediaPlayerClient
* client
,
2034 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
2035 WebContentDecryptionModule
* initial_cdm
) {
2036 #if defined(VIDEO_HOLE)
2037 if (!contains_media_player_
) {
2038 render_view_
->RegisterVideoHoleFrame(this);
2039 contains_media_player_
= true;
2041 #endif // defined(VIDEO_HOLE)
2043 blink::WebMediaStream
web_stream(
2044 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2045 if (!web_stream
.isNull())
2046 return CreateWebMediaPlayerForMediaStream(client
);
2048 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2050 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2051 scoped_refptr
<media::AudioRendererSink
> audio_renderer_sink
;
2052 media::WebMediaPlayerParams::Context3DCB context_3d_cb
;
2054 scoped_refptr
<media::AudioRendererSink
> audio_renderer_sink
=
2055 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
);
2056 media::WebMediaPlayerParams::Context3DCB context_3d_cb
=
2057 base::Bind(&GetSharedMainThreadContext3D
);
2058 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2060 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2061 media::WebMediaPlayerParams
params(
2062 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2063 base::Unretained(GetContentClient()->renderer()),
2064 static_cast<RenderFrame
*>(this), has_played_media_
),
2065 audio_renderer_sink
, media_log
, render_thread
->GetMediaThreadTaskRunner(),
2066 render_thread
->GetWorkerTaskRunner(),
2067 render_thread
->compositor_task_runner(), context_3d_cb
,
2068 GetMediaPermission(), initial_cdm
);
2070 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2071 return CreateAndroidWebMediaPlayer(client
, encrypted_client
, params
);
2073 #if defined(ENABLE_MOJO_MEDIA)
2074 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2075 new media::MojoRendererFactory(GetMediaServiceFactory()));
2077 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2078 GetContentClient()->renderer()->CreateMediaRendererFactory(
2079 this, render_thread
->GetGpuFactories(), media_log
);
2081 if (!media_renderer_factory
.get()) {
2082 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2083 media_log
, render_thread
->GetGpuFactories(),
2084 *render_thread
->GetAudioHardwareConfig()));
2086 #endif // defined(ENABLE_MOJO_MEDIA)
2088 return new media::WebMediaPlayerImpl(
2089 frame
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
2090 media_renderer_factory
.Pass(), GetCdmFactory(), params
);
2091 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2094 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2095 blink::WebLocalFrame
* frame
,
2096 blink::WebApplicationCacheHostClient
* client
) {
2097 if (!frame
|| !frame
->view())
2099 DCHECK(!frame_
|| frame_
== frame
);
2100 return new RendererWebApplicationCacheHostImpl(
2101 RenderViewImpl::FromWebView(frame
->view()), client
,
2102 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2105 blink::WebWorkerContentSettingsClientProxy
*
2106 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2107 blink::WebLocalFrame
* frame
) {
2108 if (!frame
|| !frame
->view())
2110 DCHECK(!frame_
|| frame_
== frame
);
2111 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2115 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2116 const WebPopupMenuInfo
& popup_menu_info
,
2117 WebExternalPopupMenuClient
* popup_menu_client
) {
2118 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2119 // An IPC message is sent to the browser to build and display the actual
2120 // popup. The user could have time to click a different select by the time
2121 // the popup is shown. In that case external_popup_menu_ is non NULL.
2122 // By returning NULL in that case, we instruct Blink to cancel that new
2123 // popup. So from the user perspective, only the first one will show, and
2124 // will have to close the first one before another one can be shown.
2125 if (external_popup_menu_
)
2127 external_popup_menu_
.reset(
2128 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2129 if (render_view_
->screen_metrics_emulator_
) {
2130 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2131 external_popup_menu_
.get(),
2132 render_view_
->screen_metrics_emulator_
.get());
2134 return external_popup_menu_
.get();
2140 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2141 DCHECK(!frame_
|| frame_
== frame
);
2142 return &cookie_jar_
;
2145 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2146 blink::WebLocalFrame
* frame
) {
2147 DCHECK(!frame_
|| frame_
== frame
);
2148 // At this point we should have non-null data source.
2149 DCHECK(frame
->dataSource());
2150 if (!ChildThreadImpl::current())
2151 return NULL
; // May be null in some tests.
2152 ServiceWorkerNetworkProvider
* provider
=
2153 ServiceWorkerNetworkProvider::FromDocumentState(
2154 DocumentState::FromDataSource(frame
->dataSource()));
2156 return new WebServiceWorkerProviderImpl(
2157 ChildThreadImpl::current()->thread_safe_sender(),
2158 provider
->context());
2161 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2162 DCHECK(!frame_
|| frame_
== frame
);
2163 // If the request hasn't yet committed, notify the browser process that it is
2164 // no longer safe to show the pending URL of the main frame, since a URL spoof
2165 // is now possible. (If the request has committed, the browser already knows.)
2166 if (!frame
->parent()) {
2167 DocumentState
* document_state
=
2168 DocumentState::FromDataSource(frame
->dataSource());
2169 NavigationStateImpl
* navigation_state
=
2170 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2172 if (!navigation_state
->request_committed()) {
2173 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2178 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2179 blink::WebLocalFrame
* parent
,
2180 blink::WebTreeScopeType scope
,
2181 const blink::WebString
& name
,
2182 blink::WebSandboxFlags sandbox_flags
) {
2183 // Synchronously notify the browser of a child frame creation to get the
2184 // routing_id for the RenderFrame.
2185 int child_routing_id
= MSG_ROUTING_NONE
;
2186 Send(new FrameHostMsg_CreateChildFrame(
2188 base::UTF16ToUTF8(base::StringPiece16(name
)), sandbox_flags
,
2189 &child_routing_id
));
2191 // Allocation of routing id failed, so we can't create a child frame. This can
2192 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2193 // out state or synchronous IPC message above has failed.
2194 if (child_routing_id
== MSG_ROUTING_NONE
) {
2195 NOTREACHED() << "Failed to allocate routing id for child frame.";
2199 // Create the RenderFrame and WebLocalFrame, linking the two.
2200 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2201 render_view_
.get(), child_routing_id
);
2202 blink::WebLocalFrame
* web_frame
=
2203 WebLocalFrame::create(scope
, child_render_frame
);
2204 child_render_frame
->SetWebFrame(web_frame
);
2206 // Add the frame to the frame tree and initialize it.
2207 parent
->appendChild(web_frame
);
2208 child_render_frame
->Initialize();
2213 void RenderFrameImpl::didChangeOpener(blink::WebFrame
* opener
) {
2214 // Only active frames are able to disown their opener.
2215 if (!opener
&& is_swapped_out_
)
2218 // Only a local frame should be able to update another frame's opener.
2219 DCHECK(!opener
|| opener
->isWebLocalFrame());
2221 int opener_routing_id
= opener
?
2222 RenderFrameImpl::FromWebFrame(opener
->toWebLocalFrame())->GetRoutingID() :
2224 Send(new FrameHostMsg_DidChangeOpener(routing_id_
, opener_routing_id
));
2227 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2228 // NOTE: This function is called on the frame that is being detached and not
2229 // the parent frame. This is different from createChildFrame() which is
2230 // called on the parent frame.
2231 CHECK(!is_detaching_
);
2232 DCHECK(!frame_
|| frame_
== frame
);
2234 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2235 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2236 FrameDetached(frame
));
2238 // We only notify the browser process when the frame is being detached for
2239 // removal. If the frame is being detached for swap, we don't need to do this
2240 // since we are not modifiying the frame tree.
2241 if (type
== DetachType::Remove
)
2242 Send(new FrameHostMsg_Detach(routing_id_
));
2244 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2245 // sent before setting |is_detaching_| to true.
2246 is_detaching_
= true;
2248 // Clean up the associated RenderWidget for the frame, if there is one.
2249 if (render_widget_
) {
2250 render_widget_
->UnregisterRenderFrame(this);
2251 render_widget_
->CloseForFrame();
2254 // We need to clean up subframes by removing them from the map and deleting
2255 // the RenderFrameImpl. In contrast, the main frame is owned by its
2256 // containing RenderViewHost (so that they have the same lifetime), so only
2257 // removal from the map is needed and no deletion.
2258 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2259 CHECK(it
!= g_frame_map
.Get().end());
2260 CHECK_EQ(it
->second
, this);
2261 g_frame_map
.Get().erase(it
);
2263 // Only remove the frame from the renderer's frame tree if the frame is
2264 // being detached for removal. In the case of a swap, the frame needs to
2265 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2266 if (is_subframe_
&& type
== DetachType::Remove
)
2267 frame
->parent()->removeChild(frame
);
2269 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2270 // object may not be deleted immediately and other methods may try to access
2276 // Object is invalid after this point.
2279 void RenderFrameImpl::frameFocused() {
2280 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2283 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2284 DCHECK(!frame_
|| frame_
== frame
);
2286 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2287 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2288 FrameWillClose(frame
));
2291 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2292 const blink::WebString
& name
) {
2293 DCHECK(!frame_
|| frame_
== frame
);
2295 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2296 // updates may have performance implications for benchmarks like SunSpider.
2297 // For now, send these updates only for --site-per-process, which needs to
2298 // replicate frame names to frame proxies, and when
2299 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2300 // can be optimized further by only sending the update if there are any
2301 // remote frames in the frame tree, or delaying and batching up IPCs if
2302 // updates are happening too frequently.
2303 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2304 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2305 Send(new FrameHostMsg_DidChangeName(
2306 routing_id_
, base::UTF16ToUTF8(base::StringPiece16(name
))));
2310 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2311 blink::WebSandboxFlags flags
) {
2312 int frame_routing_id
= MSG_ROUTING_NONE
;
2313 if (child_frame
->isWebRemoteFrame()) {
2315 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2318 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2321 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2325 void RenderFrameImpl::didMatchCSS(
2326 blink::WebLocalFrame
* frame
,
2327 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2328 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2329 DCHECK(!frame_
|| frame_
== frame
);
2331 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2332 DidMatchCSS(newly_matching_selectors
,
2333 stopped_matching_selectors
));
2336 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2337 const blink::WebString
& source
) {
2338 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2342 void RenderFrameImpl::didAddMessageToConsole(
2343 const blink::WebConsoleMessage
& message
,
2344 const blink::WebString
& source_name
,
2345 unsigned source_line
,
2346 const blink::WebString
& stack_trace
) {
2347 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2348 switch (message
.level
) {
2349 case blink::WebConsoleMessage::LevelDebug
:
2350 log_severity
= logging::LOG_VERBOSE
;
2352 case blink::WebConsoleMessage::LevelLog
:
2353 case blink::WebConsoleMessage::LevelInfo
:
2354 log_severity
= logging::LOG_INFO
;
2356 case blink::WebConsoleMessage::LevelWarning
:
2357 log_severity
= logging::LOG_WARNING
;
2359 case blink::WebConsoleMessage::LevelError
:
2360 log_severity
= logging::LOG_ERROR
;
2363 log_severity
= logging::LOG_VERBOSE
;
2366 if (shouldReportDetailedMessageForSource(source_name
)) {
2368 RenderFrameObserver
, observers_
,
2369 DetailedConsoleMessageAdded(message
.text
,
2373 static_cast<int32
>(log_severity
)));
2376 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2377 static_cast<int32
>(log_severity
),
2379 static_cast<int32
>(source_line
),
2383 void RenderFrameImpl::loadURLExternally(
2384 blink::WebLocalFrame
* frame
,
2385 const blink::WebURLRequest
& request
,
2386 blink::WebNavigationPolicy policy
,
2387 const blink::WebString
& suggested_name
) {
2388 DCHECK(!frame_
|| frame_
== frame
);
2389 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2390 if (policy
== blink::WebNavigationPolicyDownload
) {
2391 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2393 request
.url(), referrer
,
2396 OpenURL(frame
, request
.url(), referrer
, policy
);
2400 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2401 const NavigationPolicyInfo
& info
) {
2402 DCHECK(!frame_
|| frame_
== info
.frame
);
2403 return DecidePolicyForNavigation(this, info
);
2406 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2407 blink::WebFrame
* frame
) {
2408 DCHECK(!frame_
|| frame_
== frame
);
2409 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2412 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2413 const blink::WebFormElement
& form
) {
2414 DCHECK(!frame_
|| frame_
== frame
);
2416 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2419 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2420 const blink::WebFormElement
& form
) {
2421 DCHECK(!frame_
|| frame_
== frame
);
2422 DocumentState
* document_state
=
2423 DocumentState::FromDataSource(frame
->provisionalDataSource());
2424 NavigationStateImpl
* navigation_state
=
2425 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2426 InternalDocumentStateData
* internal_data
=
2427 InternalDocumentStateData::FromDocumentState(document_state
);
2429 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2430 ui::PAGE_TRANSITION_LINK
)) {
2431 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2434 // Save these to be processed when the ensuing navigation is committed.
2435 WebSearchableFormData
web_searchable_form_data(form
);
2436 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2437 internal_data
->set_searchable_form_encoding(
2438 web_searchable_form_data
.encoding().utf8());
2440 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2443 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2444 blink::WebDataSource
* datasource
) {
2445 DCHECK(!frame_
|| frame_
== frame
);
2447 bool content_initiated
= !pending_navigation_params_
.get();
2449 // Make sure any previous redirect URLs end up in our new data source.
2450 if (pending_navigation_params_
.get()) {
2451 for (const auto& i
:
2452 pending_navigation_params_
->request_params
.redirects
) {
2453 datasource
->appendRedirect(i
);
2457 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2458 if (!document_state
) {
2459 document_state
= new DocumentState
;
2460 datasource
->setExtraData(document_state
);
2461 if (!content_initiated
)
2462 PopulateDocumentStateFromPending(document_state
);
2465 // Carry over the user agent override flag, if it exists.
2466 blink::WebView
* webview
= render_view_
->webview();
2467 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2468 webview
->mainFrame()->isWebLocalFrame() &&
2469 webview
->mainFrame()->dataSource()) {
2470 DocumentState
* old_document_state
=
2471 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2472 if (old_document_state
) {
2473 InternalDocumentStateData
* internal_data
=
2474 InternalDocumentStateData::FromDocumentState(document_state
);
2475 InternalDocumentStateData
* old_internal_data
=
2476 InternalDocumentStateData::FromDocumentState(old_document_state
);
2477 internal_data
->set_is_overriding_user_agent(
2478 old_internal_data
->is_overriding_user_agent());
2482 // The rest of RenderView assumes that a WebDataSource will always have a
2483 // non-null NavigationState.
2484 if (content_initiated
) {
2485 document_state
->set_navigation_state(
2486 NavigationStateImpl::CreateContentInitiated());
2488 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2489 pending_navigation_params_
.reset();
2492 // DocumentState::referred_by_prefetcher_ is true if we are
2493 // navigating from a page that used prefetching using a link on that
2494 // page. We are early enough in the request process here that we
2495 // can still see the DocumentState of the previous page and set
2496 // this value appropriately.
2497 // TODO(gavinp): catch the important case of navigation in a new
2498 // renderer process.
2500 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2501 const WebURLRequest
& original_request
= datasource
->originalRequest();
2502 const GURL
referrer(
2503 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2504 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2505 DocumentState::FromDataSource(old_frame
->dataSource())
2506 ->was_prefetcher()) {
2507 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2508 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2509 if (old_frame_datasource
&&
2510 referrer
== GURL(old_frame_datasource
->request().url())) {
2511 document_state
->set_was_referred_by_prefetcher(true);
2519 if (content_initiated
) {
2520 const WebURLRequest
& request
= datasource
->request();
2521 switch (request
.cachePolicy()) {
2522 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2523 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2525 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2526 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2527 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2529 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2530 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2532 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2533 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2540 // Create the serviceworker's per-document network observing object if it
2541 // does not exist (When navigation happens within a page, the provider already
2543 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2544 DocumentState::FromDataSource(datasource
))) {
2545 ServiceWorkerProviderType provider_type
=
2546 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2547 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2548 blink::WebSandboxFlags::Origin
) {
2549 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2551 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2552 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2553 ServiceWorkerNetworkProvider::AttachToDocumentState(
2554 DocumentState::FromDataSource(datasource
),
2555 network_provider
.Pass());
2559 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2560 double triggering_event_time
) {
2561 DCHECK(!frame_
|| frame_
== frame
);
2562 WebDataSource
* ds
= frame
->provisionalDataSource();
2564 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2565 // callback is invoked.
2569 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2570 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2571 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2573 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2574 CHECK_IMPLIES(ds
->request().url() == GURL(kSwappedOutURL
), is_swapped_out_
)
2575 << "Heard swappedout:// when not swapped out.";
2577 // Update the request time if WebKit has better knowledge of it.
2578 if (document_state
->request_time().is_null() &&
2579 triggering_event_time
!= 0.0) {
2580 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2583 // Start time is only set after request time.
2584 document_state
->set_start_load_time(Time::Now());
2586 bool is_top_most
= !frame
->parent();
2588 render_view_
->set_navigation_gesture(
2589 WebUserGestureIndicator::isProcessingUserGesture() ?
2590 NavigationGestureUser
: NavigationGestureAuto
);
2591 } else if (ds
->replacesCurrentHistoryItem()) {
2592 // Subframe navigations that don't add session history items must be
2593 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2594 // handle loading of error pages.
2595 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2596 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2599 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2600 DidStartProvisionalLoad(frame
));
2601 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2603 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2604 routing_id_
, ds
->request().url()));
2607 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2608 blink::WebLocalFrame
* frame
) {
2609 DCHECK(!frame_
|| frame_
== frame
);
2610 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2613 void RenderFrameImpl::didFailProvisionalLoad(
2614 blink::WebLocalFrame
* frame
,
2615 const blink::WebURLError
& error
,
2616 blink::WebHistoryCommitType commit_type
) {
2617 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2619 DCHECK(!frame_
|| frame_
== frame
);
2620 WebDataSource
* ds
= frame
->provisionalDataSource();
2623 const WebURLRequest
& failed_request
= ds
->request();
2625 // Notify the browser that we failed a provisional load with an error.
2627 // Note: It is important this notification occur before DidStopLoading so the
2628 // SSL manager can react to the provisional load failure before being
2629 // notified the load stopped.
2631 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2632 DidFailProvisionalLoad(frame
, error
));
2633 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2634 DidFailProvisionalLoad(error
));
2636 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2638 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2641 // Make sure we never show errors in view source mode.
2642 frame
->enableViewSourceMode(false);
2644 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2645 NavigationStateImpl
* navigation_state
=
2646 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2648 // If this is a failed back/forward/reload navigation, then we need to do a
2649 // 'replace' load. This is necessary to avoid messing up session history.
2650 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2651 // as session history is concerned.
2652 bool replace
= commit_type
!= blink::WebStandardCommit
;
2654 // If we failed on a browser initiated request, then make sure that our error
2655 // page load is regarded as the same browser initiated request.
2656 if (!navigation_state
->IsContentInitiated()) {
2657 pending_navigation_params_
.reset(new NavigationParams(
2658 navigation_state
->common_params(), navigation_state
->start_params(),
2659 navigation_state
->request_params()));
2660 pending_navigation_params_
->request_params
.request_time
=
2661 document_state
->request_time();
2664 // Load an error page.
2665 LoadNavigationErrorPage(failed_request
, error
, replace
);
2668 void RenderFrameImpl::didCommitProvisionalLoad(
2669 blink::WebLocalFrame
* frame
,
2670 const blink::WebHistoryItem
& item
,
2671 blink::WebHistoryCommitType commit_type
) {
2672 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2674 "url", GetLoadingUrl().possibly_invalid_spec());
2675 DCHECK(!frame_
|| frame_
== frame
);
2676 DocumentState
* document_state
=
2677 DocumentState::FromDataSource(frame
->dataSource());
2678 NavigationStateImpl
* navigation_state
=
2679 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2681 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2682 RenderFrameProxy
* proxy
=
2683 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2685 proxy
->web_frame()->swap(frame_
);
2686 proxy_routing_id_
= MSG_ROUTING_NONE
;
2688 // If this is the main frame going from a remote frame to a local frame,
2689 // it needs to set RenderViewImpl's pointer for the main frame to itself
2690 // and ensure RenderWidget is no longer in swapped out mode.
2691 if (!is_subframe_
) {
2692 CHECK(!render_view_
->main_render_frame_
);
2693 render_view_
->main_render_frame_
= this;
2694 if (render_view_
->is_swapped_out())
2695 render_view_
->SetSwappedOut(false);
2699 // When we perform a new navigation, we need to update the last committed
2700 // session history entry with state for the page we are leaving. Do this
2701 // before updating the HistoryController state.
2702 render_view_
->SendUpdateState();
2704 render_view_
->history_controller()->UpdateForCommit(
2705 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2707 InternalDocumentStateData
* internal_data
=
2708 InternalDocumentStateData::FromDocumentState(document_state
);
2710 if (document_state
->commit_load_time().is_null())
2711 document_state
->set_commit_load_time(Time::Now());
2713 if (internal_data
->must_reset_scroll_and_scale_state()) {
2714 render_view_
->webview()->resetScrollAndScaleState();
2715 internal_data
->set_must_reset_scroll_and_scale_state(false);
2718 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2719 if (is_new_navigation
) {
2720 // We bump our Page ID to correspond with the new session history entry.
2721 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2723 // Don't update history list values for kSwappedOutURL, since
2724 // we don't want to forget the entry that was there, and since we will
2725 // never come back to kSwappedOutURL. Note that we have to call
2726 // SendUpdateState and update page_id_ even in this case, so that
2727 // the current entry gets a state update and so that we don't send a
2728 // state update to the wrong entry when we swap back in.
2730 navigation_state
->common_params().should_replace_current_entry
,
2731 render_view_
->history_list_length_
> 0);
2732 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2733 !navigation_state
->common_params().should_replace_current_entry
) {
2734 // Advance our offset in session history, applying the length limit.
2735 // There is now no forward history.
2736 render_view_
->history_list_offset_
++;
2737 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2738 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2739 render_view_
->history_list_length_
=
2740 render_view_
->history_list_offset_
+ 1;
2743 const RequestNavigationParams
& request_params
=
2744 navigation_state
->request_params();
2745 if (request_params
.nav_entry_id
!= 0 &&
2746 !request_params
.intended_as_new_entry
) {
2747 // This is a successful session history navigation!
2748 render_view_
->page_id_
= request_params
.page_id
;
2750 render_view_
->history_list_offset_
=
2751 request_params
.pending_history_list_offset
;
2756 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2757 CHECK(sent
); // http://crbug.com/407376
2759 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2760 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2762 RenderFrameObserver
, observers_
,
2763 DidCommitProvisionalLoad(is_new_navigation
,
2764 navigation_state
->WasWithinSamePage()));
2766 if (!frame
->parent()) { // Only for top frames.
2767 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2768 if (render_thread_impl
) { // Can be NULL in tests.
2769 render_thread_impl
->histogram_customizer()->
2770 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2771 RenderView::GetRenderViewCount());
2772 render_thread_impl
->GetRendererScheduler()->OnPageLoadStarted();
2776 // Remember that we've already processed this request, so we don't update
2777 // the session history again. We do this regardless of whether this is
2778 // a session history navigation, because if we attempted a session history
2779 // navigation without valid HistoryItem state, WebCore will think it is a
2781 navigation_state
->set_request_committed(true);
2783 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2785 // Check whether we have new encoding name.
2786 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2789 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2790 DCHECK(!frame_
|| frame_
== frame
);
2792 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2793 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2794 DidCreateNewDocument(frame
));
2797 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2798 DCHECK(!frame_
|| frame_
== frame
);
2800 int enabled_bindings
= render_view_
->GetEnabledBindings();
2802 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2803 WebUIExtension::Install(frame
);
2805 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2806 DomAutomationController::Install(this, frame
);
2808 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2809 StatsCollectionController::Install(frame
);
2811 const base::CommandLine
& command_line
=
2812 *base::CommandLine::ForCurrentProcess();
2814 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2815 GpuBenchmarking::Install(frame
);
2817 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2818 MemoryBenchmarkingExtension::Install(frame
);
2820 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2821 SkiaBenchmarking::Install(frame
);
2823 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2824 DidClearWindowObject(frame
));
2825 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2828 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2829 DCHECK(!frame_
|| frame_
== frame
);
2831 // Notify the browser about non-blank documents loading in the top frame.
2832 GURL url
= frame
->document().url();
2833 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2834 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2835 // frame->tree()->top().
2836 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2837 if (frame
== main_frame
) {
2838 // For now, don't remember plugin zoom values. We don't want to mix them
2839 // with normal web content (i.e. a fixed layout plugin would usually want
2841 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2842 render_view_
->GetRoutingID(),
2843 main_frame
->document().isPluginDocument()));
2847 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2848 DidCreateDocumentElement());
2849 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2850 DidCreateDocumentElement(frame
));
2853 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2854 const blink::WebString
& title
,
2855 blink::WebTextDirection direction
) {
2856 DCHECK(!frame_
|| frame_
== frame
);
2857 // Ignore all but top level navigations.
2858 if (!frame
->parent()) {
2859 base::string16 title16
= title
;
2860 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2861 routing_id_
, base::UTF16ToUTF8(title16
));
2863 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2864 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2865 shortened_title
, direction
));
2868 // Also check whether we have new encoding name.
2869 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2872 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2873 blink::WebIconURL::Type icon_type
) {
2874 DCHECK(!frame_
|| frame_
== frame
);
2875 // TODO(nasko): Investigate wheather implementation should move here.
2876 render_view_
->didChangeIcon(frame
, icon_type
);
2879 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
,
2880 bool document_is_empty
) {
2881 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2883 DCHECK(!frame_
|| frame_
== frame
);
2884 WebDataSource
* ds
= frame
->dataSource();
2885 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2886 document_state
->set_finish_document_load_time(Time::Now());
2888 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2890 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2891 DidFinishDocumentLoad(frame
));
2892 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2894 // Check whether we have new encoding name.
2895 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2897 // If this is an empty document with an http status code indicating an error,
2898 // we may want to display our own error page, so the user doesn't end up
2899 // with an unexplained blank page.
2900 if (!document_is_empty
)
2903 // Do not show error page when DevTools is attached.
2904 RenderFrameImpl
* localRoot
= this;
2905 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
2906 localRoot
->frame_
->parent()->isWebLocalFrame()) {
2907 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
2910 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
2913 // Display error page instead of a blank page, if appropriate.
2914 std::string error_domain
= "http";
2915 InternalDocumentStateData
* internal_data
=
2916 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2917 int http_status_code
= internal_data
->http_status_code();
2918 if (GetContentClient()->renderer()->HasErrorPage(http_status_code
,
2921 error
.unreachableURL
= frame
->document().url();
2922 error
.domain
= WebString::fromUTF8(error_domain
);
2923 error
.reason
= http_status_code
;
2924 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
2928 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2929 DCHECK(!frame_
|| frame_
== frame
);
2930 if (!frame
->parent()) {
2931 FrameMsg_UILoadMetricsReportType::Value report_type
=
2932 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2933 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2934 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2935 base::TimeDelta::FromSecondsD(
2936 frame
->dataSource()->request().uiStartTime());
2938 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2939 routing_id_
, report_type
, ui_timestamp
));
2943 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2944 const blink::WebURLError
& error
,
2945 blink::WebHistoryCommitType commit_type
) {
2946 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2948 DCHECK(!frame_
|| frame_
== frame
);
2949 // TODO(nasko): Move implementation here. No state needed.
2950 WebDataSource
* ds
= frame
->dataSource();
2953 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2954 DidFailLoad(frame
, error
));
2956 const WebURLRequest
& failed_request
= ds
->request();
2957 base::string16 error_description
;
2958 GetContentClient()->renderer()->GetNavigationErrorStrings(
2964 &error_description
);
2965 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2966 failed_request
.url(),
2969 error
.wasIgnoredByHandler
));
2972 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2973 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2975 DCHECK(!frame_
|| frame_
== frame
);
2976 WebDataSource
* ds
= frame
->dataSource();
2977 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2978 if (document_state
->finish_load_time().is_null()) {
2979 if (!frame
->parent()) {
2980 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2981 TRACE_EVENT_SCOPE_PROCESS
);
2983 document_state
->set_finish_load_time(Time::Now());
2986 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2987 DidFinishLoad(frame
));
2988 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2990 // Don't send this message while the frame is swapped out.
2991 if (is_swapped_out())
2994 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2995 ds
->request().url()));
2998 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2999 const blink::WebHistoryItem
& item
,
3000 blink::WebHistoryCommitType commit_type
) {
3001 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
3003 DCHECK(!frame_
|| frame_
== frame
);
3004 // If this was a reference fragment navigation that we initiated, then we
3005 // could end up having a non-null pending navigation params. We just need to
3006 // update the ExtraData on the datasource so that others who read the
3007 // ExtraData will get the new NavigationState. Similarly, if we did not
3008 // initiate this navigation, then we need to take care to reset any pre-
3009 // existing navigation state to a content-initiated navigation state.
3010 // didCreateDataSource conveniently takes care of this for us.
3011 didCreateDataSource(frame
, frame
->dataSource());
3013 DocumentState
* document_state
=
3014 DocumentState::FromDataSource(frame
->dataSource());
3015 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
3016 ->set_was_within_same_page(true);
3018 didCommitProvisionalLoad(frame
, item
, commit_type
);
3021 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
3022 DCHECK(!frame_
|| frame_
== frame
);
3023 // TODO(nasko): Move implementation here. Needed methods:
3024 // * StartNavStateSyncTimerIfNecessary
3025 render_view_
->didUpdateCurrentHistoryItem(frame
);
3028 void RenderFrameImpl::didChangeThemeColor() {
3029 if (frame_
->parent())
3032 Send(new FrameHostMsg_DidChangeThemeColor(
3033 routing_id_
, frame_
->document().themeColor()));
3036 void RenderFrameImpl::dispatchLoad() {
3037 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
3040 void RenderFrameImpl::requestNotificationPermission(
3041 const blink::WebSecurityOrigin
& origin
,
3042 blink::WebNotificationPermissionCallback
* callback
) {
3043 if (!notification_permission_dispatcher_
) {
3044 notification_permission_dispatcher_
=
3045 new NotificationPermissionDispatcher(this);
3048 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3051 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3052 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3055 if (is_empty_selection
)
3056 selection_text_
.clear();
3058 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3059 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3060 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3061 // to notify the selection was changed. Focus change should be notified
3062 // before selection change.
3063 GetRenderWidget()->UpdateTextInputState(
3064 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
3065 SyncSelectionIfRequired();
3068 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3069 blink::WebColorChooserClient
* client
,
3070 const blink::WebColor
& initial_color
,
3071 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3072 RendererWebColorChooserImpl
* color_chooser
=
3073 new RendererWebColorChooserImpl(this, client
);
3074 std::vector
<ColorSuggestion
> color_suggestions
;
3075 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3076 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3078 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3079 return color_chooser
;
3082 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3083 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3086 frame_
->document().url(),
3090 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3091 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3094 frame_
->document().url(),
3098 bool RenderFrameImpl::runModalPromptDialog(
3099 const blink::WebString
& message
,
3100 const blink::WebString
& default_value
,
3101 blink::WebString
* actual_value
) {
3102 base::string16 result
;
3103 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3106 frame_
->document().url(),
3109 actual_value
->assign(result
);
3113 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3115 const blink::WebString
& message
) {
3116 // If we are swapping out, we have already run the beforeunload handler.
3117 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3118 // at all, to avoid running it twice.
3119 if (is_swapped_out_
)
3122 // Don't allow further dialogs if we are waiting to swap out, since the
3123 // PageGroupLoadDeferrer in our stack prevents it.
3124 if (render_view()->suppress_dialogs_until_swap_out_
)
3127 bool success
= false;
3128 // This is an ignored return value, but is included so we can accept the same
3129 // response as RunJavaScriptMessage.
3130 base::string16 ignored_result
;
3131 render_view()->SendAndRunNestedMessageLoop(
3132 new FrameHostMsg_RunBeforeUnloadConfirm(
3133 routing_id_
, frame_
->document().url(), message
, is_reload
,
3134 &success
, &ignored_result
));
3138 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3139 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3140 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3141 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3142 if (GetRenderWidget()->has_host_context_menu_location()) {
3143 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3144 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3147 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3148 // it. We replace it with an empty GURL so the appropriate items are disabled
3149 // in the context menu.
3150 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3151 // data encoded images. We should have a way to save them.
3152 if (params
.src_url
.spec().size() > GetMaxURLChars())
3153 params
.src_url
= GURL();
3154 context_menu_node_
= data
.node
;
3156 #if defined(OS_ANDROID)
3157 gfx::Rect start_rect
;
3159 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3160 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3161 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3164 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3167 void RenderFrameImpl::clearContextMenu() {
3168 context_menu_node_
.reset();
3171 void RenderFrameImpl::willSendRequest(
3172 blink::WebLocalFrame
* frame
,
3173 unsigned identifier
,
3174 blink::WebURLRequest
& request
,
3175 const blink::WebURLResponse
& redirect_response
) {
3176 DCHECK(!frame_
|| frame_
== frame
);
3177 // The request my be empty during tests.
3178 if (request
.url().isEmpty())
3181 // Set the first party for cookies url if it has not been set yet (new
3182 // requests). For redirects, it is updated by WebURLLoaderImpl.
3183 if (request
.firstPartyForCookies().isEmpty()) {
3184 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3185 request
.setFirstPartyForCookies(request
.url());
3187 // TODO(nasko): When the top-level frame is remote, there is no document.
3188 // This is broken and should be fixed to propagate the first party.
3189 WebFrame
* top
= frame
->top();
3190 if (top
->isWebLocalFrame()) {
3191 request
.setFirstPartyForCookies(
3192 frame
->top()->document().firstPartyForCookies());
3197 WebDataSource
* provisional_data_source
= frame
->provisionalDataSource();
3198 WebDataSource
* data_source
=
3199 provisional_data_source
? provisional_data_source
: frame
->dataSource();
3201 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3202 DCHECK(document_state
);
3203 InternalDocumentStateData
* internal_data
=
3204 InternalDocumentStateData::FromDocumentState(document_state
);
3205 NavigationStateImpl
* navigation_state
=
3206 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3207 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3208 if (provisional_data_source
&& provisional_data_source
->isClientRedirect()) {
3209 transition_type
= ui::PageTransitionFromInt(
3210 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3213 GURL
request_url(request
.url());
3215 if (GetContentClient()->renderer()->WillSendRequest(
3219 request
.firstPartyForCookies(),
3221 request
.setURL(WebURL(new_url
));
3224 if (internal_data
->is_cache_policy_override_set())
3225 request
.setCachePolicy(internal_data
->cache_policy_override());
3227 // The request's extra data may indicate that we should set a custom user
3228 // agent. This needs to be done here, after WebKit is through with setting the
3229 // user agent on its own. Similarly, it may indicate that we should set an
3230 // X-Requested-With header. This must be done here to avoid breaking CORS
3232 // PlzNavigate: there may also be a stream url associated with the request.
3233 WebString custom_user_agent
;
3234 WebString requested_with
;
3235 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3236 if (request
.extraData()) {
3237 RequestExtraData
* old_extra_data
=
3238 static_cast<RequestExtraData
*>(request
.extraData());
3240 custom_user_agent
= old_extra_data
->custom_user_agent();
3241 if (!custom_user_agent
.isNull()) {
3242 if (custom_user_agent
.isEmpty())
3243 request
.clearHTTPHeaderField("User-Agent");
3245 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3248 requested_with
= old_extra_data
->requested_with();
3249 if (!requested_with
.isNull()) {
3250 if (requested_with
.isEmpty())
3251 request
.clearHTTPHeaderField("X-Requested-With");
3253 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3255 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3258 // Add the default accept header for frame request if it has not been set
3260 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3261 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3262 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3263 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3264 WebString::fromUTF8(kDefaultAcceptHeader
));
3267 // Add an empty HTTP origin header for non GET methods if none is currently
3269 request
.addHTTPOriginIfNeeded(WebString());
3271 // Attach |should_replace_current_entry| state to requests so that, should
3272 // this navigation later require a request transfer, all state is preserved
3273 // when it is re-created in the new process.
3274 bool should_replace_current_entry
= false;
3275 if (navigation_state
->IsContentInitiated()) {
3276 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3278 // If the navigation is browser-initiated, the NavigationState contains the
3279 // correct value instead of the WebDataSource.
3281 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3282 // NavigationState::should_replace_current_entry().
3283 should_replace_current_entry
=
3284 navigation_state
->common_params().should_replace_current_entry
;
3287 int provider_id
= kInvalidServiceWorkerProviderId
;
3288 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3289 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3290 // |provisionalDataSource| may be null in some content::ResourceFetcher
3291 // use cases, we don't hook those requests.
3292 if (frame
->provisionalDataSource()) {
3293 ServiceWorkerNetworkProvider
* provider
=
3294 ServiceWorkerNetworkProvider::FromDocumentState(
3295 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3296 provider_id
= provider
->provider_id();
3298 } else if (frame
->dataSource()) {
3299 ServiceWorkerNetworkProvider
* provider
=
3300 ServiceWorkerNetworkProvider::FromDocumentState(
3301 DocumentState::FromDataSource(frame
->dataSource()));
3302 provider_id
= provider
->provider_id();
3305 WebFrame
* parent
= frame
->parent();
3306 int parent_routing_id
= MSG_ROUTING_NONE
;
3308 parent_routing_id
= -1;
3309 } else if (parent
->isWebLocalFrame()) {
3310 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3312 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3315 RequestExtraData
* extra_data
= new RequestExtraData();
3316 extra_data
->set_visibility_state(render_view_
->visibilityState());
3317 extra_data
->set_custom_user_agent(custom_user_agent
);
3318 extra_data
->set_requested_with(requested_with
);
3319 extra_data
->set_render_frame_id(routing_id_
);
3320 extra_data
->set_is_main_frame(!parent
);
3321 extra_data
->set_frame_origin(
3322 GURL(frame
->document().securityOrigin().toString()));
3323 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3324 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3325 extra_data
->set_allow_download(
3326 navigation_state
->common_params().allow_download
);
3327 extra_data
->set_transition_type(transition_type
);
3328 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3329 extra_data
->set_transferred_request_child_id(
3330 navigation_state
->start_params().transferred_request_child_id
);
3331 extra_data
->set_transferred_request_request_id(
3332 navigation_state
->start_params().transferred_request_request_id
);
3333 extra_data
->set_service_worker_provider_id(provider_id
);
3334 extra_data
->set_stream_override(stream_override
.Pass());
3335 request
.setExtraData(extra_data
);
3337 // TODO(creis): Update prefetching to work with out-of-process iframes.
3338 WebFrame
* top_frame
= frame
->top();
3339 if (top_frame
&& top_frame
->isWebLocalFrame()) {
3340 DocumentState
* top_document_state
=
3341 DocumentState::FromDataSource(top_frame
->dataSource());
3342 if (top_document_state
) {
3343 // TODO(gavinp): separate out prefetching and prerender field trials
3344 // if the rel=prerender rel type is sticking around.
3345 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3346 top_document_state
->set_was_prefetcher(true);
3350 // This is an instance where we embed a copy of the routing id
3351 // into the data portion of the message. This can cause problems if we
3352 // don't register this id on the browser side, since the download manager
3353 // expects to find a RenderViewHost based off the id.
3354 request
.setRequestorID(render_view_
->GetRoutingID());
3355 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3357 if (!navigation_state
->start_params().extra_headers
.empty()) {
3358 for (net::HttpUtil::HeadersIterator
i(
3359 navigation_state
->start_params().extra_headers
.begin(),
3360 navigation_state
->start_params().extra_headers
.end(), "\n");
3362 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3363 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3364 blink::WebReferrerPolicyDefault
,
3366 WebString::fromUTF8(i
.values()));
3367 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3369 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3370 WebString::fromUTF8(i
.values()));
3375 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3376 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3379 void RenderFrameImpl::didReceiveResponse(
3380 blink::WebLocalFrame
* frame
,
3381 unsigned identifier
,
3382 const blink::WebURLResponse
& response
) {
3383 DCHECK(!frame_
|| frame_
== frame
);
3384 // Only do this for responses that correspond to a provisional data source
3385 // of the top-most frame. If we have a provisional data source, then we
3386 // can't have any sub-resources yet, so we know that this response must
3387 // correspond to a frame load.
3388 if (!frame
->provisionalDataSource() || frame
->parent())
3391 // If we are in view source mode, then just let the user see the source of
3392 // the server's error page.
3393 if (frame
->isViewSourceModeEnabled())
3396 DocumentState
* document_state
=
3397 DocumentState::FromDataSource(frame
->provisionalDataSource());
3398 int http_status_code
= response
.httpStatusCode();
3400 // Record page load flags.
3401 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3403 document_state
->set_was_fetched_via_spdy(
3404 extra_data
->was_fetched_via_spdy());
3405 document_state
->set_was_npn_negotiated(
3406 extra_data
->was_npn_negotiated());
3407 document_state
->set_npn_negotiated_protocol(
3408 extra_data
->npn_negotiated_protocol());
3409 document_state
->set_was_alternate_protocol_available(
3410 extra_data
->was_alternate_protocol_available());
3411 document_state
->set_connection_info(
3412 extra_data
->connection_info());
3413 document_state
->set_was_fetched_via_proxy(
3414 extra_data
->was_fetched_via_proxy());
3415 document_state
->set_proxy_server(
3416 extra_data
->proxy_server());
3418 InternalDocumentStateData
* internal_data
=
3419 InternalDocumentStateData::FromDocumentState(document_state
);
3420 internal_data
->set_http_status_code(http_status_code
);
3423 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3424 blink::WebLocalFrame
* frame
,
3425 const blink::WebURLRequest
& request
,
3426 const blink::WebURLResponse
& response
) {
3427 DCHECK(!frame_
|| frame_
== frame
);
3428 // The recipients of this message have no use for data: URLs: they don't
3429 // affect the page's insecure content list and are not in the disk cache. To
3430 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3431 // filter them out here.
3432 GURL
url(request
.url());
3433 if (url
.SchemeIs(url::kDataScheme
))
3436 // Let the browser know we loaded a resource from the memory cache. This
3437 // message is needed to display the correct SSL indicators.
3438 Send(new FrameHostMsg_DidLoadResourceFromMemoryCache(
3439 routing_id_
, url
, response
.securityInfo(), request
.httpMethod().utf8(),
3440 response
.mimeType().utf8(), WebURLRequestToResourceType(request
)));
3443 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3444 DCHECK(!frame_
|| frame_
== frame
);
3445 Send(new FrameHostMsg_DidDisplayInsecureContent(routing_id_
));
3448 void RenderFrameImpl::didRunInsecureContent(
3449 blink::WebLocalFrame
* frame
,
3450 const blink::WebSecurityOrigin
& origin
,
3451 const blink::WebURL
& target
) {
3452 DCHECK(!frame_
|| frame_
== frame
);
3453 Send(new FrameHostMsg_DidRunInsecureContent(
3454 routing_id_
, origin
.toString().utf8(), target
));
3455 GetContentClient()->renderer()->RecordRapporURL(
3456 "ContentSettings.MixedScript.RanMixedScript",
3457 GURL(origin
.toString().utf8()));
3460 void RenderFrameImpl::didChangePerformanceTiming() {
3461 FOR_EACH_OBSERVER(RenderFrameObserver
,
3463 DidChangePerformanceTiming());
3466 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3467 DCHECK(!frame_
|| frame_
== frame
);
3468 #if defined(ENABLE_PLUGINS)
3469 if (frame
!= render_view_
->webview()->mainFrame())
3471 PluginChannelHost::Broadcast(
3472 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3476 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3477 v8::Local
<v8::Context
> context
,
3478 int extension_group
,
3480 DCHECK(!frame_
|| frame_
== frame
);
3482 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3483 DidCreateScriptContext(context
, extension_group
, world_id
));
3486 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3487 v8::Local
<v8::Context
> context
,
3489 DCHECK(!frame_
|| frame_
== frame
);
3491 FOR_EACH_OBSERVER(RenderFrameObserver
,
3493 WillReleaseScriptContext(context
, world_id
));
3496 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3497 DCHECK(!frame_
|| frame_
== frame
);
3498 // TODO(nasko): Move implementation here. Needed methods:
3499 // * StartNavStateSyncTimerIfNecessary
3500 render_view_
->didChangeScrollOffset(frame
);
3502 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3505 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3506 DCHECK(!frame_
|| frame_
== frame
);
3507 if (!frame
->parent()) {
3508 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3509 render_view_
->GetRoutingID()));
3513 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3515 bool final_update
) {
3516 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3518 active_match_ordinal
= 0;
3520 render_view_
->Send(new ViewHostMsg_Find_Reply(
3521 render_view_
->GetRoutingID(), request_id
, count
,
3522 gfx::Rect(), active_match_ordinal
, final_update
));
3525 void RenderFrameImpl::reportFindInPageSelection(
3527 int active_match_ordinal
,
3528 const blink::WebRect
& selection_rect
) {
3529 render_view_
->Send(new ViewHostMsg_Find_Reply(
3530 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3531 active_match_ordinal
, false));
3534 void RenderFrameImpl::requestStorageQuota(
3535 blink::WebLocalFrame
* frame
,
3536 blink::WebStorageQuotaType type
,
3537 unsigned long long requested_size
,
3538 blink::WebStorageQuotaCallbacks callbacks
) {
3539 DCHECK(!frame_
|| frame_
== frame
);
3540 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3541 if (origin
.isUnique()) {
3542 // Unique origins cannot store persistent state.
3543 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3546 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3547 render_view_
->GetRoutingID(),
3548 GURL(origin
.toString()),
3549 static_cast<storage::StorageType
>(type
),
3551 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3554 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3555 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3556 impl
->set_render_frame_id(routing_id_
);
3559 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3560 if (!geolocation_dispatcher_
)
3561 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3562 return geolocation_dispatcher_
;
3565 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3566 if (!presentation_dispatcher_
)
3567 presentation_dispatcher_
= new PresentationDispatcher(this);
3568 return presentation_dispatcher_
;
3571 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3572 if (!push_messaging_dispatcher_
)
3573 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3574 return push_messaging_dispatcher_
;
3577 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3578 blink::WebLocalFrame
* frame
,
3579 blink::WebRTCPeerConnectionHandler
* handler
) {
3580 DCHECK(!frame_
|| frame_
== frame
);
3581 #if defined(ENABLE_WEBRTC)
3582 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3586 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3587 if (!web_user_media_client_
)
3588 InitializeUserMediaClient();
3589 return web_user_media_client_
;
3592 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3593 if (!web_encrypted_media_client_
) {
3594 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3595 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3596 // is destructed before |this|, and does not give away ownership of the
3598 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3599 base::Unretained(this)),
3600 GetCdmFactory(), GetMediaPermission()));
3602 return web_encrypted_media_client_
.get();
3605 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3606 if (!midi_dispatcher_
)
3607 midi_dispatcher_
= new MidiDispatcher(this);
3608 return midi_dispatcher_
;
3611 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3612 blink::WebLocalFrame
* source_frame
,
3613 blink::WebFrame
* target_frame
,
3614 blink::WebSecurityOrigin target_origin
,
3615 blink::WebDOMMessageEvent event
) {
3616 DCHECK(!frame_
|| frame_
== target_frame
);
3618 // Currently, a postMessage that targets a cross-process frame can be plumbed
3619 // either through this function or RenderFrameProxy::postMessageEvent. This
3620 // function is used when the target cross-process frame is a top-level frame
3621 // which has been swapped out. In that case, the corresponding WebLocalFrame
3622 // currently remains in the frame tree even in site-per-process mode (see
3623 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3624 // --site-per-process mode for all other cases.
3626 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3627 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3628 // cross-process postMessages.
3629 if (!is_swapped_out_
)
3632 // It is possible to get here on a swapped-out frame without a
3633 // |render_frame_proxy_|. This happens when:
3634 // - This process only has one active RenderView and is about to go away
3635 // (e.g., due to cross-process navigation).
3636 // - The top frame has a subframe with an unload handler.
3637 // - The subframe sends a postMessage to the top-level frame in its unload
3639 // See https://crbug.com/475651 for details. We return false here, since we
3640 // don't want to deliver the message to the new process in this case.
3641 if (!render_frame_proxy_
)
3644 render_frame_proxy_
->postMessageEvent(
3645 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3649 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3650 const blink::WebURL
& url
) {
3651 DCHECK(!frame_
|| frame_
== frame
);
3652 std::string user_agent_override_for_url
=
3653 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3654 if (!user_agent_override_for_url
.empty())
3655 return WebString::fromUTF8(user_agent_override_for_url
);
3657 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3658 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3659 return blink::WebString();
3662 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3663 // associated with it, so the checks below are not valid. Temporarily
3664 // return early and fix properly as part of https://crbug.com/426555.
3665 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3666 return blink::WebString();
3668 // If we're in the middle of committing a load, the data source we need
3669 // will still be provisional.
3670 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3671 WebDataSource
* data_source
= NULL
;
3672 if (main_frame
->provisionalDataSource())
3673 data_source
= main_frame
->provisionalDataSource();
3675 data_source
= main_frame
->dataSource();
3677 InternalDocumentStateData
* internal_data
= data_source
?
3678 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3679 if (internal_data
&& internal_data
->is_overriding_user_agent())
3680 return WebString::fromUTF8(
3681 render_view_
->renderer_preferences_
.user_agent_override
);
3682 return blink::WebString();
3685 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3686 DCHECK(!frame_
|| frame_
== frame
);
3687 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3688 return WebString::fromUTF8("1");
3692 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3693 bool default_value
) {
3694 DCHECK(!frame_
|| frame_
== frame
);
3698 bool blocked
= true;
3699 Send(new FrameHostMsg_Are3DAPIsBlocked(
3701 GURL(frame
->top()->securityOrigin().toString()),
3702 THREE_D_API_TYPE_WEBGL
,
3707 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3708 int arb_robustness_status_code
) {
3709 DCHECK(!frame_
|| frame_
== frame
);
3710 Send(new FrameHostMsg_DidLose3DContext(
3711 GURL(frame
->top()->securityOrigin().toString()),
3712 THREE_D_API_TYPE_WEBGL
,
3713 arb_robustness_status_code
));
3716 blink::WebScreenOrientationClient
*
3717 RenderFrameImpl::webScreenOrientationClient() {
3718 if (!screen_orientation_dispatcher_
)
3719 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3720 return screen_orientation_dispatcher_
;
3723 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3724 ServiceWorkerNetworkProvider
* provider
=
3725 ServiceWorkerNetworkProvider::FromDocumentState(
3726 DocumentState::FromDataSource(&data_source
));
3727 return provider
->context() && provider
->context()->controller();
3730 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3731 ServiceWorkerNetworkProvider
* provider
=
3732 ServiceWorkerNetworkProvider::FromDocumentState(
3733 DocumentState::FromDataSource(&data_source
));
3734 if (provider
->context() && provider
->context()->controller())
3735 return provider
->context()->controller()->version_id();
3736 return kInvalidServiceWorkerVersionId
;
3739 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3740 blink::WebAXEvent event
) {
3741 HandleWebAccessibilityEvent(obj
, event
);
3744 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3747 const blink::WebAXObject
& start_object
,
3749 const blink::WebAXObject
& end_object
,
3751 if (renderer_accessibility_
) {
3752 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3753 identifier
, match_index
, start_object
, start_offset
,
3754 end_object
, end_offset
);
3758 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3759 DCHECK(!frame_
|| frame_
== frame
);
3761 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3764 bool RenderFrameImpl::enterFullscreen() {
3765 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3769 bool RenderFrameImpl::exitFullscreen() {
3770 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3774 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3775 if (!permission_client_
)
3776 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3778 return permission_client_
.get();
3781 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3782 if (!app_banner_client_
) {
3783 app_banner_client_
=
3784 GetContentClient()->renderer()->CreateAppBannerClient(this);
3787 return app_banner_client_
.get();
3790 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3792 const WebString
& title
) {
3793 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3794 Send(new FrameHostMsg_RegisterProtocolHandler(
3796 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3802 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3803 const WebURL
& url
) {
3804 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3805 Send(new FrameHostMsg_UnregisterProtocolHandler(
3807 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3812 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3814 bluetooth_
.reset(new WebBluetoothImpl(
3815 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3818 return bluetooth_
.get();
3821 blink::WebUSBClient
* RenderFrameImpl::usbClient() {
3822 #if !defined(OS_ANDROID)
3824 mojo::ServiceProviderPtr device_services
=
3825 ConnectToApplication(GURL(device::kDevicesMojoAppUrl
));
3826 usb_client_
.reset(new WebUSBClientImpl(device_services
.Pass()));
3829 return usb_client_
.get();
3832 #if defined(ENABLE_WEBVR)
3833 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3834 if (!vr_dispatcher_
)
3835 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3837 return vr_dispatcher_
.get();
3841 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3842 has_played_media_
= true;
3843 Send(new FrameHostMsg_MediaPlayingNotification(
3844 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3845 player
->hasAudio(), player
->isRemote()));
3848 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3849 Send(new FrameHostMsg_MediaPausedNotification(
3850 routing_id_
, reinterpret_cast<int64
>(player
)));
3853 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3857 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3858 observers_
.AddObserver(observer
);
3861 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3862 observer
->RenderFrameGone();
3863 observers_
.RemoveObserver(observer
);
3866 void RenderFrameImpl::OnStop() {
3868 frame_
->stopLoading();
3869 if (!frame_
->parent())
3870 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3872 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3875 void RenderFrameImpl::WasHidden() {
3876 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3879 void RenderFrameImpl::WasShown() {
3880 // TODO(kenrb): Need to figure out how to do this better. Should
3881 // VisibilityState remain a page-level concept or move to frames?
3882 // The semantics of 'Show' might have to change here.
3883 if (render_widget_
) {
3884 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3885 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3887 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3890 void RenderFrameImpl::WidgetWillClose() {
3891 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3894 bool RenderFrameImpl::IsHidden() {
3895 return GetRenderWidget()->is_hidden();
3898 // Tell the embedding application that the URL of the active page has changed.
3899 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3900 blink::WebFrame
* frame
,
3901 blink::WebHistoryCommitType commit_type
,
3902 const blink::WebHistoryItem
& item
) {
3903 DCHECK(!frame_
|| frame_
== frame
);
3904 WebDataSource
* ds
= frame
->dataSource();
3907 const WebURLRequest
& request
= ds
->request();
3908 const WebURLResponse
& response
= ds
->response();
3910 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3911 NavigationStateImpl
* navigation_state
=
3912 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3913 InternalDocumentStateData
* internal_data
=
3914 InternalDocumentStateData::FromDocumentState(document_state
);
3916 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3917 params
.http_status_code
= response
.httpStatusCode();
3918 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3919 params
.is_post
= false;
3920 params
.intended_as_new_entry
=
3921 navigation_state
->request_params().intended_as_new_entry
;
3922 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3923 params
.post_id
= -1;
3924 params
.page_id
= render_view_
->page_id_
;
3925 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3926 // We need to track the RenderViewHost routing_id because of downstream
3927 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3928 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3929 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3930 // based on the ID stored in the resource requests. Once those dependencies
3931 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3932 // client to be based on the routing_id of the RenderFrameHost.
3933 params
.render_view_routing_id
= render_view_
->routing_id();
3934 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3935 params
.socket_address
.set_port(response
.remotePort());
3936 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3938 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3939 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3940 params
.security_info
= response
.securityInfo();
3942 // Set the URL to be displayed in the browser UI to the user.
3943 params
.url
= GetLoadingUrl();
3944 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3946 // Set the origin of the frame. This will be replicated to the corresponding
3947 // RenderFrameProxies in other processes.
3948 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3949 // to https://crbug.com/439608 and will be replicated as unique origins.
3950 if (!is_swapped_out_
) {
3951 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3952 if (url::IsStandard(scheme
.c_str(),
3953 url::Component(0, static_cast<int>(scheme
.length())))) {
3954 params
.origin
= frame
->document().securityOrigin();
3958 if (frame
->document().baseURL() != params
.url
)
3959 params
.base_url
= frame
->document().baseURL();
3961 GetRedirectChain(ds
, ¶ms
.redirects
);
3962 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3963 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3965 params
.searchable_form_url
= internal_data
->searchable_form_url();
3966 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3968 params
.gesture
= render_view_
->navigation_gesture_
;
3969 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3971 // Make navigation state a part of the DidCommitProvisionalLoad message so
3972 // that committed entry has it at all times.
3973 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3974 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3976 params
.page_state
= HistoryEntryToPageState(entry
);
3978 params
.page_state
= PageState::CreateFromURL(request
.url());
3980 // In --site-per-process, just send a single HistoryItem for this frame,
3981 // rather than the whole tree. It will be stored in the corresponding
3982 // FrameNavigationEntry.
3983 params
.page_state
= SingleHistoryItemToPageState(item
);
3985 params
.item_sequence_number
= item
.itemSequenceNumber();
3986 params
.document_sequence_number
= item
.documentSequenceNumber();
3988 if (!frame
->parent()) {
3989 // Top-level navigation.
3991 // Reset the zoom limits in case a plugin had changed them previously. This
3992 // will also call us back which will cause us to send a message to
3993 // update WebContentsImpl.
3994 render_view_
->webview()->zoomLimitsChanged(
3995 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3996 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3998 // Set zoom level, but don't do it for full-page plugin since they don't use
3999 // the same zoom settings.
4000 HostZoomLevels::iterator host_zoom
=
4001 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
4002 if (render_view_
->webview()->mainFrame()->isWebLocalFrame() &&
4003 render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
4004 // Reset the zoom levels for plugins.
4005 render_view_
->webview()->setZoomLevel(0);
4007 // If the zoom level is not found, then do nothing. In-page navigation
4008 // relies on not changing the zoom level in this case.
4009 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
4010 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
4013 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
4014 // This zoom level was merely recorded transiently for this load. We can
4015 // erase it now. If at some point we reload this page, the browser will
4016 // send us a new, up-to-date zoom level.
4017 render_view_
->host_zoom_levels_
.erase(host_zoom
);
4020 // Update contents MIME type for main frame.
4021 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4023 params
.transition
= navigation_state
->GetTransitionType();
4024 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4025 // If the main frame does a load, it should not be reported as a subframe
4026 // navigation. This can occur in the following case:
4027 // 1. You're on a site with frames.
4028 // 2. You do a subframe navigation. This is stored with transition type
4030 // 3. You navigate to some non-frame site, say, google.com.
4031 // 4. You navigate back to the page from step 2. Since it was initially
4032 // MANUAL_SUBFRAME, it will be that same transition type here.
4033 // We don't want that, because any navigation that changes the toplevel
4034 // frame should be tracked as a toplevel navigation (this allows us to
4035 // update the URL bar, etc).
4036 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4039 // If the page contained a client redirect (meta refresh, document.loc...),
4040 // set the referrer and transition appropriately.
4041 if (ds
->isClientRedirect()) {
4043 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4044 params
.transition
= ui::PageTransitionFromInt(
4045 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4047 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4048 frame
, ds
->request());
4051 base::string16 method
= request
.httpMethod();
4052 if (base::EqualsASCII(method
, "POST")) {
4053 params
.is_post
= true;
4054 params
.post_id
= ExtractPostId(entry
);
4057 // Send the user agent override back.
4058 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4060 // Track the URL of the original request. We use the first entry of the
4061 // redirect chain if it exists because the chain may have started in another
4063 params
.original_request_url
= GetOriginalRequestURL(ds
);
4065 params
.history_list_was_cleared
=
4066 navigation_state
->request_params().should_clear_history_list
;
4068 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4069 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4070 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4071 frame
->dataSource()->request().uiStartTime());
4073 // Save some histogram data so we can compute the average memory used per
4074 // page load of the glyphs.
4075 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4076 blink::WebGlyphCache::pageCount());
4078 // This message needs to be sent before any of allowScripts(),
4079 // allowImages(), allowPlugins() is called for the new page, so that when
4080 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4081 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4082 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4084 // Subframe navigation: the type depends on whether this navigation
4085 // generated a new session history entry. When they do generate a session
4086 // history entry, it means the user initiated the navigation and we should
4088 if (commit_type
== blink::WebStandardCommit
)
4089 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4091 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4093 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4094 params
.history_list_was_cleared
= false;
4095 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4097 // Don't send this message while the subframe is swapped out.
4098 if (!is_swapped_out())
4099 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4102 // If we end up reusing this WebRequest (for example, due to a #ref click),
4103 // we don't want the transition type to persist. Just clear it.
4104 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4107 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4108 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4110 render_view_
->FrameDidStartLoading(frame_
);
4111 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4114 void RenderFrameImpl::didStopLoading() {
4115 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4117 render_view_
->FrameDidStopLoading(frame_
);
4118 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4121 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4122 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4125 void RenderFrameImpl::HandleWebAccessibilityEvent(
4126 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4127 if (renderer_accessibility_
)
4128 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4131 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4132 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4135 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4136 if (renderer_accessibility())
4137 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4141 void RenderFrameImpl::OnCommitNavigation(
4142 const ResourceResponseHead
& response
,
4143 const GURL
& stream_url
,
4144 const CommonNavigationParams
& common_params
,
4145 const RequestNavigationParams
& request_params
) {
4146 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4147 switches::kEnableBrowserSideNavigation
));
4148 // This will override the url requested by the WebURLLoader, as well as
4149 // provide it with the response to the request.
4150 scoped_ptr
<StreamOverrideParameters
> stream_override(
4151 new StreamOverrideParameters());
4152 stream_override
->stream_url
= stream_url
;
4153 stream_override
->response
= response
;
4155 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4156 stream_override
.Pass());
4159 void RenderFrameImpl::OnFailedNavigation(
4160 const CommonNavigationParams
& common_params
,
4161 const RequestNavigationParams
& request_params
,
4162 bool has_stale_copy_in_cache
,
4164 bool is_reload
= IsReload(common_params
.navigation_type
);
4165 bool is_history_navigation
= request_params
.page_state
.IsValid();
4166 WebURLRequest::CachePolicy cache_policy
=
4167 WebURLRequest::UseProtocolCachePolicy
;
4168 RenderFrameImpl::PrepareRenderViewForNavigation(
4169 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4171 GetContentClient()->SetActiveURL(common_params
.url
);
4173 pending_navigation_params_
.reset(new NavigationParams(
4174 common_params
, StartNavigationParams(), request_params
));
4176 // Inform the browser of the start of the provisional load. This is needed so
4177 // that the load is properly tracked by the WebNavigation API.
4178 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4179 routing_id_
, common_params
.url
));
4181 // Send the provisional load failure.
4182 blink::WebURLError error
=
4183 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4184 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4185 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4186 frame_
->isViewSourceModeEnabled());
4187 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4189 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4190 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4191 // http://crbug.com/501960
4192 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4196 // Make sure errors are not shown in view source mode.
4197 frame_
->enableViewSourceMode(false);
4199 // Replace the current history entry in reloads, history navigations and loads
4200 // of the same url. This corresponds to Blink's notion of a standard
4202 // TODO(clamy): see if initial commits in subframes should be handled
4204 bool replace
= is_reload
|| is_history_navigation
||
4205 common_params
.url
== GetLoadingUrl();
4206 LoadNavigationErrorPage(failed_request
, error
, replace
);
4209 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4210 RenderFrame
* render_frame
,
4211 const NavigationPolicyInfo
& info
) {
4212 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4215 // TODO(nick): Is consulting |is_subframe_| here correct?
4216 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_
) {
4217 // There's no reason to ignore navigations on subframes, since the swap out
4218 // logic no longer applies.
4220 if (is_swapped_out_
) {
4221 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4222 // Targeted links may try to navigate a swapped out frame. Allow the
4223 // browser process to navigate the tab instead. Note that it is also
4224 // possible for non-targeted navigations (from this view) to arrive
4225 // here just after we are swapped out. It's ok to send them to the
4226 // browser, as long as they're for the top level frame.
4227 // TODO(creis): Ensure this supports targeted form submissions when
4228 // fixing http://crbug.com/101395.
4229 if (info
.frame
->parent() == NULL
) {
4230 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4231 info
.defaultPolicy
);
4232 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4235 // We should otherwise ignore in-process iframe navigations, if they
4236 // arrive just after we are swapped out.
4237 return blink::WebNavigationPolicyIgnore
;
4240 // Allow kSwappedOutURL to complete.
4241 return info
.defaultPolicy
;
4245 // Webkit is asking whether to navigate to a new URL.
4246 // This is fine normally, except if we're showing UI from one security
4247 // context and they're trying to navigate to a different context.
4248 const GURL
& url
= info
.urlRequest
.url();
4250 // A content initiated navigation may have originated from a link-click,
4251 // script, drag-n-drop operation, etc.
4252 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4253 bool is_content_initiated
=
4254 document_state
->navigation_state()->IsContentInitiated();
4256 // If the browser is interested, then give it a chance to look at the request.
4257 if (is_content_initiated
&& IsTopLevelNavigation(info
.frame
) &&
4258 render_view_
->renderer_preferences_
4259 .browser_handles_all_top_level_requests
) {
4260 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4261 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4264 // Use the frame's original request's URL rather than the document's URL for
4265 // subsequent checks. For a popup, the document's URL may become the opener
4266 // window's URL if the opener has called document.write().
4267 // See http://crbug.com/93517.
4268 GURL
old_url(info
.frame
->dataSource()->request().url());
4270 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4271 // an extension or app origin, leaving a WebUI page, etc). We only care about
4272 // top-level navigations (not iframes). But we sometimes navigate to
4273 // about:blank to clear a tab, and we want to still allow that.
4275 // Note: this is known to break POST submissions when crossing process
4276 // boundaries until http://crbug.com/101395 is fixed. This is better for
4277 // security than loading a WebUI, extension or app page in the wrong process.
4278 // POST requests don't work because this mechanism does not preserve form
4279 // POST data. We will need to send the request's httpBody data up to the
4280 // browser process, and issue a special POST navigation in WebKit (via
4281 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4282 // for examples of how to send the httpBody data.
4283 if (!info
.frame
->parent() && is_content_initiated
&&
4284 !url
.SchemeIs(url::kAboutScheme
)) {
4285 bool send_referrer
= false;
4287 // All navigations to or from WebUI URLs or within WebUI-enabled
4288 // RenderProcesses must be handled by the browser process so that the
4289 // correct bindings and data sources can be registered.
4290 // Similarly, navigations to view-source URLs or within ViewSource mode
4291 // must be handled by the browser process (except for reloads - those are
4292 // safe to leave within the renderer).
4293 // Lastly, access to file:// URLs from non-file:// URL pages must be
4294 // handled by the browser so that ordinary renderer processes don't get
4295 // blessed with file permissions.
4296 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4297 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4298 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4299 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4300 url
.SchemeIs(kViewSourceScheme
) ||
4301 (info
.frame
->isViewSourceModeEnabled() &&
4302 info
.navigationType
!= blink::WebNavigationTypeReload
);
4304 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4305 // Fork non-file to file opens. Check the opener URL if this is the
4306 // initial navigation in a newly opened window.
4307 GURL
source_url(old_url
);
4308 if (is_initial_navigation
&& source_url
.is_empty() &&
4309 info
.frame
->opener())
4310 source_url
= info
.frame
->opener()->top()->document().url();
4311 DCHECK(!source_url
.is_empty());
4312 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4316 // Give the embedder a chance.
4317 should_fork
= GetContentClient()->renderer()->ShouldFork(
4318 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4319 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4323 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4324 info
.defaultPolicy
);
4325 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4329 // Detect when a page is "forking" a new tab that can be safely rendered in
4330 // its own process. This is done by sites like Gmail that try to open links
4331 // in new windows without script connections back to the original page. We
4332 // treat such cases as browser navigations (in which we will create a new
4333 // renderer for a cross-site navigation), rather than WebKit navigations.
4335 // We use the following heuristic to decide whether to fork a new page in its
4337 // The parent page must open a new tab to about:blank, set the new tab's
4338 // window.opener to null, and then redirect the tab to a cross-site URL using
4341 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4344 // Must start from a tab showing about:blank, which is later redirected.
4345 old_url
== GURL(url::kAboutBlankURL
) &&
4346 // Must be the first real navigation of the tab.
4347 render_view_
->historyBackListCount() < 1 &&
4348 render_view_
->historyForwardListCount() < 1 &&
4349 // The parent page must have set the child's window.opener to null before
4350 // redirecting to the desired URL.
4351 info
.frame
->opener() == NULL
&&
4352 // Must be a top-level frame.
4353 info
.frame
->parent() == NULL
&&
4354 // Must not have issued the request from this page.
4355 is_content_initiated
&&
4356 // Must be targeted at the current tab.
4357 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4358 // Must be a JavaScript navigation, which appears as "other".
4359 info
.navigationType
== blink::WebNavigationTypeOther
;
4362 // Open the URL via the browser, not via WebKit.
4363 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4364 return blink::WebNavigationPolicyIgnore
;
4367 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4368 // This includes navigations with no request being sent to the network stack.
4369 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4370 switches::kEnableBrowserSideNavigation
) &&
4371 info
.urlRequest
.checkForBrowserSideNavigation() &&
4372 ShouldMakeNetworkRequestForURL(url
)) {
4373 BeginNavigation(&info
.urlRequest
);
4374 return blink::WebNavigationPolicyIgnore
;
4377 return info
.defaultPolicy
;
4380 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4382 const Referrer
& referrer
,
4383 WebNavigationPolicy policy
) {
4384 DCHECK_EQ(frame_
, frame
);
4386 FrameHostMsg_OpenURL_Params params
;
4388 params
.referrer
= referrer
;
4389 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4390 WebDataSource
* ds
= frame
->provisionalDataSource();
4392 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4393 NavigationStateImpl
* navigation_state
=
4394 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4395 if (navigation_state
->IsContentInitiated()) {
4396 params
.should_replace_current_entry
=
4397 ds
->replacesCurrentHistoryItem() &&
4398 render_view_
->history_list_length_
;
4400 // This is necessary to preserve the should_replace_current_entry value on
4401 // cross-process redirects, in the event it was set by a previous process.
4403 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4404 // NavigationState::should_replace_current_entry().
4405 params
.should_replace_current_entry
=
4406 navigation_state
->common_params().should_replace_current_entry
;
4409 params
.should_replace_current_entry
= false;
4411 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4412 if (GetContentClient()->renderer()->AllowPopup())
4413 params
.user_gesture
= true;
4415 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4416 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4417 policy
== blink::WebNavigationPolicyNewWindow
||
4418 policy
== blink::WebNavigationPolicyNewPopup
) {
4419 WebUserGestureIndicator::consumeUserGesture();
4422 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4425 void RenderFrameImpl::NavigateInternal(
4426 const CommonNavigationParams
& common_params
,
4427 const StartNavigationParams
& start_params
,
4428 const RequestNavigationParams
& request_params
,
4429 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4430 bool browser_side_navigation
=
4431 base::CommandLine::ForCurrentProcess()->HasSwitch(
4432 switches::kEnableBrowserSideNavigation
);
4433 bool is_reload
= IsReload(common_params
.navigation_type
);
4434 bool is_history_navigation
= request_params
.page_state
.IsValid();
4435 WebURLRequest::CachePolicy cache_policy
=
4436 WebURLRequest::UseProtocolCachePolicy
;
4437 RenderFrameImpl::PrepareRenderViewForNavigation(
4438 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4440 GetContentClient()->SetActiveURL(common_params
.url
);
4442 // If this frame isn't in the same process as the main frame, it may naively
4443 // assume that this is the first navigation in the iframe, but this may not
4444 // actually be the case. Inform the frame's state machine if this frame has
4445 // already committed other loads.
4446 if (request_params
.has_committed_real_load
&& frame_
->parent())
4447 frame_
->setCommittedFirstRealLoad();
4449 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4450 // We cannot reload if we do not have any history state. This happens, for
4451 // example, when recovering from a crash.
4453 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4456 pending_navigation_params_
.reset(
4457 new NavigationParams(common_params
, start_params
, request_params
));
4459 // Create parameters for a standard navigation.
4460 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4461 bool should_load_request
= false;
4462 WebHistoryItem item_for_history_navigation
;
4463 WebURLRequest request
= CreateURLRequestForNavigation(
4464 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4465 #if defined(OS_ANDROID)
4466 request
.setHasUserGesture(start_params
.has_user_gesture
);
4469 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4470 // navigation for this request (since it already went to the browser).
4471 if (browser_side_navigation
)
4472 request
.setCheckForBrowserSideNavigation(false);
4474 // If we are reloading, then use the history state of the current frame.
4475 // Otherwise, if we have history state, then we need to navigate to it, which
4476 // corresponds to a back/forward navigation event. Update the parameters
4477 // depending on the navigation type.
4479 bool ignore_cache
= (common_params
.navigation_type
==
4480 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4481 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4482 : blink::WebFrameLoadType::Reload
;
4484 if (!browser_side_navigation
) {
4485 const GURL override_url
=
4486 (common_params
.navigation_type
==
4487 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4490 request
= frame_
->requestForReload(load_type
, override_url
);
4492 should_load_request
= true;
4493 } else if (is_history_navigation
) {
4494 // We must know the page ID of the page we are navigating back to.
4495 DCHECK_NE(request_params
.page_id
, -1);
4496 // We must know the nav entry ID of the page we are navigating back to,
4497 // which should be the case because history navigations are routed via the
4499 DCHECK_NE(0, request_params
.nav_entry_id
);
4500 scoped_ptr
<HistoryEntry
> entry
=
4501 PageStateToHistoryEntry(request_params
.page_state
);
4503 // Ensure we didn't save the swapped out URL in UpdateState, since the
4504 // browser should never be telling us to navigate to swappedout://.
4505 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4507 if (!browser_side_navigation
) {
4508 scoped_ptr
<NavigationParams
> navigation_params(
4509 new NavigationParams(*pending_navigation_params_
.get()));
4510 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4511 // By default, tell the HistoryController to go the deserialized
4512 // HistoryEntry. This only works if all frames are in the same
4514 DCHECK(!frame_
->parent());
4515 render_view_
->history_controller()->GoToEntry(
4516 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4518 // In --site-per-process, the browser process sends a single
4519 // WebHistoryItem destined for this frame.
4520 // TODO(creis): Change PageState to FrameState. In the meantime, we
4521 // store the relevant frame's WebHistoryItem in the root of the
4523 SetPendingNavigationParams(navigation_params
.Pass());
4524 blink::WebHistoryItem history_item
= entry
->root();
4525 blink::WebHistoryLoadType load_type
=
4526 request_params
.is_same_document_history_load
4527 ? blink::WebHistorySameDocumentLoad
4528 : blink::WebHistoryDifferentDocumentLoad
;
4530 // Let the history controller know the provisional entry, since it is
4531 // used at commit time. Otherwise skip GoToEntry and navigate the
4533 // TODO(creis): Consider cloning the current entry to handle subframe
4534 // cases. Changes to SendUpdateState might affect this.
4535 render_view_
->history_controller()->set_provisional_entry(
4537 WebURLRequest request
=
4538 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4539 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4540 history_item
, load_type
);
4543 // TODO(clamy): this should be set to the HistoryItem sent by the
4544 // browser once the HistoryController has moved to the browser.
4545 // TODO(clamy): distinguish between different document and same document
4547 // TODO(clamy): update this for subframes history loads.
4548 item_for_history_navigation
=
4549 entry
->GetHistoryNodeForFrame(this)->item();
4550 load_type
= blink::WebFrameLoadType::BackForward
;
4551 should_load_request
= true;
4555 // Navigate to the given URL.
4556 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4557 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4558 start_params
.extra_headers
.end(),
4561 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4562 WebString::fromUTF8(i
.values()));
4566 if (start_params
.is_post
&& !browser_side_navigation
) {
4567 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4570 WebHTTPBody http_body
;
4571 http_body
.initialize();
4572 const char* data
= nullptr;
4573 if (start_params
.browser_initiated_post_data
.size()) {
4574 data
= reinterpret_cast<const char*>(
4575 &start_params
.browser_initiated_post_data
.front());
4577 http_body
.appendData(
4578 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4579 request
.setHTTPBody(http_body
);
4582 // A session history navigation should have been accompanied by state.
4583 CHECK_EQ(request_params
.page_id
, -1);
4585 should_load_request
= true;
4588 if (should_load_request
) {
4589 // Record this before starting the load. We need a lower bound of this
4590 // time to sanitize the navigationStart override set below.
4591 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4593 // Perform a navigation to a data url if needed.
4594 if (!common_params
.base_url_for_data_url
.is_empty() ||
4595 (browser_side_navigation
&&
4596 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4597 LoadDataURL(common_params
, frame_
);
4599 // Load the request.
4600 frame_
->toWebLocalFrame()->load(request
, load_type
,
4601 item_for_history_navigation
);
4604 if (load_type
== blink::WebFrameLoadType::Standard
) {
4605 UpdateFrameNavigationTiming(frame_
,
4606 request_params
.browser_navigation_start
,
4607 renderer_navigation_start
);
4611 // In case LoadRequest failed before didCreateDataSource was called.
4612 pending_navigation_params_
.reset();
4615 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4616 const std::string
& encoding_name
) {
4617 // Only update main frame's encoding_name.
4618 if (!frame
->parent())
4619 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4622 void RenderFrameImpl::SyncSelectionIfRequired() {
4623 base::string16 text
;
4626 #if defined(ENABLE_PLUGINS)
4627 if (render_view_
->focused_pepper_plugin_
) {
4628 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4629 offset
= 0; // Pepper API does not support offset reporting.
4630 // TODO(kinaba): cut as needed.
4634 size_t location
, length
;
4635 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4636 &location
, &length
)) {
4640 range
= gfx::Range(location
, location
+ length
);
4642 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4643 blink::WebTextInputTypeNone
) {
4644 // If current focused element is editable, we will send 100 more chars
4645 // before and after selection. It is for input method surrounding text
4647 if (location
> kExtraCharsBeforeAndAfterSelection
)
4648 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4651 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4652 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4653 if (!webrange
.isNull())
4654 text
= webrange
.toPlainText();
4657 text
= frame_
->selectionAsText();
4658 // http://crbug.com/101435
4659 // In some case, frame->selectionAsText() returned text's length is not
4660 // equal to the length returned from webwidget()->caretOrSelectionRange().
4661 // So we have to set the range according to text.length().
4662 range
.set_end(range
.start() + text
.length());
4666 // Sometimes we get repeated didChangeSelection calls from webkit when
4667 // the selection hasn't actually changed. We don't want to report these
4668 // because it will cause us to continually claim the X clipboard.
4669 if (selection_text_offset_
!= offset
||
4670 selection_range_
!= range
||
4671 selection_text_
!= text
) {
4672 selection_text_
= text
;
4673 selection_text_offset_
= offset
;
4674 selection_range_
= range
;
4675 SetSelectedText(text
, offset
, range
);
4677 GetRenderWidget()->UpdateSelectionBounds();
4680 void RenderFrameImpl::InitializeUserMediaClient() {
4681 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4684 #if defined(ENABLE_WEBRTC)
4685 DCHECK(!web_user_media_client_
);
4686 web_user_media_client_
= new UserMediaClientImpl(
4688 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4689 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4693 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4694 WebMediaPlayerClient
* client
) {
4695 #if defined(ENABLE_WEBRTC)
4696 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4698 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4699 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4700 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4701 scoped_refptr
<base::SingleThreadTaskRunner
> compositor_task_runner
=
4702 RenderThreadImpl::current()->compositor_task_runner();
4703 if (!compositor_task_runner
.get())
4704 compositor_task_runner
= base::MessageLoop::current()->task_runner();
4705 return new WebMediaPlayerMS(
4706 frame_
, client
, weak_factory_
.GetWeakPtr(), new RenderMediaLog(),
4707 CreateRendererFactory(),
4708 compositor_task_runner
);
4711 #endif // defined(ENABLE_WEBRTC)
4714 scoped_ptr
<MediaStreamRendererFactory
>
4715 RenderFrameImpl::CreateRendererFactory() {
4716 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4717 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4719 return factory
.Pass();
4720 #if defined(ENABLE_WEBRTC)
4721 return scoped_ptr
<MediaStreamRendererFactory
>(
4722 new MediaStreamRendererFactoryImpl());
4724 return scoped_ptr
<MediaStreamRendererFactory
>(
4725 static_cast<MediaStreamRendererFactory
*>(NULL
));
4729 void RenderFrameImpl::PrepareRenderViewForNavigation(
4731 const RequestNavigationParams
& request_params
,
4733 WebURLRequest::CachePolicy
* cache_policy
) {
4734 DCHECK(render_view_
->webview());
4736 MaybeHandleDebugURL(url
);
4739 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4741 render_view_
->history_list_offset_
=
4742 request_params
.current_history_list_offset
;
4743 render_view_
->history_list_length_
=
4744 request_params
.current_history_list_length
;
4745 if (request_params
.should_clear_history_list
) {
4746 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4747 CHECK_EQ(0, render_view_
->history_list_length_
);
4750 if (!is_swapped_out_
|| frame_
->parent())
4753 // This is a swapped out main frame, so swap the renderer back in.
4754 // We marked the view as hidden when swapping the view out, so be sure to
4755 // reset the visibility state before navigating to the new URL.
4756 render_view_
->webview()->setVisibilityState(
4757 render_view_
->visibilityState(), false);
4759 // If this is an attempt to reload while we are swapped out, we should not
4760 // reload swappedout://, but the previous page, which is stored in
4761 // params.state. Setting is_reload to false will treat this like a back
4762 // navigation to accomplish that.
4764 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4766 // We refresh timezone when a view is swapped in since timezone
4767 // can get out of sync when the system timezone is updated while
4768 // the view is swapped out.
4769 RenderThreadImpl::NotifyTimezoneChange();
4771 render_view_
->SetSwappedOut(false);
4772 is_swapped_out_
= false;
4776 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4777 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4778 switches::kEnableBrowserSideNavigation
));
4780 // TODO(clamy): Execute the beforeunload event.
4782 // Note: At this stage, the goal is to apply all the modifications the
4783 // renderer wants to make to the request, and then send it to the browser, so
4784 // that the actual network request can be started. Ideally, all such
4785 // modifications should take place in willSendRequest, and in the
4786 // implementation of willSendRequest for the various InspectorAgents
4789 // TODO(clamy): Apply devtools override.
4790 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4792 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4794 // TODO(clamy): Same-document navigations should not be sent back to the
4796 // TODO(clamy): Data urls should not be sent back to the browser either.
4797 bool should_replace_current_entry
= false;
4798 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4799 WebDataSource
* current_data_source
= frame_
->dataSource();
4800 WebDataSource
* data_source
=
4801 provisional_data_source
? provisional_data_source
: current_data_source
;
4803 // The current entry can only be replaced if there already is an entry in the
4805 if (data_source
&& render_view_
->history_list_length_
> 0) {
4806 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4808 Send(new FrameHostMsg_BeginNavigation(
4810 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4811 BeginNavigationParams(
4812 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4813 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4814 GetRequestBodyForWebURLRequest(*request
)));
4817 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4819 // A loadData request with a specified base URL.
4820 std::string mime_type
, charset
, data
;
4821 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4822 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4823 params
.url
: params
.base_url_for_data_url
;
4825 WebData(data
.c_str(), data
.length()),
4826 WebString::fromUTF8(mime_type
),
4827 WebString::fromUTF8(charset
),
4829 params
.history_url_for_data_url
,
4832 CHECK(false) << "Invalid URL passed: "
4833 << params
.url
.possibly_invalid_spec();
4837 void RenderFrameImpl::SendFailedProvisionalLoad(
4838 const blink::WebURLRequest
& request
,
4839 const blink::WebURLError
& error
,
4840 blink::WebLocalFrame
* frame
) {
4841 bool show_repost_interstitial
=
4842 (error
.reason
== net::ERR_CACHE_MISS
&&
4843 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4845 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4846 params
.error_code
= error
.reason
;
4847 GetContentClient()->renderer()->GetNavigationErrorStrings(
4848 render_view_
.get(), frame
, request
, error
, NULL
,
4849 ¶ms
.error_description
);
4850 params
.url
= error
.unreachableURL
;
4851 params
.showing_repost_interstitial
= show_repost_interstitial
;
4852 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4853 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4856 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4858 const GURL
& unreachable_url
) {
4859 // Don't display an error page if this is simply a cancelled load. Aside
4860 // from being dumb, Blink doesn't expect it and it will cause a crash.
4861 if (error_code
== net::ERR_ABORTED
)
4864 // Don't display "client blocked" error page if browser has asked us not to.
4865 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4866 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4870 // Allow the embedder to suppress an error page.
4871 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4872 this, unreachable_url
)) {
4876 if (RenderThreadImpl::current() &&
4877 RenderThreadImpl::current()->layout_test_mode()) {
4884 GURL
RenderFrameImpl::GetLoadingUrl() const {
4885 WebDataSource
* ds
= frame_
->dataSource();
4886 if (ds
->hasUnreachableURL())
4887 return ds
->unreachableURL();
4889 const WebURLRequest
& request
= ds
->request();
4890 return request
.url();
4893 void RenderFrameImpl::PopulateDocumentStateFromPending(
4894 DocumentState
* document_state
) {
4895 document_state
->set_request_time(
4896 pending_navigation_params_
->request_params
.request_time
);
4898 InternalDocumentStateData
* internal_data
=
4899 InternalDocumentStateData::FromDocumentState(document_state
);
4901 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4902 url::kJavaScriptScheme
) &&
4903 pending_navigation_params_
->common_params
.navigation_type
==
4904 FrameMsg_Navigate_Type::RESTORE
) {
4905 // We're doing a load of a page that was restored from the last session. By
4906 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4907 // can result in stale data for pages that are set to expire. We explicitly
4908 // override that by setting the policy here so that as necessary we load
4909 // from the network.
4911 // TODO(davidben): Remove this in favor of passing a cache policy to the
4912 // loadHistoryItem call in OnNavigate. That requires not overloading
4913 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4914 // policy based on load type, etc".
4915 internal_data
->set_cache_policy_override(
4916 WebURLRequest::UseProtocolCachePolicy
);
4919 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4920 document_state
->set_load_type(DocumentState::RELOAD
);
4921 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4922 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4924 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4926 internal_data
->set_is_overriding_user_agent(
4927 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4928 internal_data
->set_must_reset_scroll_and_scale_state(
4929 pending_navigation_params_
->common_params
.navigation_type
==
4930 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4931 document_state
->set_can_load_local_resources(
4932 pending_navigation_params_
->request_params
.can_load_local_resources
);
4935 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4936 // A navigation resulting from loading a javascript URL should not be treated
4937 // as a browser initiated event. Instead, we want it to look as if the page
4938 // initiated any load resulting from JS execution.
4939 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4940 url::kJavaScriptScheme
)) {
4941 return NavigationStateImpl::CreateBrowserInitiated(
4942 pending_navigation_params_
->common_params
,
4943 pending_navigation_params_
->start_params
,
4944 pending_navigation_params_
->request_params
);
4946 return NavigationStateImpl::CreateContentInitiated();
4949 #if defined(OS_ANDROID)
4950 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4951 WebMediaPlayerClient
* client
,
4952 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4953 const media::WebMediaPlayerParams
& params
) {
4954 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4955 if (SynchronousCompositorFactory
* factory
=
4956 SynchronousCompositorFactory::GetInstance()) {
4957 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4959 GpuChannelHost
* gpu_channel_host
=
4960 RenderThreadImpl::current()->EstablishGpuChannelSync(
4961 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4963 if (!gpu_channel_host
) {
4964 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4968 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4969 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4971 if (!context_provider
.get()) {
4972 LOG(ERROR
) << "Failed to get context3d for media player";
4976 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4977 context_provider
, gpu_channel_host
, routing_id_
);
4980 return new WebMediaPlayerAndroid(
4981 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
4982 GetMediaPlayerManager(), GetCdmFactory(), stream_texture_factory
, params
);
4985 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4986 if (!media_player_manager_
)
4987 media_player_manager_
= new RendererMediaPlayerManager(this);
4988 return media_player_manager_
;
4990 #endif // defined(OS_ANDROID)
4992 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4993 if (!media_permission_dispatcher_
)
4994 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
4995 return media_permission_dispatcher_
;
4998 #if defined(ENABLE_MOJO_MEDIA)
4999 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5000 if (!media_service_factory_
) {
5001 mojo::ServiceProviderPtr service_provider
=
5002 ConnectToApplication(GURL("mojo:media"));
5003 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5004 media_service_factory_
.set_connection_error_handler(
5005 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5006 base::Unretained(this)));
5009 return media_service_factory_
.get();
5012 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5013 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5014 // violation on the old |media_service_factory_| by outstanding
5015 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5017 // media_service_factory_.reset();
5021 bool RenderFrameImpl::AreSecureCodecsSupported() {
5022 #if defined(OS_ANDROID)
5023 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5024 return render_view_
->renderer_preferences_
5025 .use_video_overlay_for_embedded_encrypted_video
;
5028 #endif // defined(OS_ANDROID)
5031 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5032 #if defined(ENABLE_BROWSER_CDMS)
5034 cdm_manager_
= new RendererCdmManager(this);
5035 #endif // defined(ENABLE_BROWSER_CDMS)
5037 if (!cdm_factory_
) {
5040 #if defined(ENABLE_MOJO_MEDIA)
5041 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5043 cdm_factory_
.reset(new RenderCdmFactory(
5044 #if defined(ENABLE_PEPPER_CDMS)
5045 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5046 #elif defined(ENABLE_BROWSER_CDMS)
5050 #endif // defined(ENABLE_MOJO_MEDIA)
5053 return cdm_factory_
.get();
5056 void RenderFrameImpl::RegisterMojoServices() {
5057 // Only main frame have ImageDownloader service.
5058 if (!frame_
->parent()) {
5059 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5060 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5061 base::Unretained(this)));
5065 mojo::ServiceProviderPtr
RenderFrameImpl::ConnectToApplication(
5067 DCHECK(mojo_shell_
);
5068 mojo::ServiceProviderPtr service_provider
;
5069 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5070 request
->url
= mojo::String::From(url
);
5071 mojo_shell_
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5073 base::Bind(&OnGotContentHandlerID
));
5074 return service_provider
.Pass();
5077 } // namespace content