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/accessibility_messages.h"
39 #include "content/common/clipboard_messages.h"
40 #include "content/common/frame_messages.h"
41 #include "content/common/frame_replication_state.h"
42 #include "content/common/input_messages.h"
43 #include "content/common/navigation_params.h"
44 #include "content/common/service_worker/service_worker_types.h"
45 #include "content/common/site_isolation_policy.h"
46 #include "content/common/swapped_out_messages.h"
47 #include "content/common/view_messages.h"
48 #include "content/public/common/bindings_policy.h"
49 #include "content/public/common/content_constants.h"
50 #include "content/public/common/content_switches.h"
51 #include "content/public/common/context_menu_params.h"
52 #include "content/public/common/isolated_world_ids.h"
53 #include "content/public/common/page_state.h"
54 #include "content/public/common/resource_response.h"
55 #include "content/public/common/url_constants.h"
56 #include "content/public/common/url_utils.h"
57 #include "content/public/renderer/browser_plugin_delegate.h"
58 #include "content/public/renderer/content_renderer_client.h"
59 #include "content/public/renderer/context_menu_client.h"
60 #include "content/public/renderer/document_state.h"
61 #include "content/public/renderer/navigation_state.h"
62 #include "content/public/renderer/render_frame_observer.h"
63 #include "content/public/renderer/renderer_ppapi_host.h"
64 #include "content/renderer/accessibility/renderer_accessibility.h"
65 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
66 #include "content/renderer/browser_plugin/browser_plugin.h"
67 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
68 #include "content/renderer/child_frame_compositing_helper.h"
69 #include "content/renderer/context_menu_params_builder.h"
70 #include "content/renderer/devtools/devtools_agent.h"
71 #include "content/renderer/dom_automation_controller.h"
72 #include "content/renderer/external_popup_menu.h"
73 #include "content/renderer/geolocation_dispatcher.h"
74 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
75 #include "content/renderer/history_controller.h"
76 #include "content/renderer/history_serialization.h"
77 #include "content/renderer/image_downloader/image_downloader_impl.h"
78 #include "content/renderer/ime_event_guard.h"
79 #include "content/renderer/internal_document_state_data.h"
80 #include "content/renderer/manifest/manifest_manager.h"
81 #include "content/renderer/media/audio_renderer_mixer_manager.h"
82 #include "content/renderer/media/crypto/render_cdm_factory.h"
83 #include "content/renderer/media/media_permission_dispatcher.h"
84 #include "content/renderer/media/media_stream_dispatcher.h"
85 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
86 #include "content/renderer/media/midi_dispatcher.h"
87 #include "content/renderer/media/render_media_log.h"
88 #include "content/renderer/media/user_media_client_impl.h"
89 #include "content/renderer/media/webmediaplayer_ms.h"
90 #include "content/renderer/memory_benchmarking_extension.h"
91 #include "content/renderer/mojo/service_registry_js_wrapper.h"
92 #include "content/renderer/navigation_state_impl.h"
93 #include "content/renderer/notification_permission_dispatcher.h"
94 #include "content/renderer/npapi/plugin_channel_host.h"
95 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
96 #include "content/renderer/presentation/presentation_dispatcher.h"
97 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
98 #include "content/renderer/render_frame_proxy.h"
99 #include "content/renderer/render_process.h"
100 #include "content/renderer/render_thread_impl.h"
101 #include "content/renderer/render_view_impl.h"
102 #include "content/renderer/render_widget_fullscreen_pepper.h"
103 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
104 #include "content/renderer/renderer_webcolorchooser_impl.h"
105 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
106 #include "content/renderer/shared_worker_repository.h"
107 #include "content/renderer/skia_benchmarking_extension.h"
108 #include "content/renderer/stats_collection_controller.h"
109 #include "content/renderer/web_ui_extension.h"
110 #include "content/renderer/websharedworker_proxy.h"
111 #include "gin/modules/module_registry.h"
112 #include "media/base/audio_renderer_mixer_input.h"
113 #include "media/base/media_log.h"
114 #include "media/blink/webencryptedmediaclient_impl.h"
115 #include "media/blink/webmediaplayer_impl.h"
116 #include "media/blink/webmediaplayer_params.h"
117 #include "media/renderers/gpu_video_accelerator_factories.h"
118 #include "net/base/data_url.h"
119 #include "net/base/net_errors.h"
120 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
121 #include "net/http/http_util.h"
122 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
123 #include "third_party/WebKit/public/platform/WebString.h"
124 #include "third_party/WebKit/public/platform/WebURL.h"
125 #include "third_party/WebKit/public/platform/WebURLError.h"
126 #include "third_party/WebKit/public/platform/WebURLResponse.h"
127 #include "third_party/WebKit/public/platform/WebVector.h"
128 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
129 #include "third_party/WebKit/public/web/WebDocument.h"
130 #include "third_party/WebKit/public/web/WebFrameWidget.h"
131 #include "third_party/WebKit/public/web/WebGlyphCache.h"
132 #include "third_party/WebKit/public/web/WebKit.h"
133 #include "third_party/WebKit/public/web/WebLocalFrame.h"
134 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
135 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
136 #include "third_party/WebKit/public/web/WebPlugin.h"
137 #include "third_party/WebKit/public/web/WebPluginParams.h"
138 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
139 #include "third_party/WebKit/public/web/WebRange.h"
140 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
141 #include "third_party/WebKit/public/web/WebScriptSource.h"
142 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
143 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
144 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
145 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
146 #include "third_party/WebKit/public/web/WebSettings.h"
147 #include "third_party/WebKit/public/web/WebSurroundingText.h"
148 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
149 #include "third_party/WebKit/public/web/WebView.h"
150 #include "third_party/mojo/src/mojo/edk/js/core.h"
151 #include "third_party/mojo/src/mojo/edk/js/support.h"
152 #include "url/url_util.h"
154 #if defined(ENABLE_PLUGINS)
155 #include "content/renderer/npapi/webplugin_impl.h"
156 #include "content/renderer/pepper/pepper_browser_connection.h"
157 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
158 #include "content/renderer/pepper/pepper_webplugin_impl.h"
159 #include "content/renderer/pepper/plugin_module.h"
162 #if defined(ENABLE_WEBRTC)
163 #include "content/renderer/media/rtc_peer_connection_handler.h"
166 #if defined(OS_ANDROID)
167 #include <cpu-features.h>
169 #include "content/common/gpu/client/context_provider_command_buffer.h"
170 #include "content/renderer/android/synchronous_compositor_factory.h"
171 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
172 #include "content/renderer/media/android/renderer_media_player_manager.h"
173 #include "content/renderer/media/android/stream_texture_factory_impl.h"
174 #include "content/renderer/media/android/webmediaplayer_android.h"
176 #include "cc/blink/context_provider_web_context.h"
179 #if defined(ENABLE_PEPPER_CDMS)
180 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
181 #elif defined(ENABLE_BROWSER_CDMS)
182 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
185 #if defined(ENABLE_MOJO_MEDIA)
186 #include "media/mojo/services/mojo_cdm_factory.h"
187 #include "media/mojo/services/mojo_renderer_factory.h"
188 #include "mojo/application/public/cpp/connect.h"
189 #include "mojo/application/public/interfaces/shell.mojom.h"
190 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
192 #include "media/renderers/default_renderer_factory.h"
195 #if defined(ENABLE_WEBVR)
196 #include "content/renderer/vr/vr_dispatcher.h"
199 using blink::WebContentDecryptionModule
;
200 using blink::WebContextMenuData
;
201 using blink::WebData
;
202 using blink::WebDataSource
;
203 using blink::WebDocument
;
204 using blink::WebDOMEvent
;
205 using blink::WebDOMMessageEvent
;
206 using blink::WebElement
;
207 using blink::WebExternalPopupMenu
;
208 using blink::WebExternalPopupMenuClient
;
209 using blink::WebFrame
;
210 using blink::WebHistoryItem
;
211 using blink::WebHTTPBody
;
212 using blink::WebLocalFrame
;
213 using blink::WebMediaPlayer
;
214 using blink::WebMediaPlayerClient
;
215 using blink::WebMediaPlayerEncryptedMediaClient
;
216 using blink::WebNavigationPolicy
;
217 using blink::WebNavigationType
;
218 using blink::WebNode
;
219 using blink::WebPluginParams
;
220 using blink::WebPopupMenuInfo
;
221 using blink::WebRange
;
222 using blink::WebReferrerPolicy
;
223 using blink::WebScriptSource
;
224 using blink::WebSearchableFormData
;
225 using blink::WebSecurityOrigin
;
226 using blink::WebSecurityPolicy
;
227 using blink::WebSerializedScriptValue
;
228 using blink::WebServiceWorkerProvider
;
229 using blink::WebSettings
;
230 using blink::WebStorageQuotaCallbacks
;
231 using blink::WebString
;
233 using blink::WebURLError
;
234 using blink::WebURLRequest
;
235 using blink::WebURLResponse
;
236 using blink::WebUserGestureIndicator
;
237 using blink::WebVector
;
238 using blink::WebView
;
240 using base::TimeDelta
;
246 const char kDefaultAcceptHeader
[] =
247 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
249 const char kAcceptHeader
[] = "Accept";
251 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
253 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
254 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
255 LAZY_INSTANCE_INITIALIZER
;
257 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
258 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
260 int64
ExtractPostId(HistoryEntry
* entry
) {
264 const WebHistoryItem
& item
= entry
->root();
265 if (item
.isNull() || item
.httpBody().isNull())
268 return item
.httpBody().identifier();
271 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
272 const WebURLResponse
& response
) {
273 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
276 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
277 // Replace any occurrences of swappedout:// with about:blank.
278 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
279 WebVector
<WebURL
> urls
;
280 ds
->redirectChain(urls
);
281 result
->reserve(urls
.size());
282 for (size_t i
= 0; i
< urls
.size(); ++i
) {
283 if (urls
[i
] != GURL(kSwappedOutURL
))
284 result
->push_back(urls
[i
]);
286 result
->push_back(blank_url
);
290 // Returns the original request url. If there is no redirect, the original
291 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
292 // frame was loaded by loadData, the original url will be ds->unreachableURL()
293 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
294 // WebDataSource has unreachable URL means that the frame is loaded through
295 // blink::WebFrame::loadData(), and the base URL will be in the redirect
296 // chain. However, we never visited the baseURL. So in this case, we should
297 // use the unreachable URL as the original URL.
298 if (ds
->hasUnreachableURL())
299 return ds
->unreachableURL();
301 std::vector
<GURL
> redirects
;
302 GetRedirectChain(ds
, &redirects
);
303 if (!redirects
.empty())
304 return redirects
.at(0);
306 return ds
->originalRequest().url();
309 NOINLINE
void CrashIntentionally() {
310 // NOTE(shess): Crash directly rather than using NOTREACHED() so
311 // that the signature is easier to triage in crash reports.
312 volatile int* zero
= NULL
;
316 NOINLINE
void BadCastCrashIntentionally() {
329 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
330 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
331 // NOTE(rogerm): We intentionally perform an invalid heap access here in
332 // order to trigger an Address Sanitizer (ASAN) error report.
333 const char kCrashDomain
[] = "crash";
334 const char kHeapOverflow
[] = "/heap-overflow";
335 const char kHeapUnderflow
[] = "/heap-underflow";
336 const char kUseAfterFree
[] = "/use-after-free";
337 #if defined(SYZYASAN)
338 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
339 const char kCorruptHeap
[] = "/corrupt-heap";
342 if (!url
.DomainIs(kCrashDomain
))
348 std::string
crash_type(url
.path());
349 if (crash_type
== kHeapOverflow
) {
350 base::debug::AsanHeapOverflow();
351 } else if (crash_type
== kHeapUnderflow
) {
352 base::debug::AsanHeapUnderflow();
353 } else if (crash_type
== kUseAfterFree
) {
354 base::debug::AsanHeapUseAfterFree();
355 #if defined(SYZYASAN)
356 } else if (crash_type
== kCorruptHeapBlock
) {
357 base::debug::AsanCorruptHeapBlock();
358 } else if (crash_type
== kCorruptHeap
) {
359 base::debug::AsanCorruptHeap();
363 #endif // ADDRESS_SANITIZER || SYZYASAN
365 void MaybeHandleDebugURL(const GURL
& url
) {
366 if (!url
.SchemeIs(kChromeUIScheme
))
368 if (url
== GURL(kChromeUIBadCastCrashURL
)) {
369 BadCastCrashIntentionally();
370 } else if (url
== GURL(kChromeUICrashURL
)) {
371 CrashIntentionally();
372 } else if (url
== GURL(kChromeUIDumpURL
)) {
373 // This URL will only correctly create a crash dump file if content is
374 // hosted in a process that has correctly called
375 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
376 // of base::debug::DumpWithoutCrashing for more details.
377 base::debug::DumpWithoutCrashing();
378 } else if (url
== GURL(kChromeUIKillURL
)) {
379 base::Process::Current().Terminate(1, false);
380 } else if (url
== GURL(kChromeUIHangURL
)) {
382 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
384 } else if (url
== GURL(kChromeUIShorthangURL
)) {
385 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
388 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
389 MaybeTriggerAsanError(url
);
390 #endif // ADDRESS_SANITIZER || SYZYASAN
393 // Returns false unless this is a top-level navigation.
394 bool IsTopLevelNavigation(WebFrame
* frame
) {
395 return frame
->parent() == NULL
;
398 // Returns false unless this is a top-level navigation that crosses origins.
399 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
401 WebNavigationType type
,
403 if (!IsTopLevelNavigation(frame
))
406 // Navigations initiated within Webkit are not sent out to the external host
407 // in the following cases.
408 // 1. The url scheme is not http/https
409 // 2. The origin of the url and the opener is the same in which case the
410 // opener relationship is maintained.
411 // 3. Reloads/form submits/back forward navigations
412 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
415 if (type
!= blink::WebNavigationTypeReload
&&
416 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
417 // The opener relationship between the new window and the parent allows the
418 // new window to script the parent and vice versa. This is not allowed if
419 // the origins of the two domains are different. This can be treated as a
420 // top level navigation and routed back to the host.
421 blink::WebFrame
* opener
= frame
->opener();
425 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
431 WebURLRequest
CreateURLRequestForNavigation(
432 const CommonNavigationParams
& common_params
,
433 scoped_ptr
<StreamOverrideParameters
> stream_override
,
434 bool is_view_source_mode_enabled
) {
435 WebURLRequest
request(common_params
.url
);
436 if (is_view_source_mode_enabled
)
437 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
439 if (common_params
.referrer
.url
.is_valid()) {
440 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
441 common_params
.referrer
.policy
,
443 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
444 if (!web_referrer
.isEmpty())
445 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
448 RequestExtraData
* extra_data
= new RequestExtraData();
449 extra_data
->set_stream_override(stream_override
.Pass());
450 request
.setExtraData(extra_data
);
452 // Set the ui timestamp for this navigation. Currently the timestamp here is
453 // only non empty when the navigation was triggered by an Android intent. The
454 // timestamp is converted to a double version supported by blink. It will be
455 // passed back to the browser in the DidCommitProvisionalLoad and the
456 // DocumentLoadComplete IPCs.
457 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
458 request
.setUiStartTime(ui_timestamp
.InSecondsF());
459 request
.setInputPerfMetricReportPolicy(
460 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
461 common_params
.report_type
));
465 void UpdateFrameNavigationTiming(WebFrame
* frame
,
466 base::TimeTicks browser_navigation_start
,
467 base::TimeTicks renderer_navigation_start
) {
468 // The browser provides the navigation_start time to bootstrap the
469 // Navigation Timing information for the browser-initiated navigations. In
470 // case of cross-process navigations, this carries over the time of
471 // finishing the onbeforeunload handler of the previous page.
472 DCHECK(!browser_navigation_start
.is_null());
473 if (frame
->provisionalDataSource()) {
474 // |browser_navigation_start| is likely before this process existed, so we
475 // can't use InterProcessTimeTicksConverter. We need at least to ensure
476 // that the browser-side navigation start we set is not later than the one
477 // on the renderer side.
478 base::TimeTicks navigation_start
= std::min(
479 browser_navigation_start
, renderer_navigation_start
);
480 double navigation_start_seconds
=
481 (navigation_start
- base::TimeTicks()).InSecondsF();
482 frame
->provisionalDataSource()->setNavigationStartTime(
483 navigation_start_seconds
);
484 // TODO(clamy): We need to provide additional timing values for the
485 // Navigation Timing API to work with browser-side navigations.
490 CommonNavigationParams
MakeCommonNavigationParams(
491 blink::WebURLRequest
* request
,
492 bool should_replace_current_entry
) {
493 const RequestExtraData kEmptyData
;
494 const RequestExtraData
* extra_data
=
495 static_cast<RequestExtraData
*>(request
->extraData());
497 extra_data
= &kEmptyData
;
499 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
500 request
->referrerPolicy());
502 // Set the ui timestamp for this navigation. Currently the timestamp here is
503 // only non empty when the navigation was triggered by an Android intent, or
504 // by the user clicking on a link. The timestamp is converted from a double
505 // version supported by blink. It will be passed back to the renderer in the
506 // CommitNavigation IPC, and then back to the browser again in the
507 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
508 base::TimeTicks ui_timestamp
=
509 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
510 FrameMsg_UILoadMetricsReportType::Value report_type
=
511 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
512 request
->inputPerfMetricReportPolicy());
513 return CommonNavigationParams(
514 request
->url(), referrer
, extra_data
->transition_type(),
515 FrameMsg_Navigate_Type::NORMAL
, true, should_replace_current_entry
,
516 ui_timestamp
, report_type
, GURL(), GURL());
519 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
520 media::Context3D
GetSharedMainThreadContext3D() {
521 cc::ContextProvider
* provider
=
522 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
524 return media::Context3D();
525 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
529 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
530 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
531 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
532 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
535 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
541 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
543 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
544 CreateParams
params(render_view
, routing_id
);
546 if (g_create_render_frame_impl
)
547 return g_create_render_frame_impl(params
);
549 return new RenderFrameImpl(params
);
553 RenderFrame
* RenderFrame::FromRoutingID(int routing_id
) {
554 return RenderFrameImpl::FromRoutingID(routing_id
);
558 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int routing_id
) {
559 RoutingIDFrameMap::iterator iter
=
560 g_routing_id_frame_map
.Get().find(routing_id
);
561 if (iter
!= g_routing_id_frame_map
.Get().end())
567 void RenderFrameImpl::CreateFrame(
569 int parent_routing_id
,
570 int previous_sibling_routing_id
,
571 int proxy_routing_id
,
572 const FrameReplicationState
& replicated_state
,
573 CompositorDependencies
* compositor_deps
,
574 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
575 blink::WebLocalFrame
* web_frame
;
576 RenderFrameImpl
* render_frame
;
577 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
578 RenderFrameProxy
* parent_proxy
=
579 RenderFrameProxy::FromRoutingID(parent_routing_id
);
580 // If the browser is sending a valid parent routing id, it should already
581 // be created and registered.
583 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
585 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
586 RenderFrameProxy
* previous_sibling_proxy
=
587 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
588 if (previous_sibling_proxy
)
589 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
591 // Create the RenderFrame and WebLocalFrame, linking the two.
593 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
594 web_frame
= parent_web_frame
->createLocalChild(
595 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
596 replicated_state
.sandbox_flags
, render_frame
,
597 previous_sibling_web_frame
);
599 RenderFrameProxy
* proxy
=
600 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
602 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
604 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
605 render_frame
->proxy_routing_id_
= proxy_routing_id
;
606 web_frame
->initializeToReplaceRemoteFrame(
607 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
608 replicated_state
.sandbox_flags
);
610 render_frame
->SetWebFrame(web_frame
);
611 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
613 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
614 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
615 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
616 widget_params
.routing_id
, widget_params
.surface_id
,
617 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
618 compositor_deps
, web_frame
);
619 // TODO(kenrb): Observing shouldn't be necessary when we sort out
620 // WasShown and WasHidden, separating page-level visibility from
621 // frame-level visibility.
622 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
625 render_frame
->Initialize();
629 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
630 return RenderFrameImpl::FromWebFrame(web_frame
);
634 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
635 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
636 if (iter
!= g_frame_map
.Get().end())
642 void RenderFrameImpl::InstallCreateHook(
643 CreateRenderFrameImplFunction create_render_frame_impl
) {
644 CHECK(!g_create_render_frame_impl
);
645 g_create_render_frame_impl
= create_render_frame_impl
;
648 // RenderFrameImpl ----------------------------------------------------------
649 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
652 is_local_root_(false),
653 render_view_(params
.render_view
->AsWeakPtr()),
654 routing_id_(params
.routing_id
),
655 is_swapped_out_(false),
656 render_frame_proxy_(NULL
),
657 is_detaching_(false),
658 proxy_routing_id_(MSG_ROUTING_NONE
),
659 #if defined(ENABLE_PLUGINS)
660 plugin_power_saver_helper_(NULL
),
663 selection_text_offset_(0),
664 selection_range_(gfx::Range::InvalidRange()),
665 handling_select_range_(false),
666 notification_permission_dispatcher_(NULL
),
667 web_user_media_client_(NULL
),
668 media_permission_dispatcher_(NULL
),
669 midi_dispatcher_(NULL
),
670 #if defined(OS_ANDROID)
671 media_player_manager_(NULL
),
673 #if defined(ENABLE_BROWSER_CDMS)
676 #if defined(VIDEO_HOLE)
677 contains_media_player_(false),
679 devtools_agent_(nullptr),
680 geolocation_dispatcher_(NULL
),
681 push_messaging_dispatcher_(NULL
),
682 presentation_dispatcher_(NULL
),
683 screen_orientation_dispatcher_(NULL
),
684 manifest_manager_(NULL
),
685 accessibility_mode_(AccessibilityModeOff
),
686 renderer_accessibility_(NULL
),
687 weak_factory_(this) {
688 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
689 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
690 CHECK(result
.second
) << "Inserting a duplicate item.";
692 RenderThread::Get()->AddRoute(routing_id_
, this);
694 render_view_
->RegisterRenderFrame(this);
696 // Everything below subclasses RenderFrameObserver and is automatically
697 // deleted when the RenderFrame gets deleted.
698 #if defined(OS_ANDROID)
699 new GinJavaBridgeDispatcher(this);
702 #if defined(ENABLE_PLUGINS)
703 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
706 manifest_manager_
= new ManifestManager(this);
709 RenderFrameImpl::~RenderFrameImpl() {
710 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
711 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
713 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
715 #if defined(VIDEO_HOLE)
716 if (contains_media_player_
)
717 render_view_
->UnregisterVideoHoleFrame(this);
721 // When using swapped out frames, RenderFrameProxy is owned by
722 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
723 // along with this object.
724 if (render_frame_proxy_
&&
725 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
726 // The following method calls back into this object and clears
727 // |render_frame_proxy_|.
728 render_frame_proxy_
->frameDetached(
729 blink::WebRemoteFrameClient::DetachType::Remove
);
732 // Ensure the RenderView doesn't point to this object, once it is destroyed.
733 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
734 // is |this|, once the object is no longer leaked.
735 // See https://crbug.com/464764.
736 render_view_
->main_render_frame_
= nullptr;
739 render_view_
->UnregisterRenderFrame(this);
740 g_routing_id_frame_map
.Get().erase(routing_id_
);
741 RenderThread::Get()->RemoveRoute(routing_id_
);
744 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
747 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
748 std::make_pair(web_frame
, this));
749 CHECK(result
.second
) << "Inserting a duplicate item.";
754 void RenderFrameImpl::Initialize() {
755 is_subframe_
= !!frame_
->parent();
756 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
758 #if defined(ENABLE_PLUGINS)
759 new PepperBrowserConnection(this);
761 new SharedWorkerRepository(this);
763 if (is_local_root_
&& !render_frame_proxy_
) {
764 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
765 // when |this| is deleted.
766 devtools_agent_
= new DevToolsAgent(this);
769 RegisterMojoServices();
771 // We delay calling this until we have the WebFrame so that any observer or
772 // embedder can call GetWebFrame on any RenderFrame.
773 GetContentClient()->renderer()->RenderFrameCreated(this);
776 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
777 return render_view_
.get();
780 #if defined(ENABLE_PLUGINS)
781 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
782 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
783 DidCreatePepperPlugin(host
));
784 if (host
->GetPluginName() == kFlashPluginName
) {
785 RenderThread::Get()->RecordAction(
786 base::UserMetricsAction("FrameLoadWithFlash"));
790 void RenderFrameImpl::PepperDidChangeCursor(
791 PepperPluginInstanceImpl
* instance
,
792 const blink::WebCursorInfo
& cursor
) {
793 // Update the cursor appearance immediately if the requesting plugin is the
794 // one which receives the last mouse event. Otherwise, the new cursor won't be
795 // picked up until the plugin gets the next input event. That is bad if, e.g.,
796 // the plugin would like to set an invisible cursor when there isn't any user
797 // input for a while.
798 if (instance
== render_view_
->pepper_last_mouse_event_target())
799 GetRenderWidget()->didChangeCursor(cursor
);
802 void RenderFrameImpl::PepperDidReceiveMouseEvent(
803 PepperPluginInstanceImpl
* instance
) {
804 render_view_
->set_pepper_last_mouse_event_target(instance
);
807 void RenderFrameImpl::PepperTextInputTypeChanged(
808 PepperPluginInstanceImpl
* instance
) {
809 if (instance
!= render_view_
->focused_pepper_plugin())
812 GetRenderWidget()->UpdateTextInputState(
813 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
815 FocusedNodeChangedForAccessibility(WebNode());
818 void RenderFrameImpl::PepperCaretPositionChanged(
819 PepperPluginInstanceImpl
* instance
) {
820 if (instance
!= render_view_
->focused_pepper_plugin())
822 GetRenderWidget()->UpdateSelectionBounds();
825 void RenderFrameImpl::PepperCancelComposition(
826 PepperPluginInstanceImpl
* instance
) {
827 if (instance
!= render_view_
->focused_pepper_plugin())
829 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
830 #if defined(OS_MACOSX) || defined(USE_AURA)
831 GetRenderWidget()->UpdateCompositionInfo(true);
835 void RenderFrameImpl::PepperSelectionChanged(
836 PepperPluginInstanceImpl
* instance
) {
837 if (instance
!= render_view_
->focused_pepper_plugin())
839 SyncSelectionIfRequired();
842 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
843 PepperPluginInstanceImpl
* plugin
) {
845 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
846 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
847 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
848 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
849 plugin
, active_url
, GetRenderWidget()->screenInfo());
850 widget
->show(blink::WebNavigationPolicyIgnore
);
854 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
855 if (!render_view_
->focused_pepper_plugin())
857 return render_view_
->focused_pepper_plugin()->
858 IsPluginAcceptingCompositionEvents();
861 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
862 base::ProcessId plugin_pid
) {
863 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
864 // routing_id_ as a result.
865 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
868 void RenderFrameImpl::SimulateImeSetComposition(
869 const base::string16
& text
,
870 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
873 render_view_
->OnImeSetComposition(
874 text
, underlines
, selection_start
, selection_end
);
877 void RenderFrameImpl::SimulateImeConfirmComposition(
878 const base::string16
& text
,
879 const gfx::Range
& replacement_range
) {
880 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
883 void RenderFrameImpl::OnImeSetComposition(
884 const base::string16
& text
,
885 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
888 // When a PPAPI plugin has focus, we bypass WebKit.
889 if (!IsPepperAcceptingCompositionEvents()) {
890 pepper_composition_text_
= text
;
892 // TODO(kinaba) currently all composition events are sent directly to
893 // plugins. Use DOM event mechanism after WebKit is made aware about
894 // plugins that support composition.
895 // The code below mimics the behavior of WebCore::Editor::setComposition.
897 // Empty -> nonempty: composition started.
898 if (pepper_composition_text_
.empty() && !text
.empty()) {
899 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
902 // Nonempty -> empty: composition canceled.
903 if (!pepper_composition_text_
.empty() && text
.empty()) {
904 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
907 pepper_composition_text_
= text
;
908 // Nonempty: composition is ongoing.
909 if (!pepper_composition_text_
.empty()) {
910 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
911 pepper_composition_text_
, underlines
, selection_start
,
917 void RenderFrameImpl::OnImeConfirmComposition(
918 const base::string16
& text
,
919 const gfx::Range
& replacement_range
,
920 bool keep_selection
) {
921 // When a PPAPI plugin has focus, we bypass WebKit.
922 // Here, text.empty() has a special meaning. It means to commit the last
923 // update of composition text (see
924 // RenderWidgetHost::ImeConfirmComposition()).
925 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
928 // last_text is empty only when both text and pepper_composition_text_ is.
930 if (last_text
.empty())
933 if (!IsPepperAcceptingCompositionEvents()) {
934 base::i18n::UTF16CharIterator
iterator(&last_text
);
936 while (iterator
.Advance()) {
937 blink::WebKeyboardEvent char_event
;
938 char_event
.type
= blink::WebInputEvent::Char
;
939 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
940 char_event
.modifiers
= 0;
941 char_event
.windowsKeyCode
= last_text
[i
];
942 char_event
.nativeKeyCode
= last_text
[i
];
944 const int32 char_start
= i
;
945 for (; i
< iterator
.array_pos(); ++i
) {
946 char_event
.text
[i
- char_start
] = last_text
[i
];
947 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
950 if (GetRenderWidget()->webwidget())
951 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
954 // Mimics the order of events sent by WebKit.
955 // See WebCore::Editor::setComposition() for the corresponding code.
956 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
957 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
959 pepper_composition_text_
.clear();
961 #endif // defined(ENABLE_PLUGINS)
963 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
964 if (!web_user_media_client_
)
965 InitializeUserMediaClient();
966 return web_user_media_client_
?
967 web_user_media_client_
->media_stream_dispatcher() : NULL
;
970 bool RenderFrameImpl::Send(IPC::Message
* message
) {
975 if (is_swapped_out_
) {
976 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
982 return RenderThread::Get()->Send(message
);
985 #if defined(OS_MACOSX) || defined(OS_ANDROID)
986 void RenderFrameImpl::DidHideExternalPopupMenu() {
987 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
988 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
989 external_popup_menu_
.reset();
993 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
994 // We may get here while detaching, when the WebFrame has been deleted. Do
995 // not process any messages in this state.
999 // TODO(kenrb): document() should not be null, but as a transitional step
1000 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1001 // to this method. This happens for a top-level remote frame, where a
1002 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1003 // around and is still able to receive messages.
1004 if (!frame_
->document().isNull())
1005 GetContentClient()->SetActiveURL(frame_
->document().url());
1007 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
1008 RenderFrameObserver
* observer
;
1009 while ((observer
= it
.GetNext()) != NULL
) {
1010 if (observer
->OnMessageReceived(msg
))
1014 bool handled
= true;
1015 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1016 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1017 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1018 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1019 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1020 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1021 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1022 OnCustomContextMenuAction
)
1023 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1024 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1025 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1026 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1027 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1028 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1029 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1030 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1031 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1032 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1033 OnAdjustSelectionByCharacterOffset
)
1034 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1035 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1036 OnMoveRangeSelectionExtent
)
1037 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1038 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1039 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1040 OnExtendSelectionAndDelete
)
1041 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1042 OnSetCompositionFromExistingText
)
1043 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1044 OnExecuteNoValueEditCommand
)
1045 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1046 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1047 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1048 OnJavaScriptExecuteRequest
)
1049 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1050 OnJavaScriptExecuteRequestForTests
)
1051 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1052 OnJavaScriptExecuteRequestInIsolatedWorld
)
1053 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1054 OnVisualStateRequest
)
1055 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1056 OnSetEditableSelectionOffsets
)
1057 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1058 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1059 OnTextSurroundingSelectionRequest
)
1060 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1061 OnSetAccessibilityMode
)
1062 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1063 OnSnapshotAccessibilityTree
)
1064 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1065 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1066 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1067 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1068 OnTextTrackSettingsChanged
)
1069 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1070 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1071 #if defined(OS_ANDROID)
1072 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1073 #elif defined(OS_MACOSX)
1074 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1075 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1077 IPC_END_MESSAGE_MAP()
1082 void RenderFrameImpl::OnNavigate(
1083 const CommonNavigationParams
& common_params
,
1084 const StartNavigationParams
& start_params
,
1085 const RequestNavigationParams
& request_params
) {
1086 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1087 switches::kEnableBrowserSideNavigation
));
1088 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1089 "url", common_params
.url
.possibly_invalid_spec());
1090 NavigateInternal(common_params
, start_params
, request_params
,
1091 scoped_ptr
<StreamOverrideParameters
>());
1094 void RenderFrameImpl::NavigateToSwappedOutURL() {
1095 // We use loadRequest instead of loadHTMLString because the former commits
1096 // synchronously. Otherwise a new navigation can interrupt the navigation
1097 // to kSwappedOutURL. If that happens to be to the page we had been
1098 // showing, then WebKit will never send a commit and we'll be left spinning.
1099 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1100 // the navigation to swappedout:// is not announced to the browser side.
1101 is_swapped_out_
= true;
1102 GURL
swappedOutURL(kSwappedOutURL
);
1103 WebURLRequest
request(swappedOutURL
);
1104 frame_
->loadRequest(request
);
1107 void RenderFrameImpl::BindServiceRegistry(
1108 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1109 mojo::ServiceProviderPtr exposed_services
) {
1110 service_registry_
.Bind(services
.Pass());
1111 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1114 ManifestManager
* RenderFrameImpl::manifest_manager() {
1115 return manifest_manager_
;
1118 void RenderFrameImpl::SetPendingNavigationParams(
1119 scoped_ptr
<NavigationParams
> navigation_params
) {
1120 pending_navigation_params_
= navigation_params
.Pass();
1123 void RenderFrameImpl::OnBeforeUnload() {
1124 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1126 // TODO(creis): Right now, this is only called on the main frame. Make the
1127 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1129 CHECK(!frame_
->parent());
1131 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1132 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1133 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1134 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1135 before_unload_start_time
,
1136 before_unload_end_time
));
1139 void RenderFrameImpl::OnSwapOut(
1140 int proxy_routing_id
,
1142 const FrameReplicationState
& replicated_frame_state
) {
1143 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1144 RenderFrameProxy
* proxy
= NULL
;
1145 bool swapped_out_forbidden
=
1146 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1147 bool is_main_frame
= !frame_
->parent();
1149 // This codepath should only be hit for subframes when in --site-per-process.
1150 CHECK_IMPLIES(!is_main_frame
,
1151 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1153 // Only run unload if we're not swapped out yet, but send the ack either way.
1154 if (!is_swapped_out_
) {
1155 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1156 // a different process. This involves running the unload handler and
1157 // clearing the page. We also allow this process to exit if there are no
1158 // other active RenderFrames in it.
1160 // Send an UpdateState message before we get swapped out.
1161 render_view_
->SendUpdateState();
1163 // If we need a proxy to replace this, create it now so its routing id is
1164 // registered for receiving IPC messages.
1165 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1166 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1167 this, proxy_routing_id
, replicated_frame_state
.scope
);
1170 // Synchronously run the unload handler before sending the ACK.
1171 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1172 // unload on subframes as well.
1174 frame_
->dispatchUnloadEvent();
1176 // Swap out and stop sending any IPC messages that are not ACKs.
1178 render_view_
->SetSwappedOut(true);
1179 is_swapped_out_
= true;
1181 // Set the proxy here, since OnStop() below could cause an onload event
1182 // handler to execute, which could trigger code such as
1183 // willCheckAndDispatchMessageEvent() that needs the proxy.
1185 set_render_frame_proxy(proxy
);
1187 // Now that we're swapped out and filtering IPC messages, stop loading to
1188 // ensure that no other in-progress navigation continues. We do this here
1189 // to avoid sending a DidStopLoading message to the browser process.
1190 // TODO(creis): Should we be stopping all frames here and using
1191 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1193 if (!swapped_out_forbidden
)
1196 // Transfer settings such as initial drawing parameters to the remote frame,
1197 // if one is created, that will replace this frame.
1198 if (!is_main_frame
&& proxy
)
1199 proxy
->web_frame()->initializeFromFrame(frame_
);
1201 // Replace the page with a blank dummy URL. The unload handler will not be
1202 // run a second time, thanks to a check in FrameLoader::stopLoading.
1203 // TODO(creis): Need to add a better way to do this that avoids running the
1204 // beforeunload handler. For now, we just run it a second time silently.
1205 if (!swapped_out_forbidden
)
1206 NavigateToSwappedOutURL();
1208 // Let WebKit know that this view is hidden so it can drop resources and
1209 // stop compositing.
1210 // TODO(creis): Support this for subframes as well.
1211 if (is_main_frame
) {
1212 render_view_
->webview()->setVisibilityState(
1213 blink::WebPageVisibilityStateHidden
, false);
1217 // It is now safe to show modal dialogs again.
1218 // TODO(creis): Deal with modal dialogs from subframes.
1220 render_view_
->suppress_dialogs_until_swap_out_
= false;
1222 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1224 RenderViewImpl
* render_view
= render_view_
.get();
1226 // Now that all of the cleanup is complete and the browser side is notified,
1227 // start using the RenderFrameProxy, if one is created.
1228 if (proxy
&& swapped_out_forbidden
) {
1229 frame_
->swap(proxy
->web_frame());
1232 proxy
->OnDidStartLoading();
1235 // In --site-per-process, initialize the WebRemoteFrame with the replication
1236 // state passed by the process that is now rendering the frame.
1237 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1238 // in that case we leave the LocalFrame as the main frame visible to Blink
1239 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1240 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1241 // When we do an unconditional swap for all frames, we can remove
1242 // !is_main_frame below.
1243 if (proxy
&& swapped_out_forbidden
)
1244 proxy
->SetReplicatedState(replicated_frame_state
);
1246 // Safe to exit if no one else is using the process.
1247 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1248 // the process based on the lifetime of this RenderFrameImpl object.
1249 if (is_main_frame
) {
1250 render_view
->WasSwappedOut();
1254 void RenderFrameImpl::OnContextMenuClosed(
1255 const CustomContextMenuContext
& custom_context
) {
1256 if (custom_context
.request_id
) {
1257 // External request, should be in our map.
1258 ContextMenuClient
* client
=
1259 pending_context_menus_
.Lookup(custom_context
.request_id
);
1261 client
->OnMenuClosed(custom_context
.request_id
);
1262 pending_context_menus_
.Remove(custom_context
.request_id
);
1265 if (custom_context
.link_followed
.is_valid())
1266 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1267 // Internal request, forward to WebKit.
1268 context_menu_node_
.reset();
1272 void RenderFrameImpl::OnCustomContextMenuAction(
1273 const CustomContextMenuContext
& custom_context
,
1275 if (custom_context
.request_id
) {
1276 // External context menu request, look in our map.
1277 ContextMenuClient
* client
=
1278 pending_context_menus_
.Lookup(custom_context
.request_id
);
1280 client
->OnMenuAction(custom_context
.request_id
, action
);
1282 // Internal request, forward to WebKit.
1283 render_view_
->webview()->performCustomContextMenuAction(action
);
1287 void RenderFrameImpl::OnUndo() {
1288 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1291 void RenderFrameImpl::OnRedo() {
1292 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1295 void RenderFrameImpl::OnCut() {
1296 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1297 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1300 void RenderFrameImpl::OnCopy() {
1301 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1302 WebNode current_node
= context_menu_node_
.isNull() ?
1303 GetFocusedElement() : context_menu_node_
;
1304 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1307 void RenderFrameImpl::OnPaste() {
1308 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1309 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1312 void RenderFrameImpl::OnPasteAndMatchStyle() {
1313 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1314 frame_
->executeCommand(
1315 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1318 #if defined(OS_MACOSX)
1319 void RenderFrameImpl::OnCopyToFindPboard() {
1320 // Since the find pasteboard supports only plain text, this can be simpler
1321 // than the |OnCopy()| case.
1322 if (frame_
->hasSelection()) {
1323 base::string16 selection
= frame_
->selectionAsText();
1324 RenderThread::Get()->Send(
1325 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1330 void RenderFrameImpl::OnDelete() {
1331 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1334 void RenderFrameImpl::OnSelectAll() {
1335 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1336 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1339 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1340 const gfx::Point
& extent
) {
1341 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1342 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1344 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1345 frame_
->selectRange(base
, extent
);
1348 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1350 size_t start
, length
;
1351 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1356 // Sanity checks to disallow empty and out of range selections.
1357 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1358 || static_cast<int>(start
) + start_adjust
< 0) {
1362 // A negative adjust amount moves the selection towards the beginning of
1363 // the document, a positive amount moves the selection towards the end of
1365 start
+= start_adjust
;
1366 length
+= end_adjust
- start_adjust
;
1368 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1371 void RenderFrameImpl::OnUnselect() {
1372 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1373 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1376 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1377 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1378 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1379 GetRenderWidget()->routing_id()));
1381 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1382 frame_
->moveRangeSelectionExtent(point
);
1385 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1386 if (!frame_
->hasSelection())
1387 frame_
->selectWordAroundCaret();
1389 frame_
->replaceSelection(text
);
1392 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1393 if (!frame_
->hasSelection())
1396 frame_
->replaceMisspelledRange(text
);
1399 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1400 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1403 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1404 const std::string
& message
) {
1405 AddMessageToConsole(level
, message
);
1408 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1409 const base::string16
& jscript
,
1411 bool notify_result
) {
1412 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1413 TRACE_EVENT_SCOPE_THREAD
);
1415 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1416 v8::Local
<v8::Value
> result
=
1417 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1419 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1422 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1423 const base::string16
& jscript
,
1426 bool has_user_gesture
) {
1427 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1428 TRACE_EVENT_SCOPE_THREAD
);
1430 // A bunch of tests expect to run code in the context of a user gesture, which
1431 // can grant additional privileges (e.g. the ability to create popups).
1432 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1433 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1434 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1435 v8::Local
<v8::Value
> result
=
1436 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1438 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1441 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1442 const base::string16
& jscript
,
1446 TRACE_EVENT_INSTANT0("test_tracing",
1447 "OnJavaScriptExecuteRequestInIsolatedWorld",
1448 TRACE_EVENT_SCOPE_THREAD
);
1450 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1451 world_id
> ISOLATED_WORLD_ID_MAX
) {
1452 // Return if the world_id is not valid. world_id is passed as a plain int
1453 // over IPC and needs to be verified here, in the IPC endpoint.
1458 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1459 WebScriptSource script
= WebScriptSource(jscript
);
1460 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1461 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1462 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1466 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1470 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1472 notify_result_(notify_result
),
1473 routing_id_(routing_id
),
1474 render_frame_impl_(render_frame_impl
) {
1477 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1478 ~JavaScriptIsolatedWorldRequest() {
1481 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1482 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1483 if (!render_frame_impl_
.get()) {
1487 if (notify_result_
) {
1488 base::ListValue list
;
1489 if (!result
.isEmpty()) {
1490 // It's safe to always use the main world context when converting
1491 // here. V8ValueConverterImpl shouldn't actually care about the
1492 // context scope, and it switches to v8::Object's creation context
1493 // when encountered. (from extensions/renderer/script_injection.cc)
1494 v8::Local
<v8::Context
> context
=
1495 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1496 v8::Context::Scope
context_scope(context
);
1497 V8ValueConverterImpl converter
;
1498 converter
.SetDateAllowed(true);
1499 converter
.SetRegExpAllowed(true);
1500 for (const auto& value
: result
) {
1501 scoped_ptr
<base::Value
> result_value(
1502 converter
.FromV8Value(value
, context
));
1503 list
.Append(result_value
? result_value
.Pass()
1504 : base::Value::CreateNullValue());
1507 list
.Set(0, base::Value::CreateNullValue());
1509 render_frame_impl_
.get()->Send(
1510 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1516 void RenderFrameImpl::HandleJavascriptExecutionResult(
1517 const base::string16
& jscript
,
1520 v8::Local
<v8::Value
> result
) {
1521 if (notify_result
) {
1522 base::ListValue list
;
1523 if (!result
.IsEmpty()) {
1524 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1525 v8::Context::Scope
context_scope(context
);
1526 V8ValueConverterImpl converter
;
1527 converter
.SetDateAllowed(true);
1528 converter
.SetRegExpAllowed(true);
1529 scoped_ptr
<base::Value
> result_value(
1530 converter
.FromV8Value(result
, context
));
1531 list
.Set(0, result_value
? result_value
.Pass()
1532 : base::Value::CreateNullValue());
1534 list
.Set(0, base::Value::CreateNullValue());
1536 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1540 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1541 GetRenderWidget()->QueueMessage(
1542 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1543 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1546 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1547 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1548 if (!GetRenderWidget()->ShouldHandleImeEvent())
1550 ImeEventGuard
guard(GetRenderWidget());
1551 frame_
->setEditableSelectionOffsets(start
, end
);
1554 void RenderFrameImpl::OnSetCompositionFromExistingText(
1556 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1557 if (!GetRenderWidget()->ShouldHandleImeEvent())
1559 ImeEventGuard
guard(GetRenderWidget());
1560 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1563 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1564 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1567 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1568 if (!GetRenderWidget()->ShouldHandleImeEvent())
1571 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1573 ImeEventGuard
guard(GetRenderWidget());
1574 blink::WebScopedUserGesture gesture_indicator
;
1575 frame_
->extendSelectionAndDelete(before
, after
);
1578 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1579 if (accessibility_mode_
== new_mode
)
1581 accessibility_mode_
= new_mode
;
1582 if (renderer_accessibility_
) {
1583 // Note: this isn't called automatically by the destructor because
1584 // there'd be no point in calling it in frame teardown, only if there's
1585 // an accessibility mode change but the frame is persisting.
1586 renderer_accessibility_
->DisableAccessibility();
1588 delete renderer_accessibility_
;
1589 renderer_accessibility_
= NULL
;
1591 if (accessibility_mode_
== AccessibilityModeOff
)
1594 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1595 renderer_accessibility_
= new RendererAccessibility(this);
1598 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1599 ui::AXTreeUpdate
<AXContentNodeData
> response
;
1600 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1601 Send(new AccessibilityHostMsg_SnapshotResponse(
1602 routing_id_
, callback_id
, response
));
1605 void RenderFrameImpl::OnDisownOpener() {
1606 // TODO(creis): We should only see this for main frames for now. To support
1607 // disowning the opener on subframes, we will need to move WebContentsImpl's
1608 // opener_ to FrameTreeNode.
1609 CHECK(!frame_
->parent());
1611 if (frame_
->opener())
1612 frame_
->setOpener(NULL
);
1615 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1616 frame_
->setFrameOwnerSandboxFlags(flags
);
1619 void RenderFrameImpl::OnTextTrackSettingsChanged(
1620 const FrameMsg_TextTrackSettings_Params
& params
) {
1621 DCHECK(!frame_
->parent());
1622 if (!render_view_
->webview())
1625 if (params
.text_tracks_enabled
) {
1626 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1627 WebSettings::TextTrackKindUserPreference::Captions
);
1629 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1630 WebSettings::TextTrackKindUserPreference::Default
);
1632 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1633 WebString::fromUTF8(params
.text_track_background_color
));
1634 render_view_
->webview()->settings()->setTextTrackFontFamily(
1635 WebString::fromUTF8(params
.text_track_font_family
));
1636 render_view_
->webview()->settings()->setTextTrackFontStyle(
1637 WebString::fromUTF8(params
.text_track_font_style
));
1638 render_view_
->webview()->settings()->setTextTrackFontVariant(
1639 WebString::fromUTF8(params
.text_track_font_variant
));
1640 render_view_
->webview()->settings()->setTextTrackTextColor(
1641 WebString::fromUTF8(params
.text_track_text_color
));
1642 render_view_
->webview()->settings()->setTextTrackTextShadow(
1643 WebString::fromUTF8(params
.text_track_text_shadow
));
1644 render_view_
->webview()->settings()->setTextTrackTextSize(
1645 WebString::fromUTF8(params
.text_track_text_size
));
1648 void RenderFrameImpl::OnPostMessageEvent(
1649 const FrameMsg_PostMessage_Params
& params
) {
1650 // Find the source frame if it exists.
1651 WebFrame
* source_frame
= NULL
;
1652 if (params
.source_view_routing_id
!= MSG_ROUTING_NONE
) {
1653 // Support a legacy postMessage path for specifying a source RenderView;
1654 // this is currently used when sending messages to Android WebView.
1655 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1656 RenderViewImpl
* source_view
=
1657 RenderViewImpl::FromRoutingID(params
.source_view_routing_id
);
1659 source_frame
= source_view
->webview()->mainFrame();
1660 } else if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1661 RenderFrameProxy
* source_proxy
=
1662 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1664 // Currently, navigating a top-level frame cross-process does not swap
1665 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1666 // WebRemoteFrame will not have an associated blink::Frame. If this is
1667 // the case for |source_proxy|, use the corresponding (swapped-out)
1668 // WebLocalFrame instead, so that event.source for this message can be
1669 // set and used properly.
1670 if (source_proxy
->IsMainFrameDetachedFromTree())
1671 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1673 source_frame
= source_proxy
->web_frame();
1677 // If the message contained MessagePorts, create the corresponding endpoints.
1678 blink::WebMessagePortChannelArray channels
=
1679 WebMessagePortChannelImpl::CreatePorts(
1680 params
.message_ports
, params
.new_routing_ids
,
1681 base::ThreadTaskRunnerHandle::Get().get());
1683 WebSerializedScriptValue serialized_script_value
;
1684 if (params
.is_data_raw_string
) {
1685 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1686 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1687 v8::Context::Scope
context_scope(context
);
1688 V8ValueConverterImpl converter
;
1689 converter
.SetDateAllowed(true);
1690 converter
.SetRegExpAllowed(true);
1691 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1692 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1694 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1696 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1699 // Create an event with the message. The next-to-last parameter to
1700 // initMessageEvent is the last event ID, which is not used with postMessage.
1701 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1702 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1703 msg_event
.initMessageEvent("message",
1704 // |canBubble| and |cancellable| are always false
1706 serialized_script_value
,
1707 params
.source_origin
, source_frame
, "", channels
);
1709 // We must pass in the target_origin to do the security check on this side,
1710 // since it may have changed since the original postMessage call was made.
1711 WebSecurityOrigin target_origin
;
1712 if (!params
.target_origin
.empty()) {
1714 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1716 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1719 #if defined(OS_ANDROID)
1720 void RenderFrameImpl::OnSelectPopupMenuItems(
1722 const std::vector
<int>& selected_indices
) {
1723 // It is possible to receive more than one of these calls if the user presses
1724 // a select faster than it takes for the show-select-popup IPC message to make
1725 // it to the browser UI thread. Ignore the extra-messages.
1726 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1727 if (!external_popup_menu_
)
1730 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1731 external_popup_menu_
.reset();
1735 #if defined(OS_MACOSX)
1736 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1737 if (external_popup_menu_
== NULL
)
1739 external_popup_menu_
->DidSelectItem(selected_index
);
1740 external_popup_menu_
.reset();
1744 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1745 frame_
->reload(ignore_cache
);
1748 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1749 blink::WebSurroundingText surroundingText
;
1750 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1752 if (surroundingText
.isNull()) {
1753 // |surroundingText| might not be correctly initialized, for example if
1754 // |frame_->selectionRange().isNull()|, in other words, if there was no
1756 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1757 routing_id_
, base::string16(), 0, 0));
1761 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1763 surroundingText
.textContent(),
1764 surroundingText
.startOffsetInTextContent(),
1765 surroundingText
.endOffsetInTextContent()));
1768 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1769 const base::string16
& message
,
1770 const base::string16
& default_value
,
1771 const GURL
& frame_url
,
1772 base::string16
* result
) {
1773 // Don't allow further dialogs if we are waiting to swap out, since the
1774 // PageGroupLoadDeferrer in our stack prevents it.
1775 if (render_view()->suppress_dialogs_until_swap_out_
)
1778 bool success
= false;
1779 base::string16 result_temp
;
1781 result
= &result_temp
;
1783 render_view()->SendAndRunNestedMessageLoop(
1784 new FrameHostMsg_RunJavaScriptMessage(
1785 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1790 void RenderFrameImpl::LoadNavigationErrorPage(
1791 const WebURLRequest
& failed_request
,
1792 const WebURLError
& error
,
1794 std::string error_html
;
1795 GetContentClient()->renderer()->GetNavigationErrorStrings(
1796 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1798 frame_
->loadHTMLString(error_html
,
1799 GURL(kUnreachableWebDataURL
),
1800 error
.unreachableURL
,
1804 void RenderFrameImpl::DidCommitCompositorFrame() {
1805 if (BrowserPluginManager::Get())
1806 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1808 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1811 RenderView
* RenderFrameImpl::GetRenderView() {
1812 return render_view_
.get();
1815 int RenderFrameImpl::GetRoutingID() {
1819 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1824 WebElement
RenderFrameImpl::GetFocusedElement() const {
1825 WebDocument doc
= frame_
->document();
1827 return doc
.focusedElement();
1829 return WebElement();
1832 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1833 return render_view_
->GetWebkitPreferences();
1836 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1837 const ContextMenuParams
& params
) {
1838 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1839 ContextMenuParams
our_params(params
);
1840 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1841 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1842 return our_params
.custom_context
.request_id
;
1845 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1846 DCHECK(pending_context_menus_
.Lookup(request_id
));
1847 pending_context_menus_
.Remove(request_id
);
1850 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1851 return context_menu_node_
;
1854 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1855 blink::WebFrame
* frame
,
1856 const WebPluginInfo
& info
,
1857 const blink::WebPluginParams
& params
,
1858 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1859 DCHECK_EQ(frame_
, frame
);
1860 #if defined(ENABLE_PLUGINS)
1861 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1862 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1863 this, GetContentClient()
1865 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1870 bool pepper_plugin_was_registered
= false;
1871 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1872 this, info
, &pepper_plugin_was_registered
));
1873 if (pepper_plugin_was_registered
) {
1874 if (pepper_module
.get()) {
1875 return new PepperWebPluginImpl(
1876 pepper_module
.get(), params
, this,
1878 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1881 #if defined(OS_CHROMEOS)
1882 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1884 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1885 // TODO(jam): change to take RenderFrame.
1886 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1893 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1894 const blink::WebURLRequest
& request
,
1895 blink::WebNavigationPolicy policy
) {
1896 DCHECK(!frame_
|| frame_
== frame
);
1897 loadURLExternally(frame
, request
, policy
, WebString());
1900 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1901 OnJavaScriptExecuteRequest(javascript
, 0, false);
1904 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1905 return &service_registry_
;
1908 #if defined(ENABLE_PLUGINS)
1909 void RenderFrameImpl::RegisterPeripheralPlugin(
1910 const GURL
& content_origin
,
1911 const base::Closure
& unthrottle_callback
) {
1912 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1913 content_origin
, unthrottle_callback
);
1915 #endif // defined(ENABLE_PLUGINS)
1917 bool RenderFrameImpl::IsFTPDirectoryListing() {
1918 WebURLResponseExtraDataImpl
* extra_data
=
1919 GetExtraDataFromResponse(frame_
->dataSource()->response());
1920 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1923 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1924 BrowserPluginManager::Get()->Attach(element_instance_id
);
1927 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1928 BrowserPluginManager::Get()->Detach(element_instance_id
);
1931 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1933 const gfx::Range
& range
) {
1934 // Use the routing id of Render Widget Host.
1935 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1941 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1942 v8::Isolate
* isolate
,
1943 v8::Local
<v8::Context
> context
) {
1944 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1945 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1948 v8::HandleScope
handle_scope(isolate
);
1949 registry
->AddBuiltinModule(
1950 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1951 registry
->AddBuiltinModule(isolate
,
1952 mojo::js::Support::kModuleName
,
1953 mojo::js::Support::GetModule(isolate
));
1954 registry
->AddBuiltinModule(
1956 ServiceRegistryJsWrapper::kModuleName
,
1957 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1960 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
1961 const std::string
& message
) {
1962 if (devtools_agent_
)
1963 devtools_agent_
->AddMessageToConsole(level
, message
);
1966 // blink::WebFrameClient implementation ----------------------------------------
1968 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1969 blink::WebLocalFrame
* frame
,
1970 const blink::WebPluginParams
& params
) {
1971 DCHECK_EQ(frame_
, frame
);
1972 return GetContentClient()
1974 ->CreatePluginPlaceholder(this, frame
, params
)
1978 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1979 blink::WebLocalFrame
* frame
,
1980 const blink::WebPluginParams
& params
) {
1981 DCHECK_EQ(frame_
, frame
);
1982 blink::WebPlugin
* plugin
= NULL
;
1983 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1984 this, frame
, params
, &plugin
)) {
1988 if (base::UTF16ToUTF8(base::StringPiece16(params
.mimeType
)) ==
1989 kBrowserPluginMimeType
) {
1990 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1991 this, GetContentClient()
1993 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
1998 #if defined(ENABLE_PLUGINS)
2000 std::string mime_type
;
2002 Send(new FrameHostMsg_GetPluginInfo(
2003 routing_id_
, params
.url
, frame
->top()->document().url(),
2004 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
2008 WebPluginParams params_to_use
= params
;
2009 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2010 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2013 #endif // defined(ENABLE_PLUGINS)
2016 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2017 blink::WebLocalFrame
* frame
,
2018 const blink::WebURL
& url
,
2019 WebMediaPlayerClient
* client
,
2020 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
2021 WebContentDecryptionModule
* initial_cdm
) {
2022 #if defined(VIDEO_HOLE)
2023 if (!contains_media_player_
) {
2024 render_view_
->RegisterVideoHoleFrame(this);
2025 contains_media_player_
= true;
2027 #endif // defined(VIDEO_HOLE)
2029 blink::WebMediaStream
web_stream(
2030 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2031 if (!web_stream
.isNull())
2032 return CreateWebMediaPlayerForMediaStream(client
);
2034 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2035 return CreateAndroidWebMediaPlayer(client
, encrypted_client
,
2036 GetMediaPermission(), initial_cdm
);
2038 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2040 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2041 media::WebMediaPlayerParams
params(
2042 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2043 base::Unretained(GetContentClient()->renderer()),
2044 static_cast<RenderFrame
*>(this)),
2045 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2046 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2047 render_thread
->compositor_task_runner(),
2048 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2051 #if defined(ENABLE_MOJO_MEDIA)
2052 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2053 new media::MojoRendererFactory(GetMediaServiceFactory()));
2055 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2056 GetContentClient()->renderer()->CreateMediaRendererFactory(
2057 this, render_thread
->GetGpuFactories(), media_log
);
2059 if (!media_renderer_factory
.get()) {
2060 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2061 media_log
, render_thread
->GetGpuFactories(),
2062 *render_thread
->GetAudioHardwareConfig()));
2064 #endif // defined(ENABLE_MOJO_MEDIA)
2066 return new media::WebMediaPlayerImpl(
2067 frame
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
2068 media_renderer_factory
.Pass(), GetCdmFactory(), params
);
2069 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2072 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2073 blink::WebLocalFrame
* frame
,
2074 blink::WebApplicationCacheHostClient
* client
) {
2075 if (!frame
|| !frame
->view())
2077 DCHECK(!frame_
|| frame_
== frame
);
2078 return new RendererWebApplicationCacheHostImpl(
2079 RenderViewImpl::FromWebView(frame
->view()), client
,
2080 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2083 blink::WebWorkerContentSettingsClientProxy
*
2084 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2085 blink::WebLocalFrame
* frame
) {
2086 if (!frame
|| !frame
->view())
2088 DCHECK(!frame_
|| frame_
== frame
);
2089 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2093 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2094 const WebPopupMenuInfo
& popup_menu_info
,
2095 WebExternalPopupMenuClient
* popup_menu_client
) {
2096 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2097 // An IPC message is sent to the browser to build and display the actual
2098 // popup. The user could have time to click a different select by the time
2099 // the popup is shown. In that case external_popup_menu_ is non NULL.
2100 // By returning NULL in that case, we instruct Blink to cancel that new
2101 // popup. So from the user perspective, only the first one will show, and
2102 // will have to close the first one before another one can be shown.
2103 if (external_popup_menu_
)
2105 external_popup_menu_
.reset(
2106 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2107 if (render_view_
->screen_metrics_emulator_
) {
2108 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2109 external_popup_menu_
.get(),
2110 render_view_
->screen_metrics_emulator_
.get());
2112 return external_popup_menu_
.get();
2118 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2119 DCHECK(!frame_
|| frame_
== frame
);
2120 return &cookie_jar_
;
2123 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2124 blink::WebLocalFrame
* frame
) {
2125 DCHECK(!frame_
|| frame_
== frame
);
2126 // At this point we should have non-null data source.
2127 DCHECK(frame
->dataSource());
2128 if (!ChildThreadImpl::current())
2129 return NULL
; // May be null in some tests.
2130 ServiceWorkerNetworkProvider
* provider
=
2131 ServiceWorkerNetworkProvider::FromDocumentState(
2132 DocumentState::FromDataSource(frame
->dataSource()));
2134 return new WebServiceWorkerProviderImpl(
2135 ChildThreadImpl::current()->thread_safe_sender(),
2136 provider
->context());
2139 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2140 DCHECK(!frame_
|| frame_
== frame
);
2141 // If the request hasn't yet committed, notify the browser process that it is
2142 // no longer safe to show the pending URL of the main frame, since a URL spoof
2143 // is now possible. (If the request has committed, the browser already knows.)
2144 if (!frame
->parent()) {
2145 DocumentState
* document_state
=
2146 DocumentState::FromDataSource(frame
->dataSource());
2147 NavigationStateImpl
* navigation_state
=
2148 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2150 if (!navigation_state
->request_committed()) {
2151 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2156 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2157 blink::WebLocalFrame
* parent
,
2158 blink::WebTreeScopeType scope
,
2159 const blink::WebString
& name
,
2160 blink::WebSandboxFlags sandbox_flags
) {
2161 // Synchronously notify the browser of a child frame creation to get the
2162 // routing_id for the RenderFrame.
2163 int child_routing_id
= MSG_ROUTING_NONE
;
2164 Send(new FrameHostMsg_CreateChildFrame(
2166 base::UTF16ToUTF8(base::StringPiece16(name
)), sandbox_flags
,
2167 &child_routing_id
));
2169 // Allocation of routing id failed, so we can't create a child frame. This can
2170 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2171 // out state or synchronous IPC message above has failed.
2172 if (child_routing_id
== MSG_ROUTING_NONE
) {
2173 NOTREACHED() << "Failed to allocate routing id for child frame.";
2177 // Create the RenderFrame and WebLocalFrame, linking the two.
2178 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2179 render_view_
.get(), child_routing_id
);
2180 blink::WebLocalFrame
* web_frame
=
2181 WebLocalFrame::create(scope
, child_render_frame
);
2182 child_render_frame
->SetWebFrame(web_frame
);
2184 // Add the frame to the frame tree and initialize it.
2185 parent
->appendChild(web_frame
);
2186 child_render_frame
->Initialize();
2191 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2192 DCHECK(!frame_
|| frame_
== frame
);
2193 // We only need to notify the browser if the active, top-level frame clears
2194 // its opener. We can ignore cases where a swapped out frame clears its
2195 // opener after hearing about it from the browser, and the browser does not
2196 // (yet) care about subframe openers.
2197 if (is_swapped_out_
|| frame
->parent())
2200 // Notify WebContents and all its swapped out RenderViews.
2201 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2204 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2205 // NOTE: This function is called on the frame that is being detached and not
2206 // the parent frame. This is different from createChildFrame() which is
2207 // called on the parent frame.
2208 CHECK(!is_detaching_
);
2209 DCHECK(!frame_
|| frame_
== frame
);
2211 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2212 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2213 FrameDetached(frame
));
2215 // We only notify the browser process when the frame is being detached for
2216 // removal. If the frame is being detached for swap, we don't need to do this
2217 // since we are not modifiying the frame tree.
2218 if (type
== DetachType::Remove
)
2219 Send(new FrameHostMsg_Detach(routing_id_
));
2221 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2222 // sent before setting |is_detaching_| to true.
2223 is_detaching_
= true;
2225 // Clean up the associated RenderWidget for the frame, if there is one.
2226 if (render_widget_
) {
2227 render_widget_
->UnregisterRenderFrame(this);
2228 render_widget_
->CloseForFrame();
2231 // We need to clean up subframes by removing them from the map and deleting
2232 // the RenderFrameImpl. In contrast, the main frame is owned by its
2233 // containing RenderViewHost (so that they have the same lifetime), so only
2234 // removal from the map is needed and no deletion.
2235 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2236 CHECK(it
!= g_frame_map
.Get().end());
2237 CHECK_EQ(it
->second
, this);
2238 g_frame_map
.Get().erase(it
);
2240 // Only remove the frame from the renderer's frame tree if the frame is
2241 // being detached for removal. In the case of a swap, the frame needs to
2242 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2243 if (is_subframe_
&& type
== DetachType::Remove
)
2244 frame
->parent()->removeChild(frame
);
2246 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2247 // object may not be deleted immediately and other methods may try to access
2253 // Object is invalid after this point.
2256 void RenderFrameImpl::frameFocused() {
2257 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2260 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2261 DCHECK(!frame_
|| frame_
== frame
);
2263 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2264 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2265 FrameWillClose(frame
));
2268 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2269 const blink::WebString
& name
) {
2270 DCHECK(!frame_
|| frame_
== frame
);
2272 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2273 // updates may have performance implications for benchmarks like SunSpider.
2274 // For now, send these updates only for --site-per-process, which needs to
2275 // replicate frame names to frame proxies, and when
2276 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2277 // can be optimized further by only sending the update if there are any
2278 // remote frames in the frame tree, or delaying and batching up IPCs if
2279 // updates are happening too frequently.
2280 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2281 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2282 Send(new FrameHostMsg_DidChangeName(
2283 routing_id_
, base::UTF16ToUTF8(base::StringPiece16(name
))));
2287 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2288 blink::WebSandboxFlags flags
) {
2289 int frame_routing_id
= MSG_ROUTING_NONE
;
2290 if (child_frame
->isWebRemoteFrame()) {
2292 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2295 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2298 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2302 void RenderFrameImpl::didMatchCSS(
2303 blink::WebLocalFrame
* frame
,
2304 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2305 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2306 DCHECK(!frame_
|| frame_
== frame
);
2308 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2309 DidMatchCSS(newly_matching_selectors
,
2310 stopped_matching_selectors
));
2313 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2314 const blink::WebString
& source
) {
2315 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2319 void RenderFrameImpl::didAddMessageToConsole(
2320 const blink::WebConsoleMessage
& message
,
2321 const blink::WebString
& source_name
,
2322 unsigned source_line
,
2323 const blink::WebString
& stack_trace
) {
2324 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2325 switch (message
.level
) {
2326 case blink::WebConsoleMessage::LevelDebug
:
2327 log_severity
= logging::LOG_VERBOSE
;
2329 case blink::WebConsoleMessage::LevelLog
:
2330 case blink::WebConsoleMessage::LevelInfo
:
2331 log_severity
= logging::LOG_INFO
;
2333 case blink::WebConsoleMessage::LevelWarning
:
2334 log_severity
= logging::LOG_WARNING
;
2336 case blink::WebConsoleMessage::LevelError
:
2337 log_severity
= logging::LOG_ERROR
;
2340 log_severity
= logging::LOG_VERBOSE
;
2343 if (shouldReportDetailedMessageForSource(source_name
)) {
2345 RenderFrameObserver
, observers_
,
2346 DetailedConsoleMessageAdded(message
.text
,
2350 static_cast<int32
>(log_severity
)));
2353 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2354 static_cast<int32
>(log_severity
),
2356 static_cast<int32
>(source_line
),
2360 void RenderFrameImpl::loadURLExternally(
2361 blink::WebLocalFrame
* frame
,
2362 const blink::WebURLRequest
& request
,
2363 blink::WebNavigationPolicy policy
,
2364 const blink::WebString
& suggested_name
) {
2365 DCHECK(!frame_
|| frame_
== frame
);
2366 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2367 if (policy
== blink::WebNavigationPolicyDownload
) {
2368 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2369 request
.url(), referrer
,
2372 OpenURL(frame
, request
.url(), referrer
, policy
);
2376 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2377 const NavigationPolicyInfo
& info
) {
2378 DCHECK(!frame_
|| frame_
== info
.frame
);
2379 return DecidePolicyForNavigation(this, info
);
2382 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2383 blink::WebFrame
* frame
) {
2384 DCHECK(!frame_
|| frame_
== frame
);
2385 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2388 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2389 const blink::WebFormElement
& form
) {
2390 DCHECK(!frame_
|| frame_
== frame
);
2392 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2395 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2396 const blink::WebFormElement
& form
) {
2397 DCHECK(!frame_
|| frame_
== frame
);
2398 DocumentState
* document_state
=
2399 DocumentState::FromDataSource(frame
->provisionalDataSource());
2400 NavigationStateImpl
* navigation_state
=
2401 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2402 InternalDocumentStateData
* internal_data
=
2403 InternalDocumentStateData::FromDocumentState(document_state
);
2405 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2406 ui::PAGE_TRANSITION_LINK
)) {
2407 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2410 // Save these to be processed when the ensuing navigation is committed.
2411 WebSearchableFormData
web_searchable_form_data(form
);
2412 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2413 internal_data
->set_searchable_form_encoding(
2414 web_searchable_form_data
.encoding().utf8());
2416 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2419 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2420 blink::WebDataSource
* datasource
) {
2421 DCHECK(!frame_
|| frame_
== frame
);
2423 bool content_initiated
= !pending_navigation_params_
.get();
2425 // Make sure any previous redirect URLs end up in our new data source.
2426 if (pending_navigation_params_
.get()) {
2427 for (const auto& i
:
2428 pending_navigation_params_
->request_params
.redirects
) {
2429 datasource
->appendRedirect(i
);
2433 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2434 if (!document_state
) {
2435 document_state
= new DocumentState
;
2436 datasource
->setExtraData(document_state
);
2437 if (!content_initiated
)
2438 PopulateDocumentStateFromPending(document_state
);
2441 // Carry over the user agent override flag, if it exists.
2442 blink::WebView
* webview
= render_view_
->webview();
2443 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2444 webview
->mainFrame()->isWebLocalFrame() &&
2445 webview
->mainFrame()->dataSource()) {
2446 DocumentState
* old_document_state
=
2447 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2448 if (old_document_state
) {
2449 InternalDocumentStateData
* internal_data
=
2450 InternalDocumentStateData::FromDocumentState(document_state
);
2451 InternalDocumentStateData
* old_internal_data
=
2452 InternalDocumentStateData::FromDocumentState(old_document_state
);
2453 internal_data
->set_is_overriding_user_agent(
2454 old_internal_data
->is_overriding_user_agent());
2458 // The rest of RenderView assumes that a WebDataSource will always have a
2459 // non-null NavigationState.
2460 if (content_initiated
) {
2461 document_state
->set_navigation_state(
2462 NavigationStateImpl::CreateContentInitiated());
2464 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2465 pending_navigation_params_
.reset();
2468 // DocumentState::referred_by_prefetcher_ is true if we are
2469 // navigating from a page that used prefetching using a link on that
2470 // page. We are early enough in the request process here that we
2471 // can still see the DocumentState of the previous page and set
2472 // this value appropriately.
2473 // TODO(gavinp): catch the important case of navigation in a new
2474 // renderer process.
2476 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2477 const WebURLRequest
& original_request
= datasource
->originalRequest();
2478 const GURL
referrer(
2479 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2480 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2481 DocumentState::FromDataSource(old_frame
->dataSource())
2482 ->was_prefetcher()) {
2483 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2484 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2485 if (old_frame_datasource
&&
2486 referrer
== GURL(old_frame_datasource
->request().url())) {
2487 document_state
->set_was_referred_by_prefetcher(true);
2495 if (content_initiated
) {
2496 const WebURLRequest
& request
= datasource
->request();
2497 switch (request
.cachePolicy()) {
2498 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2499 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2501 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2502 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2503 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2505 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2506 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2508 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2509 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2516 // Create the serviceworker's per-document network observing object if it
2517 // does not exist (When navigation happens within a page, the provider already
2519 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2520 DocumentState::FromDataSource(datasource
))) {
2521 ServiceWorkerProviderType provider_type
=
2522 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2523 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2524 blink::WebSandboxFlags::Origin
) {
2525 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2527 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2528 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2529 ServiceWorkerNetworkProvider::AttachToDocumentState(
2530 DocumentState::FromDataSource(datasource
),
2531 network_provider
.Pass());
2535 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2536 double triggering_event_time
) {
2537 DCHECK(!frame_
|| frame_
== frame
);
2538 WebDataSource
* ds
= frame
->provisionalDataSource();
2540 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2541 // callback is invoked.
2545 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2546 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2547 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2549 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2550 CHECK_IMPLIES(ds
->request().url() == GURL(kSwappedOutURL
), is_swapped_out_
)
2551 << "Heard swappedout:// when not swapped out.";
2553 // Update the request time if WebKit has better knowledge of it.
2554 if (document_state
->request_time().is_null() &&
2555 triggering_event_time
!= 0.0) {
2556 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2559 // Start time is only set after request time.
2560 document_state
->set_start_load_time(Time::Now());
2562 bool is_top_most
= !frame
->parent();
2564 render_view_
->set_navigation_gesture(
2565 WebUserGestureIndicator::isProcessingUserGesture() ?
2566 NavigationGestureUser
: NavigationGestureAuto
);
2567 } else if (ds
->replacesCurrentHistoryItem()) {
2568 // Subframe navigations that don't add session history items must be
2569 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2570 // handle loading of error pages.
2571 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2572 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2575 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2576 DidStartProvisionalLoad(frame
));
2577 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2579 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2580 routing_id_
, ds
->request().url()));
2583 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2584 blink::WebLocalFrame
* frame
) {
2585 DCHECK(!frame_
|| frame_
== frame
);
2586 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2589 void RenderFrameImpl::didFailProvisionalLoad(
2590 blink::WebLocalFrame
* frame
,
2591 const blink::WebURLError
& error
,
2592 blink::WebHistoryCommitType commit_type
) {
2593 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2595 DCHECK(!frame_
|| frame_
== frame
);
2596 WebDataSource
* ds
= frame
->provisionalDataSource();
2599 const WebURLRequest
& failed_request
= ds
->request();
2601 // Notify the browser that we failed a provisional load with an error.
2603 // Note: It is important this notification occur before DidStopLoading so the
2604 // SSL manager can react to the provisional load failure before being
2605 // notified the load stopped.
2607 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2608 DidFailProvisionalLoad(frame
, error
));
2609 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2610 DidFailProvisionalLoad(error
));
2612 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2614 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2617 // Make sure we never show errors in view source mode.
2618 frame
->enableViewSourceMode(false);
2620 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2621 NavigationStateImpl
* navigation_state
=
2622 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2624 // If this is a failed back/forward/reload navigation, then we need to do a
2625 // 'replace' load. This is necessary to avoid messing up session history.
2626 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2627 // as session history is concerned.
2628 bool replace
= commit_type
!= blink::WebStandardCommit
;
2630 // If we failed on a browser initiated request, then make sure that our error
2631 // page load is regarded as the same browser initiated request.
2632 if (!navigation_state
->IsContentInitiated()) {
2633 pending_navigation_params_
.reset(new NavigationParams(
2634 navigation_state
->common_params(), navigation_state
->start_params(),
2635 navigation_state
->request_params()));
2636 pending_navigation_params_
->request_params
.request_time
=
2637 document_state
->request_time();
2640 // Load an error page.
2641 LoadNavigationErrorPage(failed_request
, error
, replace
);
2644 void RenderFrameImpl::didCommitProvisionalLoad(
2645 blink::WebLocalFrame
* frame
,
2646 const blink::WebHistoryItem
& item
,
2647 blink::WebHistoryCommitType commit_type
) {
2648 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2650 "url", GetLoadingUrl().possibly_invalid_spec());
2651 DCHECK(!frame_
|| frame_
== frame
);
2652 DocumentState
* document_state
=
2653 DocumentState::FromDataSource(frame
->dataSource());
2654 NavigationStateImpl
* navigation_state
=
2655 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2657 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2658 RenderFrameProxy
* proxy
=
2659 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2661 proxy
->web_frame()->swap(frame_
);
2662 proxy_routing_id_
= MSG_ROUTING_NONE
;
2664 // If this is the main frame going from a remote frame to a local frame,
2665 // it needs to set RenderViewImpl's pointer for the main frame to itself
2666 // and ensure RenderWidget is no longer in swapped out mode.
2667 if (!is_subframe_
) {
2668 CHECK(!render_view_
->main_render_frame_
);
2669 render_view_
->main_render_frame_
= this;
2670 if (render_view_
->is_swapped_out())
2671 render_view_
->SetSwappedOut(false);
2675 // When we perform a new navigation, we need to update the last committed
2676 // session history entry with state for the page we are leaving. Do this
2677 // before updating the HistoryController state.
2678 render_view_
->SendUpdateState();
2680 render_view_
->history_controller()->UpdateForCommit(
2681 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2683 InternalDocumentStateData
* internal_data
=
2684 InternalDocumentStateData::FromDocumentState(document_state
);
2686 if (document_state
->commit_load_time().is_null())
2687 document_state
->set_commit_load_time(Time::Now());
2689 if (internal_data
->must_reset_scroll_and_scale_state()) {
2690 render_view_
->webview()->resetScrollAndScaleState();
2691 internal_data
->set_must_reset_scroll_and_scale_state(false);
2694 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2695 if (is_new_navigation
) {
2696 // We bump our Page ID to correspond with the new session history entry.
2697 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2699 // Don't update history list values for kSwappedOutURL, since
2700 // we don't want to forget the entry that was there, and since we will
2701 // never come back to kSwappedOutURL. Note that we have to call
2702 // SendUpdateState and update page_id_ even in this case, so that
2703 // the current entry gets a state update and so that we don't send a
2704 // state update to the wrong entry when we swap back in.
2706 navigation_state
->common_params().should_replace_current_entry
,
2707 render_view_
->history_list_length_
> 0);
2708 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2709 !navigation_state
->common_params().should_replace_current_entry
) {
2710 // Advance our offset in session history, applying the length limit.
2711 // There is now no forward history.
2712 render_view_
->history_list_offset_
++;
2713 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2714 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2715 render_view_
->history_list_length_
=
2716 render_view_
->history_list_offset_
+ 1;
2719 const RequestNavigationParams
& request_params
=
2720 navigation_state
->request_params();
2721 if (request_params
.nav_entry_id
!= 0 &&
2722 !request_params
.intended_as_new_entry
) {
2723 // This is a successful session history navigation!
2724 render_view_
->page_id_
= request_params
.page_id
;
2726 render_view_
->history_list_offset_
=
2727 request_params
.pending_history_list_offset
;
2732 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2733 CHECK(sent
); // http://crbug.com/407376
2735 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2736 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2738 RenderFrameObserver
, observers_
,
2739 DidCommitProvisionalLoad(is_new_navigation
,
2740 navigation_state
->WasWithinSamePage()));
2742 if (!frame
->parent()) { // Only for top frames.
2743 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2744 if (render_thread_impl
) { // Can be NULL in tests.
2745 render_thread_impl
->histogram_customizer()->
2746 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2747 RenderView::GetRenderViewCount());
2751 // Remember that we've already processed this request, so we don't update
2752 // the session history again. We do this regardless of whether this is
2753 // a session history navigation, because if we attempted a session history
2754 // navigation without valid HistoryItem state, WebCore will think it is a
2756 navigation_state
->set_request_committed(true);
2758 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2760 // Check whether we have new encoding name.
2761 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2764 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2765 DCHECK(!frame_
|| frame_
== frame
);
2767 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2768 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2769 DidCreateNewDocument(frame
));
2772 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2773 DCHECK(!frame_
|| frame_
== frame
);
2775 int enabled_bindings
= render_view_
->GetEnabledBindings();
2777 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2778 WebUIExtension::Install(frame
);
2780 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2781 DomAutomationController::Install(this, frame
);
2783 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2784 StatsCollectionController::Install(frame
);
2786 const base::CommandLine
& command_line
=
2787 *base::CommandLine::ForCurrentProcess();
2789 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2790 GpuBenchmarking::Install(frame
);
2792 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2793 MemoryBenchmarkingExtension::Install(frame
);
2795 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2796 SkiaBenchmarking::Install(frame
);
2798 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2799 DidClearWindowObject(frame
));
2800 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2803 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2804 DCHECK(!frame_
|| frame_
== frame
);
2806 // Notify the browser about non-blank documents loading in the top frame.
2807 GURL url
= frame
->document().url();
2808 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2809 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2810 // frame->tree()->top().
2811 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2812 if (frame
== main_frame
) {
2813 // For now, don't remember plugin zoom values. We don't want to mix them
2814 // with normal web content (i.e. a fixed layout plugin would usually want
2816 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2817 render_view_
->GetRoutingID(),
2818 main_frame
->document().isPluginDocument()));
2822 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2823 DidCreateDocumentElement());
2824 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2825 DidCreateDocumentElement(frame
));
2828 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2829 const blink::WebString
& title
,
2830 blink::WebTextDirection direction
) {
2831 DCHECK(!frame_
|| frame_
== frame
);
2832 // Ignore all but top level navigations.
2833 if (!frame
->parent()) {
2834 base::string16 title16
= title
;
2835 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2836 routing_id_
, base::UTF16ToUTF8(title16
));
2838 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2839 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2840 shortened_title
, direction
));
2843 // Also check whether we have new encoding name.
2844 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2847 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2848 blink::WebIconURL::Type icon_type
) {
2849 DCHECK(!frame_
|| frame_
== frame
);
2850 // TODO(nasko): Investigate wheather implementation should move here.
2851 render_view_
->didChangeIcon(frame
, icon_type
);
2854 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
,
2855 bool document_is_empty
) {
2856 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2858 DCHECK(!frame_
|| frame_
== frame
);
2859 WebDataSource
* ds
= frame
->dataSource();
2860 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2861 document_state
->set_finish_document_load_time(Time::Now());
2863 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2865 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2866 DidFinishDocumentLoad(frame
));
2867 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2869 // Check whether we have new encoding name.
2870 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2872 // If this is an empty document with an http status code indicating an error,
2873 // we may want to display our own error page, so the user doesn't end up
2874 // with an unexplained blank page.
2875 if (!document_is_empty
)
2878 // Do not show error page when DevTools is attached.
2879 RenderFrameImpl
* localRoot
= this;
2880 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
2881 localRoot
->frame_
->parent()->isWebLocalFrame()) {
2882 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
2885 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
2888 // Display error page instead of a blank page, if appropriate.
2889 std::string error_domain
= "http";
2890 InternalDocumentStateData
* internal_data
=
2891 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2892 int http_status_code
= internal_data
->http_status_code();
2893 if (GetContentClient()->renderer()->HasErrorPage(http_status_code
,
2896 error
.unreachableURL
= frame
->document().url();
2897 error
.domain
= WebString::fromUTF8(error_domain
);
2898 error
.reason
= http_status_code
;
2899 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
2903 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2904 DCHECK(!frame_
|| frame_
== frame
);
2905 if (!frame
->parent()) {
2906 FrameMsg_UILoadMetricsReportType::Value report_type
=
2907 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2908 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2909 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2910 base::TimeDelta::FromSecondsD(
2911 frame
->dataSource()->request().uiStartTime());
2913 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2914 routing_id_
, report_type
, ui_timestamp
));
2918 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2919 const blink::WebURLError
& error
,
2920 blink::WebHistoryCommitType commit_type
) {
2921 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2923 DCHECK(!frame_
|| frame_
== frame
);
2924 // TODO(nasko): Move implementation here. No state needed.
2925 WebDataSource
* ds
= frame
->dataSource();
2928 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2929 DidFailLoad(frame
, error
));
2931 const WebURLRequest
& failed_request
= ds
->request();
2932 base::string16 error_description
;
2933 GetContentClient()->renderer()->GetNavigationErrorStrings(
2939 &error_description
);
2940 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2941 failed_request
.url(),
2944 error
.wasIgnoredByHandler
));
2947 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2948 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2950 DCHECK(!frame_
|| frame_
== frame
);
2951 WebDataSource
* ds
= frame
->dataSource();
2952 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2953 if (document_state
->finish_load_time().is_null()) {
2954 if (!frame
->parent()) {
2955 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2956 TRACE_EVENT_SCOPE_PROCESS
);
2958 document_state
->set_finish_load_time(Time::Now());
2961 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2962 DidFinishLoad(frame
));
2963 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2965 // Don't send this message while the frame is swapped out.
2966 if (is_swapped_out())
2969 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2970 ds
->request().url()));
2973 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2974 const blink::WebHistoryItem
& item
,
2975 blink::WebHistoryCommitType commit_type
) {
2976 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2978 DCHECK(!frame_
|| frame_
== frame
);
2979 // If this was a reference fragment navigation that we initiated, then we
2980 // could end up having a non-null pending navigation params. We just need to
2981 // update the ExtraData on the datasource so that others who read the
2982 // ExtraData will get the new NavigationState. Similarly, if we did not
2983 // initiate this navigation, then we need to take care to reset any pre-
2984 // existing navigation state to a content-initiated navigation state.
2985 // didCreateDataSource conveniently takes care of this for us.
2986 didCreateDataSource(frame
, frame
->dataSource());
2988 DocumentState
* document_state
=
2989 DocumentState::FromDataSource(frame
->dataSource());
2990 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2991 ->set_was_within_same_page(true);
2993 didCommitProvisionalLoad(frame
, item
, commit_type
);
2996 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2997 DCHECK(!frame_
|| frame_
== frame
);
2998 // TODO(nasko): Move implementation here. Needed methods:
2999 // * StartNavStateSyncTimerIfNecessary
3000 render_view_
->didUpdateCurrentHistoryItem(frame
);
3003 void RenderFrameImpl::didChangeThemeColor() {
3004 if (frame_
->parent())
3007 Send(new FrameHostMsg_DidChangeThemeColor(
3008 routing_id_
, frame_
->document().themeColor()));
3011 void RenderFrameImpl::dispatchLoad() {
3012 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
3015 void RenderFrameImpl::requestNotificationPermission(
3016 const blink::WebSecurityOrigin
& origin
,
3017 blink::WebNotificationPermissionCallback
* callback
) {
3018 if (!notification_permission_dispatcher_
) {
3019 notification_permission_dispatcher_
=
3020 new NotificationPermissionDispatcher(this);
3023 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3026 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3027 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3030 if (is_empty_selection
)
3031 selection_text_
.clear();
3033 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3034 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3035 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3036 // to notify the selection was changed. Focus change should be notified
3037 // before selection change.
3038 GetRenderWidget()->UpdateTextInputState(
3039 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
3040 SyncSelectionIfRequired();
3043 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3044 blink::WebColorChooserClient
* client
,
3045 const blink::WebColor
& initial_color
,
3046 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3047 RendererWebColorChooserImpl
* color_chooser
=
3048 new RendererWebColorChooserImpl(this, client
);
3049 std::vector
<ColorSuggestion
> color_suggestions
;
3050 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3051 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3053 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3054 return color_chooser
;
3057 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3058 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3061 frame_
->document().url(),
3065 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3066 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3069 frame_
->document().url(),
3073 bool RenderFrameImpl::runModalPromptDialog(
3074 const blink::WebString
& message
,
3075 const blink::WebString
& default_value
,
3076 blink::WebString
* actual_value
) {
3077 base::string16 result
;
3078 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3081 frame_
->document().url(),
3084 actual_value
->assign(result
);
3088 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3090 const blink::WebString
& message
) {
3091 // If we are swapping out, we have already run the beforeunload handler.
3092 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3093 // at all, to avoid running it twice.
3094 if (is_swapped_out_
)
3097 // Don't allow further dialogs if we are waiting to swap out, since the
3098 // PageGroupLoadDeferrer in our stack prevents it.
3099 if (render_view()->suppress_dialogs_until_swap_out_
)
3102 bool success
= false;
3103 // This is an ignored return value, but is included so we can accept the same
3104 // response as RunJavaScriptMessage.
3105 base::string16 ignored_result
;
3106 render_view()->SendAndRunNestedMessageLoop(
3107 new FrameHostMsg_RunBeforeUnloadConfirm(
3108 routing_id_
, frame_
->document().url(), message
, is_reload
,
3109 &success
, &ignored_result
));
3113 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3114 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3115 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3116 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3117 if (GetRenderWidget()->has_host_context_menu_location()) {
3118 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3119 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3122 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3123 // it. We replace it with an empty GURL so the appropriate items are disabled
3124 // in the context menu.
3125 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3126 // data encoded images. We should have a way to save them.
3127 if (params
.src_url
.spec().size() > GetMaxURLChars())
3128 params
.src_url
= GURL();
3129 context_menu_node_
= data
.node
;
3131 #if defined(OS_ANDROID)
3132 gfx::Rect start_rect
;
3134 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3135 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3136 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3139 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3142 void RenderFrameImpl::clearContextMenu() {
3143 context_menu_node_
.reset();
3146 void RenderFrameImpl::willSendRequest(
3147 blink::WebLocalFrame
* frame
,
3148 unsigned identifier
,
3149 blink::WebURLRequest
& request
,
3150 const blink::WebURLResponse
& redirect_response
) {
3151 DCHECK(!frame_
|| frame_
== frame
);
3152 // The request my be empty during tests.
3153 if (request
.url().isEmpty())
3156 // Set the first party for cookies url if it has not been set yet (new
3157 // requests). For redirects, it is updated by WebURLLoaderImpl.
3158 if (request
.firstPartyForCookies().isEmpty()) {
3159 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3160 request
.setFirstPartyForCookies(request
.url());
3162 // TODO(nasko): When the top-level frame is remote, there is no document.
3163 // This is broken and should be fixed to propagate the first party.
3164 WebFrame
* top
= frame
->top();
3165 if (top
->isWebLocalFrame()) {
3166 request
.setFirstPartyForCookies(
3167 frame
->top()->document().firstPartyForCookies());
3172 WebDataSource
* provisional_data_source
= frame
->provisionalDataSource();
3173 WebDataSource
* data_source
=
3174 provisional_data_source
? provisional_data_source
: frame
->dataSource();
3176 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3177 DCHECK(document_state
);
3178 InternalDocumentStateData
* internal_data
=
3179 InternalDocumentStateData::FromDocumentState(document_state
);
3180 NavigationStateImpl
* navigation_state
=
3181 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3182 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3183 if (provisional_data_source
&& provisional_data_source
->isClientRedirect()) {
3184 transition_type
= ui::PageTransitionFromInt(
3185 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3188 GURL
request_url(request
.url());
3190 if (GetContentClient()->renderer()->WillSendRequest(
3194 request
.firstPartyForCookies(),
3196 request
.setURL(WebURL(new_url
));
3199 if (internal_data
->is_cache_policy_override_set())
3200 request
.setCachePolicy(internal_data
->cache_policy_override());
3202 // The request's extra data may indicate that we should set a custom user
3203 // agent. This needs to be done here, after WebKit is through with setting the
3204 // user agent on its own. Similarly, it may indicate that we should set an
3205 // X-Requested-With header. This must be done here to avoid breaking CORS
3207 // PlzNavigate: there may also be a stream url associated with the request.
3208 WebString custom_user_agent
;
3209 WebString requested_with
;
3210 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3211 if (request
.extraData()) {
3212 RequestExtraData
* old_extra_data
=
3213 static_cast<RequestExtraData
*>(request
.extraData());
3215 custom_user_agent
= old_extra_data
->custom_user_agent();
3216 if (!custom_user_agent
.isNull()) {
3217 if (custom_user_agent
.isEmpty())
3218 request
.clearHTTPHeaderField("User-Agent");
3220 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3223 requested_with
= old_extra_data
->requested_with();
3224 if (!requested_with
.isNull()) {
3225 if (requested_with
.isEmpty())
3226 request
.clearHTTPHeaderField("X-Requested-With");
3228 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3230 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3233 // Add the default accept header for frame request if it has not been set
3235 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3236 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3237 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3238 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3239 WebString::fromUTF8(kDefaultAcceptHeader
));
3242 // Add an empty HTTP origin header for non GET methods if none is currently
3244 request
.addHTTPOriginIfNeeded(WebString());
3246 // Attach |should_replace_current_entry| state to requests so that, should
3247 // this navigation later require a request transfer, all state is preserved
3248 // when it is re-created in the new process.
3249 bool should_replace_current_entry
= false;
3250 if (navigation_state
->IsContentInitiated()) {
3251 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3253 // If the navigation is browser-initiated, the NavigationState contains the
3254 // correct value instead of the WebDataSource.
3256 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3257 // NavigationState::should_replace_current_entry().
3258 should_replace_current_entry
=
3259 navigation_state
->common_params().should_replace_current_entry
;
3262 int provider_id
= kInvalidServiceWorkerProviderId
;
3263 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3264 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3265 // |provisionalDataSource| may be null in some content::ResourceFetcher
3266 // use cases, we don't hook those requests.
3267 if (frame
->provisionalDataSource()) {
3268 ServiceWorkerNetworkProvider
* provider
=
3269 ServiceWorkerNetworkProvider::FromDocumentState(
3270 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3271 provider_id
= provider
->provider_id();
3273 } else if (frame
->dataSource()) {
3274 ServiceWorkerNetworkProvider
* provider
=
3275 ServiceWorkerNetworkProvider::FromDocumentState(
3276 DocumentState::FromDataSource(frame
->dataSource()));
3277 provider_id
= provider
->provider_id();
3280 WebFrame
* parent
= frame
->parent();
3281 int parent_routing_id
= MSG_ROUTING_NONE
;
3283 parent_routing_id
= -1;
3284 } else if (parent
->isWebLocalFrame()) {
3285 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3287 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3290 RequestExtraData
* extra_data
= new RequestExtraData();
3291 extra_data
->set_visibility_state(render_view_
->visibilityState());
3292 extra_data
->set_custom_user_agent(custom_user_agent
);
3293 extra_data
->set_requested_with(requested_with
);
3294 extra_data
->set_render_frame_id(routing_id_
);
3295 extra_data
->set_is_main_frame(!parent
);
3296 extra_data
->set_frame_origin(
3297 GURL(frame
->document().securityOrigin().toString()));
3298 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3299 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3300 extra_data
->set_allow_download(
3301 navigation_state
->common_params().allow_download
);
3302 extra_data
->set_transition_type(transition_type
);
3303 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3304 extra_data
->set_transferred_request_child_id(
3305 navigation_state
->start_params().transferred_request_child_id
);
3306 extra_data
->set_transferred_request_request_id(
3307 navigation_state
->start_params().transferred_request_request_id
);
3308 extra_data
->set_service_worker_provider_id(provider_id
);
3309 extra_data
->set_stream_override(stream_override
.Pass());
3310 request
.setExtraData(extra_data
);
3312 // TODO(creis): Update prefetching to work with out-of-process iframes.
3313 WebFrame
* top_frame
= frame
->top();
3314 if (top_frame
&& top_frame
->isWebLocalFrame()) {
3315 DocumentState
* top_document_state
=
3316 DocumentState::FromDataSource(top_frame
->dataSource());
3317 if (top_document_state
) {
3318 // TODO(gavinp): separate out prefetching and prerender field trials
3319 // if the rel=prerender rel type is sticking around.
3320 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3321 top_document_state
->set_was_prefetcher(true);
3325 // This is an instance where we embed a copy of the routing id
3326 // into the data portion of the message. This can cause problems if we
3327 // don't register this id on the browser side, since the download manager
3328 // expects to find a RenderViewHost based off the id.
3329 request
.setRequestorID(render_view_
->GetRoutingID());
3330 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3332 if (!navigation_state
->start_params().extra_headers
.empty()) {
3333 for (net::HttpUtil::HeadersIterator
i(
3334 navigation_state
->start_params().extra_headers
.begin(),
3335 navigation_state
->start_params().extra_headers
.end(), "\n");
3337 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3338 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3339 blink::WebReferrerPolicyDefault
,
3341 WebString::fromUTF8(i
.values()));
3342 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3344 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3345 WebString::fromUTF8(i
.values()));
3350 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3351 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3354 void RenderFrameImpl::didReceiveResponse(
3355 blink::WebLocalFrame
* frame
,
3356 unsigned identifier
,
3357 const blink::WebURLResponse
& response
) {
3358 DCHECK(!frame_
|| frame_
== frame
);
3359 // Only do this for responses that correspond to a provisional data source
3360 // of the top-most frame. If we have a provisional data source, then we
3361 // can't have any sub-resources yet, so we know that this response must
3362 // correspond to a frame load.
3363 if (!frame
->provisionalDataSource() || frame
->parent())
3366 // If we are in view source mode, then just let the user see the source of
3367 // the server's error page.
3368 if (frame
->isViewSourceModeEnabled())
3371 DocumentState
* document_state
=
3372 DocumentState::FromDataSource(frame
->provisionalDataSource());
3373 int http_status_code
= response
.httpStatusCode();
3375 // Record page load flags.
3376 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3378 document_state
->set_was_fetched_via_spdy(
3379 extra_data
->was_fetched_via_spdy());
3380 document_state
->set_was_npn_negotiated(
3381 extra_data
->was_npn_negotiated());
3382 document_state
->set_npn_negotiated_protocol(
3383 extra_data
->npn_negotiated_protocol());
3384 document_state
->set_was_alternate_protocol_available(
3385 extra_data
->was_alternate_protocol_available());
3386 document_state
->set_connection_info(
3387 extra_data
->connection_info());
3388 document_state
->set_was_fetched_via_proxy(
3389 extra_data
->was_fetched_via_proxy());
3390 document_state
->set_proxy_server(
3391 extra_data
->proxy_server());
3393 InternalDocumentStateData
* internal_data
=
3394 InternalDocumentStateData::FromDocumentState(document_state
);
3395 internal_data
->set_http_status_code(http_status_code
);
3398 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3399 blink::WebLocalFrame
* frame
,
3400 const blink::WebURLRequest
& request
,
3401 const blink::WebURLResponse
& response
) {
3402 DCHECK(!frame_
|| frame_
== frame
);
3403 // The recipients of this message have no use for data: URLs: they don't
3404 // affect the page's insecure content list and are not in the disk cache. To
3405 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3406 // filter them out here.
3407 GURL
url(request
.url());
3408 if (url
.SchemeIs(url::kDataScheme
))
3411 // Let the browser know we loaded a resource from the memory cache. This
3412 // message is needed to display the correct SSL indicators.
3413 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3414 render_view_
->GetRoutingID(),
3416 response
.securityInfo(),
3417 request
.httpMethod().utf8(),
3418 response
.mimeType().utf8(),
3419 WebURLRequestToResourceType(request
)));
3422 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3423 DCHECK(!frame_
|| frame_
== frame
);
3424 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3425 render_view_
->GetRoutingID()));
3428 void RenderFrameImpl::didRunInsecureContent(
3429 blink::WebLocalFrame
* frame
,
3430 const blink::WebSecurityOrigin
& origin
,
3431 const blink::WebURL
& target
) {
3432 DCHECK(!frame_
|| frame_
== frame
);
3433 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3434 render_view_
->GetRoutingID(),
3435 origin
.toString().utf8(),
3437 GetContentClient()->renderer()->RecordRapporURL(
3438 "ContentSettings.MixedScript.RanMixedScript",
3439 GURL(origin
.toString().utf8()));
3442 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3443 DCHECK(!frame_
|| frame_
== frame
);
3444 #if defined(ENABLE_PLUGINS)
3445 if (frame
!= render_view_
->webview()->mainFrame())
3447 PluginChannelHost::Broadcast(
3448 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3452 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3453 v8::Local
<v8::Context
> context
,
3454 int extension_group
,
3456 DCHECK(!frame_
|| frame_
== frame
);
3458 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3459 DidCreateScriptContext(context
, extension_group
, world_id
));
3462 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3463 v8::Local
<v8::Context
> context
,
3465 DCHECK(!frame_
|| frame_
== frame
);
3467 FOR_EACH_OBSERVER(RenderFrameObserver
,
3469 WillReleaseScriptContext(context
, world_id
));
3472 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3473 blink::WebLocalFrame
* frame
) {
3474 DCHECK(!frame_
|| frame_
== frame
);
3475 if (frame
->parent())
3478 InternalDocumentStateData
* data
=
3479 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3480 data
->set_did_first_visually_non_empty_layout(true);
3482 #if defined(OS_ANDROID)
3483 GetRenderWidget()->DidChangeBodyBackgroundColor(
3484 render_view_
->webwidget_
->backgroundColor());
3487 GetRenderWidget()->QueueMessage(
3488 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3489 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3492 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3493 DCHECK(!frame_
|| frame_
== frame
);
3494 // TODO(nasko): Move implementation here. Needed methods:
3495 // * StartNavStateSyncTimerIfNecessary
3496 render_view_
->didChangeScrollOffset(frame
);
3498 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3501 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3502 DCHECK(!frame_
|| frame_
== frame
);
3503 if (!frame
->parent()) {
3504 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3505 render_view_
->GetRoutingID()));
3509 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3511 bool final_update
) {
3512 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3514 active_match_ordinal
= 0;
3516 render_view_
->Send(new ViewHostMsg_Find_Reply(
3517 render_view_
->GetRoutingID(), request_id
, count
,
3518 gfx::Rect(), active_match_ordinal
, final_update
));
3521 void RenderFrameImpl::reportFindInPageSelection(
3523 int active_match_ordinal
,
3524 const blink::WebRect
& selection_rect
) {
3525 render_view_
->Send(new ViewHostMsg_Find_Reply(
3526 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3527 active_match_ordinal
, false));
3530 void RenderFrameImpl::requestStorageQuota(
3531 blink::WebLocalFrame
* frame
,
3532 blink::WebStorageQuotaType type
,
3533 unsigned long long requested_size
,
3534 blink::WebStorageQuotaCallbacks callbacks
) {
3535 DCHECK(!frame_
|| frame_
== frame
);
3536 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3537 if (origin
.isUnique()) {
3538 // Unique origins cannot store persistent state.
3539 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3542 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3543 render_view_
->GetRoutingID(),
3544 GURL(origin
.toString()),
3545 static_cast<storage::StorageType
>(type
),
3547 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3550 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3551 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3552 impl
->set_render_frame_id(routing_id_
);
3555 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3556 if (!geolocation_dispatcher_
)
3557 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3558 return geolocation_dispatcher_
;
3561 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3562 if (!presentation_dispatcher_
)
3563 presentation_dispatcher_
= new PresentationDispatcher(this);
3564 return presentation_dispatcher_
;
3567 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3568 if (!push_messaging_dispatcher_
)
3569 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3570 return push_messaging_dispatcher_
;
3573 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3574 blink::WebLocalFrame
* frame
,
3575 blink::WebRTCPeerConnectionHandler
* handler
) {
3576 DCHECK(!frame_
|| frame_
== frame
);
3577 #if defined(ENABLE_WEBRTC)
3578 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3582 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3583 if (!web_user_media_client_
)
3584 InitializeUserMediaClient();
3585 return web_user_media_client_
;
3588 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3589 if (!web_encrypted_media_client_
) {
3590 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3591 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3592 // is destructed before |this|, and does not give away ownership of the
3594 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3595 base::Unretained(this)),
3596 GetCdmFactory(), GetMediaPermission()));
3598 return web_encrypted_media_client_
.get();
3601 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3602 if (!midi_dispatcher_
)
3603 midi_dispatcher_
= new MidiDispatcher(this);
3604 return midi_dispatcher_
;
3607 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3608 blink::WebLocalFrame
* source_frame
,
3609 blink::WebFrame
* target_frame
,
3610 blink::WebSecurityOrigin target_origin
,
3611 blink::WebDOMMessageEvent event
) {
3612 DCHECK(!frame_
|| frame_
== target_frame
);
3614 // Currently, a postMessage that targets a cross-process frame can be plumbed
3615 // either through this function or RenderFrameProxy::postMessageEvent. This
3616 // function is used when the target cross-process frame is a top-level frame
3617 // which has been swapped out. In that case, the corresponding WebLocalFrame
3618 // currently remains in the frame tree even in site-per-process mode (see
3619 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3620 // --site-per-process mode for all other cases.
3622 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3623 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3624 // cross-process postMessages.
3625 if (!is_swapped_out_
)
3628 // It is possible to get here on a swapped-out frame without a
3629 // |render_frame_proxy_|. This happens when:
3630 // - This process only has one active RenderView and is about to go away
3631 // (e.g., due to cross-process navigation).
3632 // - The top frame has a subframe with an unload handler.
3633 // - The subframe sends a postMessage to the top-level frame in its unload
3635 // See https://crbug.com/475651 for details. We return false here, since we
3636 // don't want to deliver the message to the new process in this case.
3637 if (!render_frame_proxy_
)
3640 render_frame_proxy_
->postMessageEvent(
3641 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3645 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3646 const blink::WebURL
& url
) {
3647 DCHECK(!frame_
|| frame_
== frame
);
3648 std::string user_agent_override_for_url
=
3649 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3650 if (!user_agent_override_for_url
.empty())
3651 return WebString::fromUTF8(user_agent_override_for_url
);
3653 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3654 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3655 return blink::WebString();
3658 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3659 // associated with it, so the checks below are not valid. Temporarily
3660 // return early and fix properly as part of https://crbug.com/426555.
3661 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3662 return blink::WebString();
3664 // If we're in the middle of committing a load, the data source we need
3665 // will still be provisional.
3666 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3667 WebDataSource
* data_source
= NULL
;
3668 if (main_frame
->provisionalDataSource())
3669 data_source
= main_frame
->provisionalDataSource();
3671 data_source
= main_frame
->dataSource();
3673 InternalDocumentStateData
* internal_data
= data_source
?
3674 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3675 if (internal_data
&& internal_data
->is_overriding_user_agent())
3676 return WebString::fromUTF8(
3677 render_view_
->renderer_preferences_
.user_agent_override
);
3678 return blink::WebString();
3681 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3682 DCHECK(!frame_
|| frame_
== frame
);
3683 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3684 return WebString::fromUTF8("1");
3688 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3689 bool default_value
) {
3690 DCHECK(!frame_
|| frame_
== frame
);
3694 bool blocked
= true;
3695 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3696 render_view_
->GetRoutingID(),
3697 GURL(frame
->top()->securityOrigin().toString()),
3698 THREE_D_API_TYPE_WEBGL
,
3703 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3704 int arb_robustness_status_code
) {
3705 DCHECK(!frame_
|| frame_
== frame
);
3706 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3707 GURL(frame
->top()->securityOrigin().toString()),
3708 THREE_D_API_TYPE_WEBGL
,
3709 arb_robustness_status_code
));
3712 blink::WebScreenOrientationClient
*
3713 RenderFrameImpl::webScreenOrientationClient() {
3714 if (!screen_orientation_dispatcher_
)
3715 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3716 return screen_orientation_dispatcher_
;
3719 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3720 ServiceWorkerNetworkProvider
* provider
=
3721 ServiceWorkerNetworkProvider::FromDocumentState(
3722 DocumentState::FromDataSource(&data_source
));
3723 if (!provider
->context())
3725 return provider
->context()->controller_handle_id() !=
3726 kInvalidServiceWorkerHandleId
;
3729 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3730 ServiceWorkerNetworkProvider
* provider
=
3731 ServiceWorkerNetworkProvider::FromDocumentState(
3732 DocumentState::FromDataSource(&data_source
));
3733 if (provider
->context() && provider
->context()->controller())
3734 return provider
->context()->controller()->version_id();
3735 return kInvalidServiceWorkerVersionId
;
3738 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3739 blink::WebAXEvent event
) {
3740 HandleWebAccessibilityEvent(obj
, event
);
3743 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3746 const blink::WebAXObject
& start_object
,
3748 const blink::WebAXObject
& end_object
,
3750 if (renderer_accessibility_
) {
3751 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3752 identifier
, match_index
, start_object
, start_offset
,
3753 end_object
, end_offset
);
3757 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3758 DCHECK(!frame_
|| frame_
== frame
);
3760 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3763 bool RenderFrameImpl::enterFullscreen() {
3764 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3768 bool RenderFrameImpl::exitFullscreen() {
3769 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3773 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3774 if (!permission_client_
)
3775 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3777 return permission_client_
.get();
3780 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3781 if (!app_banner_client_
) {
3782 app_banner_client_
=
3783 GetContentClient()->renderer()->CreateAppBannerClient(this);
3786 return app_banner_client_
.get();
3789 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3791 const WebString
& title
) {
3792 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3793 Send(new FrameHostMsg_RegisterProtocolHandler(
3795 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3801 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3802 const WebURL
& url
) {
3803 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3804 Send(new FrameHostMsg_UnregisterProtocolHandler(
3806 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3811 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3813 bluetooth_
.reset(new WebBluetoothImpl(
3814 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3817 return bluetooth_
.get();
3820 #if defined(ENABLE_WEBVR)
3821 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3822 if (!vr_dispatcher_
)
3823 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3825 return vr_dispatcher_
.get();
3829 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3830 Send(new FrameHostMsg_MediaPlayingNotification(
3831 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3832 player
->hasAudio(), player
->isRemote()));
3835 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3836 Send(new FrameHostMsg_MediaPausedNotification(
3837 routing_id_
, reinterpret_cast<int64
>(player
)));
3840 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3844 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3845 observers_
.AddObserver(observer
);
3848 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3849 observer
->RenderFrameGone();
3850 observers_
.RemoveObserver(observer
);
3853 void RenderFrameImpl::OnStop() {
3855 frame_
->stopLoading();
3856 if (!frame_
->parent())
3857 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3859 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3862 void RenderFrameImpl::WasHidden() {
3863 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3866 void RenderFrameImpl::WasShown() {
3867 // TODO(kenrb): Need to figure out how to do this better. Should
3868 // VisibilityState remain a page-level concept or move to frames?
3869 // The semantics of 'Show' might have to change here.
3870 if (render_widget_
) {
3871 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3872 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3874 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3877 void RenderFrameImpl::WidgetWillClose() {
3878 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3881 bool RenderFrameImpl::IsHidden() {
3882 return GetRenderWidget()->is_hidden();
3885 // Tell the embedding application that the URL of the active page has changed.
3886 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3887 blink::WebFrame
* frame
,
3888 blink::WebHistoryCommitType commit_type
,
3889 const blink::WebHistoryItem
& item
) {
3890 DCHECK(!frame_
|| frame_
== frame
);
3891 WebDataSource
* ds
= frame
->dataSource();
3894 const WebURLRequest
& request
= ds
->request();
3895 const WebURLResponse
& response
= ds
->response();
3897 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3898 NavigationStateImpl
* navigation_state
=
3899 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3900 InternalDocumentStateData
* internal_data
=
3901 InternalDocumentStateData::FromDocumentState(document_state
);
3903 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3904 params
.http_status_code
= response
.httpStatusCode();
3905 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3906 params
.is_post
= false;
3907 params
.intended_as_new_entry
=
3908 navigation_state
->request_params().intended_as_new_entry
;
3909 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3910 params
.post_id
= -1;
3911 params
.page_id
= render_view_
->page_id_
;
3912 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3913 // We need to track the RenderViewHost routing_id because of downstream
3914 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3915 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3916 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3917 // based on the ID stored in the resource requests. Once those dependencies
3918 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3919 // client to be based on the routing_id of the RenderFrameHost.
3920 params
.render_view_routing_id
= render_view_
->routing_id();
3921 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3922 params
.socket_address
.set_port(response
.remotePort());
3923 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3925 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3926 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3927 params
.security_info
= response
.securityInfo();
3929 // Set the URL to be displayed in the browser UI to the user.
3930 params
.url
= GetLoadingUrl();
3931 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3933 // Set the origin of the frame. This will be replicated to the corresponding
3934 // RenderFrameProxies in other processes.
3935 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3936 // to https://crbug.com/439608 and will be replicated as unique origins.
3937 if (!is_swapped_out_
) {
3938 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3939 if (url::IsStandard(scheme
.c_str(),
3940 url::Component(0, static_cast<int>(scheme
.length())))) {
3941 params
.origin
= frame
->document().securityOrigin();
3945 if (frame
->document().baseURL() != params
.url
)
3946 params
.base_url
= frame
->document().baseURL();
3948 GetRedirectChain(ds
, ¶ms
.redirects
);
3949 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3950 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3952 params
.searchable_form_url
= internal_data
->searchable_form_url();
3953 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3955 params
.gesture
= render_view_
->navigation_gesture_
;
3956 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3958 // Make navigation state a part of the DidCommitProvisionalLoad message so
3959 // that committed entry has it at all times.
3960 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3961 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3963 params
.page_state
= HistoryEntryToPageState(entry
);
3965 params
.page_state
= PageState::CreateFromURL(request
.url());
3967 // In --site-per-process, just send a single HistoryItem for this frame,
3968 // rather than the whole tree. It will be stored in the corresponding
3969 // FrameNavigationEntry.
3970 params
.page_state
= SingleHistoryItemToPageState(item
);
3972 params
.item_sequence_number
= item
.itemSequenceNumber();
3973 params
.document_sequence_number
= item
.documentSequenceNumber();
3975 if (!frame
->parent()) {
3976 // Top-level navigation.
3978 // Reset the zoom limits in case a plugin had changed them previously. This
3979 // will also call us back which will cause us to send a message to
3980 // update WebContentsImpl.
3981 render_view_
->webview()->zoomLimitsChanged(
3982 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3983 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3985 // Set zoom level, but don't do it for full-page plugin since they don't use
3986 // the same zoom settings.
3987 HostZoomLevels::iterator host_zoom
=
3988 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3989 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3990 // Reset the zoom levels for plugins.
3991 render_view_
->webview()->setZoomLevel(0);
3993 // If the zoom level is not found, then do nothing. In-page navigation
3994 // relies on not changing the zoom level in this case.
3995 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3996 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3999 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
4000 // This zoom level was merely recorded transiently for this load. We can
4001 // erase it now. If at some point we reload this page, the browser will
4002 // send us a new, up-to-date zoom level.
4003 render_view_
->host_zoom_levels_
.erase(host_zoom
);
4006 // Update contents MIME type for main frame.
4007 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4009 params
.transition
= navigation_state
->GetTransitionType();
4010 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4011 // If the main frame does a load, it should not be reported as a subframe
4012 // navigation. This can occur in the following case:
4013 // 1. You're on a site with frames.
4014 // 2. You do a subframe navigation. This is stored with transition type
4016 // 3. You navigate to some non-frame site, say, google.com.
4017 // 4. You navigate back to the page from step 2. Since it was initially
4018 // MANUAL_SUBFRAME, it will be that same transition type here.
4019 // We don't want that, because any navigation that changes the toplevel
4020 // frame should be tracked as a toplevel navigation (this allows us to
4021 // update the URL bar, etc).
4022 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4025 // If the page contained a client redirect (meta refresh, document.loc...),
4026 // set the referrer and transition appropriately.
4027 if (ds
->isClientRedirect()) {
4029 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4030 params
.transition
= ui::PageTransitionFromInt(
4031 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4033 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4034 frame
, ds
->request());
4037 base::string16 method
= request
.httpMethod();
4038 if (base::EqualsASCII(method
, "POST")) {
4039 params
.is_post
= true;
4040 params
.post_id
= ExtractPostId(entry
);
4043 // Send the user agent override back.
4044 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4046 // Track the URL of the original request. We use the first entry of the
4047 // redirect chain if it exists because the chain may have started in another
4049 params
.original_request_url
= GetOriginalRequestURL(ds
);
4051 params
.history_list_was_cleared
=
4052 navigation_state
->request_params().should_clear_history_list
;
4054 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4055 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4056 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4057 frame
->dataSource()->request().uiStartTime());
4059 // Save some histogram data so we can compute the average memory used per
4060 // page load of the glyphs.
4061 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4062 blink::WebGlyphCache::pageCount());
4064 // This message needs to be sent before any of allowScripts(),
4065 // allowImages(), allowPlugins() is called for the new page, so that when
4066 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4067 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4068 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4070 // Subframe navigation: the type depends on whether this navigation
4071 // generated a new session history entry. When they do generate a session
4072 // history entry, it means the user initiated the navigation and we should
4074 if (commit_type
== blink::WebStandardCommit
)
4075 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4077 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4079 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4080 params
.history_list_was_cleared
= false;
4081 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4083 // Don't send this message while the subframe is swapped out.
4084 if (!is_swapped_out())
4085 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4088 // If we end up reusing this WebRequest (for example, due to a #ref click),
4089 // we don't want the transition type to persist. Just clear it.
4090 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4093 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4094 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4096 render_view_
->FrameDidStartLoading(frame_
);
4097 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4100 void RenderFrameImpl::didStopLoading() {
4101 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4103 render_view_
->FrameDidStopLoading(frame_
);
4104 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4107 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4108 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4111 void RenderFrameImpl::HandleWebAccessibilityEvent(
4112 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4113 if (renderer_accessibility_
)
4114 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4117 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4118 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4121 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4122 if (renderer_accessibility())
4123 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4127 void RenderFrameImpl::OnCommitNavigation(
4128 const ResourceResponseHead
& response
,
4129 const GURL
& stream_url
,
4130 const CommonNavigationParams
& common_params
,
4131 const RequestNavigationParams
& request_params
) {
4132 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4133 switches::kEnableBrowserSideNavigation
));
4134 // This will override the url requested by the WebURLLoader, as well as
4135 // provide it with the response to the request.
4136 scoped_ptr
<StreamOverrideParameters
> stream_override(
4137 new StreamOverrideParameters());
4138 stream_override
->stream_url
= stream_url
;
4139 stream_override
->response
= response
;
4141 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4142 stream_override
.Pass());
4145 void RenderFrameImpl::OnFailedNavigation(
4146 const CommonNavigationParams
& common_params
,
4147 const RequestNavigationParams
& request_params
,
4148 bool has_stale_copy_in_cache
,
4150 bool is_reload
= IsReload(common_params
.navigation_type
);
4151 bool is_history_navigation
= request_params
.page_state
.IsValid();
4152 WebURLRequest::CachePolicy cache_policy
=
4153 WebURLRequest::UseProtocolCachePolicy
;
4154 RenderFrameImpl::PrepareRenderViewForNavigation(
4155 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4157 GetContentClient()->SetActiveURL(common_params
.url
);
4159 pending_navigation_params_
.reset(new NavigationParams(
4160 common_params
, StartNavigationParams(), request_params
));
4162 // Inform the browser of the start of the provisional load. This is needed so
4163 // that the load is properly tracked by the WebNavigation API.
4164 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4165 routing_id_
, common_params
.url
));
4167 // Send the provisional load failure.
4168 blink::WebURLError error
=
4169 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4170 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4171 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4172 frame_
->isViewSourceModeEnabled());
4173 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4175 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4176 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4177 // http://crbug.com/501960
4178 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4182 // Make sure errors are not shown in view source mode.
4183 frame_
->enableViewSourceMode(false);
4185 // Replace the current history entry in reloads, history navigations and loads
4186 // of the same url. This corresponds to Blink's notion of a standard
4188 // TODO(clamy): see if initial commits in subframes should be handled
4190 bool replace
= is_reload
|| is_history_navigation
||
4191 common_params
.url
== GetLoadingUrl();
4192 LoadNavigationErrorPage(failed_request
, error
, replace
);
4195 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4196 RenderFrame
* render_frame
,
4197 const NavigationPolicyInfo
& info
) {
4198 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4201 // TODO(nick): Is consulting |is_subframe_| here correct?
4202 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_
) {
4203 // There's no reason to ignore navigations on subframes, since the swap out
4204 // logic no longer applies.
4206 if (is_swapped_out_
) {
4207 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4208 // Targeted links may try to navigate a swapped out frame. Allow the
4209 // browser process to navigate the tab instead. Note that it is also
4210 // possible for non-targeted navigations (from this view) to arrive
4211 // here just after we are swapped out. It's ok to send them to the
4212 // browser, as long as they're for the top level frame.
4213 // TODO(creis): Ensure this supports targeted form submissions when
4214 // fixing http://crbug.com/101395.
4215 if (info
.frame
->parent() == NULL
) {
4216 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4217 info
.defaultPolicy
);
4218 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4221 // We should otherwise ignore in-process iframe navigations, if they
4222 // arrive just after we are swapped out.
4223 return blink::WebNavigationPolicyIgnore
;
4226 // Allow kSwappedOutURL to complete.
4227 return info
.defaultPolicy
;
4231 // Webkit is asking whether to navigate to a new URL.
4232 // This is fine normally, except if we're showing UI from one security
4233 // context and they're trying to navigate to a different context.
4234 const GURL
& url
= info
.urlRequest
.url();
4236 // A content initiated navigation may have originated from a link-click,
4237 // script, drag-n-drop operation, etc.
4238 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4239 bool is_content_initiated
=
4240 document_state
->navigation_state()->IsContentInitiated();
4242 // If the browser is interested, then give it a chance to look at the request.
4243 if (is_content_initiated
) {
4245 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4246 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4247 base::EqualsASCII(base::StringPiece16(info
.urlRequest
.httpMethod()),
4249 bool browser_handles_request
=
4250 render_view_
->renderer_preferences_
4251 .browser_handles_non_local_top_level_requests
4252 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4254 if (!browser_handles_request
) {
4255 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4256 render_view_
->renderer_preferences_
4257 .browser_handles_all_top_level_requests
;
4260 if (browser_handles_request
) {
4261 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4262 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4266 // Use the frame's original request's URL rather than the document's URL for
4267 // subsequent checks. For a popup, the document's URL may become the opener
4268 // window's URL if the opener has called document.write().
4269 // See http://crbug.com/93517.
4270 GURL
old_url(info
.frame
->dataSource()->request().url());
4272 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4273 // an extension or app origin, leaving a WebUI page, etc). We only care about
4274 // top-level navigations (not iframes). But we sometimes navigate to
4275 // about:blank to clear a tab, and we want to still allow that.
4277 // Note: this is known to break POST submissions when crossing process
4278 // boundaries until http://crbug.com/101395 is fixed. This is better for
4279 // security than loading a WebUI, extension or app page in the wrong process.
4280 // POST requests don't work because this mechanism does not preserve form
4281 // POST data. We will need to send the request's httpBody data up to the
4282 // browser process, and issue a special POST navigation in WebKit (via
4283 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4284 // for examples of how to send the httpBody data.
4285 if (!info
.frame
->parent() && is_content_initiated
&&
4286 !url
.SchemeIs(url::kAboutScheme
)) {
4287 bool send_referrer
= false;
4289 // All navigations to or from WebUI URLs or within WebUI-enabled
4290 // RenderProcesses must be handled by the browser process so that the
4291 // correct bindings and data sources can be registered.
4292 // Similarly, navigations to view-source URLs or within ViewSource mode
4293 // must be handled by the browser process (except for reloads - those are
4294 // safe to leave within the renderer).
4295 // Lastly, access to file:// URLs from non-file:// URL pages must be
4296 // handled by the browser so that ordinary renderer processes don't get
4297 // blessed with file permissions.
4298 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4299 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4300 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4301 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4302 url
.SchemeIs(kViewSourceScheme
) ||
4303 (info
.frame
->isViewSourceModeEnabled() &&
4304 info
.navigationType
!= blink::WebNavigationTypeReload
);
4306 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4307 // Fork non-file to file opens. Check the opener URL if this is the
4308 // initial navigation in a newly opened window.
4309 GURL
source_url(old_url
);
4310 if (is_initial_navigation
&& source_url
.is_empty() &&
4311 info
.frame
->opener())
4312 source_url
= info
.frame
->opener()->top()->document().url();
4313 DCHECK(!source_url
.is_empty());
4314 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4318 // Give the embedder a chance.
4319 should_fork
= GetContentClient()->renderer()->ShouldFork(
4320 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4321 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4325 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4326 info
.defaultPolicy
);
4327 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4331 // Detect when a page is "forking" a new tab that can be safely rendered in
4332 // its own process. This is done by sites like Gmail that try to open links
4333 // in new windows without script connections back to the original page. We
4334 // treat such cases as browser navigations (in which we will create a new
4335 // renderer for a cross-site navigation), rather than WebKit navigations.
4337 // We use the following heuristic to decide whether to fork a new page in its
4339 // The parent page must open a new tab to about:blank, set the new tab's
4340 // window.opener to null, and then redirect the tab to a cross-site URL using
4343 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4346 // Must start from a tab showing about:blank, which is later redirected.
4347 old_url
== GURL(url::kAboutBlankURL
) &&
4348 // Must be the first real navigation of the tab.
4349 render_view_
->historyBackListCount() < 1 &&
4350 render_view_
->historyForwardListCount() < 1 &&
4351 // The parent page must have set the child's window.opener to null before
4352 // redirecting to the desired URL.
4353 info
.frame
->opener() == NULL
&&
4354 // Must be a top-level frame.
4355 info
.frame
->parent() == NULL
&&
4356 // Must not have issued the request from this page.
4357 is_content_initiated
&&
4358 // Must be targeted at the current tab.
4359 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4360 // Must be a JavaScript navigation, which appears as "other".
4361 info
.navigationType
== blink::WebNavigationTypeOther
;
4364 // Open the URL via the browser, not via WebKit.
4365 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4366 return blink::WebNavigationPolicyIgnore
;
4369 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4370 // This includes navigations with no request being sent to the network stack.
4371 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4372 switches::kEnableBrowserSideNavigation
) &&
4373 info
.urlRequest
.checkForBrowserSideNavigation() &&
4374 ShouldMakeNetworkRequestForURL(url
)) {
4375 BeginNavigation(&info
.urlRequest
);
4376 return blink::WebNavigationPolicyIgnore
;
4379 return info
.defaultPolicy
;
4382 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4384 const Referrer
& referrer
,
4385 WebNavigationPolicy policy
) {
4386 DCHECK_EQ(frame_
, frame
);
4388 FrameHostMsg_OpenURL_Params params
;
4390 params
.referrer
= referrer
;
4391 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4392 WebDataSource
* ds
= frame
->provisionalDataSource();
4394 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4395 NavigationStateImpl
* navigation_state
=
4396 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4397 if (navigation_state
->IsContentInitiated()) {
4398 params
.should_replace_current_entry
=
4399 ds
->replacesCurrentHistoryItem() &&
4400 render_view_
->history_list_length_
;
4402 // This is necessary to preserve the should_replace_current_entry value on
4403 // cross-process redirects, in the event it was set by a previous process.
4405 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4406 // NavigationState::should_replace_current_entry().
4407 params
.should_replace_current_entry
=
4408 navigation_state
->common_params().should_replace_current_entry
;
4411 params
.should_replace_current_entry
= false;
4413 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4414 if (GetContentClient()->renderer()->AllowPopup())
4415 params
.user_gesture
= true;
4417 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4418 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4419 policy
== blink::WebNavigationPolicyNewWindow
||
4420 policy
== blink::WebNavigationPolicyNewPopup
) {
4421 WebUserGestureIndicator::consumeUserGesture();
4424 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4427 void RenderFrameImpl::NavigateInternal(
4428 const CommonNavigationParams
& common_params
,
4429 const StartNavigationParams
& start_params
,
4430 const RequestNavigationParams
& request_params
,
4431 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4432 bool browser_side_navigation
=
4433 base::CommandLine::ForCurrentProcess()->HasSwitch(
4434 switches::kEnableBrowserSideNavigation
);
4435 bool is_reload
= IsReload(common_params
.navigation_type
);
4436 bool is_history_navigation
= request_params
.page_state
.IsValid();
4437 WebURLRequest::CachePolicy cache_policy
=
4438 WebURLRequest::UseProtocolCachePolicy
;
4439 RenderFrameImpl::PrepareRenderViewForNavigation(
4440 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4442 GetContentClient()->SetActiveURL(common_params
.url
);
4444 // If this frame isn't in the same process as the main frame, it may naively
4445 // assume that this is the first navigation in the iframe, but this may not
4446 // actually be the case. Inform the frame's state machine if this frame has
4447 // already committed other loads.
4448 if (request_params
.has_committed_real_load
&& frame_
->parent())
4449 frame_
->setCommittedFirstRealLoad();
4451 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4452 // We cannot reload if we do not have any history state. This happens, for
4453 // example, when recovering from a crash.
4455 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4458 pending_navigation_params_
.reset(
4459 new NavigationParams(common_params
, start_params
, request_params
));
4461 // Create parameters for a standard navigation.
4462 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4463 bool should_load_request
= false;
4464 WebHistoryItem item_for_history_navigation
;
4465 WebURLRequest request
= CreateURLRequestForNavigation(
4466 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4468 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4469 // navigation for this request (since it already went to the browser).
4470 if (browser_side_navigation
)
4471 request
.setCheckForBrowserSideNavigation(false);
4473 // If we are reloading, then use the history state of the current frame.
4474 // Otherwise, if we have history state, then we need to navigate to it, which
4475 // corresponds to a back/forward navigation event. Update the parameters
4476 // depending on the navigation type.
4478 bool ignore_cache
= (common_params
.navigation_type
==
4479 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4480 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4481 : blink::WebFrameLoadType::Reload
;
4483 if (!browser_side_navigation
) {
4484 const GURL override_url
=
4485 (common_params
.navigation_type
==
4486 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4489 request
= frame_
->requestForReload(load_type
, override_url
);
4491 should_load_request
= true;
4492 } else if (is_history_navigation
) {
4493 // We must know the page ID of the page we are navigating back to.
4494 DCHECK_NE(request_params
.page_id
, -1);
4495 // We must know the nav entry ID of the page we are navigating back to,
4496 // which should be the case because history navigations are routed via the
4498 DCHECK_NE(0, request_params
.nav_entry_id
);
4499 scoped_ptr
<HistoryEntry
> entry
=
4500 PageStateToHistoryEntry(request_params
.page_state
);
4502 // Ensure we didn't save the swapped out URL in UpdateState, since the
4503 // browser should never be telling us to navigate to swappedout://.
4504 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4506 if (!browser_side_navigation
) {
4507 scoped_ptr
<NavigationParams
> navigation_params(
4508 new NavigationParams(*pending_navigation_params_
.get()));
4509 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4510 // By default, tell the HistoryController to go the deserialized
4511 // HistoryEntry. This only works if all frames are in the same
4513 DCHECK(!frame_
->parent());
4514 render_view_
->history_controller()->GoToEntry(
4515 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4517 // In --site-per-process, the browser process sends a single
4518 // WebHistoryItem destined for this frame.
4519 // TODO(creis): Change PageState to FrameState. In the meantime, we
4520 // store the relevant frame's WebHistoryItem in the root of the
4522 SetPendingNavigationParams(navigation_params
.Pass());
4523 blink::WebHistoryItem history_item
= entry
->root();
4524 blink::WebHistoryLoadType load_type
=
4525 request_params
.is_same_document_history_load
4526 ? blink::WebHistorySameDocumentLoad
4527 : blink::WebHistoryDifferentDocumentLoad
;
4529 // Let the history controller know the provisional entry, since it is
4530 // used at commit time. Otherwise skip GoToEntry and navigate the
4532 // TODO(creis): Consider cloning the current entry to handle subframe
4533 // cases. Changes to SendUpdateState might affect this.
4534 render_view_
->history_controller()->set_provisional_entry(
4536 WebURLRequest request
=
4537 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4538 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4539 history_item
, load_type
);
4542 // TODO(clamy): this should be set to the HistoryItem sent by the
4543 // browser once the HistoryController has moved to the browser.
4544 // TODO(clamy): distinguish between different document and same document
4546 // TODO(clamy): update this for subframes history loads.
4547 item_for_history_navigation
=
4548 entry
->GetHistoryNodeForFrame(this)->item();
4549 load_type
= blink::WebFrameLoadType::BackForward
;
4550 should_load_request
= true;
4554 // Navigate to the given URL.
4555 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4556 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4557 start_params
.extra_headers
.end(),
4560 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4561 WebString::fromUTF8(i
.values()));
4565 if (start_params
.is_post
&& !browser_side_navigation
) {
4566 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4569 WebHTTPBody http_body
;
4570 http_body
.initialize();
4571 const char* data
= nullptr;
4572 if (start_params
.browser_initiated_post_data
.size()) {
4573 data
= reinterpret_cast<const char*>(
4574 &start_params
.browser_initiated_post_data
.front());
4576 http_body
.appendData(
4577 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4578 request
.setHTTPBody(http_body
);
4581 // A session history navigation should have been accompanied by state.
4582 CHECK_EQ(request_params
.page_id
, -1);
4584 should_load_request
= true;
4587 if (should_load_request
) {
4588 // Record this before starting the load. We need a lower bound of this
4589 // time to sanitize the navigationStart override set below.
4590 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4592 // Perform a navigation to a data url if needed.
4593 if (!common_params
.base_url_for_data_url
.is_empty() ||
4594 (browser_side_navigation
&&
4595 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4596 LoadDataURL(common_params
, frame_
);
4598 // Load the request.
4599 frame_
->toWebLocalFrame()->load(request
, load_type
,
4600 item_for_history_navigation
);
4603 if (load_type
== blink::WebFrameLoadType::Standard
) {
4604 UpdateFrameNavigationTiming(frame_
,
4605 request_params
.browser_navigation_start
,
4606 renderer_navigation_start
);
4610 // In case LoadRequest failed before didCreateDataSource was called.
4611 pending_navigation_params_
.reset();
4614 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4615 const std::string
& encoding_name
) {
4616 // Only update main frame's encoding_name.
4617 if (!frame
->parent())
4618 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4621 void RenderFrameImpl::SyncSelectionIfRequired() {
4622 base::string16 text
;
4625 #if defined(ENABLE_PLUGINS)
4626 if (render_view_
->focused_pepper_plugin_
) {
4627 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4628 offset
= 0; // Pepper API does not support offset reporting.
4629 // TODO(kinaba): cut as needed.
4633 size_t location
, length
;
4634 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4635 &location
, &length
)) {
4639 range
= gfx::Range(location
, location
+ length
);
4641 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4642 blink::WebTextInputTypeNone
) {
4643 // If current focused element is editable, we will send 100 more chars
4644 // before and after selection. It is for input method surrounding text
4646 if (location
> kExtraCharsBeforeAndAfterSelection
)
4647 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4650 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4651 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4652 if (!webrange
.isNull())
4653 text
= webrange
.toPlainText();
4656 text
= frame_
->selectionAsText();
4657 // http://crbug.com/101435
4658 // In some case, frame->selectionAsText() returned text's length is not
4659 // equal to the length returned from webwidget()->caretOrSelectionRange().
4660 // So we have to set the range according to text.length().
4661 range
.set_end(range
.start() + text
.length());
4665 // Sometimes we get repeated didChangeSelection calls from webkit when
4666 // the selection hasn't actually changed. We don't want to report these
4667 // because it will cause us to continually claim the X clipboard.
4668 if (selection_text_offset_
!= offset
||
4669 selection_range_
!= range
||
4670 selection_text_
!= text
) {
4671 selection_text_
= text
;
4672 selection_text_offset_
= offset
;
4673 selection_range_
= range
;
4674 SetSelectedText(text
, offset
, range
);
4676 GetRenderWidget()->UpdateSelectionBounds();
4679 void RenderFrameImpl::InitializeUserMediaClient() {
4680 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4683 #if defined(OS_ANDROID)
4684 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4685 switches::kDisableWebRTC
))
4689 #if defined(ENABLE_WEBRTC)
4690 DCHECK(!web_user_media_client_
);
4691 web_user_media_client_
= new UserMediaClientImpl(
4693 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4694 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4698 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4699 WebMediaPlayerClient
* client
) {
4700 #if defined(ENABLE_WEBRTC)
4701 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4703 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4704 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4705 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4706 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4707 new RenderMediaLog(),
4708 CreateRendererFactory());
4711 #endif // defined(ENABLE_WEBRTC)
4714 scoped_ptr
<MediaStreamRendererFactory
>
4715 RenderFrameImpl::CreateRendererFactory() {
4716 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4717 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4719 return factory
.Pass();
4720 #if defined(ENABLE_WEBRTC)
4721 return scoped_ptr
<MediaStreamRendererFactory
>(
4722 new MediaStreamRendererFactoryImpl());
4724 return scoped_ptr
<MediaStreamRendererFactory
>(
4725 static_cast<MediaStreamRendererFactory
*>(NULL
));
4729 void RenderFrameImpl::PrepareRenderViewForNavigation(
4731 const RequestNavigationParams
& request_params
,
4733 WebURLRequest::CachePolicy
* cache_policy
) {
4734 DCHECK(render_view_
->webview());
4736 MaybeHandleDebugURL(url
);
4739 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4741 render_view_
->history_list_offset_
=
4742 request_params
.current_history_list_offset
;
4743 render_view_
->history_list_length_
=
4744 request_params
.current_history_list_length
;
4745 if (request_params
.should_clear_history_list
) {
4746 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4747 CHECK_EQ(0, render_view_
->history_list_length_
);
4750 if (!is_swapped_out_
|| frame_
->parent())
4753 // This is a swapped out main frame, so swap the renderer back in.
4754 // We marked the view as hidden when swapping the view out, so be sure to
4755 // reset the visibility state before navigating to the new URL.
4756 render_view_
->webview()->setVisibilityState(
4757 render_view_
->visibilityState(), false);
4759 // If this is an attempt to reload while we are swapped out, we should not
4760 // reload swappedout://, but the previous page, which is stored in
4761 // params.state. Setting is_reload to false will treat this like a back
4762 // navigation to accomplish that.
4764 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4766 // We refresh timezone when a view is swapped in since timezone
4767 // can get out of sync when the system timezone is updated while
4768 // the view is swapped out.
4769 RenderThreadImpl::NotifyTimezoneChange();
4771 render_view_
->SetSwappedOut(false);
4772 is_swapped_out_
= false;
4776 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4777 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4778 switches::kEnableBrowserSideNavigation
));
4780 // TODO(clamy): Execute the beforeunload event.
4782 // Note: At this stage, the goal is to apply all the modifications the
4783 // renderer wants to make to the request, and then send it to the browser, so
4784 // that the actual network request can be started. Ideally, all such
4785 // modifications should take place in willSendRequest, and in the
4786 // implementation of willSendRequest for the various InspectorAgents
4789 // TODO(clamy): Apply devtools override.
4790 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4792 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4794 // TODO(clamy): Same-document navigations should not be sent back to the
4796 // TODO(clamy): Data urls should not be sent back to the browser either.
4797 bool should_replace_current_entry
= false;
4798 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4799 WebDataSource
* current_data_source
= frame_
->dataSource();
4800 WebDataSource
* data_source
=
4801 provisional_data_source
? provisional_data_source
: current_data_source
;
4803 // The current entry can only be replaced if there already is an entry in the
4805 if (data_source
&& render_view_
->history_list_length_
> 0) {
4806 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4808 Send(new FrameHostMsg_BeginNavigation(
4810 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4811 BeginNavigationParams(
4812 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4813 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4814 GetRequestBodyForWebURLRequest(*request
)));
4817 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4819 // A loadData request with a specified base URL.
4820 std::string mime_type
, charset
, data
;
4821 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4822 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4823 params
.url
: params
.base_url_for_data_url
;
4825 WebData(data
.c_str(), data
.length()),
4826 WebString::fromUTF8(mime_type
),
4827 WebString::fromUTF8(charset
),
4829 params
.history_url_for_data_url
,
4832 CHECK(false) << "Invalid URL passed: "
4833 << params
.url
.possibly_invalid_spec();
4837 void RenderFrameImpl::SendFailedProvisionalLoad(
4838 const blink::WebURLRequest
& request
,
4839 const blink::WebURLError
& error
,
4840 blink::WebLocalFrame
* frame
) {
4841 bool show_repost_interstitial
=
4842 (error
.reason
== net::ERR_CACHE_MISS
&&
4843 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4845 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4846 params
.error_code
= error
.reason
;
4847 GetContentClient()->renderer()->GetNavigationErrorStrings(
4848 render_view_
.get(), frame
, request
, error
, NULL
,
4849 ¶ms
.error_description
);
4850 params
.url
= error
.unreachableURL
;
4851 params
.showing_repost_interstitial
= show_repost_interstitial
;
4852 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4853 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4856 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4858 const GURL
& unreachable_url
) {
4859 // Don't display an error page if this is simply a cancelled load. Aside
4860 // from being dumb, Blink doesn't expect it and it will cause a crash.
4861 if (error_code
== net::ERR_ABORTED
)
4864 // Don't display "client blocked" error page if browser has asked us not to.
4865 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4866 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4870 // Allow the embedder to suppress an error page.
4871 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4872 this, unreachable_url
)) {
4876 if (RenderThreadImpl::current() &&
4877 RenderThreadImpl::current()->layout_test_mode()) {
4884 GURL
RenderFrameImpl::GetLoadingUrl() const {
4885 WebDataSource
* ds
= frame_
->dataSource();
4886 if (ds
->hasUnreachableURL())
4887 return ds
->unreachableURL();
4889 const WebURLRequest
& request
= ds
->request();
4890 return request
.url();
4893 void RenderFrameImpl::PopulateDocumentStateFromPending(
4894 DocumentState
* document_state
) {
4895 document_state
->set_request_time(
4896 pending_navigation_params_
->request_params
.request_time
);
4898 InternalDocumentStateData
* internal_data
=
4899 InternalDocumentStateData::FromDocumentState(document_state
);
4901 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4902 url::kJavaScriptScheme
) &&
4903 pending_navigation_params_
->common_params
.navigation_type
==
4904 FrameMsg_Navigate_Type::RESTORE
) {
4905 // We're doing a load of a page that was restored from the last session. By
4906 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4907 // can result in stale data for pages that are set to expire. We explicitly
4908 // override that by setting the policy here so that as necessary we load
4909 // from the network.
4911 // TODO(davidben): Remove this in favor of passing a cache policy to the
4912 // loadHistoryItem call in OnNavigate. That requires not overloading
4913 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4914 // policy based on load type, etc".
4915 internal_data
->set_cache_policy_override(
4916 WebURLRequest::UseProtocolCachePolicy
);
4919 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4920 document_state
->set_load_type(DocumentState::RELOAD
);
4921 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4922 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4924 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4926 internal_data
->set_is_overriding_user_agent(
4927 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4928 internal_data
->set_must_reset_scroll_and_scale_state(
4929 pending_navigation_params_
->common_params
.navigation_type
==
4930 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4931 document_state
->set_can_load_local_resources(
4932 pending_navigation_params_
->request_params
.can_load_local_resources
);
4935 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4936 // A navigation resulting from loading a javascript URL should not be treated
4937 // as a browser initiated event. Instead, we want it to look as if the page
4938 // initiated any load resulting from JS execution.
4939 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4940 url::kJavaScriptScheme
)) {
4941 return NavigationStateImpl::CreateBrowserInitiated(
4942 pending_navigation_params_
->common_params
,
4943 pending_navigation_params_
->start_params
,
4944 pending_navigation_params_
->request_params
);
4946 return NavigationStateImpl::CreateContentInitiated();
4949 #if defined(OS_ANDROID)
4951 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4952 WebMediaPlayerClient
* client
,
4953 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4954 media::MediaPermission
* media_permission
,
4955 WebContentDecryptionModule
* initial_cdm
) {
4956 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4957 if (SynchronousCompositorFactory
* factory
=
4958 SynchronousCompositorFactory::GetInstance()) {
4959 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4961 GpuChannelHost
* gpu_channel_host
=
4962 RenderThreadImpl::current()->EstablishGpuChannelSync(
4963 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4965 if (!gpu_channel_host
) {
4966 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4970 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4971 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4973 if (!context_provider
.get()) {
4974 LOG(ERROR
) << "Failed to get context3d for media player";
4978 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4979 context_provider
, gpu_channel_host
, routing_id_
);
4982 return new WebMediaPlayerAndroid(
4983 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
4984 GetMediaPlayerManager(), GetCdmFactory(), media_permission
, initial_cdm
,
4985 stream_texture_factory
,
4986 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4987 new RenderMediaLog());
4990 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4991 if (!media_player_manager_
)
4992 media_player_manager_
= new RendererMediaPlayerManager(this);
4993 return media_player_manager_
;
4996 #endif // defined(OS_ANDROID)
4998 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4999 if (!media_permission_dispatcher_
)
5000 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
5001 return media_permission_dispatcher_
;
5004 #if defined(ENABLE_MOJO_MEDIA)
5005 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5006 if (!media_service_factory_
) {
5007 mojo::InterfacePtr
<mojo::Shell
> shell_ptr
;
5008 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr
));
5010 mojo::ServiceProviderPtr service_provider
;
5011 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5012 request
->url
= mojo::String::From("mojo:media");
5013 shell_ptr
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5016 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5018 media_service_factory_
.set_connection_error_handler(
5019 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5020 base::Unretained(this)));
5023 return media_service_factory_
.get();
5026 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5027 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5028 // violation on the old |media_service_factory_| by outstanding
5029 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5031 // media_service_factory_.reset();
5035 bool RenderFrameImpl::AreSecureCodecsSupported() {
5036 #if defined(OS_ANDROID)
5037 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5038 return render_view_
->renderer_preferences_
5039 .use_video_overlay_for_embedded_encrypted_video
;
5042 #endif // defined(OS_ANDROID)
5045 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5046 #if defined(ENABLE_BROWSER_CDMS)
5048 cdm_manager_
= new RendererCdmManager(this);
5049 #endif // defined(ENABLE_BROWSER_CDMS)
5051 if (!cdm_factory_
) {
5054 #if defined(ENABLE_MOJO_MEDIA)
5055 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5057 cdm_factory_
.reset(new RenderCdmFactory(
5058 #if defined(ENABLE_PEPPER_CDMS)
5059 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5060 #elif defined(ENABLE_BROWSER_CDMS)
5064 #endif // defined(ENABLE_MOJO_MEDIA)
5067 return cdm_factory_
.get();
5070 void RenderFrameImpl::RegisterMojoServices() {
5071 // Only main frame have ImageDownloader service.
5072 if (!frame_
->parent()) {
5073 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5074 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5075 base::Unretained(this)));
5079 } // namespace content