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 "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/permissions/permission_dispatcher.h"
25 #include "content/child/plugin_messages.h"
26 #include "content/child/quota_dispatcher.h"
27 #include "content/child/request_extra_data.h"
28 #include "content/child/service_worker/service_worker_handle_reference.h"
29 #include "content/child/service_worker/service_worker_network_provider.h"
30 #include "content/child/service_worker/service_worker_provider_context.h"
31 #include "content/child/service_worker/web_service_worker_provider_impl.h"
32 #include "content/child/v8_value_converter_impl.h"
33 #include "content/child/web_url_loader_impl.h"
34 #include "content/child/web_url_request_util.h"
35 #include "content/child/webmessageportchannel_impl.h"
36 #include "content/child/websocket_bridge.h"
37 #include "content/child/weburlresponse_extradata_impl.h"
38 #include "content/common/clipboard_messages.h"
39 #include "content/common/frame_messages.h"
40 #include "content/common/frame_replication_state.h"
41 #include "content/common/input_messages.h"
42 #include "content/common/navigation_params.h"
43 #include "content/common/service_worker/service_worker_types.h"
44 #include "content/common/site_isolation_policy.h"
45 #include "content/common/swapped_out_messages.h"
46 #include "content/common/view_messages.h"
47 #include "content/public/common/bindings_policy.h"
48 #include "content/public/common/content_constants.h"
49 #include "content/public/common/content_switches.h"
50 #include "content/public/common/context_menu_params.h"
51 #include "content/public/common/isolated_world_ids.h"
52 #include "content/public/common/page_state.h"
53 #include "content/public/common/resource_response.h"
54 #include "content/public/common/url_constants.h"
55 #include "content/public/common/url_utils.h"
56 #include "content/public/renderer/browser_plugin_delegate.h"
57 #include "content/public/renderer/content_renderer_client.h"
58 #include "content/public/renderer/context_menu_client.h"
59 #include "content/public/renderer/document_state.h"
60 #include "content/public/renderer/navigation_state.h"
61 #include "content/public/renderer/render_frame_observer.h"
62 #include "content/public/renderer/renderer_ppapi_host.h"
63 #include "content/renderer/accessibility/renderer_accessibility.h"
64 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
65 #include "content/renderer/browser_plugin/browser_plugin.h"
66 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
67 #include "content/renderer/child_frame_compositing_helper.h"
68 #include "content/renderer/context_menu_params_builder.h"
69 #include "content/renderer/devtools/devtools_agent.h"
70 #include "content/renderer/dom_automation_controller.h"
71 #include "content/renderer/external_popup_menu.h"
72 #include "content/renderer/geolocation_dispatcher.h"
73 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
74 #include "content/renderer/history_controller.h"
75 #include "content/renderer/history_serialization.h"
76 #include "content/renderer/image_downloader/image_downloader_impl.h"
77 #include "content/renderer/ime_event_guard.h"
78 #include "content/renderer/internal_document_state_data.h"
79 #include "content/renderer/manifest/manifest_manager.h"
80 #include "content/renderer/media/audio_renderer_mixer_manager.h"
81 #include "content/renderer/media/crypto/render_cdm_factory.h"
82 #include "content/renderer/media/media_permission_dispatcher.h"
83 #include "content/renderer/media/media_stream_dispatcher.h"
84 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
85 #include "content/renderer/media/midi_dispatcher.h"
86 #include "content/renderer/media/render_media_log.h"
87 #include "content/renderer/media/user_media_client_impl.h"
88 #include "content/renderer/media/webmediaplayer_ms.h"
89 #include "content/renderer/memory_benchmarking_extension.h"
90 #include "content/renderer/mojo/service_registry_js_wrapper.h"
91 #include "content/renderer/navigation_state_impl.h"
92 #include "content/renderer/notification_permission_dispatcher.h"
93 #include "content/renderer/npapi/plugin_channel_host.h"
94 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
95 #include "content/renderer/presentation/presentation_dispatcher.h"
96 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
97 #include "content/renderer/render_frame_proxy.h"
98 #include "content/renderer/render_process.h"
99 #include "content/renderer/render_thread_impl.h"
100 #include "content/renderer/render_view_impl.h"
101 #include "content/renderer/render_widget_fullscreen_pepper.h"
102 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
103 #include "content/renderer/renderer_webcolorchooser_impl.h"
104 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
105 #include "content/renderer/shared_worker_repository.h"
106 #include "content/renderer/skia_benchmarking_extension.h"
107 #include "content/renderer/stats_collection_controller.h"
108 #include "content/renderer/web_ui_extension.h"
109 #include "content/renderer/websharedworker_proxy.h"
110 #include "gin/modules/module_registry.h"
111 #include "media/base/audio_renderer_mixer_input.h"
112 #include "media/base/media_log.h"
113 #include "media/blink/webencryptedmediaclient_impl.h"
114 #include "media/blink/webmediaplayer_impl.h"
115 #include "media/blink/webmediaplayer_params.h"
116 #include "media/renderers/gpu_video_accelerator_factories.h"
117 #include "net/base/data_url.h"
118 #include "net/base/net_errors.h"
119 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
120 #include "net/http/http_util.h"
121 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
122 #include "third_party/WebKit/public/platform/WebString.h"
123 #include "third_party/WebKit/public/platform/WebURL.h"
124 #include "third_party/WebKit/public/platform/WebURLError.h"
125 #include "third_party/WebKit/public/platform/WebURLResponse.h"
126 #include "third_party/WebKit/public/platform/WebVector.h"
127 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
128 #include "third_party/WebKit/public/web/WebDocument.h"
129 #include "third_party/WebKit/public/web/WebFrameWidget.h"
130 #include "third_party/WebKit/public/web/WebGlyphCache.h"
131 #include "third_party/WebKit/public/web/WebKit.h"
132 #include "third_party/WebKit/public/web/WebLocalFrame.h"
133 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
134 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
135 #include "third_party/WebKit/public/web/WebPlugin.h"
136 #include "third_party/WebKit/public/web/WebPluginParams.h"
137 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
138 #include "third_party/WebKit/public/web/WebRange.h"
139 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
140 #include "third_party/WebKit/public/web/WebScriptSource.h"
141 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
142 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
143 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
144 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
145 #include "third_party/WebKit/public/web/WebSettings.h"
146 #include "third_party/WebKit/public/web/WebSurroundingText.h"
147 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
148 #include "third_party/WebKit/public/web/WebView.h"
149 #include "third_party/mojo/src/mojo/edk/js/core.h"
150 #include "third_party/mojo/src/mojo/edk/js/support.h"
151 #include "url/url_util.h"
153 #if defined(ENABLE_PLUGINS)
154 #include "content/renderer/npapi/webplugin_impl.h"
155 #include "content/renderer/pepper/pepper_browser_connection.h"
156 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
157 #include "content/renderer/pepper/pepper_webplugin_impl.h"
158 #include "content/renderer/pepper/plugin_module.h"
161 #if defined(ENABLE_WEBRTC)
162 #include "content/renderer/media/rtc_peer_connection_handler.h"
165 #if defined(OS_ANDROID)
166 #include <cpu-features.h>
168 #include "content/common/gpu/client/context_provider_command_buffer.h"
169 #include "content/renderer/android/synchronous_compositor_factory.h"
170 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
171 #include "content/renderer/media/android/renderer_media_player_manager.h"
172 #include "content/renderer/media/android/stream_texture_factory_impl.h"
173 #include "content/renderer/media/android/webmediaplayer_android.h"
175 #include "cc/blink/context_provider_web_context.h"
178 #if defined(ENABLE_PEPPER_CDMS)
179 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
180 #elif defined(ENABLE_BROWSER_CDMS)
181 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
184 #if defined(ENABLE_MOJO_MEDIA)
185 #include "media/mojo/services/mojo_cdm_factory.h"
186 #include "media/mojo/services/mojo_renderer_factory.h"
187 #include "mojo/application/public/cpp/connect.h"
188 #include "mojo/application/public/interfaces/shell.mojom.h"
189 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
191 #include "media/renderers/default_renderer_factory.h"
194 #if defined(ENABLE_WEBVR)
195 #include "content/renderer/vr/vr_dispatcher.h"
198 using blink::WebContentDecryptionModule
;
199 using blink::WebContextMenuData
;
200 using blink::WebData
;
201 using blink::WebDataSource
;
202 using blink::WebDocument
;
203 using blink::WebDOMEvent
;
204 using blink::WebDOMMessageEvent
;
205 using blink::WebElement
;
206 using blink::WebExternalPopupMenu
;
207 using blink::WebExternalPopupMenuClient
;
208 using blink::WebFrame
;
209 using blink::WebHistoryItem
;
210 using blink::WebHTTPBody
;
211 using blink::WebLocalFrame
;
212 using blink::WebMediaPlayer
;
213 using blink::WebMediaPlayerClient
;
214 using blink::WebMediaPlayerEncryptedMediaClient
;
215 using blink::WebNavigationPolicy
;
216 using blink::WebNavigationType
;
217 using blink::WebNode
;
218 using blink::WebPluginParams
;
219 using blink::WebPopupMenuInfo
;
220 using blink::WebRange
;
221 using blink::WebReferrerPolicy
;
222 using blink::WebScriptSource
;
223 using blink::WebSearchableFormData
;
224 using blink::WebSecurityOrigin
;
225 using blink::WebSecurityPolicy
;
226 using blink::WebSerializedScriptValue
;
227 using blink::WebServiceWorkerProvider
;
228 using blink::WebSettings
;
229 using blink::WebStorageQuotaCallbacks
;
230 using blink::WebString
;
232 using blink::WebURLError
;
233 using blink::WebURLRequest
;
234 using blink::WebURLResponse
;
235 using blink::WebUserGestureIndicator
;
236 using blink::WebVector
;
237 using blink::WebView
;
239 using base::TimeDelta
;
245 const char kDefaultAcceptHeader
[] =
246 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
248 const char kAcceptHeader
[] = "Accept";
250 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
252 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
253 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
254 LAZY_INSTANCE_INITIALIZER
;
256 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
257 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
259 int64
ExtractPostId(HistoryEntry
* entry
) {
263 const WebHistoryItem
& item
= entry
->root();
264 if (item
.isNull() || item
.httpBody().isNull())
267 return item
.httpBody().identifier();
270 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
271 const WebURLResponse
& response
) {
272 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
275 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
276 // Replace any occurrences of swappedout:// with about:blank.
277 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
278 WebVector
<WebURL
> urls
;
279 ds
->redirectChain(urls
);
280 result
->reserve(urls
.size());
281 for (size_t i
= 0; i
< urls
.size(); ++i
) {
282 if (urls
[i
] != GURL(kSwappedOutURL
))
283 result
->push_back(urls
[i
]);
285 result
->push_back(blank_url
);
289 // Returns the original request url. If there is no redirect, the original
290 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
291 // frame was loaded by loadData, the original url will be ds->unreachableURL()
292 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
293 // WebDataSource has unreachable URL means that the frame is loaded through
294 // blink::WebFrame::loadData(), and the base URL will be in the redirect
295 // chain. However, we never visited the baseURL. So in this case, we should
296 // use the unreachable URL as the original URL.
297 if (ds
->hasUnreachableURL())
298 return ds
->unreachableURL();
300 std::vector
<GURL
> redirects
;
301 GetRedirectChain(ds
, &redirects
);
302 if (!redirects
.empty())
303 return redirects
.at(0);
305 return ds
->originalRequest().url();
308 NOINLINE
void CrashIntentionally() {
309 // NOTE(shess): Crash directly rather than using NOTREACHED() so
310 // that the signature is easier to triage in crash reports.
311 volatile int* zero
= NULL
;
315 NOINLINE
void BadCastCrashIntentionally() {
328 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
329 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
330 // NOTE(rogerm): We intentionally perform an invalid heap access here in
331 // order to trigger an Address Sanitizer (ASAN) error report.
332 const char kCrashDomain
[] = "crash";
333 const char kHeapOverflow
[] = "/heap-overflow";
334 const char kHeapUnderflow
[] = "/heap-underflow";
335 const char kUseAfterFree
[] = "/use-after-free";
336 #if defined(SYZYASAN)
337 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
338 const char kCorruptHeap
[] = "/corrupt-heap";
341 if (!url
.DomainIs(kCrashDomain
))
347 std::string
crash_type(url
.path());
348 if (crash_type
== kHeapOverflow
) {
349 base::debug::AsanHeapOverflow();
350 } else if (crash_type
== kHeapUnderflow
) {
351 base::debug::AsanHeapUnderflow();
352 } else if (crash_type
== kUseAfterFree
) {
353 base::debug::AsanHeapUseAfterFree();
354 #if defined(SYZYASAN)
355 } else if (crash_type
== kCorruptHeapBlock
) {
356 base::debug::AsanCorruptHeapBlock();
357 } else if (crash_type
== kCorruptHeap
) {
358 base::debug::AsanCorruptHeap();
362 #endif // ADDRESS_SANITIZER || SYZYASAN
364 void MaybeHandleDebugURL(const GURL
& url
) {
365 if (!url
.SchemeIs(kChromeUIScheme
))
367 if (url
== GURL(kChromeUIBadCastCrashURL
)) {
368 BadCastCrashIntentionally();
369 } else if (url
== GURL(kChromeUICrashURL
)) {
370 CrashIntentionally();
371 } else if (url
== GURL(kChromeUIDumpURL
)) {
372 // This URL will only correctly create a crash dump file if content is
373 // hosted in a process that has correctly called
374 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
375 // of base::debug::DumpWithoutCrashing for more details.
376 base::debug::DumpWithoutCrashing();
377 } else if (url
== GURL(kChromeUIKillURL
)) {
378 base::Process::Current().Terminate(1, false);
379 } else if (url
== GURL(kChromeUIHangURL
)) {
381 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
383 } else if (url
== GURL(kChromeUIShorthangURL
)) {
384 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
387 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
388 MaybeTriggerAsanError(url
);
389 #endif // ADDRESS_SANITIZER || SYZYASAN
392 // Returns false unless this is a top-level navigation.
393 bool IsTopLevelNavigation(WebFrame
* frame
) {
394 return frame
->parent() == NULL
;
397 // Returns false unless this is a top-level navigation that crosses origins.
398 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
400 WebNavigationType type
,
402 if (!IsTopLevelNavigation(frame
))
405 // Navigations initiated within Webkit are not sent out to the external host
406 // in the following cases.
407 // 1. The url scheme is not http/https
408 // 2. The origin of the url and the opener is the same in which case the
409 // opener relationship is maintained.
410 // 3. Reloads/form submits/back forward navigations
411 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
414 if (type
!= blink::WebNavigationTypeReload
&&
415 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
416 // The opener relationship between the new window and the parent allows the
417 // new window to script the parent and vice versa. This is not allowed if
418 // the origins of the two domains are different. This can be treated as a
419 // top level navigation and routed back to the host.
420 blink::WebFrame
* opener
= frame
->opener();
424 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
430 WebURLRequest
CreateURLRequestForNavigation(
431 const CommonNavigationParams
& common_params
,
432 scoped_ptr
<StreamOverrideParameters
> stream_override
,
433 bool is_view_source_mode_enabled
) {
434 WebURLRequest
request(common_params
.url
);
435 if (is_view_source_mode_enabled
)
436 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
438 if (common_params
.referrer
.url
.is_valid()) {
439 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
440 common_params
.referrer
.policy
,
442 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
443 if (!web_referrer
.isEmpty())
444 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
447 RequestExtraData
* extra_data
= new RequestExtraData();
448 extra_data
->set_stream_override(stream_override
.Pass());
449 request
.setExtraData(extra_data
);
451 // Set the ui timestamp for this navigation. Currently the timestamp here is
452 // only non empty when the navigation was triggered by an Android intent. The
453 // timestamp is converted to a double version supported by blink. It will be
454 // passed back to the browser in the DidCommitProvisionalLoad and the
455 // DocumentLoadComplete IPCs.
456 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
457 request
.setUiStartTime(ui_timestamp
.InSecondsF());
458 request
.setInputPerfMetricReportPolicy(
459 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
460 common_params
.report_type
));
464 void UpdateFrameNavigationTiming(WebFrame
* frame
,
465 base::TimeTicks browser_navigation_start
,
466 base::TimeTicks renderer_navigation_start
) {
467 // The browser provides the navigation_start time to bootstrap the
468 // Navigation Timing information for the browser-initiated navigations. In
469 // case of cross-process navigations, this carries over the time of
470 // finishing the onbeforeunload handler of the previous page.
471 DCHECK(!browser_navigation_start
.is_null());
472 if (frame
->provisionalDataSource()) {
473 // |browser_navigation_start| is likely before this process existed, so we
474 // can't use InterProcessTimeTicksConverter. We need at least to ensure
475 // that the browser-side navigation start we set is not later than the one
476 // on the renderer side.
477 base::TimeTicks navigation_start
= std::min(
478 browser_navigation_start
, renderer_navigation_start
);
479 double navigation_start_seconds
=
480 (navigation_start
- base::TimeTicks()).InSecondsF();
481 frame
->provisionalDataSource()->setNavigationStartTime(
482 navigation_start_seconds
);
483 // TODO(clamy): We need to provide additional timing values for the
484 // Navigation Timing API to work with browser-side navigations.
489 CommonNavigationParams
MakeCommonNavigationParams(
490 blink::WebURLRequest
* request
,
491 bool should_replace_current_entry
) {
492 const RequestExtraData kEmptyData
;
493 const RequestExtraData
* extra_data
=
494 static_cast<RequestExtraData
*>(request
->extraData());
496 extra_data
= &kEmptyData
;
498 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
499 request
->referrerPolicy());
501 // Set the ui timestamp for this navigation. Currently the timestamp here is
502 // only non empty when the navigation was triggered by an Android intent, or
503 // by the user clicking on a link. The timestamp is converted from a double
504 // version supported by blink. It will be passed back to the renderer in the
505 // CommitNavigation IPC, and then back to the browser again in the
506 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
507 base::TimeTicks ui_timestamp
=
508 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
509 FrameMsg_UILoadMetricsReportType::Value report_type
=
510 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
511 request
->inputPerfMetricReportPolicy());
512 return CommonNavigationParams(
513 request
->url(), referrer
, extra_data
->transition_type(),
514 FrameMsg_Navigate_Type::NORMAL
, true, should_replace_current_entry
,
515 ui_timestamp
, report_type
, GURL(), GURL());
518 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
519 media::Context3D
GetSharedMainThreadContext3D() {
520 cc::ContextProvider
* provider
=
521 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
523 return media::Context3D();
524 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
528 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
529 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
530 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
531 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
534 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
540 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
542 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
543 CreateParams
params(render_view
, routing_id
);
545 if (g_create_render_frame_impl
)
546 return g_create_render_frame_impl(params
);
548 return new RenderFrameImpl(params
);
552 RenderFrame
* RenderFrame::FromRoutingID(int routing_id
) {
553 return RenderFrameImpl::FromRoutingID(routing_id
);
557 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int routing_id
) {
558 RoutingIDFrameMap::iterator iter
=
559 g_routing_id_frame_map
.Get().find(routing_id
);
560 if (iter
!= g_routing_id_frame_map
.Get().end())
566 void RenderFrameImpl::CreateFrame(
568 int parent_routing_id
,
569 int previous_sibling_routing_id
,
570 int proxy_routing_id
,
571 const FrameReplicationState
& replicated_state
,
572 CompositorDependencies
* compositor_deps
,
573 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
574 blink::WebLocalFrame
* web_frame
;
575 RenderFrameImpl
* render_frame
;
576 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
577 RenderFrameProxy
* parent_proxy
=
578 RenderFrameProxy::FromRoutingID(parent_routing_id
);
579 // If the browser is sending a valid parent routing id, it should already
580 // be created and registered.
582 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
584 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
585 RenderFrameProxy
* previous_sibling_proxy
=
586 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
587 if (previous_sibling_proxy
)
588 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
590 // Create the RenderFrame and WebLocalFrame, linking the two.
592 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
593 web_frame
= parent_web_frame
->createLocalChild(
594 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
595 replicated_state
.sandbox_flags
, render_frame
,
596 previous_sibling_web_frame
);
598 RenderFrameProxy
* proxy
=
599 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
601 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
603 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
604 render_frame
->proxy_routing_id_
= proxy_routing_id
;
605 web_frame
->initializeToReplaceRemoteFrame(
606 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
607 replicated_state
.sandbox_flags
);
609 render_frame
->SetWebFrame(web_frame
);
610 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
612 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
613 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
614 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
615 widget_params
.routing_id
, widget_params
.surface_id
,
616 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
617 compositor_deps
, web_frame
);
618 // TODO(kenrb): Observing shouldn't be necessary when we sort out
619 // WasShown and WasHidden, separating page-level visibility from
620 // frame-level visibility.
621 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
624 render_frame
->Initialize();
628 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
629 return RenderFrameImpl::FromWebFrame(web_frame
);
633 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
634 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
635 if (iter
!= g_frame_map
.Get().end())
641 void RenderFrameImpl::InstallCreateHook(
642 CreateRenderFrameImplFunction create_render_frame_impl
) {
643 CHECK(!g_create_render_frame_impl
);
644 g_create_render_frame_impl
= create_render_frame_impl
;
647 // RenderFrameImpl ----------------------------------------------------------
648 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
651 is_local_root_(false),
652 render_view_(params
.render_view
->AsWeakPtr()),
653 routing_id_(params
.routing_id
),
654 is_swapped_out_(false),
655 render_frame_proxy_(NULL
),
656 is_detaching_(false),
657 proxy_routing_id_(MSG_ROUTING_NONE
),
658 #if defined(ENABLE_PLUGINS)
659 plugin_power_saver_helper_(NULL
),
662 selection_text_offset_(0),
663 selection_range_(gfx::Range::InvalidRange()),
664 handling_select_range_(false),
665 notification_permission_dispatcher_(NULL
),
666 web_user_media_client_(NULL
),
667 media_permission_dispatcher_(NULL
),
668 midi_dispatcher_(NULL
),
669 #if defined(OS_ANDROID)
670 media_player_manager_(NULL
),
672 #if defined(ENABLE_BROWSER_CDMS)
675 #if defined(VIDEO_HOLE)
676 contains_media_player_(false),
678 devtools_agent_(nullptr),
679 geolocation_dispatcher_(NULL
),
680 push_messaging_dispatcher_(NULL
),
681 presentation_dispatcher_(NULL
),
682 screen_orientation_dispatcher_(NULL
),
683 manifest_manager_(NULL
),
684 accessibility_mode_(AccessibilityModeOff
),
685 renderer_accessibility_(NULL
),
686 weak_factory_(this) {
687 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
688 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
689 CHECK(result
.second
) << "Inserting a duplicate item.";
691 RenderThread::Get()->AddRoute(routing_id_
, this);
693 render_view_
->RegisterRenderFrame(this);
695 // Everything below subclasses RenderFrameObserver and is automatically
696 // deleted when the RenderFrame gets deleted.
697 #if defined(OS_ANDROID)
698 new GinJavaBridgeDispatcher(this);
701 #if defined(ENABLE_PLUGINS)
702 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
705 manifest_manager_
= new ManifestManager(this);
708 RenderFrameImpl::~RenderFrameImpl() {
709 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
710 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
712 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
714 #if defined(VIDEO_HOLE)
715 if (contains_media_player_
)
716 render_view_
->UnregisterVideoHoleFrame(this);
720 // When using swapped out frames, RenderFrameProxy is owned by
721 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
722 // along with this object.
723 if (render_frame_proxy_
&&
724 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
725 // The following method calls back into this object and clears
726 // |render_frame_proxy_|.
727 render_frame_proxy_
->frameDetached(
728 blink::WebRemoteFrameClient::DetachType::Remove
);
731 // Ensure the RenderView doesn't point to this object, once it is destroyed.
732 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
733 // is |this|, once the object is no longer leaked.
734 // See https://crbug.com/464764.
735 render_view_
->main_render_frame_
= nullptr;
738 render_view_
->UnregisterRenderFrame(this);
739 g_routing_id_frame_map
.Get().erase(routing_id_
);
740 RenderThread::Get()->RemoveRoute(routing_id_
);
743 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
746 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
747 std::make_pair(web_frame
, this));
748 CHECK(result
.second
) << "Inserting a duplicate item.";
753 void RenderFrameImpl::Initialize() {
754 is_subframe_
= !!frame_
->parent();
755 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
757 #if defined(ENABLE_PLUGINS)
758 new PepperBrowserConnection(this);
760 new SharedWorkerRepository(this);
762 if (is_local_root_
&& !render_frame_proxy_
) {
763 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
764 // when |this| is deleted.
765 devtools_agent_
= new DevToolsAgent(this);
768 RegisterMojoServices();
770 // We delay calling this until we have the WebFrame so that any observer or
771 // embedder can call GetWebFrame on any RenderFrame.
772 GetContentClient()->renderer()->RenderFrameCreated(this);
775 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
776 return render_view_
.get();
779 #if defined(ENABLE_PLUGINS)
780 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
781 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
782 DidCreatePepperPlugin(host
));
783 if (host
->GetPluginName() == kFlashPluginName
) {
784 RenderThread::Get()->RecordAction(
785 base::UserMetricsAction("FrameLoadWithFlash"));
789 void RenderFrameImpl::PepperDidChangeCursor(
790 PepperPluginInstanceImpl
* instance
,
791 const blink::WebCursorInfo
& cursor
) {
792 // Update the cursor appearance immediately if the requesting plugin is the
793 // one which receives the last mouse event. Otherwise, the new cursor won't be
794 // picked up until the plugin gets the next input event. That is bad if, e.g.,
795 // the plugin would like to set an invisible cursor when there isn't any user
796 // input for a while.
797 if (instance
== render_view_
->pepper_last_mouse_event_target())
798 GetRenderWidget()->didChangeCursor(cursor
);
801 void RenderFrameImpl::PepperDidReceiveMouseEvent(
802 PepperPluginInstanceImpl
* instance
) {
803 render_view_
->set_pepper_last_mouse_event_target(instance
);
806 void RenderFrameImpl::PepperTextInputTypeChanged(
807 PepperPluginInstanceImpl
* instance
) {
808 if (instance
!= render_view_
->focused_pepper_plugin())
811 GetRenderWidget()->UpdateTextInputState(
812 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
814 FocusedNodeChangedForAccessibility(WebNode());
817 void RenderFrameImpl::PepperCaretPositionChanged(
818 PepperPluginInstanceImpl
* instance
) {
819 if (instance
!= render_view_
->focused_pepper_plugin())
821 GetRenderWidget()->UpdateSelectionBounds();
824 void RenderFrameImpl::PepperCancelComposition(
825 PepperPluginInstanceImpl
* instance
) {
826 if (instance
!= render_view_
->focused_pepper_plugin())
828 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
829 #if defined(OS_MACOSX) || defined(USE_AURA)
830 GetRenderWidget()->UpdateCompositionInfo(true);
834 void RenderFrameImpl::PepperSelectionChanged(
835 PepperPluginInstanceImpl
* instance
) {
836 if (instance
!= render_view_
->focused_pepper_plugin())
838 SyncSelectionIfRequired();
841 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
842 PepperPluginInstanceImpl
* plugin
) {
844 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
845 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
846 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
847 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
848 plugin
, active_url
, GetRenderWidget()->screenInfo());
849 widget
->show(blink::WebNavigationPolicyIgnore
);
853 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
854 if (!render_view_
->focused_pepper_plugin())
856 return render_view_
->focused_pepper_plugin()->
857 IsPluginAcceptingCompositionEvents();
860 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
861 base::ProcessId plugin_pid
) {
862 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
863 // routing_id_ as a result.
864 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
867 void RenderFrameImpl::SimulateImeSetComposition(
868 const base::string16
& text
,
869 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
872 render_view_
->OnImeSetComposition(
873 text
, underlines
, selection_start
, selection_end
);
876 void RenderFrameImpl::SimulateImeConfirmComposition(
877 const base::string16
& text
,
878 const gfx::Range
& replacement_range
) {
879 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
882 void RenderFrameImpl::OnImeSetComposition(
883 const base::string16
& text
,
884 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
887 // When a PPAPI plugin has focus, we bypass WebKit.
888 if (!IsPepperAcceptingCompositionEvents()) {
889 pepper_composition_text_
= text
;
891 // TODO(kinaba) currently all composition events are sent directly to
892 // plugins. Use DOM event mechanism after WebKit is made aware about
893 // plugins that support composition.
894 // The code below mimics the behavior of WebCore::Editor::setComposition.
896 // Empty -> nonempty: composition started.
897 if (pepper_composition_text_
.empty() && !text
.empty()) {
898 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
901 // Nonempty -> empty: composition canceled.
902 if (!pepper_composition_text_
.empty() && text
.empty()) {
903 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
906 pepper_composition_text_
= text
;
907 // Nonempty: composition is ongoing.
908 if (!pepper_composition_text_
.empty()) {
909 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
910 pepper_composition_text_
, underlines
, selection_start
,
916 void RenderFrameImpl::OnImeConfirmComposition(
917 const base::string16
& text
,
918 const gfx::Range
& replacement_range
,
919 bool keep_selection
) {
920 // When a PPAPI plugin has focus, we bypass WebKit.
921 // Here, text.empty() has a special meaning. It means to commit the last
922 // update of composition text (see
923 // RenderWidgetHost::ImeConfirmComposition()).
924 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
927 // last_text is empty only when both text and pepper_composition_text_ is.
929 if (last_text
.empty())
932 if (!IsPepperAcceptingCompositionEvents()) {
933 base::i18n::UTF16CharIterator
iterator(&last_text
);
935 while (iterator
.Advance()) {
936 blink::WebKeyboardEvent char_event
;
937 char_event
.type
= blink::WebInputEvent::Char
;
938 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
939 char_event
.modifiers
= 0;
940 char_event
.windowsKeyCode
= last_text
[i
];
941 char_event
.nativeKeyCode
= last_text
[i
];
943 const int32 char_start
= i
;
944 for (; i
< iterator
.array_pos(); ++i
) {
945 char_event
.text
[i
- char_start
] = last_text
[i
];
946 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
949 if (GetRenderWidget()->webwidget())
950 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
953 // Mimics the order of events sent by WebKit.
954 // See WebCore::Editor::setComposition() for the corresponding code.
955 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
956 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
958 pepper_composition_text_
.clear();
960 #endif // defined(ENABLE_PLUGINS)
962 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
963 if (!web_user_media_client_
)
964 InitializeUserMediaClient();
965 return web_user_media_client_
?
966 web_user_media_client_
->media_stream_dispatcher() : NULL
;
969 bool RenderFrameImpl::Send(IPC::Message
* message
) {
974 if (is_swapped_out_
) {
975 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
981 return RenderThread::Get()->Send(message
);
984 #if defined(OS_MACOSX) || defined(OS_ANDROID)
985 void RenderFrameImpl::DidHideExternalPopupMenu() {
986 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
987 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
988 external_popup_menu_
.reset();
992 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
993 // We may get here while detaching, when the WebFrame has been deleted. Do
994 // not process any messages in this state.
998 // TODO(kenrb): document() should not be null, but as a transitional step
999 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1000 // to this method. This happens for a top-level remote frame, where a
1001 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1002 // around and is still able to receive messages.
1003 if (!frame_
->document().isNull())
1004 GetContentClient()->SetActiveURL(frame_
->document().url());
1006 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
1007 RenderFrameObserver
* observer
;
1008 while ((observer
= it
.GetNext()) != NULL
) {
1009 if (observer
->OnMessageReceived(msg
))
1013 bool handled
= true;
1014 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1015 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1016 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1017 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1018 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1019 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1020 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1021 OnCustomContextMenuAction
)
1022 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1023 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1024 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1025 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1026 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1027 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1028 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1029 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1030 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1031 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1032 OnAdjustSelectionByCharacterOffset
)
1033 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1034 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1035 OnMoveRangeSelectionExtent
)
1036 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1037 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1038 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1039 OnExtendSelectionAndDelete
)
1040 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1041 OnSetCompositionFromExistingText
)
1042 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1043 OnExecuteNoValueEditCommand
)
1044 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1045 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1046 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1047 OnJavaScriptExecuteRequest
)
1048 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1049 OnJavaScriptExecuteRequestForTests
)
1050 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1051 OnJavaScriptExecuteRequestInIsolatedWorld
)
1052 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1053 OnVisualStateRequest
)
1054 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1055 OnSetEditableSelectionOffsets
)
1056 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1057 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1058 OnTextSurroundingSelectionRequest
)
1059 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1060 OnSetAccessibilityMode
)
1061 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1062 OnSnapshotAccessibilityTree
)
1063 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1064 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1065 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1066 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1067 OnTextTrackSettingsChanged
)
1068 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1069 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1070 #if defined(OS_ANDROID)
1071 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1072 #elif defined(OS_MACOSX)
1073 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1074 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1076 IPC_END_MESSAGE_MAP()
1081 void RenderFrameImpl::OnNavigate(
1082 const CommonNavigationParams
& common_params
,
1083 const StartNavigationParams
& start_params
,
1084 const RequestNavigationParams
& request_params
) {
1085 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1086 switches::kEnableBrowserSideNavigation
));
1087 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1088 "url", common_params
.url
.possibly_invalid_spec());
1089 NavigateInternal(common_params
, start_params
, request_params
,
1090 scoped_ptr
<StreamOverrideParameters
>());
1093 void RenderFrameImpl::NavigateToSwappedOutURL() {
1094 // We use loadRequest instead of loadHTMLString because the former commits
1095 // synchronously. Otherwise a new navigation can interrupt the navigation
1096 // to kSwappedOutURL. If that happens to be to the page we had been
1097 // showing, then WebKit will never send a commit and we'll be left spinning.
1098 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1099 // the navigation to swappedout:// is not announced to the browser side.
1100 is_swapped_out_
= true;
1101 GURL
swappedOutURL(kSwappedOutURL
);
1102 WebURLRequest
request(swappedOutURL
);
1103 frame_
->loadRequest(request
);
1106 void RenderFrameImpl::BindServiceRegistry(
1107 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1108 mojo::ServiceProviderPtr exposed_services
) {
1109 service_registry_
.Bind(services
.Pass());
1110 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1113 ManifestManager
* RenderFrameImpl::manifest_manager() {
1114 return manifest_manager_
;
1117 void RenderFrameImpl::SetPendingNavigationParams(
1118 scoped_ptr
<NavigationParams
> navigation_params
) {
1119 pending_navigation_params_
= navigation_params
.Pass();
1122 void RenderFrameImpl::OnBeforeUnload() {
1123 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1125 // TODO(creis): Right now, this is only called on the main frame. Make the
1126 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1128 CHECK(!frame_
->parent());
1130 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1131 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1132 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1133 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1134 before_unload_start_time
,
1135 before_unload_end_time
));
1138 void RenderFrameImpl::OnSwapOut(
1139 int proxy_routing_id
,
1141 const FrameReplicationState
& replicated_frame_state
) {
1142 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1143 RenderFrameProxy
* proxy
= NULL
;
1144 bool swapped_out_forbidden
=
1145 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1146 bool is_main_frame
= !frame_
->parent();
1148 // This codepath should only be hit for subframes when in --site-per-process.
1149 CHECK_IMPLIES(!is_main_frame
,
1150 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1152 // Only run unload if we're not swapped out yet, but send the ack either way.
1153 if (!is_swapped_out_
) {
1154 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1155 // a different process. This involves running the unload handler and
1156 // clearing the page. We also allow this process to exit if there are no
1157 // other active RenderFrames in it.
1159 // Send an UpdateState message before we get swapped out.
1160 render_view_
->SendUpdateState();
1162 // If we need a proxy to replace this, create it now so its routing id is
1163 // registered for receiving IPC messages.
1164 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1165 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1166 this, proxy_routing_id
, replicated_frame_state
.scope
);
1169 // Synchronously run the unload handler before sending the ACK.
1170 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1171 // unload on subframes as well.
1173 frame_
->dispatchUnloadEvent();
1175 // Swap out and stop sending any IPC messages that are not ACKs.
1177 render_view_
->SetSwappedOut(true);
1178 is_swapped_out_
= true;
1180 // Set the proxy here, since OnStop() below could cause an onload event
1181 // handler to execute, which could trigger code such as
1182 // willCheckAndDispatchMessageEvent() that needs the proxy.
1184 set_render_frame_proxy(proxy
);
1186 // Now that we're swapped out and filtering IPC messages, stop loading to
1187 // ensure that no other in-progress navigation continues. We do this here
1188 // to avoid sending a DidStopLoading message to the browser process.
1189 // TODO(creis): Should we be stopping all frames here and using
1190 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1192 if (!swapped_out_forbidden
)
1195 // Transfer settings such as initial drawing parameters to the remote frame,
1196 // if one is created, that will replace this frame.
1197 if (!is_main_frame
&& proxy
)
1198 proxy
->web_frame()->initializeFromFrame(frame_
);
1200 // Replace the page with a blank dummy URL. The unload handler will not be
1201 // run a second time, thanks to a check in FrameLoader::stopLoading.
1202 // TODO(creis): Need to add a better way to do this that avoids running the
1203 // beforeunload handler. For now, we just run it a second time silently.
1204 if (!swapped_out_forbidden
)
1205 NavigateToSwappedOutURL();
1207 // Let WebKit know that this view is hidden so it can drop resources and
1208 // stop compositing.
1209 // TODO(creis): Support this for subframes as well.
1210 if (is_main_frame
) {
1211 render_view_
->webview()->setVisibilityState(
1212 blink::WebPageVisibilityStateHidden
, false);
1216 // It is now safe to show modal dialogs again.
1217 // TODO(creis): Deal with modal dialogs from subframes.
1219 render_view_
->suppress_dialogs_until_swap_out_
= false;
1221 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1223 RenderViewImpl
* render_view
= render_view_
.get();
1225 // Now that all of the cleanup is complete and the browser side is notified,
1226 // start using the RenderFrameProxy, if one is created.
1227 if (proxy
&& swapped_out_forbidden
) {
1228 frame_
->swap(proxy
->web_frame());
1231 proxy
->OnDidStartLoading();
1234 // In --site-per-process, initialize the WebRemoteFrame with the replication
1235 // state passed by the process that is now rendering the frame.
1236 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1237 // in that case we leave the LocalFrame as the main frame visible to Blink
1238 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1239 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1240 // When we do an unconditional swap for all frames, we can remove
1241 // !is_main_frame below.
1242 if (proxy
&& swapped_out_forbidden
)
1243 proxy
->SetReplicatedState(replicated_frame_state
);
1245 // Safe to exit if no one else is using the process.
1246 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1247 // the process based on the lifetime of this RenderFrameImpl object.
1248 if (is_main_frame
) {
1249 render_view
->WasSwappedOut();
1253 void RenderFrameImpl::OnContextMenuClosed(
1254 const CustomContextMenuContext
& custom_context
) {
1255 if (custom_context
.request_id
) {
1256 // External request, should be in our map.
1257 ContextMenuClient
* client
=
1258 pending_context_menus_
.Lookup(custom_context
.request_id
);
1260 client
->OnMenuClosed(custom_context
.request_id
);
1261 pending_context_menus_
.Remove(custom_context
.request_id
);
1264 if (custom_context
.link_followed
.is_valid())
1265 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1266 // Internal request, forward to WebKit.
1267 context_menu_node_
.reset();
1271 void RenderFrameImpl::OnCustomContextMenuAction(
1272 const CustomContextMenuContext
& custom_context
,
1274 if (custom_context
.request_id
) {
1275 // External context menu request, look in our map.
1276 ContextMenuClient
* client
=
1277 pending_context_menus_
.Lookup(custom_context
.request_id
);
1279 client
->OnMenuAction(custom_context
.request_id
, action
);
1281 // Internal request, forward to WebKit.
1282 render_view_
->webview()->performCustomContextMenuAction(action
);
1286 void RenderFrameImpl::OnUndo() {
1287 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1290 void RenderFrameImpl::OnRedo() {
1291 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1294 void RenderFrameImpl::OnCut() {
1295 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1296 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1299 void RenderFrameImpl::OnCopy() {
1300 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1301 WebNode current_node
= context_menu_node_
.isNull() ?
1302 GetFocusedElement() : context_menu_node_
;
1303 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1306 void RenderFrameImpl::OnPaste() {
1307 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1308 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1311 void RenderFrameImpl::OnPasteAndMatchStyle() {
1312 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1313 frame_
->executeCommand(
1314 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1317 #if defined(OS_MACOSX)
1318 void RenderFrameImpl::OnCopyToFindPboard() {
1319 // Since the find pasteboard supports only plain text, this can be simpler
1320 // than the |OnCopy()| case.
1321 if (frame_
->hasSelection()) {
1322 base::string16 selection
= frame_
->selectionAsText();
1323 RenderThread::Get()->Send(
1324 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1329 void RenderFrameImpl::OnDelete() {
1330 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1333 void RenderFrameImpl::OnSelectAll() {
1334 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1335 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1338 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1339 const gfx::Point
& extent
) {
1340 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1341 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1343 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1344 frame_
->selectRange(base
, extent
);
1347 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1349 size_t start
, length
;
1350 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1355 // Sanity checks to disallow empty and out of range selections.
1356 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1357 || static_cast<int>(start
) + start_adjust
< 0) {
1361 // A negative adjust amount moves the selection towards the beginning of
1362 // the document, a positive amount moves the selection towards the end of
1364 start
+= start_adjust
;
1365 length
+= end_adjust
- start_adjust
;
1367 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1370 void RenderFrameImpl::OnUnselect() {
1371 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1372 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1375 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1376 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1377 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1378 GetRenderWidget()->routing_id()));
1380 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1381 frame_
->moveRangeSelectionExtent(point
);
1384 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1385 if (!frame_
->hasSelection())
1386 frame_
->selectWordAroundCaret();
1388 frame_
->replaceSelection(text
);
1391 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1392 if (!frame_
->hasSelection())
1395 frame_
->replaceMisspelledRange(text
);
1398 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1399 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1402 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1403 const std::string
& message
) {
1404 AddMessageToConsole(level
, message
);
1407 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1408 const base::string16
& jscript
,
1410 bool notify_result
) {
1411 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1412 TRACE_EVENT_SCOPE_THREAD
);
1414 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1415 v8::Local
<v8::Value
> result
=
1416 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1418 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1421 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1422 const base::string16
& jscript
,
1425 bool has_user_gesture
) {
1426 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1427 TRACE_EVENT_SCOPE_THREAD
);
1429 // A bunch of tests expect to run code in the context of a user gesture, which
1430 // can grant additional privileges (e.g. the ability to create popups).
1431 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1432 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1433 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1434 v8::Local
<v8::Value
> result
=
1435 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1437 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1440 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1441 const base::string16
& jscript
,
1445 TRACE_EVENT_INSTANT0("test_tracing",
1446 "OnJavaScriptExecuteRequestInIsolatedWorld",
1447 TRACE_EVENT_SCOPE_THREAD
);
1449 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1450 world_id
> ISOLATED_WORLD_ID_MAX
) {
1451 // Return if the world_id is not valid. world_id is passed as a plain int
1452 // over IPC and needs to be verified here, in the IPC endpoint.
1457 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1458 WebScriptSource script
= WebScriptSource(jscript
);
1459 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1460 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1461 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1465 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1469 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1471 notify_result_(notify_result
),
1472 routing_id_(routing_id
),
1473 render_frame_impl_(render_frame_impl
) {
1476 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1477 ~JavaScriptIsolatedWorldRequest() {
1480 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1481 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1482 if (!render_frame_impl_
.get()) {
1486 if (notify_result_
) {
1487 base::ListValue list
;
1488 if (!result
.isEmpty()) {
1489 // It's safe to always use the main world context when converting
1490 // here. V8ValueConverterImpl shouldn't actually care about the
1491 // context scope, and it switches to v8::Object's creation context
1492 // when encountered. (from extensions/renderer/script_injection.cc)
1493 v8::Local
<v8::Context
> context
=
1494 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1495 v8::Context::Scope
context_scope(context
);
1496 V8ValueConverterImpl converter
;
1497 converter
.SetDateAllowed(true);
1498 converter
.SetRegExpAllowed(true);
1499 for (const auto& value
: result
) {
1500 scoped_ptr
<base::Value
> result_value(
1501 converter
.FromV8Value(value
, context
));
1502 list
.Append(result_value
? result_value
.Pass()
1503 : base::Value::CreateNullValue());
1506 list
.Set(0, base::Value::CreateNullValue());
1508 render_frame_impl_
.get()->Send(
1509 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1515 void RenderFrameImpl::HandleJavascriptExecutionResult(
1516 const base::string16
& jscript
,
1519 v8::Local
<v8::Value
> result
) {
1520 if (notify_result
) {
1521 base::ListValue list
;
1522 if (!result
.IsEmpty()) {
1523 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1524 v8::Context::Scope
context_scope(context
);
1525 V8ValueConverterImpl converter
;
1526 converter
.SetDateAllowed(true);
1527 converter
.SetRegExpAllowed(true);
1528 scoped_ptr
<base::Value
> result_value(
1529 converter
.FromV8Value(result
, context
));
1530 list
.Set(0, result_value
? result_value
.Pass()
1531 : base::Value::CreateNullValue());
1533 list
.Set(0, base::Value::CreateNullValue());
1535 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1539 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1540 GetRenderWidget()->QueueMessage(
1541 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1542 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1545 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1546 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1547 if (!GetRenderWidget()->ShouldHandleImeEvent())
1549 ImeEventGuard
guard(GetRenderWidget());
1550 frame_
->setEditableSelectionOffsets(start
, end
);
1553 void RenderFrameImpl::OnSetCompositionFromExistingText(
1555 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1556 if (!GetRenderWidget()->ShouldHandleImeEvent())
1558 ImeEventGuard
guard(GetRenderWidget());
1559 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1562 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1563 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1566 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1567 if (!GetRenderWidget()->ShouldHandleImeEvent())
1570 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1572 ImeEventGuard
guard(GetRenderWidget());
1573 blink::WebScopedUserGesture gesture_indicator
;
1574 frame_
->extendSelectionAndDelete(before
, after
);
1577 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1578 if (accessibility_mode_
== new_mode
)
1580 accessibility_mode_
= new_mode
;
1581 if (renderer_accessibility_
) {
1582 // Note: this isn't called automatically by the destructor because
1583 // there'd be no point in calling it in frame teardown, only if there's
1584 // an accessibility mode change but the frame is persisting.
1585 renderer_accessibility_
->DisableAccessibility();
1587 delete renderer_accessibility_
;
1588 renderer_accessibility_
= NULL
;
1590 if (accessibility_mode_
== AccessibilityModeOff
)
1593 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1594 renderer_accessibility_
= new RendererAccessibility(this);
1597 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1598 ui::AXTreeUpdate response
;
1599 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1600 Send(new AccessibilityHostMsg_SnapshotResponse(
1601 routing_id_
, callback_id
, response
));
1604 void RenderFrameImpl::OnDisownOpener() {
1605 // TODO(creis): We should only see this for main frames for now. To support
1606 // disowning the opener on subframes, we will need to move WebContentsImpl's
1607 // opener_ to FrameTreeNode.
1608 CHECK(!frame_
->parent());
1610 if (frame_
->opener())
1611 frame_
->setOpener(NULL
);
1614 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1615 frame_
->setFrameOwnerSandboxFlags(flags
);
1618 void RenderFrameImpl::OnTextTrackSettingsChanged(
1619 const FrameMsg_TextTrackSettings_Params
& params
) {
1620 DCHECK(!frame_
->parent());
1621 if (!render_view_
->webview())
1624 if (params
.text_tracks_enabled
) {
1625 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1626 WebSettings::TextTrackKindUserPreference::Captions
);
1628 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1629 WebSettings::TextTrackKindUserPreference::Default
);
1631 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1632 WebString::fromUTF8(params
.text_track_background_color
));
1633 render_view_
->webview()->settings()->setTextTrackFontFamily(
1634 WebString::fromUTF8(params
.text_track_font_family
));
1635 render_view_
->webview()->settings()->setTextTrackFontStyle(
1636 WebString::fromUTF8(params
.text_track_font_style
));
1637 render_view_
->webview()->settings()->setTextTrackFontVariant(
1638 WebString::fromUTF8(params
.text_track_font_variant
));
1639 render_view_
->webview()->settings()->setTextTrackTextColor(
1640 WebString::fromUTF8(params
.text_track_text_color
));
1641 render_view_
->webview()->settings()->setTextTrackTextShadow(
1642 WebString::fromUTF8(params
.text_track_text_shadow
));
1643 render_view_
->webview()->settings()->setTextTrackTextSize(
1644 WebString::fromUTF8(params
.text_track_text_size
));
1647 void RenderFrameImpl::OnPostMessageEvent(
1648 const FrameMsg_PostMessage_Params
& params
) {
1649 // Find the source frame if it exists.
1650 WebFrame
* source_frame
= NULL
;
1651 if (params
.source_view_routing_id
!= MSG_ROUTING_NONE
) {
1652 // Support a legacy postMessage path for specifying a source RenderView;
1653 // this is currently used when sending messages to Android WebView.
1654 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1655 RenderViewImpl
* source_view
=
1656 RenderViewImpl::FromRoutingID(params
.source_view_routing_id
);
1658 source_frame
= source_view
->webview()->mainFrame();
1659 } else if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1660 RenderFrameProxy
* source_proxy
=
1661 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1663 // Currently, navigating a top-level frame cross-process does not swap
1664 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1665 // WebRemoteFrame will not have an associated blink::Frame. If this is
1666 // the case for |source_proxy|, use the corresponding (swapped-out)
1667 // WebLocalFrame instead, so that event.source for this message can be
1668 // set and used properly.
1669 if (source_proxy
->IsMainFrameDetachedFromTree())
1670 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1672 source_frame
= source_proxy
->web_frame();
1676 // If the message contained MessagePorts, create the corresponding endpoints.
1677 blink::WebMessagePortChannelArray channels
=
1678 WebMessagePortChannelImpl::CreatePorts(
1679 params
.message_ports
, params
.new_routing_ids
,
1680 base::ThreadTaskRunnerHandle::Get().get());
1682 WebSerializedScriptValue serialized_script_value
;
1683 if (params
.is_data_raw_string
) {
1684 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1685 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1686 v8::Context::Scope
context_scope(context
);
1687 V8ValueConverterImpl converter
;
1688 converter
.SetDateAllowed(true);
1689 converter
.SetRegExpAllowed(true);
1690 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1691 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1693 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1695 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1698 // Create an event with the message. The next-to-last parameter to
1699 // initMessageEvent is the last event ID, which is not used with postMessage.
1700 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1701 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1702 msg_event
.initMessageEvent("message",
1703 // |canBubble| and |cancellable| are always false
1705 serialized_script_value
,
1706 params
.source_origin
, source_frame
, "", channels
);
1708 // We must pass in the target_origin to do the security check on this side,
1709 // since it may have changed since the original postMessage call was made.
1710 WebSecurityOrigin target_origin
;
1711 if (!params
.target_origin
.empty()) {
1713 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1715 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1718 #if defined(OS_ANDROID)
1719 void RenderFrameImpl::OnSelectPopupMenuItems(
1721 const std::vector
<int>& selected_indices
) {
1722 // It is possible to receive more than one of these calls if the user presses
1723 // a select faster than it takes for the show-select-popup IPC message to make
1724 // it to the browser UI thread. Ignore the extra-messages.
1725 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1726 if (!external_popup_menu_
)
1729 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1730 external_popup_menu_
.reset();
1734 #if defined(OS_MACOSX)
1735 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1736 if (external_popup_menu_
== NULL
)
1738 external_popup_menu_
->DidSelectItem(selected_index
);
1739 external_popup_menu_
.reset();
1743 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1744 frame_
->reload(ignore_cache
);
1747 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1748 blink::WebSurroundingText surroundingText
;
1749 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1751 if (surroundingText
.isNull()) {
1752 // |surroundingText| might not be correctly initialized, for example if
1753 // |frame_->selectionRange().isNull()|, in other words, if there was no
1755 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1756 routing_id_
, base::string16(), 0, 0));
1760 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1762 surroundingText
.textContent(),
1763 surroundingText
.startOffsetInTextContent(),
1764 surroundingText
.endOffsetInTextContent()));
1767 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1768 const base::string16
& message
,
1769 const base::string16
& default_value
,
1770 const GURL
& frame_url
,
1771 base::string16
* result
) {
1772 // Don't allow further dialogs if we are waiting to swap out, since the
1773 // PageGroupLoadDeferrer in our stack prevents it.
1774 if (render_view()->suppress_dialogs_until_swap_out_
)
1777 bool success
= false;
1778 base::string16 result_temp
;
1780 result
= &result_temp
;
1782 render_view()->SendAndRunNestedMessageLoop(
1783 new FrameHostMsg_RunJavaScriptMessage(
1784 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1789 void RenderFrameImpl::LoadNavigationErrorPage(
1790 const WebURLRequest
& failed_request
,
1791 const WebURLError
& error
,
1793 std::string error_html
;
1794 GetContentClient()->renderer()->GetNavigationErrorStrings(
1795 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1797 frame_
->loadHTMLString(error_html
,
1798 GURL(kUnreachableWebDataURL
),
1799 error
.unreachableURL
,
1803 void RenderFrameImpl::DidCommitCompositorFrame() {
1804 if (BrowserPluginManager::Get())
1805 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1807 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1810 RenderView
* RenderFrameImpl::GetRenderView() {
1811 return render_view_
.get();
1814 int RenderFrameImpl::GetRoutingID() {
1818 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1823 WebElement
RenderFrameImpl::GetFocusedElement() const {
1824 WebDocument doc
= frame_
->document();
1826 return doc
.focusedElement();
1828 return WebElement();
1831 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1832 return render_view_
->GetWebkitPreferences();
1835 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1836 const ContextMenuParams
& params
) {
1837 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1838 ContextMenuParams
our_params(params
);
1839 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1840 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1841 return our_params
.custom_context
.request_id
;
1844 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1845 DCHECK(pending_context_menus_
.Lookup(request_id
));
1846 pending_context_menus_
.Remove(request_id
);
1849 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1850 return context_menu_node_
;
1853 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1854 blink::WebFrame
* frame
,
1855 const WebPluginInfo
& info
,
1856 const blink::WebPluginParams
& params
,
1857 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1858 DCHECK_EQ(frame_
, frame
);
1859 #if defined(ENABLE_PLUGINS)
1860 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1861 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1862 this, GetContentClient()
1864 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1869 bool pepper_plugin_was_registered
= false;
1870 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1871 this, info
, &pepper_plugin_was_registered
));
1872 if (pepper_plugin_was_registered
) {
1873 if (pepper_module
.get()) {
1874 return new PepperWebPluginImpl(
1875 pepper_module
.get(), params
, this,
1877 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1880 #if defined(OS_CHROMEOS)
1881 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1883 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1884 // TODO(jam): change to take RenderFrame.
1885 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1892 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1893 const blink::WebURLRequest
& request
,
1894 blink::WebNavigationPolicy policy
) {
1895 DCHECK(!frame_
|| frame_
== frame
);
1896 loadURLExternally(frame
, request
, policy
, WebString());
1899 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1900 OnJavaScriptExecuteRequest(javascript
, 0, false);
1903 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1904 return &service_registry_
;
1907 #if defined(ENABLE_PLUGINS)
1908 void RenderFrameImpl::RegisterPeripheralPlugin(
1909 const GURL
& content_origin
,
1910 const base::Closure
& unthrottle_callback
) {
1911 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1912 content_origin
, unthrottle_callback
);
1914 #endif // defined(ENABLE_PLUGINS)
1916 bool RenderFrameImpl::IsFTPDirectoryListing() {
1917 WebURLResponseExtraDataImpl
* extra_data
=
1918 GetExtraDataFromResponse(frame_
->dataSource()->response());
1919 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1922 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1923 BrowserPluginManager::Get()->Attach(element_instance_id
);
1926 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1927 BrowserPluginManager::Get()->Detach(element_instance_id
);
1930 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1932 const gfx::Range
& range
) {
1933 // Use the routing id of Render Widget Host.
1934 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1940 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1941 v8::Isolate
* isolate
,
1942 v8::Local
<v8::Context
> context
) {
1943 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1944 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1947 v8::HandleScope
handle_scope(isolate
);
1948 registry
->AddBuiltinModule(
1949 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1950 registry
->AddBuiltinModule(isolate
,
1951 mojo::js::Support::kModuleName
,
1952 mojo::js::Support::GetModule(isolate
));
1953 registry
->AddBuiltinModule(
1955 ServiceRegistryJsWrapper::kModuleName
,
1956 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1959 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
1960 const std::string
& message
) {
1961 if (devtools_agent_
)
1962 devtools_agent_
->AddMessageToConsole(level
, message
);
1965 // blink::WebFrameClient implementation ----------------------------------------
1967 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1968 blink::WebLocalFrame
* frame
,
1969 const blink::WebPluginParams
& params
) {
1970 DCHECK_EQ(frame_
, frame
);
1971 return GetContentClient()
1973 ->CreatePluginPlaceholder(this, frame
, params
)
1977 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1978 blink::WebLocalFrame
* frame
,
1979 const blink::WebPluginParams
& params
) {
1980 DCHECK_EQ(frame_
, frame
);
1981 blink::WebPlugin
* plugin
= NULL
;
1982 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1983 this, frame
, params
, &plugin
)) {
1987 if (base::UTF16ToUTF8(base::StringPiece16(params
.mimeType
)) ==
1988 kBrowserPluginMimeType
) {
1989 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1990 this, GetContentClient()
1992 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
1997 #if defined(ENABLE_PLUGINS)
1999 std::string mime_type
;
2001 Send(new FrameHostMsg_GetPluginInfo(
2002 routing_id_
, params
.url
, frame
->top()->document().url(),
2003 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
2007 WebPluginParams params_to_use
= params
;
2008 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2009 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2012 #endif // defined(ENABLE_PLUGINS)
2015 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2016 blink::WebLocalFrame
* frame
,
2017 const blink::WebURL
& url
,
2018 WebMediaPlayerClient
* client
,
2019 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
2020 WebContentDecryptionModule
* initial_cdm
) {
2021 #if defined(VIDEO_HOLE)
2022 if (!contains_media_player_
) {
2023 render_view_
->RegisterVideoHoleFrame(this);
2024 contains_media_player_
= true;
2026 #endif // defined(VIDEO_HOLE)
2028 blink::WebMediaStream
web_stream(
2029 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2030 if (!web_stream
.isNull())
2031 return CreateWebMediaPlayerForMediaStream(client
);
2033 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2034 return CreateAndroidWebMediaPlayer(client
, encrypted_client
,
2035 GetMediaPermission(), initial_cdm
);
2037 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2039 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2040 media::WebMediaPlayerParams
params(
2041 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2042 base::Unretained(GetContentClient()->renderer()),
2043 static_cast<RenderFrame
*>(this)),
2044 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2045 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2046 render_thread
->compositor_task_runner(),
2047 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2050 #if defined(ENABLE_MOJO_MEDIA)
2051 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2052 new media::MojoRendererFactory(GetMediaServiceFactory()));
2054 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2055 GetContentClient()->renderer()->CreateMediaRendererFactory(
2056 this, render_thread
->GetGpuFactories(), media_log
);
2058 if (!media_renderer_factory
.get()) {
2059 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2060 media_log
, render_thread
->GetGpuFactories(),
2061 *render_thread
->GetAudioHardwareConfig()));
2063 #endif // defined(ENABLE_MOJO_MEDIA)
2065 return new media::WebMediaPlayerImpl(
2066 frame
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
2067 media_renderer_factory
.Pass(), GetCdmFactory(), params
);
2068 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2071 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2072 blink::WebLocalFrame
* frame
,
2073 blink::WebApplicationCacheHostClient
* client
) {
2074 if (!frame
|| !frame
->view())
2076 DCHECK(!frame_
|| frame_
== frame
);
2077 return new RendererWebApplicationCacheHostImpl(
2078 RenderViewImpl::FromWebView(frame
->view()), client
,
2079 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2082 blink::WebWorkerContentSettingsClientProxy
*
2083 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2084 blink::WebLocalFrame
* frame
) {
2085 if (!frame
|| !frame
->view())
2087 DCHECK(!frame_
|| frame_
== frame
);
2088 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2092 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2093 const WebPopupMenuInfo
& popup_menu_info
,
2094 WebExternalPopupMenuClient
* popup_menu_client
) {
2095 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2096 // An IPC message is sent to the browser to build and display the actual
2097 // popup. The user could have time to click a different select by the time
2098 // the popup is shown. In that case external_popup_menu_ is non NULL.
2099 // By returning NULL in that case, we instruct Blink to cancel that new
2100 // popup. So from the user perspective, only the first one will show, and
2101 // will have to close the first one before another one can be shown.
2102 if (external_popup_menu_
)
2104 external_popup_menu_
.reset(
2105 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2106 if (render_view_
->screen_metrics_emulator_
) {
2107 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2108 external_popup_menu_
.get(),
2109 render_view_
->screen_metrics_emulator_
.get());
2111 return external_popup_menu_
.get();
2117 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2118 DCHECK(!frame_
|| frame_
== frame
);
2119 return &cookie_jar_
;
2122 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2123 blink::WebLocalFrame
* frame
) {
2124 DCHECK(!frame_
|| frame_
== frame
);
2125 // At this point we should have non-null data source.
2126 DCHECK(frame
->dataSource());
2127 if (!ChildThreadImpl::current())
2128 return NULL
; // May be null in some tests.
2129 ServiceWorkerNetworkProvider
* provider
=
2130 ServiceWorkerNetworkProvider::FromDocumentState(
2131 DocumentState::FromDataSource(frame
->dataSource()));
2133 return new WebServiceWorkerProviderImpl(
2134 ChildThreadImpl::current()->thread_safe_sender(),
2135 provider
->context());
2138 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2139 DCHECK(!frame_
|| frame_
== frame
);
2140 // If the request hasn't yet committed, notify the browser process that it is
2141 // no longer safe to show the pending URL of the main frame, since a URL spoof
2142 // is now possible. (If the request has committed, the browser already knows.)
2143 if (!frame
->parent()) {
2144 DocumentState
* document_state
=
2145 DocumentState::FromDataSource(frame
->dataSource());
2146 NavigationStateImpl
* navigation_state
=
2147 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2149 if (!navigation_state
->request_committed()) {
2150 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2155 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2156 blink::WebLocalFrame
* parent
,
2157 blink::WebTreeScopeType scope
,
2158 const blink::WebString
& name
,
2159 blink::WebSandboxFlags sandbox_flags
) {
2160 // Synchronously notify the browser of a child frame creation to get the
2161 // routing_id for the RenderFrame.
2162 int child_routing_id
= MSG_ROUTING_NONE
;
2163 Send(new FrameHostMsg_CreateChildFrame(
2165 base::UTF16ToUTF8(base::StringPiece16(name
)), sandbox_flags
,
2166 &child_routing_id
));
2168 // Allocation of routing id failed, so we can't create a child frame. This can
2169 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2170 // out state or synchronous IPC message above has failed.
2171 if (child_routing_id
== MSG_ROUTING_NONE
) {
2172 NOTREACHED() << "Failed to allocate routing id for child frame.";
2176 // Create the RenderFrame and WebLocalFrame, linking the two.
2177 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2178 render_view_
.get(), child_routing_id
);
2179 blink::WebLocalFrame
* web_frame
=
2180 WebLocalFrame::create(scope
, child_render_frame
);
2181 child_render_frame
->SetWebFrame(web_frame
);
2183 // Add the frame to the frame tree and initialize it.
2184 parent
->appendChild(web_frame
);
2185 child_render_frame
->Initialize();
2190 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2191 DCHECK(!frame_
|| frame_
== frame
);
2192 // We only need to notify the browser if the active, top-level frame clears
2193 // its opener. We can ignore cases where a swapped out frame clears its
2194 // opener after hearing about it from the browser, and the browser does not
2195 // (yet) care about subframe openers.
2196 if (is_swapped_out_
|| frame
->parent())
2199 // Notify WebContents and all its swapped out RenderViews.
2200 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2203 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2204 // NOTE: This function is called on the frame that is being detached and not
2205 // the parent frame. This is different from createChildFrame() which is
2206 // called on the parent frame.
2207 CHECK(!is_detaching_
);
2208 DCHECK(!frame_
|| frame_
== frame
);
2210 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2211 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2212 FrameDetached(frame
));
2214 // We only notify the browser process when the frame is being detached for
2215 // removal. If the frame is being detached for swap, we don't need to do this
2216 // since we are not modifiying the frame tree.
2217 if (type
== DetachType::Remove
)
2218 Send(new FrameHostMsg_Detach(routing_id_
));
2220 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2221 // sent before setting |is_detaching_| to true.
2222 is_detaching_
= true;
2224 // Clean up the associated RenderWidget for the frame, if there is one.
2225 if (render_widget_
) {
2226 render_widget_
->UnregisterRenderFrame(this);
2227 render_widget_
->CloseForFrame();
2230 // We need to clean up subframes by removing them from the map and deleting
2231 // the RenderFrameImpl. In contrast, the main frame is owned by its
2232 // containing RenderViewHost (so that they have the same lifetime), so only
2233 // removal from the map is needed and no deletion.
2234 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2235 CHECK(it
!= g_frame_map
.Get().end());
2236 CHECK_EQ(it
->second
, this);
2237 g_frame_map
.Get().erase(it
);
2239 // Only remove the frame from the renderer's frame tree if the frame is
2240 // being detached for removal. In the case of a swap, the frame needs to
2241 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2242 if (is_subframe_
&& type
== DetachType::Remove
)
2243 frame
->parent()->removeChild(frame
);
2245 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2246 // object may not be deleted immediately and other methods may try to access
2252 // Object is invalid after this point.
2255 void RenderFrameImpl::frameFocused() {
2256 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2259 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2260 DCHECK(!frame_
|| frame_
== frame
);
2262 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2263 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2264 FrameWillClose(frame
));
2267 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2268 const blink::WebString
& name
) {
2269 DCHECK(!frame_
|| frame_
== frame
);
2271 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2272 // updates may have performance implications for benchmarks like SunSpider.
2273 // For now, send these updates only for --site-per-process, which needs to
2274 // replicate frame names to frame proxies, and when
2275 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2276 // can be optimized further by only sending the update if there are any
2277 // remote frames in the frame tree, or delaying and batching up IPCs if
2278 // updates are happening too frequently.
2279 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2280 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2281 Send(new FrameHostMsg_DidChangeName(
2282 routing_id_
, base::UTF16ToUTF8(base::StringPiece16(name
))));
2286 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2287 blink::WebSandboxFlags flags
) {
2288 int frame_routing_id
= MSG_ROUTING_NONE
;
2289 if (child_frame
->isWebRemoteFrame()) {
2291 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2294 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2297 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2301 void RenderFrameImpl::didMatchCSS(
2302 blink::WebLocalFrame
* frame
,
2303 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2304 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2305 DCHECK(!frame_
|| frame_
== frame
);
2307 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2308 DidMatchCSS(newly_matching_selectors
,
2309 stopped_matching_selectors
));
2312 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2313 const blink::WebString
& source
) {
2314 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2318 void RenderFrameImpl::didAddMessageToConsole(
2319 const blink::WebConsoleMessage
& message
,
2320 const blink::WebString
& source_name
,
2321 unsigned source_line
,
2322 const blink::WebString
& stack_trace
) {
2323 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2324 switch (message
.level
) {
2325 case blink::WebConsoleMessage::LevelDebug
:
2326 log_severity
= logging::LOG_VERBOSE
;
2328 case blink::WebConsoleMessage::LevelLog
:
2329 case blink::WebConsoleMessage::LevelInfo
:
2330 log_severity
= logging::LOG_INFO
;
2332 case blink::WebConsoleMessage::LevelWarning
:
2333 log_severity
= logging::LOG_WARNING
;
2335 case blink::WebConsoleMessage::LevelError
:
2336 log_severity
= logging::LOG_ERROR
;
2339 log_severity
= logging::LOG_VERBOSE
;
2342 if (shouldReportDetailedMessageForSource(source_name
)) {
2344 RenderFrameObserver
, observers_
,
2345 DetailedConsoleMessageAdded(message
.text
,
2349 static_cast<int32
>(log_severity
)));
2352 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2353 static_cast<int32
>(log_severity
),
2355 static_cast<int32
>(source_line
),
2359 void RenderFrameImpl::loadURLExternally(
2360 blink::WebLocalFrame
* frame
,
2361 const blink::WebURLRequest
& request
,
2362 blink::WebNavigationPolicy policy
,
2363 const blink::WebString
& suggested_name
) {
2364 DCHECK(!frame_
|| frame_
== frame
);
2365 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2366 if (policy
== blink::WebNavigationPolicyDownload
) {
2367 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2368 request
.url(), referrer
,
2371 OpenURL(frame
, request
.url(), referrer
, policy
);
2375 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2376 const NavigationPolicyInfo
& info
) {
2377 DCHECK(!frame_
|| frame_
== info
.frame
);
2378 return DecidePolicyForNavigation(this, info
);
2381 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2382 blink::WebFrame
* frame
) {
2383 DCHECK(!frame_
|| frame_
== frame
);
2384 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2387 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2388 const blink::WebFormElement
& form
) {
2389 DCHECK(!frame_
|| frame_
== frame
);
2391 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2394 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2395 const blink::WebFormElement
& form
) {
2396 DCHECK(!frame_
|| frame_
== frame
);
2397 DocumentState
* document_state
=
2398 DocumentState::FromDataSource(frame
->provisionalDataSource());
2399 NavigationStateImpl
* navigation_state
=
2400 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2401 InternalDocumentStateData
* internal_data
=
2402 InternalDocumentStateData::FromDocumentState(document_state
);
2404 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2405 ui::PAGE_TRANSITION_LINK
)) {
2406 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2409 // Save these to be processed when the ensuing navigation is committed.
2410 WebSearchableFormData
web_searchable_form_data(form
);
2411 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2412 internal_data
->set_searchable_form_encoding(
2413 web_searchable_form_data
.encoding().utf8());
2415 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2418 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2419 blink::WebDataSource
* datasource
) {
2420 DCHECK(!frame_
|| frame_
== frame
);
2422 bool content_initiated
= !pending_navigation_params_
.get();
2424 // Make sure any previous redirect URLs end up in our new data source.
2425 if (pending_navigation_params_
.get()) {
2426 for (const auto& i
:
2427 pending_navigation_params_
->request_params
.redirects
) {
2428 datasource
->appendRedirect(i
);
2432 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2433 if (!document_state
) {
2434 document_state
= new DocumentState
;
2435 datasource
->setExtraData(document_state
);
2436 if (!content_initiated
)
2437 PopulateDocumentStateFromPending(document_state
);
2440 // Carry over the user agent override flag, if it exists.
2441 blink::WebView
* webview
= render_view_
->webview();
2442 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2443 webview
->mainFrame()->isWebLocalFrame() &&
2444 webview
->mainFrame()->dataSource()) {
2445 DocumentState
* old_document_state
=
2446 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2447 if (old_document_state
) {
2448 InternalDocumentStateData
* internal_data
=
2449 InternalDocumentStateData::FromDocumentState(document_state
);
2450 InternalDocumentStateData
* old_internal_data
=
2451 InternalDocumentStateData::FromDocumentState(old_document_state
);
2452 internal_data
->set_is_overriding_user_agent(
2453 old_internal_data
->is_overriding_user_agent());
2457 // The rest of RenderView assumes that a WebDataSource will always have a
2458 // non-null NavigationState.
2459 if (content_initiated
) {
2460 document_state
->set_navigation_state(
2461 NavigationStateImpl::CreateContentInitiated());
2463 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2464 pending_navigation_params_
.reset();
2467 // DocumentState::referred_by_prefetcher_ is true if we are
2468 // navigating from a page that used prefetching using a link on that
2469 // page. We are early enough in the request process here that we
2470 // can still see the DocumentState of the previous page and set
2471 // this value appropriately.
2472 // TODO(gavinp): catch the important case of navigation in a new
2473 // renderer process.
2475 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2476 const WebURLRequest
& original_request
= datasource
->originalRequest();
2477 const GURL
referrer(
2478 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2479 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2480 DocumentState::FromDataSource(old_frame
->dataSource())
2481 ->was_prefetcher()) {
2482 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2483 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2484 if (old_frame_datasource
&&
2485 referrer
== GURL(old_frame_datasource
->request().url())) {
2486 document_state
->set_was_referred_by_prefetcher(true);
2494 if (content_initiated
) {
2495 const WebURLRequest
& request
= datasource
->request();
2496 switch (request
.cachePolicy()) {
2497 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2498 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2500 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2501 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2502 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2504 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2505 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2507 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2508 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2515 // Create the serviceworker's per-document network observing object if it
2516 // does not exist (When navigation happens within a page, the provider already
2518 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2519 DocumentState::FromDataSource(datasource
))) {
2520 ServiceWorkerProviderType provider_type
=
2521 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2522 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2523 blink::WebSandboxFlags::Origin
) {
2524 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2526 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2527 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2528 ServiceWorkerNetworkProvider::AttachToDocumentState(
2529 DocumentState::FromDataSource(datasource
),
2530 network_provider
.Pass());
2534 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2535 double triggering_event_time
) {
2536 DCHECK(!frame_
|| frame_
== frame
);
2537 WebDataSource
* ds
= frame
->provisionalDataSource();
2539 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2540 // callback is invoked.
2544 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2545 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2546 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2548 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2549 CHECK_IMPLIES(ds
->request().url() == GURL(kSwappedOutURL
), is_swapped_out_
)
2550 << "Heard swappedout:// when not swapped out.";
2552 // Update the request time if WebKit has better knowledge of it.
2553 if (document_state
->request_time().is_null() &&
2554 triggering_event_time
!= 0.0) {
2555 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2558 // Start time is only set after request time.
2559 document_state
->set_start_load_time(Time::Now());
2561 bool is_top_most
= !frame
->parent();
2563 render_view_
->set_navigation_gesture(
2564 WebUserGestureIndicator::isProcessingUserGesture() ?
2565 NavigationGestureUser
: NavigationGestureAuto
);
2566 } else if (ds
->replacesCurrentHistoryItem()) {
2567 // Subframe navigations that don't add session history items must be
2568 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2569 // handle loading of error pages.
2570 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2571 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2574 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2575 DidStartProvisionalLoad(frame
));
2576 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2578 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2579 routing_id_
, ds
->request().url()));
2582 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2583 blink::WebLocalFrame
* frame
) {
2584 DCHECK(!frame_
|| frame_
== frame
);
2585 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2588 void RenderFrameImpl::didFailProvisionalLoad(
2589 blink::WebLocalFrame
* frame
,
2590 const blink::WebURLError
& error
,
2591 blink::WebHistoryCommitType commit_type
) {
2592 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2594 DCHECK(!frame_
|| frame_
== frame
);
2595 WebDataSource
* ds
= frame
->provisionalDataSource();
2598 const WebURLRequest
& failed_request
= ds
->request();
2600 // Notify the browser that we failed a provisional load with an error.
2602 // Note: It is important this notification occur before DidStopLoading so the
2603 // SSL manager can react to the provisional load failure before being
2604 // notified the load stopped.
2606 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2607 DidFailProvisionalLoad(frame
, error
));
2608 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2609 DidFailProvisionalLoad(error
));
2611 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2613 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2616 // Make sure we never show errors in view source mode.
2617 frame
->enableViewSourceMode(false);
2619 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2620 NavigationStateImpl
* navigation_state
=
2621 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2623 // If this is a failed back/forward/reload navigation, then we need to do a
2624 // 'replace' load. This is necessary to avoid messing up session history.
2625 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2626 // as session history is concerned.
2627 bool replace
= commit_type
!= blink::WebStandardCommit
;
2629 // If we failed on a browser initiated request, then make sure that our error
2630 // page load is regarded as the same browser initiated request.
2631 if (!navigation_state
->IsContentInitiated()) {
2632 pending_navigation_params_
.reset(new NavigationParams(
2633 navigation_state
->common_params(), navigation_state
->start_params(),
2634 navigation_state
->request_params()));
2635 pending_navigation_params_
->request_params
.request_time
=
2636 document_state
->request_time();
2639 // Load an error page.
2640 LoadNavigationErrorPage(failed_request
, error
, replace
);
2643 void RenderFrameImpl::didCommitProvisionalLoad(
2644 blink::WebLocalFrame
* frame
,
2645 const blink::WebHistoryItem
& item
,
2646 blink::WebHistoryCommitType commit_type
) {
2647 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2649 "url", GetLoadingUrl().possibly_invalid_spec());
2650 DCHECK(!frame_
|| frame_
== frame
);
2651 DocumentState
* document_state
=
2652 DocumentState::FromDataSource(frame
->dataSource());
2653 NavigationStateImpl
* navigation_state
=
2654 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2656 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2657 RenderFrameProxy
* proxy
=
2658 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2660 proxy
->web_frame()->swap(frame_
);
2661 proxy_routing_id_
= MSG_ROUTING_NONE
;
2663 // If this is the main frame going from a remote frame to a local frame,
2664 // it needs to set RenderViewImpl's pointer for the main frame to itself
2665 // and ensure RenderWidget is no longer in swapped out mode.
2666 if (!is_subframe_
) {
2667 CHECK(!render_view_
->main_render_frame_
);
2668 render_view_
->main_render_frame_
= this;
2669 if (render_view_
->is_swapped_out())
2670 render_view_
->SetSwappedOut(false);
2674 // When we perform a new navigation, we need to update the last committed
2675 // session history entry with state for the page we are leaving. Do this
2676 // before updating the HistoryController state.
2677 render_view_
->SendUpdateState();
2679 render_view_
->history_controller()->UpdateForCommit(
2680 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2682 InternalDocumentStateData
* internal_data
=
2683 InternalDocumentStateData::FromDocumentState(document_state
);
2685 if (document_state
->commit_load_time().is_null())
2686 document_state
->set_commit_load_time(Time::Now());
2688 if (internal_data
->must_reset_scroll_and_scale_state()) {
2689 render_view_
->webview()->resetScrollAndScaleState();
2690 internal_data
->set_must_reset_scroll_and_scale_state(false);
2693 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2694 if (is_new_navigation
) {
2695 // We bump our Page ID to correspond with the new session history entry.
2696 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2698 // Don't update history list values for kSwappedOutURL, since
2699 // we don't want to forget the entry that was there, and since we will
2700 // never come back to kSwappedOutURL. Note that we have to call
2701 // SendUpdateState and update page_id_ even in this case, so that
2702 // the current entry gets a state update and so that we don't send a
2703 // state update to the wrong entry when we swap back in.
2705 navigation_state
->common_params().should_replace_current_entry
,
2706 render_view_
->history_list_length_
> 0);
2707 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2708 !navigation_state
->common_params().should_replace_current_entry
) {
2709 // Advance our offset in session history, applying the length limit.
2710 // There is now no forward history.
2711 render_view_
->history_list_offset_
++;
2712 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2713 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2714 render_view_
->history_list_length_
=
2715 render_view_
->history_list_offset_
+ 1;
2718 const RequestNavigationParams
& request_params
=
2719 navigation_state
->request_params();
2720 if (request_params
.nav_entry_id
!= 0 &&
2721 !request_params
.intended_as_new_entry
) {
2722 // This is a successful session history navigation!
2723 render_view_
->page_id_
= request_params
.page_id
;
2725 render_view_
->history_list_offset_
=
2726 request_params
.pending_history_list_offset
;
2731 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2732 CHECK(sent
); // http://crbug.com/407376
2734 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2735 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2737 RenderFrameObserver
, observers_
,
2738 DidCommitProvisionalLoad(is_new_navigation
,
2739 navigation_state
->WasWithinSamePage()));
2741 if (!frame
->parent()) { // Only for top frames.
2742 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2743 if (render_thread_impl
) { // Can be NULL in tests.
2744 render_thread_impl
->histogram_customizer()->
2745 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2746 RenderView::GetRenderViewCount());
2750 // Remember that we've already processed this request, so we don't update
2751 // the session history again. We do this regardless of whether this is
2752 // a session history navigation, because if we attempted a session history
2753 // navigation without valid HistoryItem state, WebCore will think it is a
2755 navigation_state
->set_request_committed(true);
2757 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2759 // Check whether we have new encoding name.
2760 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2763 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2764 DCHECK(!frame_
|| frame_
== frame
);
2766 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2767 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2768 DidCreateNewDocument(frame
));
2771 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2772 DCHECK(!frame_
|| frame_
== frame
);
2774 int enabled_bindings
= render_view_
->GetEnabledBindings();
2776 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2777 WebUIExtension::Install(frame
);
2779 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2780 DomAutomationController::Install(this, frame
);
2782 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2783 StatsCollectionController::Install(frame
);
2785 const base::CommandLine
& command_line
=
2786 *base::CommandLine::ForCurrentProcess();
2788 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2789 GpuBenchmarking::Install(frame
);
2791 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2792 MemoryBenchmarkingExtension::Install(frame
);
2794 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2795 SkiaBenchmarking::Install(frame
);
2797 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2798 DidClearWindowObject(frame
));
2799 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2802 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2803 DCHECK(!frame_
|| frame_
== frame
);
2805 // Notify the browser about non-blank documents loading in the top frame.
2806 GURL url
= frame
->document().url();
2807 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2808 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2809 // frame->tree()->top().
2810 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2811 if (frame
== main_frame
) {
2812 // For now, don't remember plugin zoom values. We don't want to mix them
2813 // with normal web content (i.e. a fixed layout plugin would usually want
2815 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2816 render_view_
->GetRoutingID(),
2817 main_frame
->document().isPluginDocument()));
2821 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2822 DidCreateDocumentElement());
2823 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2824 DidCreateDocumentElement(frame
));
2827 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2828 const blink::WebString
& title
,
2829 blink::WebTextDirection direction
) {
2830 DCHECK(!frame_
|| frame_
== frame
);
2831 // Ignore all but top level navigations.
2832 if (!frame
->parent()) {
2833 base::string16 title16
= title
;
2834 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2835 routing_id_
, base::UTF16ToUTF8(title16
));
2837 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2838 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2839 shortened_title
, direction
));
2842 // Also check whether we have new encoding name.
2843 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2846 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2847 blink::WebIconURL::Type icon_type
) {
2848 DCHECK(!frame_
|| frame_
== frame
);
2849 // TODO(nasko): Investigate wheather implementation should move here.
2850 render_view_
->didChangeIcon(frame
, icon_type
);
2853 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
,
2854 bool document_is_empty
) {
2855 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2857 DCHECK(!frame_
|| frame_
== frame
);
2858 WebDataSource
* ds
= frame
->dataSource();
2859 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2860 document_state
->set_finish_document_load_time(Time::Now());
2862 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2864 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2865 DidFinishDocumentLoad(frame
));
2866 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2868 // Check whether we have new encoding name.
2869 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2871 // If this is an empty document with an http status code indicating an error,
2872 // we may want to display our own error page, so the user doesn't end up
2873 // with an unexplained blank page.
2874 if (!document_is_empty
)
2877 // Do not show error page when DevTools is attached.
2878 RenderFrameImpl
* localRoot
= this;
2879 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
2880 localRoot
->frame_
->parent()->isWebLocalFrame()) {
2881 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
2884 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
2887 // Display error page instead of a blank page, if appropriate.
2888 std::string error_domain
= "http";
2889 InternalDocumentStateData
* internal_data
=
2890 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2891 int http_status_code
= internal_data
->http_status_code();
2892 if (GetContentClient()->renderer()->HasErrorPage(http_status_code
,
2895 error
.unreachableURL
= frame
->document().url();
2896 error
.domain
= WebString::fromUTF8(error_domain
);
2897 error
.reason
= http_status_code
;
2898 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
2902 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2903 DCHECK(!frame_
|| frame_
== frame
);
2904 if (!frame
->parent()) {
2905 FrameMsg_UILoadMetricsReportType::Value report_type
=
2906 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2907 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2908 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2909 base::TimeDelta::FromSecondsD(
2910 frame
->dataSource()->request().uiStartTime());
2912 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2913 routing_id_
, report_type
, ui_timestamp
));
2917 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2918 const blink::WebURLError
& error
,
2919 blink::WebHistoryCommitType commit_type
) {
2920 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2922 DCHECK(!frame_
|| frame_
== frame
);
2923 // TODO(nasko): Move implementation here. No state needed.
2924 WebDataSource
* ds
= frame
->dataSource();
2927 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2928 DidFailLoad(frame
, error
));
2930 const WebURLRequest
& failed_request
= ds
->request();
2931 base::string16 error_description
;
2932 GetContentClient()->renderer()->GetNavigationErrorStrings(
2938 &error_description
);
2939 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2940 failed_request
.url(),
2943 error
.wasIgnoredByHandler
));
2946 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2947 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2949 DCHECK(!frame_
|| frame_
== frame
);
2950 WebDataSource
* ds
= frame
->dataSource();
2951 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2952 if (document_state
->finish_load_time().is_null()) {
2953 if (!frame
->parent()) {
2954 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2955 TRACE_EVENT_SCOPE_PROCESS
);
2957 document_state
->set_finish_load_time(Time::Now());
2960 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2961 DidFinishLoad(frame
));
2962 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2964 // Don't send this message while the frame is swapped out.
2965 if (is_swapped_out())
2968 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2969 ds
->request().url()));
2972 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2973 const blink::WebHistoryItem
& item
,
2974 blink::WebHistoryCommitType commit_type
) {
2975 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2977 DCHECK(!frame_
|| frame_
== frame
);
2978 // If this was a reference fragment navigation that we initiated, then we
2979 // could end up having a non-null pending navigation params. We just need to
2980 // update the ExtraData on the datasource so that others who read the
2981 // ExtraData will get the new NavigationState. Similarly, if we did not
2982 // initiate this navigation, then we need to take care to reset any pre-
2983 // existing navigation state to a content-initiated navigation state.
2984 // didCreateDataSource conveniently takes care of this for us.
2985 didCreateDataSource(frame
, frame
->dataSource());
2987 DocumentState
* document_state
=
2988 DocumentState::FromDataSource(frame
->dataSource());
2989 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2990 ->set_was_within_same_page(true);
2992 didCommitProvisionalLoad(frame
, item
, commit_type
);
2995 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2996 DCHECK(!frame_
|| frame_
== frame
);
2997 // TODO(nasko): Move implementation here. Needed methods:
2998 // * StartNavStateSyncTimerIfNecessary
2999 render_view_
->didUpdateCurrentHistoryItem(frame
);
3002 void RenderFrameImpl::didChangeThemeColor() {
3003 if (frame_
->parent())
3006 Send(new FrameHostMsg_DidChangeThemeColor(
3007 routing_id_
, frame_
->document().themeColor()));
3010 void RenderFrameImpl::dispatchLoad() {
3011 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
3014 void RenderFrameImpl::requestNotificationPermission(
3015 const blink::WebSecurityOrigin
& origin
,
3016 blink::WebNotificationPermissionCallback
* callback
) {
3017 if (!notification_permission_dispatcher_
) {
3018 notification_permission_dispatcher_
=
3019 new NotificationPermissionDispatcher(this);
3022 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3025 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3026 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3029 if (is_empty_selection
)
3030 selection_text_
.clear();
3032 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3033 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3034 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3035 // to notify the selection was changed. Focus change should be notified
3036 // before selection change.
3037 GetRenderWidget()->UpdateTextInputState(
3038 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
3039 SyncSelectionIfRequired();
3042 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3043 blink::WebColorChooserClient
* client
,
3044 const blink::WebColor
& initial_color
,
3045 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3046 RendererWebColorChooserImpl
* color_chooser
=
3047 new RendererWebColorChooserImpl(this, client
);
3048 std::vector
<ColorSuggestion
> color_suggestions
;
3049 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3050 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3052 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3053 return color_chooser
;
3056 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3057 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3060 frame_
->document().url(),
3064 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3065 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3068 frame_
->document().url(),
3072 bool RenderFrameImpl::runModalPromptDialog(
3073 const blink::WebString
& message
,
3074 const blink::WebString
& default_value
,
3075 blink::WebString
* actual_value
) {
3076 base::string16 result
;
3077 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3080 frame_
->document().url(),
3083 actual_value
->assign(result
);
3087 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3089 const blink::WebString
& message
) {
3090 // If we are swapping out, we have already run the beforeunload handler.
3091 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3092 // at all, to avoid running it twice.
3093 if (is_swapped_out_
)
3096 // Don't allow further dialogs if we are waiting to swap out, since the
3097 // PageGroupLoadDeferrer in our stack prevents it.
3098 if (render_view()->suppress_dialogs_until_swap_out_
)
3101 bool success
= false;
3102 // This is an ignored return value, but is included so we can accept the same
3103 // response as RunJavaScriptMessage.
3104 base::string16 ignored_result
;
3105 render_view()->SendAndRunNestedMessageLoop(
3106 new FrameHostMsg_RunBeforeUnloadConfirm(
3107 routing_id_
, frame_
->document().url(), message
, is_reload
,
3108 &success
, &ignored_result
));
3112 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3113 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3114 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3115 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3116 if (GetRenderWidget()->has_host_context_menu_location()) {
3117 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3118 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3121 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3122 // it. We replace it with an empty GURL so the appropriate items are disabled
3123 // in the context menu.
3124 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3125 // data encoded images. We should have a way to save them.
3126 if (params
.src_url
.spec().size() > GetMaxURLChars())
3127 params
.src_url
= GURL();
3128 context_menu_node_
= data
.node
;
3130 #if defined(OS_ANDROID)
3131 gfx::Rect start_rect
;
3133 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3134 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3135 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3138 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3141 void RenderFrameImpl::clearContextMenu() {
3142 context_menu_node_
.reset();
3145 void RenderFrameImpl::willSendRequest(
3146 blink::WebLocalFrame
* frame
,
3147 unsigned identifier
,
3148 blink::WebURLRequest
& request
,
3149 const blink::WebURLResponse
& redirect_response
) {
3150 DCHECK(!frame_
|| frame_
== frame
);
3151 // The request my be empty during tests.
3152 if (request
.url().isEmpty())
3155 // Set the first party for cookies url if it has not been set yet (new
3156 // requests). For redirects, it is updated by WebURLLoaderImpl.
3157 if (request
.firstPartyForCookies().isEmpty()) {
3158 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3159 request
.setFirstPartyForCookies(request
.url());
3161 // TODO(nasko): When the top-level frame is remote, there is no document.
3162 // This is broken and should be fixed to propagate the first party.
3163 WebFrame
* top
= frame
->top();
3164 if (top
->isWebLocalFrame()) {
3165 request
.setFirstPartyForCookies(
3166 frame
->top()->document().firstPartyForCookies());
3171 WebDataSource
* provisional_data_source
= frame
->provisionalDataSource();
3172 WebDataSource
* data_source
=
3173 provisional_data_source
? provisional_data_source
: frame
->dataSource();
3175 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3176 DCHECK(document_state
);
3177 InternalDocumentStateData
* internal_data
=
3178 InternalDocumentStateData::FromDocumentState(document_state
);
3179 NavigationStateImpl
* navigation_state
=
3180 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3181 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3182 if (provisional_data_source
&& provisional_data_source
->isClientRedirect()) {
3183 transition_type
= ui::PageTransitionFromInt(
3184 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3187 GURL
request_url(request
.url());
3189 if (GetContentClient()->renderer()->WillSendRequest(
3193 request
.firstPartyForCookies(),
3195 request
.setURL(WebURL(new_url
));
3198 if (internal_data
->is_cache_policy_override_set())
3199 request
.setCachePolicy(internal_data
->cache_policy_override());
3201 // The request's extra data may indicate that we should set a custom user
3202 // agent. This needs to be done here, after WebKit is through with setting the
3203 // user agent on its own. Similarly, it may indicate that we should set an
3204 // X-Requested-With header. This must be done here to avoid breaking CORS
3206 // PlzNavigate: there may also be a stream url associated with the request.
3207 WebString custom_user_agent
;
3208 WebString requested_with
;
3209 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3210 if (request
.extraData()) {
3211 RequestExtraData
* old_extra_data
=
3212 static_cast<RequestExtraData
*>(request
.extraData());
3214 custom_user_agent
= old_extra_data
->custom_user_agent();
3215 if (!custom_user_agent
.isNull()) {
3216 if (custom_user_agent
.isEmpty())
3217 request
.clearHTTPHeaderField("User-Agent");
3219 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3222 requested_with
= old_extra_data
->requested_with();
3223 if (!requested_with
.isNull()) {
3224 if (requested_with
.isEmpty())
3225 request
.clearHTTPHeaderField("X-Requested-With");
3227 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3229 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3232 // Add the default accept header for frame request if it has not been set
3234 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3235 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3236 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3237 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3238 WebString::fromUTF8(kDefaultAcceptHeader
));
3241 // Add an empty HTTP origin header for non GET methods if none is currently
3243 request
.addHTTPOriginIfNeeded(WebString());
3245 // Attach |should_replace_current_entry| state to requests so that, should
3246 // this navigation later require a request transfer, all state is preserved
3247 // when it is re-created in the new process.
3248 bool should_replace_current_entry
= false;
3249 if (navigation_state
->IsContentInitiated()) {
3250 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3252 // If the navigation is browser-initiated, the NavigationState contains the
3253 // correct value instead of the WebDataSource.
3255 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3256 // NavigationState::should_replace_current_entry().
3257 should_replace_current_entry
=
3258 navigation_state
->common_params().should_replace_current_entry
;
3261 int provider_id
= kInvalidServiceWorkerProviderId
;
3262 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3263 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3264 // |provisionalDataSource| may be null in some content::ResourceFetcher
3265 // use cases, we don't hook those requests.
3266 if (frame
->provisionalDataSource()) {
3267 ServiceWorkerNetworkProvider
* provider
=
3268 ServiceWorkerNetworkProvider::FromDocumentState(
3269 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3270 provider_id
= provider
->provider_id();
3272 } else if (frame
->dataSource()) {
3273 ServiceWorkerNetworkProvider
* provider
=
3274 ServiceWorkerNetworkProvider::FromDocumentState(
3275 DocumentState::FromDataSource(frame
->dataSource()));
3276 provider_id
= provider
->provider_id();
3279 WebFrame
* parent
= frame
->parent();
3280 int parent_routing_id
= MSG_ROUTING_NONE
;
3282 parent_routing_id
= -1;
3283 } else if (parent
->isWebLocalFrame()) {
3284 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3286 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3289 RequestExtraData
* extra_data
= new RequestExtraData();
3290 extra_data
->set_visibility_state(render_view_
->visibilityState());
3291 extra_data
->set_custom_user_agent(custom_user_agent
);
3292 extra_data
->set_requested_with(requested_with
);
3293 extra_data
->set_render_frame_id(routing_id_
);
3294 extra_data
->set_is_main_frame(!parent
);
3295 extra_data
->set_frame_origin(
3296 GURL(frame
->document().securityOrigin().toString()));
3297 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3298 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3299 extra_data
->set_allow_download(
3300 navigation_state
->common_params().allow_download
);
3301 extra_data
->set_transition_type(transition_type
);
3302 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3303 extra_data
->set_transferred_request_child_id(
3304 navigation_state
->start_params().transferred_request_child_id
);
3305 extra_data
->set_transferred_request_request_id(
3306 navigation_state
->start_params().transferred_request_request_id
);
3307 extra_data
->set_service_worker_provider_id(provider_id
);
3308 extra_data
->set_stream_override(stream_override
.Pass());
3309 request
.setExtraData(extra_data
);
3311 // TODO(creis): Update prefetching to work with out-of-process iframes.
3312 WebFrame
* top_frame
= frame
->top();
3313 if (top_frame
&& top_frame
->isWebLocalFrame()) {
3314 DocumentState
* top_document_state
=
3315 DocumentState::FromDataSource(top_frame
->dataSource());
3316 if (top_document_state
) {
3317 // TODO(gavinp): separate out prefetching and prerender field trials
3318 // if the rel=prerender rel type is sticking around.
3319 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3320 top_document_state
->set_was_prefetcher(true);
3324 // This is an instance where we embed a copy of the routing id
3325 // into the data portion of the message. This can cause problems if we
3326 // don't register this id on the browser side, since the download manager
3327 // expects to find a RenderViewHost based off the id.
3328 request
.setRequestorID(render_view_
->GetRoutingID());
3329 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3331 if (!navigation_state
->start_params().extra_headers
.empty()) {
3332 for (net::HttpUtil::HeadersIterator
i(
3333 navigation_state
->start_params().extra_headers
.begin(),
3334 navigation_state
->start_params().extra_headers
.end(), "\n");
3336 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3337 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3338 blink::WebReferrerPolicyDefault
,
3340 WebString::fromUTF8(i
.values()));
3341 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3343 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3344 WebString::fromUTF8(i
.values()));
3349 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3350 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3353 void RenderFrameImpl::didReceiveResponse(
3354 blink::WebLocalFrame
* frame
,
3355 unsigned identifier
,
3356 const blink::WebURLResponse
& response
) {
3357 DCHECK(!frame_
|| frame_
== frame
);
3358 // Only do this for responses that correspond to a provisional data source
3359 // of the top-most frame. If we have a provisional data source, then we
3360 // can't have any sub-resources yet, so we know that this response must
3361 // correspond to a frame load.
3362 if (!frame
->provisionalDataSource() || frame
->parent())
3365 // If we are in view source mode, then just let the user see the source of
3366 // the server's error page.
3367 if (frame
->isViewSourceModeEnabled())
3370 DocumentState
* document_state
=
3371 DocumentState::FromDataSource(frame
->provisionalDataSource());
3372 int http_status_code
= response
.httpStatusCode();
3374 // Record page load flags.
3375 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3377 document_state
->set_was_fetched_via_spdy(
3378 extra_data
->was_fetched_via_spdy());
3379 document_state
->set_was_npn_negotiated(
3380 extra_data
->was_npn_negotiated());
3381 document_state
->set_npn_negotiated_protocol(
3382 extra_data
->npn_negotiated_protocol());
3383 document_state
->set_was_alternate_protocol_available(
3384 extra_data
->was_alternate_protocol_available());
3385 document_state
->set_connection_info(
3386 extra_data
->connection_info());
3387 document_state
->set_was_fetched_via_proxy(
3388 extra_data
->was_fetched_via_proxy());
3389 document_state
->set_proxy_server(
3390 extra_data
->proxy_server());
3392 InternalDocumentStateData
* internal_data
=
3393 InternalDocumentStateData::FromDocumentState(document_state
);
3394 internal_data
->set_http_status_code(http_status_code
);
3397 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3398 blink::WebLocalFrame
* frame
,
3399 const blink::WebURLRequest
& request
,
3400 const blink::WebURLResponse
& response
) {
3401 DCHECK(!frame_
|| frame_
== frame
);
3402 // The recipients of this message have no use for data: URLs: they don't
3403 // affect the page's insecure content list and are not in the disk cache. To
3404 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3405 // filter them out here.
3406 GURL
url(request
.url());
3407 if (url
.SchemeIs(url::kDataScheme
))
3410 // Let the browser know we loaded a resource from the memory cache. This
3411 // message is needed to display the correct SSL indicators.
3412 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3413 render_view_
->GetRoutingID(),
3415 response
.securityInfo(),
3416 request
.httpMethod().utf8(),
3417 response
.mimeType().utf8(),
3418 WebURLRequestToResourceType(request
)));
3421 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3422 DCHECK(!frame_
|| frame_
== frame
);
3423 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3424 render_view_
->GetRoutingID()));
3427 void RenderFrameImpl::didRunInsecureContent(
3428 blink::WebLocalFrame
* frame
,
3429 const blink::WebSecurityOrigin
& origin
,
3430 const blink::WebURL
& target
) {
3431 DCHECK(!frame_
|| frame_
== frame
);
3432 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3433 render_view_
->GetRoutingID(),
3434 origin
.toString().utf8(),
3436 GetContentClient()->renderer()->RecordRapporURL(
3437 "ContentSettings.MixedScript.RanMixedScript",
3438 GURL(origin
.toString().utf8()));
3441 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3442 DCHECK(!frame_
|| frame_
== frame
);
3443 #if defined(ENABLE_PLUGINS)
3444 if (frame
!= render_view_
->webview()->mainFrame())
3446 PluginChannelHost::Broadcast(
3447 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3451 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3452 v8::Local
<v8::Context
> context
,
3453 int extension_group
,
3455 DCHECK(!frame_
|| frame_
== frame
);
3457 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3458 DidCreateScriptContext(context
, extension_group
, world_id
));
3461 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3462 v8::Local
<v8::Context
> context
,
3464 DCHECK(!frame_
|| frame_
== frame
);
3466 FOR_EACH_OBSERVER(RenderFrameObserver
,
3468 WillReleaseScriptContext(context
, world_id
));
3471 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3472 blink::WebLocalFrame
* frame
) {
3473 DCHECK(!frame_
|| frame_
== frame
);
3474 if (frame
->parent())
3477 InternalDocumentStateData
* data
=
3478 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3479 data
->set_did_first_visually_non_empty_layout(true);
3481 #if defined(OS_ANDROID)
3482 GetRenderWidget()->DidChangeBodyBackgroundColor(
3483 render_view_
->webwidget_
->backgroundColor());
3486 GetRenderWidget()->QueueMessage(
3487 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3488 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3491 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3492 DCHECK(!frame_
|| frame_
== frame
);
3493 // TODO(nasko): Move implementation here. Needed methods:
3494 // * StartNavStateSyncTimerIfNecessary
3495 render_view_
->didChangeScrollOffset(frame
);
3497 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3500 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3501 DCHECK(!frame_
|| frame_
== frame
);
3502 if (!frame
->parent()) {
3503 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3504 render_view_
->GetRoutingID()));
3508 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3510 bool final_update
) {
3511 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3513 active_match_ordinal
= 0;
3515 render_view_
->Send(new ViewHostMsg_Find_Reply(
3516 render_view_
->GetRoutingID(), request_id
, count
,
3517 gfx::Rect(), active_match_ordinal
, final_update
));
3520 void RenderFrameImpl::reportFindInPageSelection(
3522 int active_match_ordinal
,
3523 const blink::WebRect
& selection_rect
) {
3524 render_view_
->Send(new ViewHostMsg_Find_Reply(
3525 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3526 active_match_ordinal
, false));
3529 void RenderFrameImpl::requestStorageQuota(
3530 blink::WebLocalFrame
* frame
,
3531 blink::WebStorageQuotaType type
,
3532 unsigned long long requested_size
,
3533 blink::WebStorageQuotaCallbacks callbacks
) {
3534 DCHECK(!frame_
|| frame_
== frame
);
3535 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3536 if (origin
.isUnique()) {
3537 // Unique origins cannot store persistent state.
3538 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3541 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3542 render_view_
->GetRoutingID(),
3543 GURL(origin
.toString()),
3544 static_cast<storage::StorageType
>(type
),
3546 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3549 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3550 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3551 impl
->set_render_frame_id(routing_id_
);
3554 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3555 if (!geolocation_dispatcher_
)
3556 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3557 return geolocation_dispatcher_
;
3560 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3561 if (!presentation_dispatcher_
)
3562 presentation_dispatcher_
= new PresentationDispatcher(this);
3563 return presentation_dispatcher_
;
3566 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3567 if (!push_messaging_dispatcher_
)
3568 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3569 return push_messaging_dispatcher_
;
3572 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3573 blink::WebLocalFrame
* frame
,
3574 blink::WebRTCPeerConnectionHandler
* handler
) {
3575 DCHECK(!frame_
|| frame_
== frame
);
3576 #if defined(ENABLE_WEBRTC)
3577 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3581 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3582 if (!web_user_media_client_
)
3583 InitializeUserMediaClient();
3584 return web_user_media_client_
;
3587 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3588 if (!web_encrypted_media_client_
) {
3589 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3590 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3591 // is destructed before |this|, and does not give away ownership of the
3593 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3594 base::Unretained(this)),
3595 GetCdmFactory(), GetMediaPermission()));
3597 return web_encrypted_media_client_
.get();
3600 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3601 if (!midi_dispatcher_
)
3602 midi_dispatcher_
= new MidiDispatcher(this);
3603 return midi_dispatcher_
;
3606 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3607 blink::WebLocalFrame
* source_frame
,
3608 blink::WebFrame
* target_frame
,
3609 blink::WebSecurityOrigin target_origin
,
3610 blink::WebDOMMessageEvent event
) {
3611 DCHECK(!frame_
|| frame_
== target_frame
);
3613 // Currently, a postMessage that targets a cross-process frame can be plumbed
3614 // either through this function or RenderFrameProxy::postMessageEvent. This
3615 // function is used when the target cross-process frame is a top-level frame
3616 // which has been swapped out. In that case, the corresponding WebLocalFrame
3617 // currently remains in the frame tree even in site-per-process mode (see
3618 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3619 // --site-per-process mode for all other cases.
3621 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3622 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3623 // cross-process postMessages.
3624 if (!is_swapped_out_
)
3627 // It is possible to get here on a swapped-out frame without a
3628 // |render_frame_proxy_|. This happens when:
3629 // - This process only has one active RenderView and is about to go away
3630 // (e.g., due to cross-process navigation).
3631 // - The top frame has a subframe with an unload handler.
3632 // - The subframe sends a postMessage to the top-level frame in its unload
3634 // See https://crbug.com/475651 for details. We return false here, since we
3635 // don't want to deliver the message to the new process in this case.
3636 if (!render_frame_proxy_
)
3639 render_frame_proxy_
->postMessageEvent(
3640 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3644 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3645 const blink::WebURL
& url
) {
3646 DCHECK(!frame_
|| frame_
== frame
);
3647 std::string user_agent_override_for_url
=
3648 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3649 if (!user_agent_override_for_url
.empty())
3650 return WebString::fromUTF8(user_agent_override_for_url
);
3652 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3653 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3654 return blink::WebString();
3657 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3658 // associated with it, so the checks below are not valid. Temporarily
3659 // return early and fix properly as part of https://crbug.com/426555.
3660 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3661 return blink::WebString();
3663 // If we're in the middle of committing a load, the data source we need
3664 // will still be provisional.
3665 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3666 WebDataSource
* data_source
= NULL
;
3667 if (main_frame
->provisionalDataSource())
3668 data_source
= main_frame
->provisionalDataSource();
3670 data_source
= main_frame
->dataSource();
3672 InternalDocumentStateData
* internal_data
= data_source
?
3673 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3674 if (internal_data
&& internal_data
->is_overriding_user_agent())
3675 return WebString::fromUTF8(
3676 render_view_
->renderer_preferences_
.user_agent_override
);
3677 return blink::WebString();
3680 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3681 DCHECK(!frame_
|| frame_
== frame
);
3682 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3683 return WebString::fromUTF8("1");
3687 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3688 bool default_value
) {
3689 DCHECK(!frame_
|| frame_
== frame
);
3693 bool blocked
= true;
3694 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3695 render_view_
->GetRoutingID(),
3696 GURL(frame
->top()->securityOrigin().toString()),
3697 THREE_D_API_TYPE_WEBGL
,
3702 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3703 int arb_robustness_status_code
) {
3704 DCHECK(!frame_
|| frame_
== frame
);
3705 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3706 GURL(frame
->top()->securityOrigin().toString()),
3707 THREE_D_API_TYPE_WEBGL
,
3708 arb_robustness_status_code
));
3711 blink::WebScreenOrientationClient
*
3712 RenderFrameImpl::webScreenOrientationClient() {
3713 if (!screen_orientation_dispatcher_
)
3714 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3715 return screen_orientation_dispatcher_
;
3718 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3719 ServiceWorkerNetworkProvider
* provider
=
3720 ServiceWorkerNetworkProvider::FromDocumentState(
3721 DocumentState::FromDataSource(&data_source
));
3722 if (!provider
->context())
3724 return provider
->context()->controller_handle_id() !=
3725 kInvalidServiceWorkerHandleId
;
3728 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3729 ServiceWorkerNetworkProvider
* provider
=
3730 ServiceWorkerNetworkProvider::FromDocumentState(
3731 DocumentState::FromDataSource(&data_source
));
3732 if (provider
->context() && provider
->context()->controller())
3733 return provider
->context()->controller()->version_id();
3734 return kInvalidServiceWorkerVersionId
;
3737 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3738 blink::WebAXEvent event
) {
3739 HandleWebAccessibilityEvent(obj
, event
);
3742 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3745 const blink::WebAXObject
& start_object
,
3747 const blink::WebAXObject
& end_object
,
3749 if (renderer_accessibility_
) {
3750 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3751 identifier
, match_index
, start_object
, start_offset
,
3752 end_object
, end_offset
);
3756 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3757 DCHECK(!frame_
|| frame_
== frame
);
3759 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3762 bool RenderFrameImpl::enterFullscreen() {
3763 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3767 bool RenderFrameImpl::exitFullscreen() {
3768 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3772 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3773 if (!permission_client_
)
3774 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3776 return permission_client_
.get();
3779 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3780 if (!app_banner_client_
) {
3781 app_banner_client_
=
3782 GetContentClient()->renderer()->CreateAppBannerClient(this);
3785 return app_banner_client_
.get();
3788 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3790 const WebString
& title
) {
3791 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3792 Send(new FrameHostMsg_RegisterProtocolHandler(
3794 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3800 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3801 const WebURL
& url
) {
3802 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3803 Send(new FrameHostMsg_UnregisterProtocolHandler(
3805 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3810 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3812 bluetooth_
.reset(new WebBluetoothImpl(
3813 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3816 return bluetooth_
.get();
3819 #if defined(ENABLE_WEBVR)
3820 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3821 if (!vr_dispatcher_
)
3822 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3824 return vr_dispatcher_
.get();
3828 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3829 Send(new FrameHostMsg_MediaPlayingNotification(
3830 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3831 player
->hasAudio(), player
->isRemote()));
3834 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3835 Send(new FrameHostMsg_MediaPausedNotification(
3836 routing_id_
, reinterpret_cast<int64
>(player
)));
3839 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3843 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3844 observers_
.AddObserver(observer
);
3847 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3848 observer
->RenderFrameGone();
3849 observers_
.RemoveObserver(observer
);
3852 void RenderFrameImpl::OnStop() {
3854 frame_
->stopLoading();
3855 if (!frame_
->parent())
3856 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3858 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3861 void RenderFrameImpl::WasHidden() {
3862 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3865 void RenderFrameImpl::WasShown() {
3866 // TODO(kenrb): Need to figure out how to do this better. Should
3867 // VisibilityState remain a page-level concept or move to frames?
3868 // The semantics of 'Show' might have to change here.
3869 if (render_widget_
) {
3870 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3871 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3873 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3876 void RenderFrameImpl::WidgetWillClose() {
3877 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3880 bool RenderFrameImpl::IsHidden() {
3881 return GetRenderWidget()->is_hidden();
3884 // Tell the embedding application that the URL of the active page has changed.
3885 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3886 blink::WebFrame
* frame
,
3887 blink::WebHistoryCommitType commit_type
,
3888 const blink::WebHistoryItem
& item
) {
3889 DCHECK(!frame_
|| frame_
== frame
);
3890 WebDataSource
* ds
= frame
->dataSource();
3893 const WebURLRequest
& request
= ds
->request();
3894 const WebURLResponse
& response
= ds
->response();
3896 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3897 NavigationStateImpl
* navigation_state
=
3898 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3899 InternalDocumentStateData
* internal_data
=
3900 InternalDocumentStateData::FromDocumentState(document_state
);
3902 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3903 params
.http_status_code
= response
.httpStatusCode();
3904 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3905 params
.is_post
= false;
3906 params
.intended_as_new_entry
=
3907 navigation_state
->request_params().intended_as_new_entry
;
3908 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3909 params
.post_id
= -1;
3910 params
.page_id
= render_view_
->page_id_
;
3911 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3912 // We need to track the RenderViewHost routing_id because of downstream
3913 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3914 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3915 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3916 // based on the ID stored in the resource requests. Once those dependencies
3917 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3918 // client to be based on the routing_id of the RenderFrameHost.
3919 params
.render_view_routing_id
= render_view_
->routing_id();
3920 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3921 params
.socket_address
.set_port(response
.remotePort());
3922 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3924 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3925 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3926 params
.security_info
= response
.securityInfo();
3928 // Set the URL to be displayed in the browser UI to the user.
3929 params
.url
= GetLoadingUrl();
3930 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3932 // Set the origin of the frame. This will be replicated to the corresponding
3933 // RenderFrameProxies in other processes.
3934 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3935 // to https://crbug.com/439608 and will be replicated as unique origins.
3936 if (!is_swapped_out_
) {
3937 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3938 if (url::IsStandard(scheme
.c_str(),
3939 url::Component(0, static_cast<int>(scheme
.length())))) {
3940 params
.origin
= frame
->document().securityOrigin();
3944 if (frame
->document().baseURL() != params
.url
)
3945 params
.base_url
= frame
->document().baseURL();
3947 GetRedirectChain(ds
, ¶ms
.redirects
);
3948 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3949 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3951 params
.searchable_form_url
= internal_data
->searchable_form_url();
3952 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3954 params
.gesture
= render_view_
->navigation_gesture_
;
3955 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3957 // Make navigation state a part of the DidCommitProvisionalLoad message so
3958 // that committed entry has it at all times.
3959 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3960 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3962 params
.page_state
= HistoryEntryToPageState(entry
);
3964 params
.page_state
= PageState::CreateFromURL(request
.url());
3966 // In --site-per-process, just send a single HistoryItem for this frame,
3967 // rather than the whole tree. It will be stored in the corresponding
3968 // FrameNavigationEntry.
3969 params
.page_state
= SingleHistoryItemToPageState(item
);
3971 params
.item_sequence_number
= item
.itemSequenceNumber();
3972 params
.document_sequence_number
= item
.documentSequenceNumber();
3974 if (!frame
->parent()) {
3975 // Top-level navigation.
3977 // Reset the zoom limits in case a plugin had changed them previously. This
3978 // will also call us back which will cause us to send a message to
3979 // update WebContentsImpl.
3980 render_view_
->webview()->zoomLimitsChanged(
3981 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3982 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3984 // Set zoom level, but don't do it for full-page plugin since they don't use
3985 // the same zoom settings.
3986 HostZoomLevels::iterator host_zoom
=
3987 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3988 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3989 // Reset the zoom levels for plugins.
3990 render_view_
->webview()->setZoomLevel(0);
3992 // If the zoom level is not found, then do nothing. In-page navigation
3993 // relies on not changing the zoom level in this case.
3994 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3995 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3998 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3999 // This zoom level was merely recorded transiently for this load. We can
4000 // erase it now. If at some point we reload this page, the browser will
4001 // send us a new, up-to-date zoom level.
4002 render_view_
->host_zoom_levels_
.erase(host_zoom
);
4005 // Update contents MIME type for main frame.
4006 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4008 params
.transition
= navigation_state
->GetTransitionType();
4009 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4010 // If the main frame does a load, it should not be reported as a subframe
4011 // navigation. This can occur in the following case:
4012 // 1. You're on a site with frames.
4013 // 2. You do a subframe navigation. This is stored with transition type
4015 // 3. You navigate to some non-frame site, say, google.com.
4016 // 4. You navigate back to the page from step 2. Since it was initially
4017 // MANUAL_SUBFRAME, it will be that same transition type here.
4018 // We don't want that, because any navigation that changes the toplevel
4019 // frame should be tracked as a toplevel navigation (this allows us to
4020 // update the URL bar, etc).
4021 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4024 // If the page contained a client redirect (meta refresh, document.loc...),
4025 // set the referrer and transition appropriately.
4026 if (ds
->isClientRedirect()) {
4028 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4029 params
.transition
= ui::PageTransitionFromInt(
4030 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4032 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4033 frame
, ds
->request());
4036 base::string16 method
= request
.httpMethod();
4037 if (base::EqualsASCII(method
, "POST")) {
4038 params
.is_post
= true;
4039 params
.post_id
= ExtractPostId(entry
);
4042 // Send the user agent override back.
4043 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4045 // Track the URL of the original request. We use the first entry of the
4046 // redirect chain if it exists because the chain may have started in another
4048 params
.original_request_url
= GetOriginalRequestURL(ds
);
4050 params
.history_list_was_cleared
=
4051 navigation_state
->request_params().should_clear_history_list
;
4053 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4054 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4055 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4056 frame
->dataSource()->request().uiStartTime());
4058 // Save some histogram data so we can compute the average memory used per
4059 // page load of the glyphs.
4060 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4061 blink::WebGlyphCache::pageCount());
4063 // This message needs to be sent before any of allowScripts(),
4064 // allowImages(), allowPlugins() is called for the new page, so that when
4065 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4066 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4067 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4069 // Subframe navigation: the type depends on whether this navigation
4070 // generated a new session history entry. When they do generate a session
4071 // history entry, it means the user initiated the navigation and we should
4073 if (commit_type
== blink::WebStandardCommit
)
4074 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4076 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4078 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4079 params
.history_list_was_cleared
= false;
4080 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4082 // Don't send this message while the subframe is swapped out.
4083 if (!is_swapped_out())
4084 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4087 // If we end up reusing this WebRequest (for example, due to a #ref click),
4088 // we don't want the transition type to persist. Just clear it.
4089 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4092 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4093 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4095 render_view_
->FrameDidStartLoading(frame_
);
4096 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4099 void RenderFrameImpl::didStopLoading() {
4100 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4102 render_view_
->FrameDidStopLoading(frame_
);
4103 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4106 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4107 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4110 void RenderFrameImpl::HandleWebAccessibilityEvent(
4111 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4112 if (renderer_accessibility_
)
4113 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4116 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4117 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4120 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4121 if (renderer_accessibility())
4122 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4126 void RenderFrameImpl::OnCommitNavigation(
4127 const ResourceResponseHead
& response
,
4128 const GURL
& stream_url
,
4129 const CommonNavigationParams
& common_params
,
4130 const RequestNavigationParams
& request_params
) {
4131 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4132 switches::kEnableBrowserSideNavigation
));
4133 // This will override the url requested by the WebURLLoader, as well as
4134 // provide it with the response to the request.
4135 scoped_ptr
<StreamOverrideParameters
> stream_override(
4136 new StreamOverrideParameters());
4137 stream_override
->stream_url
= stream_url
;
4138 stream_override
->response
= response
;
4140 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4141 stream_override
.Pass());
4144 void RenderFrameImpl::OnFailedNavigation(
4145 const CommonNavigationParams
& common_params
,
4146 const RequestNavigationParams
& request_params
,
4147 bool has_stale_copy_in_cache
,
4149 bool is_reload
= IsReload(common_params
.navigation_type
);
4150 bool is_history_navigation
= request_params
.page_state
.IsValid();
4151 WebURLRequest::CachePolicy cache_policy
=
4152 WebURLRequest::UseProtocolCachePolicy
;
4153 RenderFrameImpl::PrepareRenderViewForNavigation(
4154 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4156 GetContentClient()->SetActiveURL(common_params
.url
);
4158 pending_navigation_params_
.reset(new NavigationParams(
4159 common_params
, StartNavigationParams(), request_params
));
4161 // Inform the browser of the start of the provisional load. This is needed so
4162 // that the load is properly tracked by the WebNavigation API.
4163 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4164 routing_id_
, common_params
.url
));
4166 // Send the provisional load failure.
4167 blink::WebURLError error
=
4168 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4169 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4170 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4171 frame_
->isViewSourceModeEnabled());
4172 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4174 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4175 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4176 // http://crbug.com/501960
4177 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4181 // Make sure errors are not shown in view source mode.
4182 frame_
->enableViewSourceMode(false);
4184 // Replace the current history entry in reloads, history navigations and loads
4185 // of the same url. This corresponds to Blink's notion of a standard
4187 // TODO(clamy): see if initial commits in subframes should be handled
4189 bool replace
= is_reload
|| is_history_navigation
||
4190 common_params
.url
== GetLoadingUrl();
4191 LoadNavigationErrorPage(failed_request
, error
, replace
);
4194 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4195 RenderFrame
* render_frame
,
4196 const NavigationPolicyInfo
& info
) {
4197 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4200 // TODO(nick): Is consulting |is_subframe_| here correct?
4201 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_
) {
4202 // There's no reason to ignore navigations on subframes, since the swap out
4203 // logic no longer applies.
4205 if (is_swapped_out_
) {
4206 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4207 // Targeted links may try to navigate a swapped out frame. Allow the
4208 // browser process to navigate the tab instead. Note that it is also
4209 // possible for non-targeted navigations (from this view) to arrive
4210 // here just after we are swapped out. It's ok to send them to the
4211 // browser, as long as they're for the top level frame.
4212 // TODO(creis): Ensure this supports targeted form submissions when
4213 // fixing http://crbug.com/101395.
4214 if (info
.frame
->parent() == NULL
) {
4215 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4216 info
.defaultPolicy
);
4217 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4220 // We should otherwise ignore in-process iframe navigations, if they
4221 // arrive just after we are swapped out.
4222 return blink::WebNavigationPolicyIgnore
;
4225 // Allow kSwappedOutURL to complete.
4226 return info
.defaultPolicy
;
4230 // Webkit is asking whether to navigate to a new URL.
4231 // This is fine normally, except if we're showing UI from one security
4232 // context and they're trying to navigate to a different context.
4233 const GURL
& url
= info
.urlRequest
.url();
4235 // A content initiated navigation may have originated from a link-click,
4236 // script, drag-n-drop operation, etc.
4237 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4238 bool is_content_initiated
=
4239 document_state
->navigation_state()->IsContentInitiated();
4241 // If the browser is interested, then give it a chance to look at the request.
4242 if (is_content_initiated
) {
4244 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4245 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4246 base::EqualsASCII(base::StringPiece16(info
.urlRequest
.httpMethod()),
4248 bool browser_handles_request
=
4249 render_view_
->renderer_preferences_
4250 .browser_handles_non_local_top_level_requests
4251 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4253 if (!browser_handles_request
) {
4254 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4255 render_view_
->renderer_preferences_
4256 .browser_handles_all_top_level_requests
;
4259 if (browser_handles_request
) {
4260 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4261 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4265 // Use the frame's original request's URL rather than the document's URL for
4266 // subsequent checks. For a popup, the document's URL may become the opener
4267 // window's URL if the opener has called document.write().
4268 // See http://crbug.com/93517.
4269 GURL
old_url(info
.frame
->dataSource()->request().url());
4271 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4272 // an extension or app origin, leaving a WebUI page, etc). We only care about
4273 // top-level navigations (not iframes). But we sometimes navigate to
4274 // about:blank to clear a tab, and we want to still allow that.
4276 // Note: this is known to break POST submissions when crossing process
4277 // boundaries until http://crbug.com/101395 is fixed. This is better for
4278 // security than loading a WebUI, extension or app page in the wrong process.
4279 // POST requests don't work because this mechanism does not preserve form
4280 // POST data. We will need to send the request's httpBody data up to the
4281 // browser process, and issue a special POST navigation in WebKit (via
4282 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4283 // for examples of how to send the httpBody data.
4284 if (!info
.frame
->parent() && is_content_initiated
&&
4285 !url
.SchemeIs(url::kAboutScheme
)) {
4286 bool send_referrer
= false;
4288 // All navigations to or from WebUI URLs or within WebUI-enabled
4289 // RenderProcesses must be handled by the browser process so that the
4290 // correct bindings and data sources can be registered.
4291 // Similarly, navigations to view-source URLs or within ViewSource mode
4292 // must be handled by the browser process (except for reloads - those are
4293 // safe to leave within the renderer).
4294 // Lastly, access to file:// URLs from non-file:// URL pages must be
4295 // handled by the browser so that ordinary renderer processes don't get
4296 // blessed with file permissions.
4297 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4298 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4299 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4300 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4301 url
.SchemeIs(kViewSourceScheme
) ||
4302 (info
.frame
->isViewSourceModeEnabled() &&
4303 info
.navigationType
!= blink::WebNavigationTypeReload
);
4305 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4306 // Fork non-file to file opens. Check the opener URL if this is the
4307 // initial navigation in a newly opened window.
4308 GURL
source_url(old_url
);
4309 if (is_initial_navigation
&& source_url
.is_empty() &&
4310 info
.frame
->opener())
4311 source_url
= info
.frame
->opener()->top()->document().url();
4312 DCHECK(!source_url
.is_empty());
4313 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4317 // Give the embedder a chance.
4318 should_fork
= GetContentClient()->renderer()->ShouldFork(
4319 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4320 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4324 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4325 info
.defaultPolicy
);
4326 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4330 // Detect when a page is "forking" a new tab that can be safely rendered in
4331 // its own process. This is done by sites like Gmail that try to open links
4332 // in new windows without script connections back to the original page. We
4333 // treat such cases as browser navigations (in which we will create a new
4334 // renderer for a cross-site navigation), rather than WebKit navigations.
4336 // We use the following heuristic to decide whether to fork a new page in its
4338 // The parent page must open a new tab to about:blank, set the new tab's
4339 // window.opener to null, and then redirect the tab to a cross-site URL using
4342 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4345 // Must start from a tab showing about:blank, which is later redirected.
4346 old_url
== GURL(url::kAboutBlankURL
) &&
4347 // Must be the first real navigation of the tab.
4348 render_view_
->historyBackListCount() < 1 &&
4349 render_view_
->historyForwardListCount() < 1 &&
4350 // The parent page must have set the child's window.opener to null before
4351 // redirecting to the desired URL.
4352 info
.frame
->opener() == NULL
&&
4353 // Must be a top-level frame.
4354 info
.frame
->parent() == NULL
&&
4355 // Must not have issued the request from this page.
4356 is_content_initiated
&&
4357 // Must be targeted at the current tab.
4358 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4359 // Must be a JavaScript navigation, which appears as "other".
4360 info
.navigationType
== blink::WebNavigationTypeOther
;
4363 // Open the URL via the browser, not via WebKit.
4364 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4365 return blink::WebNavigationPolicyIgnore
;
4368 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4369 // This includes navigations with no request being sent to the network stack.
4370 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4371 switches::kEnableBrowserSideNavigation
) &&
4372 info
.urlRequest
.checkForBrowserSideNavigation() &&
4373 ShouldMakeNetworkRequestForURL(url
)) {
4374 BeginNavigation(&info
.urlRequest
);
4375 return blink::WebNavigationPolicyIgnore
;
4378 return info
.defaultPolicy
;
4381 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4383 const Referrer
& referrer
,
4384 WebNavigationPolicy policy
) {
4385 DCHECK_EQ(frame_
, frame
);
4387 FrameHostMsg_OpenURL_Params params
;
4389 params
.referrer
= referrer
;
4390 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4391 WebDataSource
* ds
= frame
->provisionalDataSource();
4393 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4394 NavigationStateImpl
* navigation_state
=
4395 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4396 if (navigation_state
->IsContentInitiated()) {
4397 params
.should_replace_current_entry
=
4398 ds
->replacesCurrentHistoryItem() &&
4399 render_view_
->history_list_length_
;
4401 // This is necessary to preserve the should_replace_current_entry value on
4402 // cross-process redirects, in the event it was set by a previous process.
4404 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4405 // NavigationState::should_replace_current_entry().
4406 params
.should_replace_current_entry
=
4407 navigation_state
->common_params().should_replace_current_entry
;
4410 params
.should_replace_current_entry
= false;
4412 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4413 if (GetContentClient()->renderer()->AllowPopup())
4414 params
.user_gesture
= true;
4416 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4417 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4418 policy
== blink::WebNavigationPolicyNewWindow
||
4419 policy
== blink::WebNavigationPolicyNewPopup
) {
4420 WebUserGestureIndicator::consumeUserGesture();
4423 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4426 void RenderFrameImpl::NavigateInternal(
4427 const CommonNavigationParams
& common_params
,
4428 const StartNavigationParams
& start_params
,
4429 const RequestNavigationParams
& request_params
,
4430 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4431 bool browser_side_navigation
=
4432 base::CommandLine::ForCurrentProcess()->HasSwitch(
4433 switches::kEnableBrowserSideNavigation
);
4434 bool is_reload
= IsReload(common_params
.navigation_type
);
4435 bool is_history_navigation
= request_params
.page_state
.IsValid();
4436 WebURLRequest::CachePolicy cache_policy
=
4437 WebURLRequest::UseProtocolCachePolicy
;
4438 RenderFrameImpl::PrepareRenderViewForNavigation(
4439 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4441 GetContentClient()->SetActiveURL(common_params
.url
);
4443 // If this frame isn't in the same process as the main frame, it may naively
4444 // assume that this is the first navigation in the iframe, but this may not
4445 // actually be the case. Inform the frame's state machine if this frame has
4446 // already committed other loads.
4447 if (request_params
.has_committed_real_load
&& frame_
->parent())
4448 frame_
->setCommittedFirstRealLoad();
4450 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4451 // We cannot reload if we do not have any history state. This happens, for
4452 // example, when recovering from a crash.
4454 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4457 pending_navigation_params_
.reset(
4458 new NavigationParams(common_params
, start_params
, request_params
));
4460 // Create parameters for a standard navigation.
4461 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4462 bool should_load_request
= false;
4463 WebHistoryItem item_for_history_navigation
;
4464 WebURLRequest request
= CreateURLRequestForNavigation(
4465 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4467 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4468 // navigation for this request (since it already went to the browser).
4469 if (browser_side_navigation
)
4470 request
.setCheckForBrowserSideNavigation(false);
4472 // If we are reloading, then use the history state of the current frame.
4473 // Otherwise, if we have history state, then we need to navigate to it, which
4474 // corresponds to a back/forward navigation event. Update the parameters
4475 // depending on the navigation type.
4477 bool ignore_cache
= (common_params
.navigation_type
==
4478 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4479 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4480 : blink::WebFrameLoadType::Reload
;
4482 if (!browser_side_navigation
) {
4483 const GURL override_url
=
4484 (common_params
.navigation_type
==
4485 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4488 request
= frame_
->requestForReload(load_type
, override_url
);
4490 should_load_request
= true;
4491 } else if (is_history_navigation
) {
4492 // We must know the page ID of the page we are navigating back to.
4493 DCHECK_NE(request_params
.page_id
, -1);
4494 // We must know the nav entry ID of the page we are navigating back to,
4495 // which should be the case because history navigations are routed via the
4497 DCHECK_NE(0, request_params
.nav_entry_id
);
4498 scoped_ptr
<HistoryEntry
> entry
=
4499 PageStateToHistoryEntry(request_params
.page_state
);
4501 // Ensure we didn't save the swapped out URL in UpdateState, since the
4502 // browser should never be telling us to navigate to swappedout://.
4503 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4505 if (!browser_side_navigation
) {
4506 scoped_ptr
<NavigationParams
> navigation_params(
4507 new NavigationParams(*pending_navigation_params_
.get()));
4508 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4509 // By default, tell the HistoryController to go the deserialized
4510 // HistoryEntry. This only works if all frames are in the same
4512 DCHECK(!frame_
->parent());
4513 render_view_
->history_controller()->GoToEntry(
4514 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4516 // In --site-per-process, the browser process sends a single
4517 // WebHistoryItem destined for this frame.
4518 // TODO(creis): Change PageState to FrameState. In the meantime, we
4519 // store the relevant frame's WebHistoryItem in the root of the
4521 SetPendingNavigationParams(navigation_params
.Pass());
4522 blink::WebHistoryItem history_item
= entry
->root();
4523 blink::WebHistoryLoadType load_type
=
4524 request_params
.is_same_document_history_load
4525 ? blink::WebHistorySameDocumentLoad
4526 : blink::WebHistoryDifferentDocumentLoad
;
4528 // Let the history controller know the provisional entry, since it is
4529 // used at commit time. Otherwise skip GoToEntry and navigate the
4531 // TODO(creis): Consider cloning the current entry to handle subframe
4532 // cases. Changes to SendUpdateState might affect this.
4533 render_view_
->history_controller()->set_provisional_entry(
4535 WebURLRequest request
=
4536 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4537 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4538 history_item
, load_type
);
4541 // TODO(clamy): this should be set to the HistoryItem sent by the
4542 // browser once the HistoryController has moved to the browser.
4543 // TODO(clamy): distinguish between different document and same document
4545 // TODO(clamy): update this for subframes history loads.
4546 item_for_history_navigation
=
4547 entry
->GetHistoryNodeForFrame(this)->item();
4548 load_type
= blink::WebFrameLoadType::BackForward
;
4549 should_load_request
= true;
4553 // Navigate to the given URL.
4554 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4555 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4556 start_params
.extra_headers
.end(),
4559 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4560 WebString::fromUTF8(i
.values()));
4564 if (start_params
.is_post
&& !browser_side_navigation
) {
4565 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4568 WebHTTPBody http_body
;
4569 http_body
.initialize();
4570 const char* data
= nullptr;
4571 if (start_params
.browser_initiated_post_data
.size()) {
4572 data
= reinterpret_cast<const char*>(
4573 &start_params
.browser_initiated_post_data
.front());
4575 http_body
.appendData(
4576 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4577 request
.setHTTPBody(http_body
);
4580 // A session history navigation should have been accompanied by state.
4581 CHECK_EQ(request_params
.page_id
, -1);
4583 should_load_request
= true;
4586 if (should_load_request
) {
4587 // Record this before starting the load. We need a lower bound of this
4588 // time to sanitize the navigationStart override set below.
4589 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4591 // Perform a navigation to a data url if needed.
4592 if (!common_params
.base_url_for_data_url
.is_empty() ||
4593 (browser_side_navigation
&&
4594 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4595 LoadDataURL(common_params
, frame_
);
4597 // Load the request.
4598 frame_
->toWebLocalFrame()->load(request
, load_type
,
4599 item_for_history_navigation
);
4602 if (load_type
== blink::WebFrameLoadType::Standard
) {
4603 UpdateFrameNavigationTiming(frame_
,
4604 request_params
.browser_navigation_start
,
4605 renderer_navigation_start
);
4609 // In case LoadRequest failed before didCreateDataSource was called.
4610 pending_navigation_params_
.reset();
4613 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4614 const std::string
& encoding_name
) {
4615 // Only update main frame's encoding_name.
4616 if (!frame
->parent())
4617 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4620 void RenderFrameImpl::SyncSelectionIfRequired() {
4621 base::string16 text
;
4624 #if defined(ENABLE_PLUGINS)
4625 if (render_view_
->focused_pepper_plugin_
) {
4626 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4627 offset
= 0; // Pepper API does not support offset reporting.
4628 // TODO(kinaba): cut as needed.
4632 size_t location
, length
;
4633 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4634 &location
, &length
)) {
4638 range
= gfx::Range(location
, location
+ length
);
4640 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4641 blink::WebTextInputTypeNone
) {
4642 // If current focused element is editable, we will send 100 more chars
4643 // before and after selection. It is for input method surrounding text
4645 if (location
> kExtraCharsBeforeAndAfterSelection
)
4646 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4649 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4650 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4651 if (!webrange
.isNull())
4652 text
= webrange
.toPlainText();
4655 text
= frame_
->selectionAsText();
4656 // http://crbug.com/101435
4657 // In some case, frame->selectionAsText() returned text's length is not
4658 // equal to the length returned from webwidget()->caretOrSelectionRange().
4659 // So we have to set the range according to text.length().
4660 range
.set_end(range
.start() + text
.length());
4664 // Sometimes we get repeated didChangeSelection calls from webkit when
4665 // the selection hasn't actually changed. We don't want to report these
4666 // because it will cause us to continually claim the X clipboard.
4667 if (selection_text_offset_
!= offset
||
4668 selection_range_
!= range
||
4669 selection_text_
!= text
) {
4670 selection_text_
= text
;
4671 selection_text_offset_
= offset
;
4672 selection_range_
= range
;
4673 SetSelectedText(text
, offset
, range
);
4675 GetRenderWidget()->UpdateSelectionBounds();
4678 void RenderFrameImpl::InitializeUserMediaClient() {
4679 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4682 #if defined(OS_ANDROID)
4683 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4684 switches::kDisableWebRTC
))
4688 #if defined(ENABLE_WEBRTC)
4689 DCHECK(!web_user_media_client_
);
4690 web_user_media_client_
= new UserMediaClientImpl(
4692 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4693 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4697 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4698 WebMediaPlayerClient
* client
) {
4699 #if defined(ENABLE_WEBRTC)
4700 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4702 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4703 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4704 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4705 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4706 new RenderMediaLog(),
4707 CreateRendererFactory());
4710 #endif // defined(ENABLE_WEBRTC)
4713 scoped_ptr
<MediaStreamRendererFactory
>
4714 RenderFrameImpl::CreateRendererFactory() {
4715 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4716 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4718 return factory
.Pass();
4719 #if defined(ENABLE_WEBRTC)
4720 return scoped_ptr
<MediaStreamRendererFactory
>(
4721 new MediaStreamRendererFactoryImpl());
4723 return scoped_ptr
<MediaStreamRendererFactory
>(
4724 static_cast<MediaStreamRendererFactory
*>(NULL
));
4728 void RenderFrameImpl::PrepareRenderViewForNavigation(
4730 const RequestNavigationParams
& request_params
,
4732 WebURLRequest::CachePolicy
* cache_policy
) {
4733 DCHECK(render_view_
->webview());
4735 MaybeHandleDebugURL(url
);
4738 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4740 render_view_
->history_list_offset_
=
4741 request_params
.current_history_list_offset
;
4742 render_view_
->history_list_length_
=
4743 request_params
.current_history_list_length
;
4744 if (request_params
.should_clear_history_list
) {
4745 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4746 CHECK_EQ(0, render_view_
->history_list_length_
);
4749 if (!is_swapped_out_
|| frame_
->parent())
4752 // This is a swapped out main frame, so swap the renderer back in.
4753 // We marked the view as hidden when swapping the view out, so be sure to
4754 // reset the visibility state before navigating to the new URL.
4755 render_view_
->webview()->setVisibilityState(
4756 render_view_
->visibilityState(), false);
4758 // If this is an attempt to reload while we are swapped out, we should not
4759 // reload swappedout://, but the previous page, which is stored in
4760 // params.state. Setting is_reload to false will treat this like a back
4761 // navigation to accomplish that.
4763 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4765 // We refresh timezone when a view is swapped in since timezone
4766 // can get out of sync when the system timezone is updated while
4767 // the view is swapped out.
4768 RenderThreadImpl::NotifyTimezoneChange();
4770 render_view_
->SetSwappedOut(false);
4771 is_swapped_out_
= false;
4775 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4776 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4777 switches::kEnableBrowserSideNavigation
));
4779 // TODO(clamy): Execute the beforeunload event.
4781 // Note: At this stage, the goal is to apply all the modifications the
4782 // renderer wants to make to the request, and then send it to the browser, so
4783 // that the actual network request can be started. Ideally, all such
4784 // modifications should take place in willSendRequest, and in the
4785 // implementation of willSendRequest for the various InspectorAgents
4788 // TODO(clamy): Apply devtools override.
4789 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4791 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4793 // TODO(clamy): Same-document navigations should not be sent back to the
4795 // TODO(clamy): Data urls should not be sent back to the browser either.
4796 bool should_replace_current_entry
= false;
4797 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4798 WebDataSource
* current_data_source
= frame_
->dataSource();
4799 WebDataSource
* data_source
=
4800 provisional_data_source
? provisional_data_source
: current_data_source
;
4802 // The current entry can only be replaced if there already is an entry in the
4804 if (data_source
&& render_view_
->history_list_length_
> 0) {
4805 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4807 Send(new FrameHostMsg_BeginNavigation(
4809 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4810 BeginNavigationParams(
4811 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4812 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4813 GetRequestBodyForWebURLRequest(*request
)));
4816 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4818 // A loadData request with a specified base URL.
4819 std::string mime_type
, charset
, data
;
4820 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4821 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4822 params
.url
: params
.base_url_for_data_url
;
4824 WebData(data
.c_str(), data
.length()),
4825 WebString::fromUTF8(mime_type
),
4826 WebString::fromUTF8(charset
),
4828 params
.history_url_for_data_url
,
4831 CHECK(false) << "Invalid URL passed: "
4832 << params
.url
.possibly_invalid_spec();
4836 void RenderFrameImpl::SendFailedProvisionalLoad(
4837 const blink::WebURLRequest
& request
,
4838 const blink::WebURLError
& error
,
4839 blink::WebLocalFrame
* frame
) {
4840 bool show_repost_interstitial
=
4841 (error
.reason
== net::ERR_CACHE_MISS
&&
4842 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4844 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4845 params
.error_code
= error
.reason
;
4846 GetContentClient()->renderer()->GetNavigationErrorStrings(
4847 render_view_
.get(), frame
, request
, error
, NULL
,
4848 ¶ms
.error_description
);
4849 params
.url
= error
.unreachableURL
;
4850 params
.showing_repost_interstitial
= show_repost_interstitial
;
4851 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4852 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4855 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4857 const GURL
& unreachable_url
) {
4858 // Don't display an error page if this is simply a cancelled load. Aside
4859 // from being dumb, Blink doesn't expect it and it will cause a crash.
4860 if (error_code
== net::ERR_ABORTED
)
4863 // Don't display "client blocked" error page if browser has asked us not to.
4864 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4865 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4869 // Allow the embedder to suppress an error page.
4870 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4871 this, unreachable_url
)) {
4875 if (RenderThreadImpl::current() &&
4876 RenderThreadImpl::current()->layout_test_mode()) {
4883 GURL
RenderFrameImpl::GetLoadingUrl() const {
4884 WebDataSource
* ds
= frame_
->dataSource();
4885 if (ds
->hasUnreachableURL())
4886 return ds
->unreachableURL();
4888 const WebURLRequest
& request
= ds
->request();
4889 return request
.url();
4892 void RenderFrameImpl::PopulateDocumentStateFromPending(
4893 DocumentState
* document_state
) {
4894 document_state
->set_request_time(
4895 pending_navigation_params_
->request_params
.request_time
);
4897 InternalDocumentStateData
* internal_data
=
4898 InternalDocumentStateData::FromDocumentState(document_state
);
4900 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4901 url::kJavaScriptScheme
) &&
4902 pending_navigation_params_
->common_params
.navigation_type
==
4903 FrameMsg_Navigate_Type::RESTORE
) {
4904 // We're doing a load of a page that was restored from the last session. By
4905 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4906 // can result in stale data for pages that are set to expire. We explicitly
4907 // override that by setting the policy here so that as necessary we load
4908 // from the network.
4910 // TODO(davidben): Remove this in favor of passing a cache policy to the
4911 // loadHistoryItem call in OnNavigate. That requires not overloading
4912 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4913 // policy based on load type, etc".
4914 internal_data
->set_cache_policy_override(
4915 WebURLRequest::UseProtocolCachePolicy
);
4918 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4919 document_state
->set_load_type(DocumentState::RELOAD
);
4920 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4921 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4923 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4925 internal_data
->set_is_overriding_user_agent(
4926 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4927 internal_data
->set_must_reset_scroll_and_scale_state(
4928 pending_navigation_params_
->common_params
.navigation_type
==
4929 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4930 document_state
->set_can_load_local_resources(
4931 pending_navigation_params_
->request_params
.can_load_local_resources
);
4934 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4935 // A navigation resulting from loading a javascript URL should not be treated
4936 // as a browser initiated event. Instead, we want it to look as if the page
4937 // initiated any load resulting from JS execution.
4938 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4939 url::kJavaScriptScheme
)) {
4940 return NavigationStateImpl::CreateBrowserInitiated(
4941 pending_navigation_params_
->common_params
,
4942 pending_navigation_params_
->start_params
,
4943 pending_navigation_params_
->request_params
);
4945 return NavigationStateImpl::CreateContentInitiated();
4948 #if defined(OS_ANDROID)
4950 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4951 WebMediaPlayerClient
* client
,
4952 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4953 media::MediaPermission
* media_permission
,
4954 WebContentDecryptionModule
* initial_cdm
) {
4955 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4956 if (SynchronousCompositorFactory
* factory
=
4957 SynchronousCompositorFactory::GetInstance()) {
4958 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4960 GpuChannelHost
* gpu_channel_host
=
4961 RenderThreadImpl::current()->EstablishGpuChannelSync(
4962 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4964 if (!gpu_channel_host
) {
4965 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4969 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4970 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4972 if (!context_provider
.get()) {
4973 LOG(ERROR
) << "Failed to get context3d for media player";
4977 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4978 context_provider
, gpu_channel_host
, routing_id_
);
4981 return new WebMediaPlayerAndroid(
4982 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
4983 GetMediaPlayerManager(), GetCdmFactory(), media_permission
, initial_cdm
,
4984 stream_texture_factory
,
4985 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4986 new RenderMediaLog());
4989 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4990 if (!media_player_manager_
)
4991 media_player_manager_
= new RendererMediaPlayerManager(this);
4992 return media_player_manager_
;
4995 #endif // defined(OS_ANDROID)
4997 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4998 if (!media_permission_dispatcher_
)
4999 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
5000 return media_permission_dispatcher_
;
5003 #if defined(ENABLE_MOJO_MEDIA)
5004 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5005 if (!media_service_factory_
) {
5006 mojo::InterfacePtr
<mojo::Shell
> shell_ptr
;
5007 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr
));
5009 mojo::ServiceProviderPtr service_provider
;
5010 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5011 request
->url
= mojo::String::From("mojo:media");
5012 shell_ptr
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5015 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5017 media_service_factory_
.set_connection_error_handler(
5018 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5019 base::Unretained(this)));
5022 return media_service_factory_
.get();
5025 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5026 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5027 // violation on the old |media_service_factory_| by outstanding
5028 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5030 // media_service_factory_.reset();
5034 bool RenderFrameImpl::AreSecureCodecsSupported() {
5035 #if defined(OS_ANDROID)
5036 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5037 return render_view_
->renderer_preferences_
5038 .use_video_overlay_for_embedded_encrypted_video
;
5041 #endif // defined(OS_ANDROID)
5044 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5045 #if defined(ENABLE_BROWSER_CDMS)
5047 cdm_manager_
= new RendererCdmManager(this);
5048 #endif // defined(ENABLE_BROWSER_CDMS)
5050 if (!cdm_factory_
) {
5053 #if defined(ENABLE_MOJO_MEDIA)
5054 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5056 cdm_factory_
.reset(new RenderCdmFactory(
5057 #if defined(ENABLE_PEPPER_CDMS)
5058 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5059 #elif defined(ENABLE_BROWSER_CDMS)
5063 #endif // defined(ENABLE_MOJO_MEDIA)
5066 return cdm_factory_
.get();
5069 void RenderFrameImpl::RegisterMojoServices() {
5070 // Only main frame have ImageDownloader service.
5071 if (!frame_
->parent()) {
5072 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5073 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5074 base::Unretained(this)));
5078 } // namespace content