1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/time/time.h"
22 #include "cc/base/switches.h"
23 #include "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/permissions/permission_dispatcher.h"
25 #include "content/child/plugin_messages.h"
26 #include "content/child/quota_dispatcher.h"
27 #include "content/child/request_extra_data.h"
28 #include "content/child/service_worker/service_worker_handle_reference.h"
29 #include "content/child/service_worker/service_worker_network_provider.h"
30 #include "content/child/service_worker/service_worker_provider_context.h"
31 #include "content/child/service_worker/web_service_worker_provider_impl.h"
32 #include "content/child/v8_value_converter_impl.h"
33 #include "content/child/web_url_loader_impl.h"
34 #include "content/child/web_url_request_util.h"
35 #include "content/child/webmessageportchannel_impl.h"
36 #include "content/child/websocket_bridge.h"
37 #include "content/child/weburlresponse_extradata_impl.h"
38 #include "content/common/clipboard_messages.h"
39 #include "content/common/frame_messages.h"
40 #include "content/common/frame_replication_state.h"
41 #include "content/common/input_messages.h"
42 #include "content/common/navigation_params.h"
43 #include "content/common/service_worker/service_worker_types.h"
44 #include "content/common/swapped_out_messages.h"
45 #include "content/common/view_messages.h"
46 #include "content/public/common/bindings_policy.h"
47 #include "content/public/common/content_constants.h"
48 #include "content/public/common/content_switches.h"
49 #include "content/public/common/context_menu_params.h"
50 #include "content/public/common/isolated_world_ids.h"
51 #include "content/public/common/page_state.h"
52 #include "content/public/common/resource_response.h"
53 #include "content/public/common/url_constants.h"
54 #include "content/public/common/url_utils.h"
55 #include "content/public/renderer/browser_plugin_delegate.h"
56 #include "content/public/renderer/content_renderer_client.h"
57 #include "content/public/renderer/context_menu_client.h"
58 #include "content/public/renderer/document_state.h"
59 #include "content/public/renderer/navigation_state.h"
60 #include "content/public/renderer/render_frame_observer.h"
61 #include "content/public/renderer/renderer_ppapi_host.h"
62 #include "content/renderer/accessibility/renderer_accessibility.h"
63 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
64 #include "content/renderer/browser_plugin/browser_plugin.h"
65 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
66 #include "content/renderer/child_frame_compositing_helper.h"
67 #include "content/renderer/context_menu_params_builder.h"
68 #include "content/renderer/devtools/devtools_agent.h"
69 #include "content/renderer/dom_automation_controller.h"
70 #include "content/renderer/external_popup_menu.h"
71 #include "content/renderer/geolocation_dispatcher.h"
72 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
73 #include "content/renderer/history_controller.h"
74 #include "content/renderer/history_serialization.h"
75 #include "content/renderer/image_downloader/image_downloader_impl.h"
76 #include "content/renderer/ime_event_guard.h"
77 #include "content/renderer/internal_document_state_data.h"
78 #include "content/renderer/manifest/manifest_manager.h"
79 #include "content/renderer/media/audio_renderer_mixer_manager.h"
80 #include "content/renderer/media/crypto/render_cdm_factory.h"
81 #include "content/renderer/media/media_permission_dispatcher.h"
82 #include "content/renderer/media/media_stream_dispatcher.h"
83 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
84 #include "content/renderer/media/midi_dispatcher.h"
85 #include "content/renderer/media/render_media_log.h"
86 #include "content/renderer/media/user_media_client_impl.h"
87 #include "content/renderer/media/webmediaplayer_ms.h"
88 #include "content/renderer/memory_benchmarking_extension.h"
89 #include "content/renderer/mojo/service_registry_js_wrapper.h"
90 #include "content/renderer/navigation_state_impl.h"
91 #include "content/renderer/notification_permission_dispatcher.h"
92 #include "content/renderer/npapi/plugin_channel_host.h"
93 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
94 #include "content/renderer/presentation/presentation_dispatcher.h"
95 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
96 #include "content/renderer/render_frame_proxy.h"
97 #include "content/renderer/render_process.h"
98 #include "content/renderer/render_thread_impl.h"
99 #include "content/renderer/render_view_impl.h"
100 #include "content/renderer/render_widget_fullscreen_pepper.h"
101 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
102 #include "content/renderer/renderer_webcolorchooser_impl.h"
103 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
104 #include "content/renderer/shared_worker_repository.h"
105 #include "content/renderer/skia_benchmarking_extension.h"
106 #include "content/renderer/stats_collection_controller.h"
107 #include "content/renderer/web_ui_extension.h"
108 #include "content/renderer/websharedworker_proxy.h"
109 #include "gin/modules/module_registry.h"
110 #include "media/base/audio_renderer_mixer_input.h"
111 #include "media/base/media_log.h"
112 #include "media/blink/webencryptedmediaclient_impl.h"
113 #include "media/blink/webmediaplayer_impl.h"
114 #include "media/blink/webmediaplayer_params.h"
115 #include "media/renderers/gpu_video_accelerator_factories.h"
116 #include "net/base/data_url.h"
117 #include "net/base/net_errors.h"
118 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
119 #include "net/http/http_util.h"
120 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
121 #include "third_party/WebKit/public/platform/WebString.h"
122 #include "third_party/WebKit/public/platform/WebURL.h"
123 #include "third_party/WebKit/public/platform/WebURLError.h"
124 #include "third_party/WebKit/public/platform/WebURLResponse.h"
125 #include "third_party/WebKit/public/platform/WebVector.h"
126 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
127 #include "third_party/WebKit/public/web/WebDocument.h"
128 #include "third_party/WebKit/public/web/WebFrameWidget.h"
129 #include "third_party/WebKit/public/web/WebGlyphCache.h"
130 #include "third_party/WebKit/public/web/WebKit.h"
131 #include "third_party/WebKit/public/web/WebLocalFrame.h"
132 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
133 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
134 #include "third_party/WebKit/public/web/WebPlugin.h"
135 #include "third_party/WebKit/public/web/WebPluginParams.h"
136 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
137 #include "third_party/WebKit/public/web/WebRange.h"
138 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
139 #include "third_party/WebKit/public/web/WebScriptSource.h"
140 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
141 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
142 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
143 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
144 #include "third_party/WebKit/public/web/WebSettings.h"
145 #include "third_party/WebKit/public/web/WebSurroundingText.h"
146 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
147 #include "third_party/WebKit/public/web/WebView.h"
148 #include "third_party/mojo/src/mojo/edk/js/core.h"
149 #include "third_party/mojo/src/mojo/edk/js/support.h"
150 #include "url/url_util.h"
152 #if defined(ENABLE_PLUGINS)
153 #include "content/renderer/npapi/webplugin_impl.h"
154 #include "content/renderer/pepper/pepper_browser_connection.h"
155 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
156 #include "content/renderer/pepper/pepper_webplugin_impl.h"
157 #include "content/renderer/pepper/plugin_module.h"
160 #if defined(ENABLE_WEBRTC)
161 #include "content/renderer/media/rtc_peer_connection_handler.h"
164 #if defined(OS_ANDROID)
165 #include <cpu-features.h>
167 #include "content/common/gpu/client/context_provider_command_buffer.h"
168 #include "content/renderer/android/synchronous_compositor_factory.h"
169 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
170 #include "content/renderer/media/android/renderer_media_player_manager.h"
171 #include "content/renderer/media/android/stream_texture_factory_impl.h"
172 #include "content/renderer/media/android/webmediaplayer_android.h"
174 #include "cc/blink/context_provider_web_context.h"
177 #if defined(ENABLE_PEPPER_CDMS)
178 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
179 #elif defined(ENABLE_BROWSER_CDMS)
180 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
183 #if defined(ENABLE_MOJO_MEDIA)
184 #include "media/mojo/services/mojo_cdm_factory.h"
185 #include "media/mojo/services/mojo_renderer_factory.h"
186 #include "mojo/application/public/cpp/connect.h"
187 #include "mojo/application/public/interfaces/shell.mojom.h"
188 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
190 #include "media/renderers/default_renderer_factory.h"
193 #if defined(ENABLE_WEBVR)
194 #include "content/renderer/vr/vr_dispatcher.h"
197 using blink::WebContentDecryptionModule
;
198 using blink::WebContextMenuData
;
199 using blink::WebData
;
200 using blink::WebDataSource
;
201 using blink::WebDocument
;
202 using blink::WebDOMEvent
;
203 using blink::WebDOMMessageEvent
;
204 using blink::WebElement
;
205 using blink::WebExternalPopupMenu
;
206 using blink::WebExternalPopupMenuClient
;
207 using blink::WebFrame
;
208 using blink::WebHistoryItem
;
209 using blink::WebHTTPBody
;
210 using blink::WebLocalFrame
;
211 using blink::WebMediaPlayer
;
212 using blink::WebMediaPlayerClient
;
213 using blink::WebMediaPlayerEncryptedMediaClient
;
214 using blink::WebNavigationPolicy
;
215 using blink::WebNavigationType
;
216 using blink::WebNode
;
217 using blink::WebPluginParams
;
218 using blink::WebPopupMenuInfo
;
219 using blink::WebRange
;
220 using blink::WebReferrerPolicy
;
221 using blink::WebScriptSource
;
222 using blink::WebSearchableFormData
;
223 using blink::WebSecurityOrigin
;
224 using blink::WebSecurityPolicy
;
225 using blink::WebSerializedScriptValue
;
226 using blink::WebServiceWorkerProvider
;
227 using blink::WebSettings
;
228 using blink::WebStorageQuotaCallbacks
;
229 using blink::WebString
;
231 using blink::WebURLError
;
232 using blink::WebURLRequest
;
233 using blink::WebURLResponse
;
234 using blink::WebUserGestureIndicator
;
235 using blink::WebVector
;
236 using blink::WebView
;
238 using base::TimeDelta
;
244 const char kDefaultAcceptHeader
[] =
245 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
247 const char kAcceptHeader
[] = "Accept";
249 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
251 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
252 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
253 LAZY_INSTANCE_INITIALIZER
;
255 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
256 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
258 int64
ExtractPostId(HistoryEntry
* entry
) {
262 const WebHistoryItem
& item
= entry
->root();
263 if (item
.isNull() || item
.httpBody().isNull())
266 return item
.httpBody().identifier();
269 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
270 const WebURLResponse
& response
) {
271 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
274 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
275 // Replace any occurrences of swappedout:// with about:blank.
276 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
277 WebVector
<WebURL
> urls
;
278 ds
->redirectChain(urls
);
279 result
->reserve(urls
.size());
280 for (size_t i
= 0; i
< urls
.size(); ++i
) {
281 if (urls
[i
] != GURL(kSwappedOutURL
))
282 result
->push_back(urls
[i
]);
284 result
->push_back(blank_url
);
288 // Returns the original request url. If there is no redirect, the original
289 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
290 // frame was loaded by loadData, the original url will be ds->unreachableURL()
291 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
292 // WebDataSource has unreachable URL means that the frame is loaded through
293 // blink::WebFrame::loadData(), and the base URL will be in the redirect
294 // chain. However, we never visited the baseURL. So in this case, we should
295 // use the unreachable URL as the original URL.
296 if (ds
->hasUnreachableURL())
297 return ds
->unreachableURL();
299 std::vector
<GURL
> redirects
;
300 GetRedirectChain(ds
, &redirects
);
301 if (!redirects
.empty())
302 return redirects
.at(0);
304 return ds
->originalRequest().url();
307 NOINLINE
void CrashIntentionally() {
308 // NOTE(shess): Crash directly rather than using NOTREACHED() so
309 // that the signature is easier to triage in crash reports.
310 volatile int* zero
= NULL
;
314 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
315 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
316 // NOTE(rogerm): We intentionally perform an invalid heap access here in
317 // order to trigger an Address Sanitizer (ASAN) error report.
318 const char kCrashDomain
[] = "crash";
319 const char kHeapOverflow
[] = "/heap-overflow";
320 const char kHeapUnderflow
[] = "/heap-underflow";
321 const char kUseAfterFree
[] = "/use-after-free";
322 #if defined(SYZYASAN)
323 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
324 const char kCorruptHeap
[] = "/corrupt-heap";
327 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
333 std::string
crash_type(url
.path());
334 if (crash_type
== kHeapOverflow
) {
335 base::debug::AsanHeapOverflow();
336 } else if (crash_type
== kHeapUnderflow
) {
337 base::debug::AsanHeapUnderflow();
338 } else if (crash_type
== kUseAfterFree
) {
339 base::debug::AsanHeapUseAfterFree();
340 #if defined(SYZYASAN)
341 } else if (crash_type
== kCorruptHeapBlock
) {
342 base::debug::AsanCorruptHeapBlock();
343 } else if (crash_type
== kCorruptHeap
) {
344 base::debug::AsanCorruptHeap();
348 #endif // ADDRESS_SANITIZER || SYZYASAN
350 void MaybeHandleDebugURL(const GURL
& url
) {
351 if (!url
.SchemeIs(kChromeUIScheme
))
353 if (url
== GURL(kChromeUICrashURL
)) {
354 CrashIntentionally();
355 } else if (url
== GURL(kChromeUIDumpURL
)) {
356 // This URL will only correctly create a crash dump file if content is
357 // hosted in a process that has correctly called
358 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
359 // of base::debug::DumpWithoutCrashing for more details.
360 base::debug::DumpWithoutCrashing();
361 } else if (url
== GURL(kChromeUIKillURL
)) {
362 base::Process::Current().Terminate(1, false);
363 } else if (url
== GURL(kChromeUIHangURL
)) {
365 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
367 } else if (url
== GURL(kChromeUIShorthangURL
)) {
368 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
371 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
372 MaybeTriggerAsanError(url
);
373 #endif // ADDRESS_SANITIZER || SYZYASAN
376 // Returns false unless this is a top-level navigation.
377 bool IsTopLevelNavigation(WebFrame
* frame
) {
378 return frame
->parent() == NULL
;
381 // Returns false unless this is a top-level navigation that crosses origins.
382 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
384 WebNavigationType type
,
386 if (!IsTopLevelNavigation(frame
))
389 // Navigations initiated within Webkit are not sent out to the external host
390 // in the following cases.
391 // 1. The url scheme is not http/https
392 // 2. The origin of the url and the opener is the same in which case the
393 // opener relationship is maintained.
394 // 3. Reloads/form submits/back forward navigations
395 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
398 if (type
!= blink::WebNavigationTypeReload
&&
399 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
400 // The opener relationship between the new window and the parent allows the
401 // new window to script the parent and vice versa. This is not allowed if
402 // the origins of the two domains are different. This can be treated as a
403 // top level navigation and routed back to the host.
404 blink::WebFrame
* opener
= frame
->opener();
408 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
414 WebURLRequest
CreateURLRequestForNavigation(
415 const CommonNavigationParams
& common_params
,
416 scoped_ptr
<StreamOverrideParameters
> stream_override
,
417 bool is_view_source_mode_enabled
) {
418 WebURLRequest
request(common_params
.url
);
419 if (is_view_source_mode_enabled
)
420 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
422 if (common_params
.referrer
.url
.is_valid()) {
423 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
424 common_params
.referrer
.policy
,
426 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
427 if (!web_referrer
.isEmpty())
428 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
431 RequestExtraData
* extra_data
= new RequestExtraData();
432 extra_data
->set_stream_override(stream_override
.Pass());
433 request
.setExtraData(extra_data
);
435 // Set the ui timestamp for this navigation. Currently the timestamp here is
436 // only non empty when the navigation was triggered by an Android intent. The
437 // timestamp is converted to a double version supported by blink. It will be
438 // passed back to the browser in the DidCommitProvisionalLoad and the
439 // DocumentLoadComplete IPCs.
440 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
441 request
.setUiStartTime(ui_timestamp
.InSecondsF());
442 request
.setInputPerfMetricReportPolicy(
443 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
444 common_params
.report_type
));
448 void UpdateFrameNavigationTiming(WebFrame
* frame
,
449 base::TimeTicks browser_navigation_start
,
450 base::TimeTicks renderer_navigation_start
) {
451 // The browser provides the navigation_start time to bootstrap the
452 // Navigation Timing information for the browser-initiated navigations. In
453 // case of cross-process navigations, this carries over the time of
454 // finishing the onbeforeunload handler of the previous page.
455 DCHECK(!browser_navigation_start
.is_null());
456 if (frame
->provisionalDataSource()) {
457 // |browser_navigation_start| is likely before this process existed, so we
458 // can't use InterProcessTimeTicksConverter. We need at least to ensure
459 // that the browser-side navigation start we set is not later than the one
460 // on the renderer side.
461 base::TimeTicks navigation_start
= std::min(
462 browser_navigation_start
, renderer_navigation_start
);
463 double navigation_start_seconds
=
464 (navigation_start
- base::TimeTicks()).InSecondsF();
465 frame
->provisionalDataSource()->setNavigationStartTime(
466 navigation_start_seconds
);
467 // TODO(clamy): We need to provide additional timing values for the
468 // Navigation Timing API to work with browser-side navigations.
473 CommonNavigationParams
MakeCommonNavigationParams(
474 blink::WebURLRequest
* request
,
475 bool should_replace_current_entry
) {
476 const RequestExtraData kEmptyData
;
477 const RequestExtraData
* extra_data
=
478 static_cast<RequestExtraData
*>(request
->extraData());
480 extra_data
= &kEmptyData
;
482 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
483 request
->referrerPolicy());
485 // Set the ui timestamp for this navigation. Currently the timestamp here is
486 // only non empty when the navigation was triggered by an Android intent, or
487 // by the user clicking on a link. The timestamp is converted from a double
488 // version supported by blink. It will be passed back to the renderer in the
489 // CommitNavigation IPC, and then back to the browser again in the
490 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
491 base::TimeTicks ui_timestamp
=
492 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
493 FrameMsg_UILoadMetricsReportType::Value report_type
=
494 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
495 request
->inputPerfMetricReportPolicy());
496 return CommonNavigationParams(
497 request
->url(), referrer
, extra_data
->transition_type(),
498 FrameMsg_Navigate_Type::NORMAL
, true, should_replace_current_entry
,
499 ui_timestamp
, report_type
, GURL(), GURL());
502 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
503 media::Context3D
GetSharedMainThreadContext3D() {
504 cc::ContextProvider
* provider
=
505 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
507 return media::Context3D();
508 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
512 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
513 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
514 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
515 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
518 bool IsSwappedOutStateForbidden() {
519 return base::CommandLine::ForCurrentProcess()->HasSwitch(
520 switches::kSitePerProcess
);
523 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
529 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
531 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
532 CreateParams
params(render_view
, routing_id
);
534 if (g_create_render_frame_impl
)
535 return g_create_render_frame_impl(params
);
537 return new RenderFrameImpl(params
);
541 RenderFrame
* RenderFrame::FromRoutingID(int routing_id
) {
542 return RenderFrameImpl::FromRoutingID(routing_id
);
546 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int routing_id
) {
547 RoutingIDFrameMap::iterator iter
=
548 g_routing_id_frame_map
.Get().find(routing_id
);
549 if (iter
!= g_routing_id_frame_map
.Get().end())
555 void RenderFrameImpl::CreateFrame(
557 int parent_routing_id
,
558 int previous_sibling_routing_id
,
559 int proxy_routing_id
,
560 const FrameReplicationState
& replicated_state
,
561 CompositorDependencies
* compositor_deps
,
562 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
563 blink::WebLocalFrame
* web_frame
;
564 RenderFrameImpl
* render_frame
;
565 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
566 RenderFrameProxy
* parent_proxy
=
567 RenderFrameProxy::FromRoutingID(parent_routing_id
);
568 // If the browser is sending a valid parent routing id, it should already
569 // be created and registered.
571 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
573 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
574 RenderFrameProxy
* previous_sibling_proxy
=
575 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
576 if (previous_sibling_proxy
)
577 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
579 // Create the RenderFrame and WebLocalFrame, linking the two.
581 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
582 web_frame
= parent_web_frame
->createLocalChild(
583 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
584 replicated_state
.sandbox_flags
, render_frame
,
585 previous_sibling_web_frame
);
587 RenderFrameProxy
* proxy
=
588 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
590 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
592 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
593 render_frame
->proxy_routing_id_
= proxy_routing_id
;
594 web_frame
->initializeToReplaceRemoteFrame(
595 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
596 replicated_state
.sandbox_flags
);
598 render_frame
->SetWebFrame(web_frame
);
599 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
601 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
602 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
603 switches::kSitePerProcess
));
604 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
605 widget_params
.routing_id
, widget_params
.surface_id
,
606 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
607 compositor_deps
, web_frame
);
608 // TODO(kenrb): Observing shouldn't be necessary when we sort out
609 // WasShown and WasHidden, separating page-level visibility from
610 // frame-level visibility.
611 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
614 render_frame
->Initialize();
618 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
619 return RenderFrameImpl::FromWebFrame(web_frame
);
623 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
624 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
625 if (iter
!= g_frame_map
.Get().end())
631 void RenderFrameImpl::InstallCreateHook(
632 CreateRenderFrameImplFunction create_render_frame_impl
) {
633 CHECK(!g_create_render_frame_impl
);
634 g_create_render_frame_impl
= create_render_frame_impl
;
637 // RenderFrameImpl ----------------------------------------------------------
638 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
641 is_local_root_(false),
642 render_view_(params
.render_view
->AsWeakPtr()),
643 routing_id_(params
.routing_id
),
644 is_swapped_out_(false),
645 render_frame_proxy_(NULL
),
646 is_detaching_(false),
647 proxy_routing_id_(MSG_ROUTING_NONE
),
648 #if defined(ENABLE_PLUGINS)
649 plugin_power_saver_helper_(NULL
),
652 selection_text_offset_(0),
653 selection_range_(gfx::Range::InvalidRange()),
654 handling_select_range_(false),
655 notification_permission_dispatcher_(NULL
),
656 web_user_media_client_(NULL
),
657 media_permission_dispatcher_(NULL
),
658 midi_dispatcher_(NULL
),
659 #if defined(OS_ANDROID)
660 media_player_manager_(NULL
),
662 #if defined(ENABLE_BROWSER_CDMS)
665 #if defined(VIDEO_HOLE)
666 contains_media_player_(false),
668 devtools_agent_(nullptr),
669 geolocation_dispatcher_(NULL
),
670 push_messaging_dispatcher_(NULL
),
671 presentation_dispatcher_(NULL
),
672 screen_orientation_dispatcher_(NULL
),
673 manifest_manager_(NULL
),
674 accessibility_mode_(AccessibilityModeOff
),
675 renderer_accessibility_(NULL
),
676 weak_factory_(this) {
677 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
678 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
679 CHECK(result
.second
) << "Inserting a duplicate item.";
681 RenderThread::Get()->AddRoute(routing_id_
, this);
683 render_view_
->RegisterRenderFrame(this);
685 // Everything below subclasses RenderFrameObserver and is automatically
686 // deleted when the RenderFrame gets deleted.
687 #if defined(OS_ANDROID)
688 new GinJavaBridgeDispatcher(this);
691 #if defined(ENABLE_PLUGINS)
692 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
695 manifest_manager_
= new ManifestManager(this);
698 RenderFrameImpl::~RenderFrameImpl() {
699 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
700 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
702 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
704 #if defined(VIDEO_HOLE)
705 if (contains_media_player_
)
706 render_view_
->UnregisterVideoHoleFrame(this);
710 if (!IsSwappedOutStateForbidden()) {
711 // When using swapped out frames, RenderFrameProxy is "owned" by
712 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
713 // along with this object.
714 if (render_frame_proxy_
&&
715 !base::CommandLine::ForCurrentProcess()->HasSwitch(
716 switches::kSitePerProcess
)) {
717 // The following method calls back into this object and clears
718 // |render_frame_proxy_|.
719 render_frame_proxy_
->frameDetached(
720 blink::WebRemoteFrameClient::DetachType::Remove
);
724 // Ensure the RenderView doesn't point to this object, once it is destroyed.
725 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
726 // is |this|, once the object is no longer leaked.
727 // See https://crbug.com/464764.
728 render_view_
->main_render_frame_
= nullptr;
731 render_view_
->UnregisterRenderFrame(this);
732 g_routing_id_frame_map
.Get().erase(routing_id_
);
733 RenderThread::Get()->RemoveRoute(routing_id_
);
736 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
739 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
740 std::make_pair(web_frame
, this));
741 CHECK(result
.second
) << "Inserting a duplicate item.";
746 void RenderFrameImpl::Initialize() {
747 is_subframe_
= !!frame_
->parent();
748 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
750 #if defined(ENABLE_PLUGINS)
751 new PepperBrowserConnection(this);
753 new SharedWorkerRepository(this);
755 if (is_local_root_
&& !render_frame_proxy_
) {
756 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
757 // when |this| is deleted.
758 devtools_agent_
= new DevToolsAgent(this);
761 RegisterMojoServices();
763 // We delay calling this until we have the WebFrame so that any observer or
764 // embedder can call GetWebFrame on any RenderFrame.
765 GetContentClient()->renderer()->RenderFrameCreated(this);
768 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
769 return render_view_
.get();
772 #if defined(ENABLE_PLUGINS)
773 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
774 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
775 DidCreatePepperPlugin(host
));
776 if (host
->GetPluginName() == kFlashPluginName
) {
777 RenderThread::Get()->RecordAction(
778 base::UserMetricsAction("FrameLoadWithFlash"));
782 void RenderFrameImpl::PepperDidChangeCursor(
783 PepperPluginInstanceImpl
* instance
,
784 const blink::WebCursorInfo
& cursor
) {
785 // Update the cursor appearance immediately if the requesting plugin is the
786 // one which receives the last mouse event. Otherwise, the new cursor won't be
787 // picked up until the plugin gets the next input event. That is bad if, e.g.,
788 // the plugin would like to set an invisible cursor when there isn't any user
789 // input for a while.
790 if (instance
== render_view_
->pepper_last_mouse_event_target())
791 GetRenderWidget()->didChangeCursor(cursor
);
794 void RenderFrameImpl::PepperDidReceiveMouseEvent(
795 PepperPluginInstanceImpl
* instance
) {
796 render_view_
->set_pepper_last_mouse_event_target(instance
);
799 void RenderFrameImpl::PepperTextInputTypeChanged(
800 PepperPluginInstanceImpl
* instance
) {
801 if (instance
!= render_view_
->focused_pepper_plugin())
804 GetRenderWidget()->UpdateTextInputType();
806 FocusedNodeChangedForAccessibility(WebNode());
809 void RenderFrameImpl::PepperCaretPositionChanged(
810 PepperPluginInstanceImpl
* instance
) {
811 if (instance
!= render_view_
->focused_pepper_plugin())
813 GetRenderWidget()->UpdateSelectionBounds();
816 void RenderFrameImpl::PepperCancelComposition(
817 PepperPluginInstanceImpl
* instance
) {
818 if (instance
!= render_view_
->focused_pepper_plugin())
820 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
821 #if defined(OS_MACOSX) || defined(USE_AURA)
822 GetRenderWidget()->UpdateCompositionInfo(true);
826 void RenderFrameImpl::PepperSelectionChanged(
827 PepperPluginInstanceImpl
* instance
) {
828 if (instance
!= render_view_
->focused_pepper_plugin())
830 SyncSelectionIfRequired();
833 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
834 PepperPluginInstanceImpl
* plugin
) {
836 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
837 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
838 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
839 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
840 plugin
, active_url
, GetRenderWidget()->screenInfo());
841 widget
->show(blink::WebNavigationPolicyIgnore
);
845 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
846 if (!render_view_
->focused_pepper_plugin())
848 return render_view_
->focused_pepper_plugin()->
849 IsPluginAcceptingCompositionEvents();
852 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
853 base::ProcessId plugin_pid
) {
854 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
855 // routing_id_ as a result.
856 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
859 void RenderFrameImpl::SimulateImeSetComposition(
860 const base::string16
& text
,
861 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
864 render_view_
->OnImeSetComposition(
865 text
, underlines
, selection_start
, selection_end
);
868 void RenderFrameImpl::SimulateImeConfirmComposition(
869 const base::string16
& text
,
870 const gfx::Range
& replacement_range
) {
871 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
874 void RenderFrameImpl::OnImeSetComposition(
875 const base::string16
& text
,
876 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
879 // When a PPAPI plugin has focus, we bypass WebKit.
880 if (!IsPepperAcceptingCompositionEvents()) {
881 pepper_composition_text_
= text
;
883 // TODO(kinaba) currently all composition events are sent directly to
884 // plugins. Use DOM event mechanism after WebKit is made aware about
885 // plugins that support composition.
886 // The code below mimics the behavior of WebCore::Editor::setComposition.
888 // Empty -> nonempty: composition started.
889 if (pepper_composition_text_
.empty() && !text
.empty()) {
890 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
893 // Nonempty -> empty: composition canceled.
894 if (!pepper_composition_text_
.empty() && text
.empty()) {
895 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
898 pepper_composition_text_
= text
;
899 // Nonempty: composition is ongoing.
900 if (!pepper_composition_text_
.empty()) {
901 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
902 pepper_composition_text_
, underlines
, selection_start
,
908 void RenderFrameImpl::OnImeConfirmComposition(
909 const base::string16
& text
,
910 const gfx::Range
& replacement_range
,
911 bool keep_selection
) {
912 // When a PPAPI plugin has focus, we bypass WebKit.
913 // Here, text.empty() has a special meaning. It means to commit the last
914 // update of composition text (see
915 // RenderWidgetHost::ImeConfirmComposition()).
916 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
919 // last_text is empty only when both text and pepper_composition_text_ is.
921 if (last_text
.empty())
924 if (!IsPepperAcceptingCompositionEvents()) {
925 base::i18n::UTF16CharIterator
iterator(&last_text
);
927 while (iterator
.Advance()) {
928 blink::WebKeyboardEvent char_event
;
929 char_event
.type
= blink::WebInputEvent::Char
;
930 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
931 char_event
.modifiers
= 0;
932 char_event
.windowsKeyCode
= last_text
[i
];
933 char_event
.nativeKeyCode
= last_text
[i
];
935 const int32 char_start
= i
;
936 for (; i
< iterator
.array_pos(); ++i
) {
937 char_event
.text
[i
- char_start
] = last_text
[i
];
938 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
941 if (GetRenderWidget()->webwidget())
942 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
945 // Mimics the order of events sent by WebKit.
946 // See WebCore::Editor::setComposition() for the corresponding code.
947 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
948 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
950 pepper_composition_text_
.clear();
952 #endif // defined(ENABLE_PLUGINS)
954 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
955 if (!web_user_media_client_
)
956 InitializeUserMediaClient();
957 return web_user_media_client_
?
958 web_user_media_client_
->media_stream_dispatcher() : NULL
;
961 bool RenderFrameImpl::Send(IPC::Message
* message
) {
966 if (is_swapped_out_
) {
967 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
973 return RenderThread::Get()->Send(message
);
976 #if defined(OS_MACOSX) || defined(OS_ANDROID)
977 void RenderFrameImpl::DidHideExternalPopupMenu() {
978 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
979 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
980 external_popup_menu_
.reset();
984 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
985 // We may get here while detaching, when the WebFrame has been deleted. Do
986 // not process any messages in this state.
990 // TODO(kenrb): document() should not be null, but as a transitional step
991 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
992 // to this method. This happens for a top-level remote frame, where a
993 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
994 // around and is still able to receive messages.
995 if (!frame_
->document().isNull())
996 GetContentClient()->SetActiveURL(frame_
->document().url());
998 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
999 RenderFrameObserver
* observer
;
1000 while ((observer
= it
.GetNext()) != NULL
) {
1001 if (observer
->OnMessageReceived(msg
))
1005 bool handled
= true;
1006 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1007 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1008 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1009 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1010 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1011 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1012 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1013 OnCustomContextMenuAction
)
1014 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1015 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1016 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1017 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1018 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1019 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1020 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1021 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1022 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1023 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1024 OnAdjustSelectionByCharacterOffset
)
1025 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1026 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1027 OnMoveRangeSelectionExtent
)
1028 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1029 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1030 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1031 OnExtendSelectionAndDelete
)
1032 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1033 OnSetCompositionFromExistingText
)
1034 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1035 OnExecuteNoValueEditCommand
)
1036 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1037 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1038 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1039 OnJavaScriptExecuteRequest
)
1040 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1041 OnJavaScriptExecuteRequestForTests
)
1042 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1043 OnJavaScriptExecuteRequestInIsolatedWorld
)
1044 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1045 OnVisualStateRequest
)
1046 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1047 OnSetEditableSelectionOffsets
)
1048 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1049 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1050 OnTextSurroundingSelectionRequest
)
1051 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1052 OnSetAccessibilityMode
)
1053 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1054 OnSnapshotAccessibilityTree
)
1055 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1056 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1057 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1058 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1059 OnTextTrackSettingsChanged
)
1060 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1061 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1062 #if defined(OS_ANDROID)
1063 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1064 #elif defined(OS_MACOSX)
1065 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1066 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1068 IPC_END_MESSAGE_MAP()
1073 void RenderFrameImpl::OnNavigate(
1074 const CommonNavigationParams
& common_params
,
1075 const StartNavigationParams
& start_params
,
1076 const RequestNavigationParams
& request_params
) {
1077 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1078 switches::kEnableBrowserSideNavigation
));
1079 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1080 "url", common_params
.url
.possibly_invalid_spec());
1081 NavigateInternal(common_params
, start_params
, request_params
,
1082 scoped_ptr
<StreamOverrideParameters
>());
1085 void RenderFrameImpl::NavigateToSwappedOutURL() {
1086 // We use loadRequest instead of loadHTMLString because the former commits
1087 // synchronously. Otherwise a new navigation can interrupt the navigation
1088 // to kSwappedOutURL. If that happens to be to the page we had been
1089 // showing, then WebKit will never send a commit and we'll be left spinning.
1090 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1091 // the navigation to swappedout:// is not announced to the browser side.
1092 is_swapped_out_
= true;
1093 GURL
swappedOutURL(kSwappedOutURL
);
1094 WebURLRequest
request(swappedOutURL
);
1095 frame_
->loadRequest(request
);
1098 void RenderFrameImpl::BindServiceRegistry(
1099 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1100 mojo::ServiceProviderPtr exposed_services
) {
1101 service_registry_
.Bind(services
.Pass());
1102 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1105 ManifestManager
* RenderFrameImpl::manifest_manager() {
1106 return manifest_manager_
;
1109 void RenderFrameImpl::SetPendingNavigationParams(
1110 scoped_ptr
<NavigationParams
> navigation_params
) {
1111 pending_navigation_params_
= navigation_params
.Pass();
1114 void RenderFrameImpl::OnBeforeUnload() {
1115 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1117 // TODO(creis): Right now, this is only called on the main frame. Make the
1118 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1120 CHECK(!frame_
->parent());
1122 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1123 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1124 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1125 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1126 before_unload_start_time
,
1127 before_unload_end_time
));
1130 void RenderFrameImpl::OnSwapOut(
1131 int proxy_routing_id
,
1133 const FrameReplicationState
& replicated_frame_state
) {
1134 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1135 RenderFrameProxy
* proxy
= NULL
;
1136 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1137 switches::kSitePerProcess
);
1138 bool is_main_frame
= !frame_
->parent();
1140 // This codepath should only be hit for subframes when in --site-per-process.
1141 CHECK_IMPLIES(!is_main_frame
, is_site_per_process
);
1143 // Only run unload if we're not swapped out yet, but send the ack either way.
1144 if (!is_swapped_out_
) {
1145 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1146 // a different process. This involves running the unload handler and
1147 // clearing the page. We also allow this process to exit if there are no
1148 // other active RenderFrames in it.
1150 // Send an UpdateState message before we get swapped out.
1151 render_view_
->SendUpdateState();
1153 // If we need a proxy to replace this, create it now so its routing id is
1154 // registered for receiving IPC messages.
1155 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1156 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1157 this, proxy_routing_id
, replicated_frame_state
.scope
);
1160 // Synchronously run the unload handler before sending the ACK.
1161 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1162 // unload on subframes as well.
1164 frame_
->dispatchUnloadEvent();
1166 // Swap out and stop sending any IPC messages that are not ACKs.
1168 render_view_
->SetSwappedOut(true);
1169 is_swapped_out_
= true;
1171 // Set the proxy here, since OnStop() below could cause an onload event
1172 // handler to execute, which could trigger code such as
1173 // willCheckAndDispatchMessageEvent() that needs the proxy.
1175 set_render_frame_proxy(proxy
);
1177 // Now that we're swapped out and filtering IPC messages, stop loading to
1178 // ensure that no other in-progress navigation continues. We do this here
1179 // to avoid sending a DidStopLoading message to the browser process.
1180 // TODO(creis): Should we be stopping all frames here and using
1181 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1183 if (!IsSwappedOutStateForbidden())
1186 // Transfer settings such as initial drawing parameters to the remote frame,
1187 // if one is created, that will replace this frame.
1188 if (!is_main_frame
&& proxy
)
1189 proxy
->web_frame()->initializeFromFrame(frame_
);
1191 // Replace the page with a blank dummy URL. The unload handler will not be
1192 // run a second time, thanks to a check in FrameLoader::stopLoading.
1193 // TODO(creis): Need to add a better way to do this that avoids running the
1194 // beforeunload handler. For now, we just run it a second time silently.
1195 if (!IsSwappedOutStateForbidden())
1196 NavigateToSwappedOutURL();
1198 // Let WebKit know that this view is hidden so it can drop resources and
1199 // stop compositing.
1200 // TODO(creis): Support this for subframes as well.
1201 if (is_main_frame
) {
1202 render_view_
->webview()->setVisibilityState(
1203 blink::WebPageVisibilityStateHidden
, false);
1207 // It is now safe to show modal dialogs again.
1208 // TODO(creis): Deal with modal dialogs from subframes.
1210 render_view_
->suppress_dialogs_until_swap_out_
= false;
1212 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1214 RenderViewImpl
* render_view
= render_view_
.get();
1216 // Now that all of the cleanup is complete and the browser side is notified,
1217 // start using the RenderFrameProxy, if one is created.
1218 if (proxy
&& IsSwappedOutStateForbidden()) {
1219 frame_
->swap(proxy
->web_frame());
1222 proxy
->OnDidStartLoading();
1225 // In --site-per-process, initialize the WebRemoteFrame with the replication
1226 // state passed by the process that is now rendering the frame.
1227 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1228 // in that case we leave the LocalFrame as the main frame visible to Blink
1229 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1230 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1231 // When we do an unconditional swap for all frames, we can remove
1232 // !is_main_frame below.
1233 if (proxy
&& IsSwappedOutStateForbidden())
1234 proxy
->SetReplicatedState(replicated_frame_state
);
1236 // Safe to exit if no one else is using the process.
1237 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1238 // the process based on the lifetime of this RenderFrameImpl object.
1239 if (is_main_frame
) {
1240 render_view
->WasSwappedOut();
1244 void RenderFrameImpl::OnContextMenuClosed(
1245 const CustomContextMenuContext
& custom_context
) {
1246 if (custom_context
.request_id
) {
1247 // External request, should be in our map.
1248 ContextMenuClient
* client
=
1249 pending_context_menus_
.Lookup(custom_context
.request_id
);
1251 client
->OnMenuClosed(custom_context
.request_id
);
1252 pending_context_menus_
.Remove(custom_context
.request_id
);
1255 if (custom_context
.link_followed
.is_valid())
1256 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1257 // Internal request, forward to WebKit.
1258 context_menu_node_
.reset();
1262 void RenderFrameImpl::OnCustomContextMenuAction(
1263 const CustomContextMenuContext
& custom_context
,
1265 if (custom_context
.request_id
) {
1266 // External context menu request, look in our map.
1267 ContextMenuClient
* client
=
1268 pending_context_menus_
.Lookup(custom_context
.request_id
);
1270 client
->OnMenuAction(custom_context
.request_id
, action
);
1272 // Internal request, forward to WebKit.
1273 render_view_
->webview()->performCustomContextMenuAction(action
);
1277 void RenderFrameImpl::OnUndo() {
1278 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1281 void RenderFrameImpl::OnRedo() {
1282 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1285 void RenderFrameImpl::OnCut() {
1286 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1287 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1290 void RenderFrameImpl::OnCopy() {
1291 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1292 WebNode current_node
= context_menu_node_
.isNull() ?
1293 GetFocusedElement() : context_menu_node_
;
1294 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1297 void RenderFrameImpl::OnPaste() {
1298 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1299 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1302 void RenderFrameImpl::OnPasteAndMatchStyle() {
1303 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1304 frame_
->executeCommand(
1305 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1308 #if defined(OS_MACOSX)
1309 void RenderFrameImpl::OnCopyToFindPboard() {
1310 // Since the find pasteboard supports only plain text, this can be simpler
1311 // than the |OnCopy()| case.
1312 if (frame_
->hasSelection()) {
1313 base::string16 selection
= frame_
->selectionAsText();
1314 RenderThread::Get()->Send(
1315 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1320 void RenderFrameImpl::OnDelete() {
1321 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1324 void RenderFrameImpl::OnSelectAll() {
1325 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1326 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1329 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1330 const gfx::Point
& extent
) {
1331 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1332 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1334 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1335 frame_
->selectRange(base
, extent
);
1338 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1340 size_t start
, length
;
1341 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1346 // Sanity checks to disallow empty and out of range selections.
1347 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1348 || static_cast<int>(start
) + start_adjust
< 0) {
1352 // A negative adjust amount moves the selection towards the beginning of
1353 // the document, a positive amount moves the selection towards the end of
1355 start
+= start_adjust
;
1356 length
+= end_adjust
- start_adjust
;
1358 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1361 void RenderFrameImpl::OnUnselect() {
1362 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1363 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1366 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1367 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1368 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1369 GetRenderWidget()->routing_id()));
1371 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1372 frame_
->moveRangeSelectionExtent(point
);
1375 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1376 if (!frame_
->hasSelection())
1377 frame_
->selectWordAroundCaret();
1379 frame_
->replaceSelection(text
);
1382 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1383 if (!frame_
->hasSelection())
1386 frame_
->replaceMisspelledRange(text
);
1389 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1390 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1393 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1394 const std::string
& message
) {
1395 AddMessageToConsole(level
, message
);
1398 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1399 const base::string16
& jscript
,
1401 bool notify_result
) {
1402 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1403 TRACE_EVENT_SCOPE_THREAD
);
1405 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1406 v8::Local
<v8::Value
> result
=
1407 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1409 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1412 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1413 const base::string16
& jscript
,
1416 bool has_user_gesture
) {
1417 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1418 TRACE_EVENT_SCOPE_THREAD
);
1420 // A bunch of tests expect to run code in the context of a user gesture, which
1421 // can grant additional privileges (e.g. the ability to create popups).
1422 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1423 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1424 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1425 v8::Local
<v8::Value
> result
=
1426 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1428 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1431 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1432 const base::string16
& jscript
,
1436 TRACE_EVENT_INSTANT0("test_tracing",
1437 "OnJavaScriptExecuteRequestInIsolatedWorld",
1438 TRACE_EVENT_SCOPE_THREAD
);
1440 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1441 world_id
> ISOLATED_WORLD_ID_MAX
) {
1442 // Return if the world_id is not valid. world_id is passed as a plain int
1443 // over IPC and needs to be verified here, in the IPC endpoint.
1448 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1449 WebScriptSource script
= WebScriptSource(jscript
);
1450 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1451 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1452 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1456 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1460 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1462 notify_result_(notify_result
),
1463 routing_id_(routing_id
),
1464 render_frame_impl_(render_frame_impl
) {
1467 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1468 ~JavaScriptIsolatedWorldRequest() {
1471 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1472 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1473 if (!render_frame_impl_
.get()) {
1477 if (notify_result_
) {
1478 base::ListValue list
;
1479 if (!result
.isEmpty()) {
1480 // It's safe to always use the main world context when converting
1481 // here. V8ValueConverterImpl shouldn't actually care about the
1482 // context scope, and it switches to v8::Object's creation context
1483 // when encountered. (from extensions/renderer/script_injection.cc)
1484 v8::Local
<v8::Context
> context
=
1485 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1486 v8::Context::Scope
context_scope(context
);
1487 V8ValueConverterImpl converter
;
1488 converter
.SetDateAllowed(true);
1489 converter
.SetRegExpAllowed(true);
1490 for (const auto& value
: result
) {
1491 scoped_ptr
<base::Value
> result_value(
1492 converter
.FromV8Value(value
, context
));
1493 list
.Append(result_value
? result_value
.Pass()
1494 : base::Value::CreateNullValue());
1497 list
.Set(0, base::Value::CreateNullValue());
1499 render_frame_impl_
.get()->Send(
1500 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1506 void RenderFrameImpl::HandleJavascriptExecutionResult(
1507 const base::string16
& jscript
,
1510 v8::Local
<v8::Value
> result
) {
1511 if (notify_result
) {
1512 base::ListValue list
;
1513 if (!result
.IsEmpty()) {
1514 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1515 v8::Context::Scope
context_scope(context
);
1516 V8ValueConverterImpl converter
;
1517 converter
.SetDateAllowed(true);
1518 converter
.SetRegExpAllowed(true);
1519 scoped_ptr
<base::Value
> result_value(
1520 converter
.FromV8Value(result
, context
));
1521 list
.Set(0, result_value
? result_value
.Pass()
1522 : base::Value::CreateNullValue());
1524 list
.Set(0, base::Value::CreateNullValue());
1526 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1530 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1531 GetRenderWidget()->QueueMessage(
1532 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1533 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1536 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1537 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1538 if (!GetRenderWidget()->ShouldHandleImeEvent())
1540 ImeEventGuard
guard(GetRenderWidget());
1541 frame_
->setEditableSelectionOffsets(start
, end
);
1544 void RenderFrameImpl::OnSetCompositionFromExistingText(
1546 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1547 if (!GetRenderWidget()->ShouldHandleImeEvent())
1549 ImeEventGuard
guard(GetRenderWidget());
1550 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1553 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1554 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1557 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1558 if (!GetRenderWidget()->ShouldHandleImeEvent())
1560 ImeEventGuard
guard(GetRenderWidget());
1561 frame_
->extendSelectionAndDelete(before
, after
);
1564 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1565 if (accessibility_mode_
== new_mode
)
1567 accessibility_mode_
= new_mode
;
1568 if (renderer_accessibility_
) {
1569 // Note: this isn't called automatically by the destructor because
1570 // there'd be no point in calling it in frame teardown, only if there's
1571 // an accessibility mode change but the frame is persisting.
1572 renderer_accessibility_
->DisableAccessibility();
1574 delete renderer_accessibility_
;
1575 renderer_accessibility_
= NULL
;
1577 if (accessibility_mode_
== AccessibilityModeOff
)
1580 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1581 renderer_accessibility_
= new RendererAccessibility(this);
1584 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1585 ui::AXTreeUpdate response
;
1586 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1587 Send(new AccessibilityHostMsg_SnapshotResponse(
1588 routing_id_
, callback_id
, response
));
1591 void RenderFrameImpl::OnDisownOpener() {
1592 // TODO(creis): We should only see this for main frames for now. To support
1593 // disowning the opener on subframes, we will need to move WebContentsImpl's
1594 // opener_ to FrameTreeNode.
1595 CHECK(!frame_
->parent());
1597 if (frame_
->opener())
1598 frame_
->setOpener(NULL
);
1601 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1602 frame_
->setFrameOwnerSandboxFlags(flags
);
1605 void RenderFrameImpl::OnTextTrackSettingsChanged(
1606 const FrameMsg_TextTrackSettings_Params
& params
) {
1607 DCHECK(!frame_
->parent());
1608 if (!render_view_
->webview())
1611 if (params
.text_tracks_enabled
) {
1612 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1613 WebSettings::TextTrackKindUserPreference::Captions
);
1615 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1616 WebSettings::TextTrackKindUserPreference::Default
);
1618 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1619 WebString::fromUTF8(params
.text_track_background_color
));
1620 render_view_
->webview()->settings()->setTextTrackFontFamily(
1621 WebString::fromUTF8(params
.text_track_font_family
));
1622 render_view_
->webview()->settings()->setTextTrackFontStyle(
1623 WebString::fromUTF8(params
.text_track_font_style
));
1624 render_view_
->webview()->settings()->setTextTrackFontVariant(
1625 WebString::fromUTF8(params
.text_track_font_variant
));
1626 render_view_
->webview()->settings()->setTextTrackTextColor(
1627 WebString::fromUTF8(params
.text_track_text_color
));
1628 render_view_
->webview()->settings()->setTextTrackTextShadow(
1629 WebString::fromUTF8(params
.text_track_text_shadow
));
1630 render_view_
->webview()->settings()->setTextTrackTextSize(
1631 WebString::fromUTF8(params
.text_track_text_size
));
1634 void RenderFrameImpl::OnPostMessageEvent(
1635 const FrameMsg_PostMessage_Params
& params
) {
1636 // Find the source frame if it exists.
1637 WebFrame
* source_frame
= NULL
;
1638 if (params
.source_view_routing_id
!= MSG_ROUTING_NONE
) {
1639 // Support a legacy postMessage path for specifying a source RenderView;
1640 // this is currently used when sending messages to Android WebView.
1641 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1642 RenderViewImpl
* source_view
=
1643 RenderViewImpl::FromRoutingID(params
.source_view_routing_id
);
1645 source_frame
= source_view
->webview()->mainFrame();
1646 } else if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1647 RenderFrameProxy
* source_proxy
=
1648 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1650 // Currently, navigating a top-level frame cross-process does not swap
1651 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1652 // WebRemoteFrame will not have an associated blink::Frame. If this is
1653 // the case for |source_proxy|, use the corresponding (swapped-out)
1654 // WebLocalFrame instead, so that event.source for this message can be
1655 // set and used properly.
1656 if (source_proxy
->IsMainFrameDetachedFromTree())
1657 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1659 source_frame
= source_proxy
->web_frame();
1663 // If the message contained MessagePorts, create the corresponding endpoints.
1664 blink::WebMessagePortChannelArray channels
=
1665 WebMessagePortChannelImpl::CreatePorts(
1666 params
.message_ports
, params
.new_routing_ids
,
1667 base::ThreadTaskRunnerHandle::Get().get());
1669 WebSerializedScriptValue serialized_script_value
;
1670 if (params
.is_data_raw_string
) {
1671 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1672 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1673 v8::Context::Scope
context_scope(context
);
1674 V8ValueConverterImpl converter
;
1675 converter
.SetDateAllowed(true);
1676 converter
.SetRegExpAllowed(true);
1677 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1678 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1680 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1682 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1685 // Create an event with the message. The next-to-last parameter to
1686 // initMessageEvent is the last event ID, which is not used with postMessage.
1687 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1688 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1689 msg_event
.initMessageEvent("message",
1690 // |canBubble| and |cancellable| are always false
1692 serialized_script_value
,
1693 params
.source_origin
, source_frame
, "", channels
);
1695 // We must pass in the target_origin to do the security check on this side,
1696 // since it may have changed since the original postMessage call was made.
1697 WebSecurityOrigin target_origin
;
1698 if (!params
.target_origin
.empty()) {
1700 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1702 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1705 #if defined(OS_ANDROID)
1706 void RenderFrameImpl::OnSelectPopupMenuItems(
1708 const std::vector
<int>& selected_indices
) {
1709 // It is possible to receive more than one of these calls if the user presses
1710 // a select faster than it takes for the show-select-popup IPC message to make
1711 // it to the browser UI thread. Ignore the extra-messages.
1712 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1713 if (!external_popup_menu_
)
1716 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1717 external_popup_menu_
.reset();
1721 #if defined(OS_MACOSX)
1722 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1723 if (external_popup_menu_
== NULL
)
1725 external_popup_menu_
->DidSelectItem(selected_index
);
1726 external_popup_menu_
.reset();
1730 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1731 frame_
->reload(ignore_cache
);
1734 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1735 blink::WebSurroundingText surroundingText
;
1736 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1738 if (surroundingText
.isNull()) {
1739 // |surroundingText| might not be correctly initialized, for example if
1740 // |frame_->selectionRange().isNull()|, in other words, if there was no
1742 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1743 routing_id_
, base::string16(), 0, 0));
1747 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1749 surroundingText
.textContent(),
1750 surroundingText
.startOffsetInTextContent(),
1751 surroundingText
.endOffsetInTextContent()));
1754 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1755 const base::string16
& message
,
1756 const base::string16
& default_value
,
1757 const GURL
& frame_url
,
1758 base::string16
* result
) {
1759 // Don't allow further dialogs if we are waiting to swap out, since the
1760 // PageGroupLoadDeferrer in our stack prevents it.
1761 if (render_view()->suppress_dialogs_until_swap_out_
)
1764 bool success
= false;
1765 base::string16 result_temp
;
1767 result
= &result_temp
;
1769 render_view()->SendAndRunNestedMessageLoop(
1770 new FrameHostMsg_RunJavaScriptMessage(
1771 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1776 void RenderFrameImpl::LoadNavigationErrorPage(
1777 const WebURLRequest
& failed_request
,
1778 const WebURLError
& error
,
1780 std::string error_html
;
1781 GetContentClient()->renderer()->GetNavigationErrorStrings(
1782 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1784 frame_
->loadHTMLString(error_html
,
1785 GURL(kUnreachableWebDataURL
),
1786 error
.unreachableURL
,
1790 void RenderFrameImpl::DidCommitCompositorFrame() {
1791 if (BrowserPluginManager::Get())
1792 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1794 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1797 RenderView
* RenderFrameImpl::GetRenderView() {
1798 return render_view_
.get();
1801 int RenderFrameImpl::GetRoutingID() {
1805 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1810 WebElement
RenderFrameImpl::GetFocusedElement() const {
1811 WebDocument doc
= frame_
->document();
1813 return doc
.focusedElement();
1815 return WebElement();
1818 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1819 return render_view_
->GetWebkitPreferences();
1822 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1823 const ContextMenuParams
& params
) {
1824 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1825 ContextMenuParams
our_params(params
);
1826 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1827 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1828 return our_params
.custom_context
.request_id
;
1831 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1832 DCHECK(pending_context_menus_
.Lookup(request_id
));
1833 pending_context_menus_
.Remove(request_id
);
1836 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1837 return context_menu_node_
;
1840 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1841 blink::WebFrame
* frame
,
1842 const WebPluginInfo
& info
,
1843 const blink::WebPluginParams
& params
,
1844 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1845 DCHECK_EQ(frame_
, frame
);
1846 #if defined(ENABLE_PLUGINS)
1847 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1848 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1849 this, GetContentClient()
1851 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1856 bool pepper_plugin_was_registered
= false;
1857 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1858 this, info
, &pepper_plugin_was_registered
));
1859 if (pepper_plugin_was_registered
) {
1860 if (pepper_module
.get()) {
1861 return new PepperWebPluginImpl(
1862 pepper_module
.get(), params
, this,
1864 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1867 #if defined(OS_CHROMEOS)
1868 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1870 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1871 // TODO(jam): change to take RenderFrame.
1872 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1879 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1880 const blink::WebURLRequest
& request
,
1881 blink::WebNavigationPolicy policy
) {
1882 DCHECK(!frame_
|| frame_
== frame
);
1883 loadURLExternally(frame
, request
, policy
, WebString());
1886 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1887 OnJavaScriptExecuteRequest(javascript
, 0, false);
1890 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1891 return &service_registry_
;
1894 #if defined(ENABLE_PLUGINS)
1895 void RenderFrameImpl::RegisterPeripheralPlugin(
1896 const GURL
& content_origin
,
1897 const base::Closure
& unthrottle_callback
) {
1898 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1899 content_origin
, unthrottle_callback
);
1901 #endif // defined(ENABLE_PLUGINS)
1903 bool RenderFrameImpl::IsFTPDirectoryListing() {
1904 WebURLResponseExtraDataImpl
* extra_data
=
1905 GetExtraDataFromResponse(frame_
->dataSource()->response());
1906 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1909 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1910 BrowserPluginManager::Get()->Attach(element_instance_id
);
1913 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1914 BrowserPluginManager::Get()->Detach(element_instance_id
);
1917 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1919 const gfx::Range
& range
) {
1920 // Use the routing id of Render Widget Host.
1921 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1927 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1928 v8::Isolate
* isolate
,
1929 v8::Local
<v8::Context
> context
) {
1930 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1931 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1934 v8::HandleScope
handle_scope(isolate
);
1935 registry
->AddBuiltinModule(
1936 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1937 registry
->AddBuiltinModule(isolate
,
1938 mojo::js::Support::kModuleName
,
1939 mojo::js::Support::GetModule(isolate
));
1940 registry
->AddBuiltinModule(
1942 ServiceRegistryJsWrapper::kModuleName
,
1943 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1946 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
1947 const std::string
& message
) {
1948 if (devtools_agent_
)
1949 devtools_agent_
->AddMessageToConsole(level
, message
);
1952 // blink::WebFrameClient implementation ----------------------------------------
1954 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1955 blink::WebLocalFrame
* frame
,
1956 const blink::WebPluginParams
& params
) {
1957 DCHECK_EQ(frame_
, frame
);
1958 return GetContentClient()
1960 ->CreatePluginPlaceholder(this, frame
, params
)
1964 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1965 blink::WebLocalFrame
* frame
,
1966 const blink::WebPluginParams
& params
) {
1967 DCHECK_EQ(frame_
, frame
);
1968 blink::WebPlugin
* plugin
= NULL
;
1969 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1970 this, frame
, params
, &plugin
)) {
1974 if (base::UTF16ToUTF8(base::StringPiece16(params
.mimeType
)) ==
1975 kBrowserPluginMimeType
) {
1976 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1977 this, GetContentClient()
1979 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
1984 #if defined(ENABLE_PLUGINS)
1986 std::string mime_type
;
1988 Send(new FrameHostMsg_GetPluginInfo(
1989 routing_id_
, params
.url
, frame
->top()->document().url(),
1990 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
1994 WebPluginParams params_to_use
= params
;
1995 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
1996 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
1999 #endif // defined(ENABLE_PLUGINS)
2002 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2003 blink::WebLocalFrame
* frame
,
2004 const blink::WebURL
& url
,
2005 WebMediaPlayerClient
* client
,
2006 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
2007 WebContentDecryptionModule
* initial_cdm
) {
2008 #if defined(VIDEO_HOLE)
2009 if (!contains_media_player_
) {
2010 render_view_
->RegisterVideoHoleFrame(this);
2011 contains_media_player_
= true;
2013 #endif // defined(VIDEO_HOLE)
2015 blink::WebMediaStream
web_stream(
2016 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2017 if (!web_stream
.isNull())
2018 return CreateWebMediaPlayerForMediaStream(client
);
2020 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2021 return CreateAndroidWebMediaPlayer(client
, encrypted_client
,
2022 GetMediaPermission(), initial_cdm
);
2024 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2026 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2027 media::WebMediaPlayerParams
params(
2028 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2029 base::Unretained(GetContentClient()->renderer()),
2030 static_cast<RenderFrame
*>(this)),
2031 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2032 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2033 render_thread
->compositor_task_runner(),
2034 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2037 #if defined(ENABLE_MOJO_MEDIA)
2038 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2039 new media::MojoRendererFactory(GetMediaServiceFactory()));
2041 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2042 GetContentClient()->renderer()->CreateMediaRendererFactory(
2043 this, render_thread
->GetGpuFactories(), media_log
);
2045 if (!media_renderer_factory
.get()) {
2046 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2047 media_log
, render_thread
->GetGpuFactories(),
2048 *render_thread
->GetAudioHardwareConfig()));
2050 #endif // defined(ENABLE_MOJO_MEDIA)
2052 return new media::WebMediaPlayerImpl(
2053 frame
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
2054 media_renderer_factory
.Pass(), GetCdmFactory(), params
);
2055 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2058 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2059 blink::WebLocalFrame
* frame
,
2060 blink::WebApplicationCacheHostClient
* client
) {
2061 if (!frame
|| !frame
->view())
2063 DCHECK(!frame_
|| frame_
== frame
);
2064 return new RendererWebApplicationCacheHostImpl(
2065 RenderViewImpl::FromWebView(frame
->view()), client
,
2066 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2069 blink::WebWorkerContentSettingsClientProxy
*
2070 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2071 blink::WebLocalFrame
* frame
) {
2072 if (!frame
|| !frame
->view())
2074 DCHECK(!frame_
|| frame_
== frame
);
2075 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2079 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2080 const WebPopupMenuInfo
& popup_menu_info
,
2081 WebExternalPopupMenuClient
* popup_menu_client
) {
2082 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2083 // An IPC message is sent to the browser to build and display the actual
2084 // popup. The user could have time to click a different select by the time
2085 // the popup is shown. In that case external_popup_menu_ is non NULL.
2086 // By returning NULL in that case, we instruct Blink to cancel that new
2087 // popup. So from the user perspective, only the first one will show, and
2088 // will have to close the first one before another one can be shown.
2089 if (external_popup_menu_
)
2091 external_popup_menu_
.reset(
2092 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2093 if (render_view_
->screen_metrics_emulator_
) {
2094 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2095 external_popup_menu_
.get(),
2096 render_view_
->screen_metrics_emulator_
.get());
2098 return external_popup_menu_
.get();
2104 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2105 DCHECK(!frame_
|| frame_
== frame
);
2106 return &cookie_jar_
;
2109 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2110 blink::WebLocalFrame
* frame
) {
2111 DCHECK(!frame_
|| frame_
== frame
);
2112 // At this point we should have non-null data source.
2113 DCHECK(frame
->dataSource());
2114 if (!ChildThreadImpl::current())
2115 return NULL
; // May be null in some tests.
2116 ServiceWorkerNetworkProvider
* provider
=
2117 ServiceWorkerNetworkProvider::FromDocumentState(
2118 DocumentState::FromDataSource(frame
->dataSource()));
2120 return new WebServiceWorkerProviderImpl(
2121 ChildThreadImpl::current()->thread_safe_sender(),
2122 provider
->context());
2125 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2126 DCHECK(!frame_
|| frame_
== frame
);
2127 // If the request hasn't yet committed, notify the browser process that it is
2128 // no longer safe to show the pending URL of the main frame, since a URL spoof
2129 // is now possible. (If the request has committed, the browser already knows.)
2130 if (!frame
->parent()) {
2131 DocumentState
* document_state
=
2132 DocumentState::FromDataSource(frame
->dataSource());
2133 NavigationStateImpl
* navigation_state
=
2134 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2136 if (!navigation_state
->request_committed()) {
2137 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2142 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2143 blink::WebLocalFrame
* parent
,
2144 blink::WebTreeScopeType scope
,
2145 const blink::WebString
& name
,
2146 blink::WebSandboxFlags sandbox_flags
) {
2147 // Synchronously notify the browser of a child frame creation to get the
2148 // routing_id for the RenderFrame.
2149 int child_routing_id
= MSG_ROUTING_NONE
;
2150 Send(new FrameHostMsg_CreateChildFrame(
2152 base::UTF16ToUTF8(base::StringPiece16(name
)), sandbox_flags
,
2153 &child_routing_id
));
2155 // Allocation of routing id failed, so we can't create a child frame. This can
2156 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2157 // out state or synchronous IPC message above has failed.
2158 if (child_routing_id
== MSG_ROUTING_NONE
) {
2159 NOTREACHED() << "Failed to allocate routing id for child frame.";
2163 // Create the RenderFrame and WebLocalFrame, linking the two.
2164 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2165 render_view_
.get(), child_routing_id
);
2166 blink::WebLocalFrame
* web_frame
=
2167 WebLocalFrame::create(scope
, child_render_frame
);
2168 child_render_frame
->SetWebFrame(web_frame
);
2170 // Add the frame to the frame tree and initialize it.
2171 parent
->appendChild(web_frame
);
2172 child_render_frame
->Initialize();
2177 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2178 DCHECK(!frame_
|| frame_
== frame
);
2179 // We only need to notify the browser if the active, top-level frame clears
2180 // its opener. We can ignore cases where a swapped out frame clears its
2181 // opener after hearing about it from the browser, and the browser does not
2182 // (yet) care about subframe openers.
2183 if (is_swapped_out_
|| frame
->parent())
2186 // Notify WebContents and all its swapped out RenderViews.
2187 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2190 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2191 // NOTE: This function is called on the frame that is being detached and not
2192 // the parent frame. This is different from createChildFrame() which is
2193 // called on the parent frame.
2194 CHECK(!is_detaching_
);
2195 DCHECK(!frame_
|| frame_
== frame
);
2197 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2198 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2199 FrameDetached(frame
));
2201 // We only notify the browser process when the frame is being detached for
2202 // removal. If the frame is being detached for swap, we don't need to do this
2203 // since we are not modifiying the frame tree.
2204 if (type
== DetachType::Remove
)
2205 Send(new FrameHostMsg_Detach(routing_id_
));
2207 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2208 // sent before setting |is_detaching_| to true.
2209 is_detaching_
= true;
2211 // Clean up the associated RenderWidget for the frame, if there is one.
2212 if (render_widget_
) {
2213 render_widget_
->UnregisterRenderFrame(this);
2214 render_widget_
->CloseForFrame();
2217 // We need to clean up subframes by removing them from the map and deleting
2218 // the RenderFrameImpl. In contrast, the main frame is owned by its
2219 // containing RenderViewHost (so that they have the same lifetime), so only
2220 // removal from the map is needed and no deletion.
2221 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2222 CHECK(it
!= g_frame_map
.Get().end());
2223 CHECK_EQ(it
->second
, this);
2224 g_frame_map
.Get().erase(it
);
2226 // Only remove the frame from the renderer's frame tree if the frame is
2227 // being detached for removal. In the case of a swap, the frame needs to
2228 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2229 if (is_subframe_
&& type
== DetachType::Remove
)
2230 frame
->parent()->removeChild(frame
);
2232 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2233 // object may not be deleted immediately and other methods may try to access
2239 // Object is invalid after this point.
2242 void RenderFrameImpl::frameFocused() {
2243 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2246 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2247 DCHECK(!frame_
|| frame_
== frame
);
2249 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2250 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2251 FrameWillClose(frame
));
2254 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2255 const blink::WebString
& name
) {
2256 DCHECK(!frame_
|| frame_
== frame
);
2258 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2259 // updates may have performance implications for benchmarks like SunSpider.
2260 // For now, send these updates only for --site-per-process, which needs to
2261 // replicate frame names to frame proxies, and when
2262 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2263 // can be optimized further by only sending the update if there are any
2264 // remote frames in the frame tree, or delaying and batching up IPCs if
2265 // updates are happening too frequently.
2266 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
2267 switches::kSitePerProcess
);
2268 if (is_site_per_process
||
2269 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2270 Send(new FrameHostMsg_DidChangeName(
2271 routing_id_
, base::UTF16ToUTF8(base::StringPiece16(name
))));
2275 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2276 blink::WebSandboxFlags flags
) {
2277 int frame_routing_id
= MSG_ROUTING_NONE
;
2278 if (child_frame
->isWebRemoteFrame()) {
2280 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2283 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2286 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2290 void RenderFrameImpl::didMatchCSS(
2291 blink::WebLocalFrame
* frame
,
2292 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2293 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2294 DCHECK(!frame_
|| frame_
== frame
);
2296 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2297 DidMatchCSS(newly_matching_selectors
,
2298 stopped_matching_selectors
));
2301 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2302 const blink::WebString
& source
) {
2303 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2307 void RenderFrameImpl::didAddMessageToConsole(
2308 const blink::WebConsoleMessage
& message
,
2309 const blink::WebString
& source_name
,
2310 unsigned source_line
,
2311 const blink::WebString
& stack_trace
) {
2312 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2313 switch (message
.level
) {
2314 case blink::WebConsoleMessage::LevelDebug
:
2315 log_severity
= logging::LOG_VERBOSE
;
2317 case blink::WebConsoleMessage::LevelLog
:
2318 case blink::WebConsoleMessage::LevelInfo
:
2319 log_severity
= logging::LOG_INFO
;
2321 case blink::WebConsoleMessage::LevelWarning
:
2322 log_severity
= logging::LOG_WARNING
;
2324 case blink::WebConsoleMessage::LevelError
:
2325 log_severity
= logging::LOG_ERROR
;
2328 log_severity
= logging::LOG_VERBOSE
;
2331 if (shouldReportDetailedMessageForSource(source_name
)) {
2333 RenderFrameObserver
, observers_
,
2334 DetailedConsoleMessageAdded(message
.text
,
2338 static_cast<int32
>(log_severity
)));
2341 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2342 static_cast<int32
>(log_severity
),
2344 static_cast<int32
>(source_line
),
2348 void RenderFrameImpl::loadURLExternally(
2349 blink::WebLocalFrame
* frame
,
2350 const blink::WebURLRequest
& request
,
2351 blink::WebNavigationPolicy policy
,
2352 const blink::WebString
& suggested_name
) {
2353 DCHECK(!frame_
|| frame_
== frame
);
2354 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2355 if (policy
== blink::WebNavigationPolicyDownload
) {
2356 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2357 request
.url(), referrer
,
2360 OpenURL(frame
, request
.url(), referrer
, policy
);
2364 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2365 const NavigationPolicyInfo
& info
) {
2366 DCHECK(!frame_
|| frame_
== info
.frame
);
2367 return DecidePolicyForNavigation(this, info
);
2370 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2371 blink::WebFrame
* frame
) {
2372 DCHECK(!frame_
|| frame_
== frame
);
2373 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2376 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2377 const blink::WebFormElement
& form
) {
2378 DCHECK(!frame_
|| frame_
== frame
);
2380 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2383 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2384 const blink::WebFormElement
& form
) {
2385 DCHECK(!frame_
|| frame_
== frame
);
2386 DocumentState
* document_state
=
2387 DocumentState::FromDataSource(frame
->provisionalDataSource());
2388 NavigationStateImpl
* navigation_state
=
2389 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2390 InternalDocumentStateData
* internal_data
=
2391 InternalDocumentStateData::FromDocumentState(document_state
);
2393 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2394 ui::PAGE_TRANSITION_LINK
)) {
2395 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2398 // Save these to be processed when the ensuing navigation is committed.
2399 WebSearchableFormData
web_searchable_form_data(form
);
2400 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2401 internal_data
->set_searchable_form_encoding(
2402 web_searchable_form_data
.encoding().utf8());
2404 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2407 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2408 blink::WebDataSource
* datasource
) {
2409 DCHECK(!frame_
|| frame_
== frame
);
2411 bool content_initiated
= !pending_navigation_params_
.get();
2413 // Make sure any previous redirect URLs end up in our new data source.
2414 if (pending_navigation_params_
.get()) {
2415 for (const auto& i
:
2416 pending_navigation_params_
->request_params
.redirects
) {
2417 datasource
->appendRedirect(i
);
2421 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2422 if (!document_state
) {
2423 document_state
= new DocumentState
;
2424 datasource
->setExtraData(document_state
);
2425 if (!content_initiated
)
2426 PopulateDocumentStateFromPending(document_state
);
2429 // Carry over the user agent override flag, if it exists.
2430 blink::WebView
* webview
= render_view_
->webview();
2431 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2432 webview
->mainFrame()->isWebLocalFrame() &&
2433 webview
->mainFrame()->dataSource()) {
2434 DocumentState
* old_document_state
=
2435 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2436 if (old_document_state
) {
2437 InternalDocumentStateData
* internal_data
=
2438 InternalDocumentStateData::FromDocumentState(document_state
);
2439 InternalDocumentStateData
* old_internal_data
=
2440 InternalDocumentStateData::FromDocumentState(old_document_state
);
2441 internal_data
->set_is_overriding_user_agent(
2442 old_internal_data
->is_overriding_user_agent());
2446 // The rest of RenderView assumes that a WebDataSource will always have a
2447 // non-null NavigationState.
2448 if (content_initiated
) {
2449 document_state
->set_navigation_state(
2450 NavigationStateImpl::CreateContentInitiated());
2452 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2453 pending_navigation_params_
.reset();
2456 // DocumentState::referred_by_prefetcher_ is true if we are
2457 // navigating from a page that used prefetching using a link on that
2458 // page. We are early enough in the request process here that we
2459 // can still see the DocumentState of the previous page and set
2460 // this value appropriately.
2461 // TODO(gavinp): catch the important case of navigation in a new
2462 // renderer process.
2464 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2465 const WebURLRequest
& original_request
= datasource
->originalRequest();
2466 const GURL
referrer(
2467 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2468 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2469 DocumentState::FromDataSource(old_frame
->dataSource())
2470 ->was_prefetcher()) {
2471 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2472 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2473 if (old_frame_datasource
&&
2474 referrer
== GURL(old_frame_datasource
->request().url())) {
2475 document_state
->set_was_referred_by_prefetcher(true);
2483 if (content_initiated
) {
2484 const WebURLRequest
& request
= datasource
->request();
2485 switch (request
.cachePolicy()) {
2486 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2487 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2489 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2490 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2491 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2493 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2494 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2496 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2497 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2504 // Create the serviceworker's per-document network observing object if it
2505 // does not exist (When navigation happens within a page, the provider already
2507 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2508 DocumentState::FromDataSource(datasource
))) {
2509 ServiceWorkerProviderType provider_type
=
2510 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2511 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2512 blink::WebSandboxFlags::Origin
) {
2513 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2515 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2516 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2517 ServiceWorkerNetworkProvider::AttachToDocumentState(
2518 DocumentState::FromDataSource(datasource
),
2519 network_provider
.Pass());
2523 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2524 double triggering_event_time
) {
2525 DCHECK(!frame_
|| frame_
== frame
);
2526 WebDataSource
* ds
= frame
->provisionalDataSource();
2528 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2529 // callback is invoked.
2533 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2534 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2535 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2537 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2538 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2540 "Heard swappedout:// when not swapped out.";
2542 // Update the request time if WebKit has better knowledge of it.
2543 if (document_state
->request_time().is_null() &&
2544 triggering_event_time
!= 0.0) {
2545 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2548 // Start time is only set after request time.
2549 document_state
->set_start_load_time(Time::Now());
2551 bool is_top_most
= !frame
->parent();
2553 render_view_
->set_navigation_gesture(
2554 WebUserGestureIndicator::isProcessingUserGesture() ?
2555 NavigationGestureUser
: NavigationGestureAuto
);
2556 } else if (ds
->replacesCurrentHistoryItem()) {
2557 // Subframe navigations that don't add session history items must be
2558 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2559 // handle loading of error pages.
2560 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2561 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2564 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2565 DidStartProvisionalLoad(frame
));
2566 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2568 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2569 routing_id_
, ds
->request().url()));
2572 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2573 blink::WebLocalFrame
* frame
) {
2574 DCHECK(!frame_
|| frame_
== frame
);
2575 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2578 void RenderFrameImpl::didFailProvisionalLoad(
2579 blink::WebLocalFrame
* frame
,
2580 const blink::WebURLError
& error
,
2581 blink::WebHistoryCommitType commit_type
) {
2582 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2584 DCHECK(!frame_
|| frame_
== frame
);
2585 WebDataSource
* ds
= frame
->provisionalDataSource();
2588 const WebURLRequest
& failed_request
= ds
->request();
2590 // Notify the browser that we failed a provisional load with an error.
2592 // Note: It is important this notification occur before DidStopLoading so the
2593 // SSL manager can react to the provisional load failure before being
2594 // notified the load stopped.
2596 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2597 DidFailProvisionalLoad(frame
, error
));
2598 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2599 DidFailProvisionalLoad(error
));
2601 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2603 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2606 // Make sure we never show errors in view source mode.
2607 frame
->enableViewSourceMode(false);
2609 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2610 NavigationStateImpl
* navigation_state
=
2611 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2613 // If this is a failed back/forward/reload navigation, then we need to do a
2614 // 'replace' load. This is necessary to avoid messing up session history.
2615 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2616 // as session history is concerned.
2617 bool replace
= commit_type
!= blink::WebStandardCommit
;
2619 // If we failed on a browser initiated request, then make sure that our error
2620 // page load is regarded as the same browser initiated request.
2621 if (!navigation_state
->IsContentInitiated()) {
2622 pending_navigation_params_
.reset(new NavigationParams(
2623 navigation_state
->common_params(), navigation_state
->start_params(),
2624 navigation_state
->request_params()));
2625 pending_navigation_params_
->request_params
.request_time
=
2626 document_state
->request_time();
2629 // Load an error page.
2630 LoadNavigationErrorPage(failed_request
, error
, replace
);
2633 void RenderFrameImpl::didCommitProvisionalLoad(
2634 blink::WebLocalFrame
* frame
,
2635 const blink::WebHistoryItem
& item
,
2636 blink::WebHistoryCommitType commit_type
) {
2637 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2639 "url", GetLoadingUrl().possibly_invalid_spec());
2640 DCHECK(!frame_
|| frame_
== frame
);
2641 DocumentState
* document_state
=
2642 DocumentState::FromDataSource(frame
->dataSource());
2643 NavigationStateImpl
* navigation_state
=
2644 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2646 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2647 RenderFrameProxy
* proxy
=
2648 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2650 proxy
->web_frame()->swap(frame_
);
2651 proxy_routing_id_
= MSG_ROUTING_NONE
;
2653 // If this is the main frame going from a remote frame to a local frame,
2654 // it needs to set RenderViewImpl's pointer for the main frame to itself
2655 // and ensure RenderWidget is no longer in swapped out mode.
2656 if (!is_subframe_
) {
2657 CHECK(!render_view_
->main_render_frame_
);
2658 render_view_
->main_render_frame_
= this;
2659 if (render_view_
->is_swapped_out())
2660 render_view_
->SetSwappedOut(false);
2664 // When we perform a new navigation, we need to update the last committed
2665 // session history entry with state for the page we are leaving. Do this
2666 // before updating the HistoryController state.
2667 render_view_
->SendUpdateState();
2669 render_view_
->history_controller()->UpdateForCommit(
2670 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2672 InternalDocumentStateData
* internal_data
=
2673 InternalDocumentStateData::FromDocumentState(document_state
);
2675 if (document_state
->commit_load_time().is_null())
2676 document_state
->set_commit_load_time(Time::Now());
2678 if (internal_data
->must_reset_scroll_and_scale_state()) {
2679 render_view_
->webview()->resetScrollAndScaleState();
2680 internal_data
->set_must_reset_scroll_and_scale_state(false);
2683 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2684 if (is_new_navigation
) {
2685 // We bump our Page ID to correspond with the new session history entry.
2686 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2688 // Don't update history list values for kSwappedOutURL, since
2689 // we don't want to forget the entry that was there, and since we will
2690 // never come back to kSwappedOutURL. Note that we have to call
2691 // SendUpdateState and update page_id_ even in this case, so that
2692 // the current entry gets a state update and so that we don't send a
2693 // state update to the wrong entry when we swap back in.
2695 navigation_state
->common_params().should_replace_current_entry
,
2696 render_view_
->history_list_length_
> 0);
2697 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2698 !navigation_state
->common_params().should_replace_current_entry
) {
2699 // Advance our offset in session history, applying the length limit.
2700 // There is now no forward history.
2701 render_view_
->history_list_offset_
++;
2702 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2703 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2704 render_view_
->history_list_length_
=
2705 render_view_
->history_list_offset_
+ 1;
2708 const RequestNavigationParams
& request_params
=
2709 navigation_state
->request_params();
2710 if (request_params
.nav_entry_id
!= 0 &&
2711 !request_params
.intended_as_new_entry
) {
2712 // This is a successful session history navigation!
2713 render_view_
->page_id_
= request_params
.page_id
;
2715 render_view_
->history_list_offset_
=
2716 request_params
.pending_history_list_offset
;
2721 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2722 CHECK(sent
); // http://crbug.com/407376
2724 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2725 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2727 RenderFrameObserver
, observers_
,
2728 DidCommitProvisionalLoad(is_new_navigation
,
2729 navigation_state
->WasWithinSamePage()));
2731 if (!frame
->parent()) { // Only for top frames.
2732 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2733 if (render_thread_impl
) { // Can be NULL in tests.
2734 render_thread_impl
->histogram_customizer()->
2735 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2736 RenderView::GetRenderViewCount());
2740 // Remember that we've already processed this request, so we don't update
2741 // the session history again. We do this regardless of whether this is
2742 // a session history navigation, because if we attempted a session history
2743 // navigation without valid HistoryItem state, WebCore will think it is a
2745 navigation_state
->set_request_committed(true);
2747 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2749 // Check whether we have new encoding name.
2750 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2753 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2754 DCHECK(!frame_
|| frame_
== frame
);
2756 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2757 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2758 DidCreateNewDocument(frame
));
2761 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2762 DCHECK(!frame_
|| frame_
== frame
);
2764 int enabled_bindings
= render_view_
->GetEnabledBindings();
2766 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2767 WebUIExtension::Install(frame
);
2769 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2770 DomAutomationController::Install(this, frame
);
2772 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2773 StatsCollectionController::Install(frame
);
2775 const base::CommandLine
& command_line
=
2776 *base::CommandLine::ForCurrentProcess();
2778 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2779 GpuBenchmarking::Install(frame
);
2781 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2782 MemoryBenchmarkingExtension::Install(frame
);
2784 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2785 SkiaBenchmarking::Install(frame
);
2787 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2788 DidClearWindowObject(frame
));
2789 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2792 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2793 DCHECK(!frame_
|| frame_
== frame
);
2795 // Notify the browser about non-blank documents loading in the top frame.
2796 GURL url
= frame
->document().url();
2797 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2798 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2799 // frame->tree()->top().
2800 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2801 if (frame
== main_frame
) {
2802 // For now, don't remember plugin zoom values. We don't want to mix them
2803 // with normal web content (i.e. a fixed layout plugin would usually want
2805 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2806 render_view_
->GetRoutingID(),
2807 main_frame
->document().isPluginDocument()));
2811 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2812 DidCreateDocumentElement());
2813 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2814 DidCreateDocumentElement(frame
));
2817 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2818 const blink::WebString
& title
,
2819 blink::WebTextDirection direction
) {
2820 DCHECK(!frame_
|| frame_
== frame
);
2821 // Ignore all but top level navigations.
2822 if (!frame
->parent()) {
2823 base::string16 title16
= title
;
2824 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2825 routing_id_
, base::UTF16ToUTF8(title16
));
2827 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2828 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2829 shortened_title
, direction
));
2832 // Also check whether we have new encoding name.
2833 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2836 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2837 blink::WebIconURL::Type icon_type
) {
2838 DCHECK(!frame_
|| frame_
== frame
);
2839 // TODO(nasko): Investigate wheather implementation should move here.
2840 render_view_
->didChangeIcon(frame
, icon_type
);
2843 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
,
2844 bool document_is_empty
) {
2845 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2847 DCHECK(!frame_
|| frame_
== frame
);
2848 WebDataSource
* ds
= frame
->dataSource();
2849 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2850 document_state
->set_finish_document_load_time(Time::Now());
2852 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2854 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2855 DidFinishDocumentLoad(frame
));
2856 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2858 // Check whether we have new encoding name.
2859 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2861 // If this is an empty document with an http status code indicating an error,
2862 // we may want to display our own error page, so the user doesn't end up
2863 // with an unexplained blank page.
2864 if (!document_is_empty
)
2867 // Do not show error page when DevTools is attached.
2868 RenderFrameImpl
* localRoot
= this;
2869 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
2870 localRoot
->frame_
->parent()->isWebLocalFrame()) {
2871 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
2874 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
2877 // Display error page instead of a blank page, if appropriate.
2878 std::string error_domain
= "http";
2879 InternalDocumentStateData
* internal_data
=
2880 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2881 int http_status_code
= internal_data
->http_status_code();
2882 if (GetContentClient()->renderer()->HasErrorPage(http_status_code
,
2885 error
.unreachableURL
= frame
->document().url();
2886 error
.domain
= WebString::fromUTF8(error_domain
);
2887 error
.reason
= http_status_code
;
2888 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
2892 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2893 DCHECK(!frame_
|| frame_
== frame
);
2894 if (!frame
->parent()) {
2895 FrameMsg_UILoadMetricsReportType::Value report_type
=
2896 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2897 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2898 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2899 base::TimeDelta::FromSecondsD(
2900 frame
->dataSource()->request().uiStartTime());
2902 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2903 routing_id_
, report_type
, ui_timestamp
));
2907 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2908 const blink::WebURLError
& error
,
2909 blink::WebHistoryCommitType commit_type
) {
2910 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2912 DCHECK(!frame_
|| frame_
== frame
);
2913 // TODO(nasko): Move implementation here. No state needed.
2914 WebDataSource
* ds
= frame
->dataSource();
2917 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2918 DidFailLoad(frame
, error
));
2920 const WebURLRequest
& failed_request
= ds
->request();
2921 base::string16 error_description
;
2922 GetContentClient()->renderer()->GetNavigationErrorStrings(
2928 &error_description
);
2929 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2930 failed_request
.url(),
2933 error
.wasIgnoredByHandler
));
2936 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2937 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2939 DCHECK(!frame_
|| frame_
== frame
);
2940 WebDataSource
* ds
= frame
->dataSource();
2941 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2942 if (document_state
->finish_load_time().is_null()) {
2943 if (!frame
->parent()) {
2944 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2945 TRACE_EVENT_SCOPE_PROCESS
);
2947 document_state
->set_finish_load_time(Time::Now());
2950 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2951 DidFinishLoad(frame
));
2952 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2954 // Don't send this message while the frame is swapped out.
2955 if (is_swapped_out())
2958 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2959 ds
->request().url()));
2962 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2963 const blink::WebHistoryItem
& item
,
2964 blink::WebHistoryCommitType commit_type
) {
2965 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2967 DCHECK(!frame_
|| frame_
== frame
);
2968 // If this was a reference fragment navigation that we initiated, then we
2969 // could end up having a non-null pending navigation params. We just need to
2970 // update the ExtraData on the datasource so that others who read the
2971 // ExtraData will get the new NavigationState. Similarly, if we did not
2972 // initiate this navigation, then we need to take care to reset any pre-
2973 // existing navigation state to a content-initiated navigation state.
2974 // didCreateDataSource conveniently takes care of this for us.
2975 didCreateDataSource(frame
, frame
->dataSource());
2977 DocumentState
* document_state
=
2978 DocumentState::FromDataSource(frame
->dataSource());
2979 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2980 ->set_was_within_same_page(true);
2982 didCommitProvisionalLoad(frame
, item
, commit_type
);
2985 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2986 DCHECK(!frame_
|| frame_
== frame
);
2987 // TODO(nasko): Move implementation here. Needed methods:
2988 // * StartNavStateSyncTimerIfNecessary
2989 render_view_
->didUpdateCurrentHistoryItem(frame
);
2992 void RenderFrameImpl::didChangeThemeColor() {
2993 if (frame_
->parent())
2996 Send(new FrameHostMsg_DidChangeThemeColor(
2997 routing_id_
, frame_
->document().themeColor()));
3000 void RenderFrameImpl::dispatchLoad() {
3001 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
3004 void RenderFrameImpl::requestNotificationPermission(
3005 const blink::WebSecurityOrigin
& origin
,
3006 blink::WebNotificationPermissionCallback
* callback
) {
3007 if (!notification_permission_dispatcher_
) {
3008 notification_permission_dispatcher_
=
3009 new NotificationPermissionDispatcher(this);
3012 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3015 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3016 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3019 if (is_empty_selection
)
3020 selection_text_
.clear();
3022 // UpdateTextInputType should be called before SyncSelectionIfRequired.
3023 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
3024 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3025 // to notify the selection was changed. Focus change should be notified
3026 // before selection change.
3027 GetRenderWidget()->UpdateTextInputType();
3028 SyncSelectionIfRequired();
3029 #if defined(OS_ANDROID)
3030 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
3031 RenderWidget::FROM_NON_IME
);
3035 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3036 blink::WebColorChooserClient
* client
,
3037 const blink::WebColor
& initial_color
,
3038 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3039 RendererWebColorChooserImpl
* color_chooser
=
3040 new RendererWebColorChooserImpl(this, client
);
3041 std::vector
<ColorSuggestion
> color_suggestions
;
3042 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3043 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3045 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3046 return color_chooser
;
3049 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3050 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3053 frame_
->document().url(),
3057 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3058 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3061 frame_
->document().url(),
3065 bool RenderFrameImpl::runModalPromptDialog(
3066 const blink::WebString
& message
,
3067 const blink::WebString
& default_value
,
3068 blink::WebString
* actual_value
) {
3069 base::string16 result
;
3070 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3073 frame_
->document().url(),
3076 actual_value
->assign(result
);
3080 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3082 const blink::WebString
& message
) {
3083 // If we are swapping out, we have already run the beforeunload handler.
3084 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3085 // at all, to avoid running it twice.
3086 if (is_swapped_out_
)
3089 // Don't allow further dialogs if we are waiting to swap out, since the
3090 // PageGroupLoadDeferrer in our stack prevents it.
3091 if (render_view()->suppress_dialogs_until_swap_out_
)
3094 bool success
= false;
3095 // This is an ignored return value, but is included so we can accept the same
3096 // response as RunJavaScriptMessage.
3097 base::string16 ignored_result
;
3098 render_view()->SendAndRunNestedMessageLoop(
3099 new FrameHostMsg_RunBeforeUnloadConfirm(
3100 routing_id_
, frame_
->document().url(), message
, is_reload
,
3101 &success
, &ignored_result
));
3105 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3106 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3107 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3108 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3109 if (GetRenderWidget()->has_host_context_menu_location()) {
3110 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3111 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3114 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3115 // it. We replace it with an empty GURL so the appropriate items are disabled
3116 // in the context menu.
3117 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3118 // data encoded images. We should have a way to save them.
3119 if (params
.src_url
.spec().size() > GetMaxURLChars())
3120 params
.src_url
= GURL();
3121 context_menu_node_
= data
.node
;
3123 #if defined(OS_ANDROID)
3124 gfx::Rect start_rect
;
3126 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3127 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3128 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3131 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3134 void RenderFrameImpl::clearContextMenu() {
3135 context_menu_node_
.reset();
3138 void RenderFrameImpl::willSendRequest(
3139 blink::WebLocalFrame
* frame
,
3140 unsigned identifier
,
3141 blink::WebURLRequest
& request
,
3142 const blink::WebURLResponse
& redirect_response
) {
3143 DCHECK(!frame_
|| frame_
== frame
);
3144 // The request my be empty during tests.
3145 if (request
.url().isEmpty())
3148 // Set the first party for cookies url if it has not been set yet (new
3149 // requests). For redirects, it is updated by WebURLLoaderImpl.
3150 if (request
.firstPartyForCookies().isEmpty()) {
3151 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3152 request
.setFirstPartyForCookies(request
.url());
3154 // TODO(nasko): When the top-level frame is remote, there is no document.
3155 // This is broken and should be fixed to propagate the first party.
3156 WebFrame
* top
= frame
->top();
3157 if (top
->isWebLocalFrame()) {
3158 request
.setFirstPartyForCookies(
3159 frame
->top()->document().firstPartyForCookies());
3164 WebDataSource
* provisional_data_source
= frame
->provisionalDataSource();
3165 WebDataSource
* data_source
=
3166 provisional_data_source
? provisional_data_source
: frame
->dataSource();
3168 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3169 DCHECK(document_state
);
3170 InternalDocumentStateData
* internal_data
=
3171 InternalDocumentStateData::FromDocumentState(document_state
);
3172 NavigationStateImpl
* navigation_state
=
3173 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3174 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3175 if (provisional_data_source
&& provisional_data_source
->isClientRedirect()) {
3176 transition_type
= ui::PageTransitionFromInt(
3177 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3180 GURL
request_url(request
.url());
3182 if (GetContentClient()->renderer()->WillSendRequest(
3186 request
.firstPartyForCookies(),
3188 request
.setURL(WebURL(new_url
));
3191 if (internal_data
->is_cache_policy_override_set())
3192 request
.setCachePolicy(internal_data
->cache_policy_override());
3194 // The request's extra data may indicate that we should set a custom user
3195 // agent. This needs to be done here, after WebKit is through with setting the
3196 // user agent on its own. Similarly, it may indicate that we should set an
3197 // X-Requested-With header. This must be done here to avoid breaking CORS
3199 // PlzNavigate: there may also be a stream url associated with the request.
3200 WebString custom_user_agent
;
3201 WebString requested_with
;
3202 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3203 if (request
.extraData()) {
3204 RequestExtraData
* old_extra_data
=
3205 static_cast<RequestExtraData
*>(request
.extraData());
3207 custom_user_agent
= old_extra_data
->custom_user_agent();
3208 if (!custom_user_agent
.isNull()) {
3209 if (custom_user_agent
.isEmpty())
3210 request
.clearHTTPHeaderField("User-Agent");
3212 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3215 requested_with
= old_extra_data
->requested_with();
3216 if (!requested_with
.isNull()) {
3217 if (requested_with
.isEmpty())
3218 request
.clearHTTPHeaderField("X-Requested-With");
3220 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3222 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3225 // Add the default accept header for frame request if it has not been set
3227 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3228 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3229 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3230 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3231 WebString::fromUTF8(kDefaultAcceptHeader
));
3234 // Add an empty HTTP origin header for non GET methods if none is currently
3236 request
.addHTTPOriginIfNeeded(WebString());
3238 // Attach |should_replace_current_entry| state to requests so that, should
3239 // this navigation later require a request transfer, all state is preserved
3240 // when it is re-created in the new process.
3241 bool should_replace_current_entry
= false;
3242 if (navigation_state
->IsContentInitiated()) {
3243 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3245 // If the navigation is browser-initiated, the NavigationState contains the
3246 // correct value instead of the WebDataSource.
3248 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3249 // NavigationState::should_replace_current_entry().
3250 should_replace_current_entry
=
3251 navigation_state
->common_params().should_replace_current_entry
;
3254 int provider_id
= kInvalidServiceWorkerProviderId
;
3255 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3256 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3257 // |provisionalDataSource| may be null in some content::ResourceFetcher
3258 // use cases, we don't hook those requests.
3259 if (frame
->provisionalDataSource()) {
3260 ServiceWorkerNetworkProvider
* provider
=
3261 ServiceWorkerNetworkProvider::FromDocumentState(
3262 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3263 provider_id
= provider
->provider_id();
3265 } else if (frame
->dataSource()) {
3266 ServiceWorkerNetworkProvider
* provider
=
3267 ServiceWorkerNetworkProvider::FromDocumentState(
3268 DocumentState::FromDataSource(frame
->dataSource()));
3269 provider_id
= provider
->provider_id();
3272 WebFrame
* parent
= frame
->parent();
3273 int parent_routing_id
= MSG_ROUTING_NONE
;
3275 parent_routing_id
= -1;
3276 } else if (parent
->isWebLocalFrame()) {
3277 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3279 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3282 RequestExtraData
* extra_data
= new RequestExtraData();
3283 extra_data
->set_visibility_state(render_view_
->visibilityState());
3284 extra_data
->set_custom_user_agent(custom_user_agent
);
3285 extra_data
->set_requested_with(requested_with
);
3286 extra_data
->set_render_frame_id(routing_id_
);
3287 extra_data
->set_is_main_frame(!parent
);
3288 extra_data
->set_frame_origin(
3289 GURL(frame
->document().securityOrigin().toString()));
3290 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3291 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3292 extra_data
->set_allow_download(
3293 navigation_state
->common_params().allow_download
);
3294 extra_data
->set_transition_type(transition_type
);
3295 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3296 extra_data
->set_transferred_request_child_id(
3297 navigation_state
->start_params().transferred_request_child_id
);
3298 extra_data
->set_transferred_request_request_id(
3299 navigation_state
->start_params().transferred_request_request_id
);
3300 extra_data
->set_service_worker_provider_id(provider_id
);
3301 extra_data
->set_stream_override(stream_override
.Pass());
3302 request
.setExtraData(extra_data
);
3304 // TODO(creis): Update prefetching to work with out-of-process iframes.
3305 WebFrame
* top_frame
= frame
->top();
3306 if (top_frame
&& top_frame
->isWebLocalFrame()) {
3307 DocumentState
* top_document_state
=
3308 DocumentState::FromDataSource(top_frame
->dataSource());
3309 if (top_document_state
) {
3310 // TODO(gavinp): separate out prefetching and prerender field trials
3311 // if the rel=prerender rel type is sticking around.
3312 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3313 top_document_state
->set_was_prefetcher(true);
3317 // This is an instance where we embed a copy of the routing id
3318 // into the data portion of the message. This can cause problems if we
3319 // don't register this id on the browser side, since the download manager
3320 // expects to find a RenderViewHost based off the id.
3321 request
.setRequestorID(render_view_
->GetRoutingID());
3322 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3324 if (!navigation_state
->start_params().extra_headers
.empty()) {
3325 for (net::HttpUtil::HeadersIterator
i(
3326 navigation_state
->start_params().extra_headers
.begin(),
3327 navigation_state
->start_params().extra_headers
.end(), "\n");
3329 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3330 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3331 blink::WebReferrerPolicyDefault
,
3333 WebString::fromUTF8(i
.values()));
3334 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3336 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3337 WebString::fromUTF8(i
.values()));
3342 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3343 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3346 void RenderFrameImpl::didReceiveResponse(
3347 blink::WebLocalFrame
* frame
,
3348 unsigned identifier
,
3349 const blink::WebURLResponse
& response
) {
3350 DCHECK(!frame_
|| frame_
== frame
);
3351 // Only do this for responses that correspond to a provisional data source
3352 // of the top-most frame. If we have a provisional data source, then we
3353 // can't have any sub-resources yet, so we know that this response must
3354 // correspond to a frame load.
3355 if (!frame
->provisionalDataSource() || frame
->parent())
3358 // If we are in view source mode, then just let the user see the source of
3359 // the server's error page.
3360 if (frame
->isViewSourceModeEnabled())
3363 DocumentState
* document_state
=
3364 DocumentState::FromDataSource(frame
->provisionalDataSource());
3365 int http_status_code
= response
.httpStatusCode();
3367 // Record page load flags.
3368 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3370 document_state
->set_was_fetched_via_spdy(
3371 extra_data
->was_fetched_via_spdy());
3372 document_state
->set_was_npn_negotiated(
3373 extra_data
->was_npn_negotiated());
3374 document_state
->set_npn_negotiated_protocol(
3375 extra_data
->npn_negotiated_protocol());
3376 document_state
->set_was_alternate_protocol_available(
3377 extra_data
->was_alternate_protocol_available());
3378 document_state
->set_connection_info(
3379 extra_data
->connection_info());
3380 document_state
->set_was_fetched_via_proxy(
3381 extra_data
->was_fetched_via_proxy());
3382 document_state
->set_proxy_server(
3383 extra_data
->proxy_server());
3385 InternalDocumentStateData
* internal_data
=
3386 InternalDocumentStateData::FromDocumentState(document_state
);
3387 internal_data
->set_http_status_code(http_status_code
);
3390 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3391 blink::WebLocalFrame
* frame
,
3392 const blink::WebURLRequest
& request
,
3393 const blink::WebURLResponse
& response
) {
3394 DCHECK(!frame_
|| frame_
== frame
);
3395 // The recipients of this message have no use for data: URLs: they don't
3396 // affect the page's insecure content list and are not in the disk cache. To
3397 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3398 // filter them out here.
3399 GURL
url(request
.url());
3400 if (url
.SchemeIs(url::kDataScheme
))
3403 // Let the browser know we loaded a resource from the memory cache. This
3404 // message is needed to display the correct SSL indicators.
3405 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3406 render_view_
->GetRoutingID(),
3408 response
.securityInfo(),
3409 request
.httpMethod().utf8(),
3410 response
.mimeType().utf8(),
3411 WebURLRequestToResourceType(request
)));
3414 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3415 DCHECK(!frame_
|| frame_
== frame
);
3416 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3417 render_view_
->GetRoutingID()));
3420 void RenderFrameImpl::didRunInsecureContent(
3421 blink::WebLocalFrame
* frame
,
3422 const blink::WebSecurityOrigin
& origin
,
3423 const blink::WebURL
& target
) {
3424 DCHECK(!frame_
|| frame_
== frame
);
3425 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3426 render_view_
->GetRoutingID(),
3427 origin
.toString().utf8(),
3429 GetContentClient()->renderer()->RecordRapporURL(
3430 "ContentSettings.MixedScript.RanMixedScript",
3431 GURL(origin
.toString().utf8()));
3434 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3435 DCHECK(!frame_
|| frame_
== frame
);
3436 #if defined(ENABLE_PLUGINS)
3437 if (frame
!= render_view_
->webview()->mainFrame())
3439 PluginChannelHost::Broadcast(
3440 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3444 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3445 v8::Local
<v8::Context
> context
,
3446 int extension_group
,
3448 DCHECK(!frame_
|| frame_
== frame
);
3450 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3451 DidCreateScriptContext(context
, extension_group
, world_id
));
3454 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3455 v8::Local
<v8::Context
> context
,
3457 DCHECK(!frame_
|| frame_
== frame
);
3459 FOR_EACH_OBSERVER(RenderFrameObserver
,
3461 WillReleaseScriptContext(context
, world_id
));
3464 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3465 blink::WebLocalFrame
* frame
) {
3466 DCHECK(!frame_
|| frame_
== frame
);
3467 if (frame
->parent())
3470 InternalDocumentStateData
* data
=
3471 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3472 data
->set_did_first_visually_non_empty_layout(true);
3474 #if defined(OS_ANDROID)
3475 GetRenderWidget()->DidChangeBodyBackgroundColor(
3476 render_view_
->webwidget_
->backgroundColor());
3479 GetRenderWidget()->QueueMessage(
3480 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3481 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3484 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3485 DCHECK(!frame_
|| frame_
== frame
);
3486 // TODO(nasko): Move implementation here. Needed methods:
3487 // * StartNavStateSyncTimerIfNecessary
3488 render_view_
->didChangeScrollOffset(frame
);
3490 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3493 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3494 DCHECK(!frame_
|| frame_
== frame
);
3495 if (!frame
->parent()) {
3496 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3497 render_view_
->GetRoutingID()));
3501 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3503 bool final_update
) {
3504 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3506 active_match_ordinal
= 0;
3508 render_view_
->Send(new ViewHostMsg_Find_Reply(
3509 render_view_
->GetRoutingID(), request_id
, count
,
3510 gfx::Rect(), active_match_ordinal
, final_update
));
3513 void RenderFrameImpl::reportFindInPageSelection(
3515 int active_match_ordinal
,
3516 const blink::WebRect
& selection_rect
) {
3517 render_view_
->Send(new ViewHostMsg_Find_Reply(
3518 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3519 active_match_ordinal
, false));
3522 void RenderFrameImpl::requestStorageQuota(
3523 blink::WebLocalFrame
* frame
,
3524 blink::WebStorageQuotaType type
,
3525 unsigned long long requested_size
,
3526 blink::WebStorageQuotaCallbacks callbacks
) {
3527 DCHECK(!frame_
|| frame_
== frame
);
3528 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3529 if (origin
.isUnique()) {
3530 // Unique origins cannot store persistent state.
3531 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3534 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3535 render_view_
->GetRoutingID(),
3536 GURL(origin
.toString()),
3537 static_cast<storage::StorageType
>(type
),
3539 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3542 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3543 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3544 impl
->set_render_frame_id(routing_id_
);
3547 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3548 if (!geolocation_dispatcher_
)
3549 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3550 return geolocation_dispatcher_
;
3553 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3554 if (!presentation_dispatcher_
)
3555 presentation_dispatcher_
= new PresentationDispatcher(this);
3556 return presentation_dispatcher_
;
3559 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3560 if (!push_messaging_dispatcher_
)
3561 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3562 return push_messaging_dispatcher_
;
3565 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3566 blink::WebLocalFrame
* frame
,
3567 blink::WebRTCPeerConnectionHandler
* handler
) {
3568 DCHECK(!frame_
|| frame_
== frame
);
3569 #if defined(ENABLE_WEBRTC)
3570 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3574 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3575 if (!web_user_media_client_
)
3576 InitializeUserMediaClient();
3577 return web_user_media_client_
;
3580 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3581 if (!web_encrypted_media_client_
) {
3582 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3583 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3584 // is destructed before |this|, and does not give away ownership of the
3586 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3587 base::Unretained(this)),
3588 GetCdmFactory(), GetMediaPermission()));
3590 return web_encrypted_media_client_
.get();
3593 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3594 if (!midi_dispatcher_
)
3595 midi_dispatcher_
= new MidiDispatcher(this);
3596 return midi_dispatcher_
;
3599 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3600 blink::WebLocalFrame
* source_frame
,
3601 blink::WebFrame
* target_frame
,
3602 blink::WebSecurityOrigin target_origin
,
3603 blink::WebDOMMessageEvent event
) {
3604 DCHECK(!frame_
|| frame_
== target_frame
);
3606 // Currently, a postMessage that targets a cross-process frame can be plumbed
3607 // either through this function or RenderFrameProxy::postMessageEvent. This
3608 // function is used when the target cross-process frame is a top-level frame
3609 // which has been swapped out. In that case, the corresponding WebLocalFrame
3610 // currently remains in the frame tree even in site-per-process mode (see
3611 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3612 // --site-per-process mode for all other cases.
3614 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3615 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3616 // cross-process postMessages.
3617 if (!is_swapped_out_
)
3620 // It is possible to get here on a swapped-out frame without a
3621 // |render_frame_proxy_|. This happens when:
3622 // - This process only has one active RenderView and is about to go away
3623 // (e.g., due to cross-process navigation).
3624 // - The top frame has a subframe with an unload handler.
3625 // - The subframe sends a postMessage to the top-level frame in its unload
3627 // See https://crbug.com/475651 for details. We return false here, since we
3628 // don't want to deliver the message to the new process in this case.
3629 if (!render_frame_proxy_
)
3632 render_frame_proxy_
->postMessageEvent(
3633 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3637 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3638 const blink::WebURL
& url
) {
3639 DCHECK(!frame_
|| frame_
== frame
);
3640 std::string user_agent_override_for_url
=
3641 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3642 if (!user_agent_override_for_url
.empty())
3643 return WebString::fromUTF8(user_agent_override_for_url
);
3645 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3646 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3647 return blink::WebString();
3650 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3651 // associated with it, so the checks below are not valid. Temporarily
3652 // return early and fix properly as part of https://crbug.com/426555.
3653 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3654 return blink::WebString();
3656 // If we're in the middle of committing a load, the data source we need
3657 // will still be provisional.
3658 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3659 WebDataSource
* data_source
= NULL
;
3660 if (main_frame
->provisionalDataSource())
3661 data_source
= main_frame
->provisionalDataSource();
3663 data_source
= main_frame
->dataSource();
3665 InternalDocumentStateData
* internal_data
= data_source
?
3666 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3667 if (internal_data
&& internal_data
->is_overriding_user_agent())
3668 return WebString::fromUTF8(
3669 render_view_
->renderer_preferences_
.user_agent_override
);
3670 return blink::WebString();
3673 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3674 DCHECK(!frame_
|| frame_
== frame
);
3675 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3676 return WebString::fromUTF8("1");
3680 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3681 bool default_value
) {
3682 DCHECK(!frame_
|| frame_
== frame
);
3686 bool blocked
= true;
3687 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3688 render_view_
->GetRoutingID(),
3689 GURL(frame
->top()->securityOrigin().toString()),
3690 THREE_D_API_TYPE_WEBGL
,
3695 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3696 int arb_robustness_status_code
) {
3697 DCHECK(!frame_
|| frame_
== frame
);
3698 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3699 GURL(frame
->top()->securityOrigin().toString()),
3700 THREE_D_API_TYPE_WEBGL
,
3701 arb_robustness_status_code
));
3704 blink::WebScreenOrientationClient
*
3705 RenderFrameImpl::webScreenOrientationClient() {
3706 if (!screen_orientation_dispatcher_
)
3707 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3708 return screen_orientation_dispatcher_
;
3711 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3712 ServiceWorkerNetworkProvider
* provider
=
3713 ServiceWorkerNetworkProvider::FromDocumentState(
3714 DocumentState::FromDataSource(&data_source
));
3715 if (!provider
->context())
3717 return provider
->context()->controller_handle_id() !=
3718 kInvalidServiceWorkerHandleId
;
3721 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3722 ServiceWorkerNetworkProvider
* provider
=
3723 ServiceWorkerNetworkProvider::FromDocumentState(
3724 DocumentState::FromDataSource(&data_source
));
3725 if (provider
->context() && provider
->context()->controller())
3726 return provider
->context()->controller()->version_id();
3727 return kInvalidServiceWorkerVersionId
;
3730 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3731 blink::WebAXEvent event
) {
3732 HandleWebAccessibilityEvent(obj
, event
);
3735 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3738 const blink::WebAXObject
& start_object
,
3740 const blink::WebAXObject
& end_object
,
3742 if (renderer_accessibility_
) {
3743 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3744 identifier
, match_index
, start_object
, start_offset
,
3745 end_object
, end_offset
);
3749 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3750 DCHECK(!frame_
|| frame_
== frame
);
3752 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3755 bool RenderFrameImpl::enterFullscreen() {
3756 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3760 bool RenderFrameImpl::exitFullscreen() {
3761 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3765 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3766 if (!permission_client_
)
3767 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3769 return permission_client_
.get();
3772 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3773 if (!app_banner_client_
) {
3774 app_banner_client_
=
3775 GetContentClient()->renderer()->CreateAppBannerClient(this);
3778 return app_banner_client_
.get();
3781 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3783 const WebString
& title
) {
3784 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3785 Send(new FrameHostMsg_RegisterProtocolHandler(
3787 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3793 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3794 const WebURL
& url
) {
3795 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3796 Send(new FrameHostMsg_UnregisterProtocolHandler(
3798 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3803 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3805 bluetooth_
.reset(new WebBluetoothImpl(
3806 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3809 return bluetooth_
.get();
3812 #if defined(ENABLE_WEBVR)
3813 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3814 if (!vr_dispatcher_
)
3815 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3817 return vr_dispatcher_
.get();
3821 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3822 Send(new FrameHostMsg_MediaPlayingNotification(
3823 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3824 player
->hasAudio(), player
->isRemote()));
3827 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3828 Send(new FrameHostMsg_MediaPausedNotification(
3829 routing_id_
, reinterpret_cast<int64
>(player
)));
3832 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3836 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3837 observers_
.AddObserver(observer
);
3840 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3841 observer
->RenderFrameGone();
3842 observers_
.RemoveObserver(observer
);
3845 void RenderFrameImpl::OnStop() {
3847 frame_
->stopLoading();
3848 if (!frame_
->parent())
3849 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3851 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3854 void RenderFrameImpl::WasHidden() {
3855 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3858 void RenderFrameImpl::WasShown() {
3859 // TODO(kenrb): Need to figure out how to do this better. Should
3860 // VisibilityState remain a page-level concept or move to frames?
3861 // The semantics of 'Show' might have to change here.
3862 if (render_widget_
) {
3863 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3864 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3866 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3869 void RenderFrameImpl::WidgetWillClose() {
3870 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3873 bool RenderFrameImpl::IsHidden() {
3874 return GetRenderWidget()->is_hidden();
3877 // Tell the embedding application that the URL of the active page has changed.
3878 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3879 blink::WebFrame
* frame
,
3880 blink::WebHistoryCommitType commit_type
,
3881 const blink::WebHistoryItem
& item
) {
3882 DCHECK(!frame_
|| frame_
== frame
);
3883 WebDataSource
* ds
= frame
->dataSource();
3886 const WebURLRequest
& request
= ds
->request();
3887 const WebURLResponse
& response
= ds
->response();
3889 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3890 NavigationStateImpl
* navigation_state
=
3891 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3892 InternalDocumentStateData
* internal_data
=
3893 InternalDocumentStateData::FromDocumentState(document_state
);
3895 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3896 params
.http_status_code
= response
.httpStatusCode();
3897 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3898 params
.is_post
= false;
3899 params
.intended_as_new_entry
=
3900 navigation_state
->request_params().intended_as_new_entry
;
3901 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3902 params
.post_id
= -1;
3903 params
.page_id
= render_view_
->page_id_
;
3904 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3905 // We need to track the RenderViewHost routing_id because of downstream
3906 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3907 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3908 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3909 // based on the ID stored in the resource requests. Once those dependencies
3910 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3911 // client to be based on the routing_id of the RenderFrameHost.
3912 params
.render_view_routing_id
= render_view_
->routing_id();
3913 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3914 params
.socket_address
.set_port(response
.remotePort());
3915 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3917 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3918 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3919 params
.security_info
= response
.securityInfo();
3921 // Set the URL to be displayed in the browser UI to the user.
3922 params
.url
= GetLoadingUrl();
3923 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3925 // Set the origin of the frame. This will be replicated to the corresponding
3926 // RenderFrameProxies in other processes.
3927 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3928 // to https://crbug.com/439608 and will be replicated as unique origins.
3929 if (!is_swapped_out_
) {
3930 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3931 if (url::IsStandard(scheme
.c_str(),
3932 url::Component(0, static_cast<int>(scheme
.length())))) {
3933 params
.origin
= frame
->document().securityOrigin();
3937 if (frame
->document().baseURL() != params
.url
)
3938 params
.base_url
= frame
->document().baseURL();
3940 GetRedirectChain(ds
, ¶ms
.redirects
);
3941 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3942 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3944 params
.searchable_form_url
= internal_data
->searchable_form_url();
3945 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3947 params
.gesture
= render_view_
->navigation_gesture_
;
3948 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3950 // Make navigation state a part of the DidCommitProvisionalLoad message so
3951 // that committed entry has it at all times.
3952 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3953 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
3954 switches::kSitePerProcess
)) {
3956 params
.page_state
= HistoryEntryToPageState(entry
);
3958 params
.page_state
= PageState::CreateFromURL(request
.url());
3960 // In --site-per-process, just send a single HistoryItem for this frame,
3961 // rather than the whole tree. It will be stored in the corresponding
3962 // FrameNavigationEntry.
3963 params
.page_state
= SingleHistoryItemToPageState(item
);
3965 params
.item_sequence_number
= item
.itemSequenceNumber();
3966 params
.document_sequence_number
= item
.documentSequenceNumber();
3968 if (!frame
->parent()) {
3969 // Top-level navigation.
3971 // Reset the zoom limits in case a plugin had changed them previously. This
3972 // will also call us back which will cause us to send a message to
3973 // update WebContentsImpl.
3974 render_view_
->webview()->zoomLimitsChanged(
3975 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3976 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3978 // Set zoom level, but don't do it for full-page plugin since they don't use
3979 // the same zoom settings.
3980 HostZoomLevels::iterator host_zoom
=
3981 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3982 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3983 // Reset the zoom levels for plugins.
3984 render_view_
->webview()->setZoomLevel(0);
3986 // If the zoom level is not found, then do nothing. In-page navigation
3987 // relies on not changing the zoom level in this case.
3988 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3989 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3992 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3993 // This zoom level was merely recorded transiently for this load. We can
3994 // erase it now. If at some point we reload this page, the browser will
3995 // send us a new, up-to-date zoom level.
3996 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3999 // Update contents MIME type for main frame.
4000 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4002 params
.transition
= navigation_state
->GetTransitionType();
4003 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4004 // If the main frame does a load, it should not be reported as a subframe
4005 // navigation. This can occur in the following case:
4006 // 1. You're on a site with frames.
4007 // 2. You do a subframe navigation. This is stored with transition type
4009 // 3. You navigate to some non-frame site, say, google.com.
4010 // 4. You navigate back to the page from step 2. Since it was initially
4011 // MANUAL_SUBFRAME, it will be that same transition type here.
4012 // We don't want that, because any navigation that changes the toplevel
4013 // frame should be tracked as a toplevel navigation (this allows us to
4014 // update the URL bar, etc).
4015 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4018 // If the page contained a client redirect (meta refresh, document.loc...),
4019 // set the referrer and transition appropriately.
4020 if (ds
->isClientRedirect()) {
4022 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4023 params
.transition
= ui::PageTransitionFromInt(
4024 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4026 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4027 frame
, ds
->request());
4030 base::string16 method
= request
.httpMethod();
4031 if (base::EqualsASCII(method
, "POST")) {
4032 params
.is_post
= true;
4033 params
.post_id
= ExtractPostId(entry
);
4036 // Send the user agent override back.
4037 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4039 // Track the URL of the original request. We use the first entry of the
4040 // redirect chain if it exists because the chain may have started in another
4042 params
.original_request_url
= GetOriginalRequestURL(ds
);
4044 params
.history_list_was_cleared
=
4045 navigation_state
->request_params().should_clear_history_list
;
4047 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4048 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4049 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4050 frame
->dataSource()->request().uiStartTime());
4052 // Save some histogram data so we can compute the average memory used per
4053 // page load of the glyphs.
4054 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4055 blink::WebGlyphCache::pageCount());
4057 // This message needs to be sent before any of allowScripts(),
4058 // allowImages(), allowPlugins() is called for the new page, so that when
4059 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4060 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4061 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4063 // Subframe navigation: the type depends on whether this navigation
4064 // generated a new session history entry. When they do generate a session
4065 // history entry, it means the user initiated the navigation and we should
4067 if (commit_type
== blink::WebStandardCommit
)
4068 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4070 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4072 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4073 params
.history_list_was_cleared
= false;
4074 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4076 // Don't send this message while the subframe is swapped out.
4077 if (!is_swapped_out())
4078 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4081 // If we end up reusing this WebRequest (for example, due to a #ref click),
4082 // we don't want the transition type to persist. Just clear it.
4083 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4086 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4087 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4089 render_view_
->FrameDidStartLoading(frame_
);
4090 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4093 void RenderFrameImpl::didStopLoading() {
4094 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4096 render_view_
->FrameDidStopLoading(frame_
);
4097 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4100 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4101 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4104 void RenderFrameImpl::HandleWebAccessibilityEvent(
4105 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4106 if (renderer_accessibility_
)
4107 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4110 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4111 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4114 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4115 if (renderer_accessibility())
4116 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4120 void RenderFrameImpl::OnCommitNavigation(
4121 const ResourceResponseHead
& response
,
4122 const GURL
& stream_url
,
4123 const CommonNavigationParams
& common_params
,
4124 const RequestNavigationParams
& request_params
) {
4125 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4126 switches::kEnableBrowserSideNavigation
));
4127 // This will override the url requested by the WebURLLoader, as well as
4128 // provide it with the response to the request.
4129 scoped_ptr
<StreamOverrideParameters
> stream_override(
4130 new StreamOverrideParameters());
4131 stream_override
->stream_url
= stream_url
;
4132 stream_override
->response
= response
;
4134 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4135 stream_override
.Pass());
4138 void RenderFrameImpl::OnFailedNavigation(
4139 const CommonNavigationParams
& common_params
,
4140 const RequestNavigationParams
& request_params
,
4141 bool has_stale_copy_in_cache
,
4143 bool is_reload
= IsReload(common_params
.navigation_type
);
4144 bool is_history_navigation
= request_params
.page_state
.IsValid();
4145 WebURLRequest::CachePolicy cache_policy
=
4146 WebURLRequest::UseProtocolCachePolicy
;
4147 RenderFrameImpl::PrepareRenderViewForNavigation(
4148 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4150 GetContentClient()->SetActiveURL(common_params
.url
);
4152 pending_navigation_params_
.reset(new NavigationParams(
4153 common_params
, StartNavigationParams(), request_params
));
4155 // Inform the browser of the start of the provisional load. This is needed so
4156 // that the load is properly tracked by the WebNavigation API.
4157 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4158 routing_id_
, common_params
.url
));
4160 // Send the provisional load failure.
4161 blink::WebURLError error
=
4162 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4163 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4164 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4165 frame_
->isViewSourceModeEnabled());
4166 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4168 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4169 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4170 // http://crbug.com/501960
4171 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4175 // Make sure errors are not shown in view source mode.
4176 frame_
->enableViewSourceMode(false);
4178 // Replace the current history entry in reloads, history navigations and loads
4179 // of the same url. This corresponds to Blink's notion of a standard
4181 // TODO(clamy): see if initial commits in subframes should be handled
4183 bool replace
= is_reload
|| is_history_navigation
||
4184 common_params
.url
== GetLoadingUrl();
4185 LoadNavigationErrorPage(failed_request
, error
, replace
);
4188 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4189 RenderFrame
* render_frame
,
4190 const NavigationPolicyInfo
& info
) {
4191 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4193 const base::CommandLine
& command_line
=
4194 *base::CommandLine::ForCurrentProcess();
4196 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe_
) {
4197 // There's no reason to ignore navigations on subframes, since the swap out
4198 // logic no longer applies.
4200 if (is_swapped_out_
) {
4201 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4202 // Targeted links may try to navigate a swapped out frame. Allow the
4203 // browser process to navigate the tab instead. Note that it is also
4204 // possible for non-targeted navigations (from this view) to arrive
4205 // here just after we are swapped out. It's ok to send them to the
4206 // browser, as long as they're for the top level frame.
4207 // TODO(creis): Ensure this supports targeted form submissions when
4208 // fixing http://crbug.com/101395.
4209 if (info
.frame
->parent() == NULL
) {
4210 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4211 info
.defaultPolicy
);
4212 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4215 // We should otherwise ignore in-process iframe navigations, if they
4216 // arrive just after we are swapped out.
4217 return blink::WebNavigationPolicyIgnore
;
4220 // Allow kSwappedOutURL to complete.
4221 return info
.defaultPolicy
;
4225 // Webkit is asking whether to navigate to a new URL.
4226 // This is fine normally, except if we're showing UI from one security
4227 // context and they're trying to navigate to a different context.
4228 const GURL
& url
= info
.urlRequest
.url();
4230 // A content initiated navigation may have originated from a link-click,
4231 // script, drag-n-drop operation, etc.
4232 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4233 bool is_content_initiated
=
4234 document_state
->navigation_state()->IsContentInitiated();
4236 // If the browser is interested, then give it a chance to look at the request.
4237 if (is_content_initiated
) {
4239 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4240 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4241 base::EqualsASCII(base::StringPiece16(info
.urlRequest
.httpMethod()),
4243 bool browser_handles_request
=
4244 render_view_
->renderer_preferences_
4245 .browser_handles_non_local_top_level_requests
4246 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4248 if (!browser_handles_request
) {
4249 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4250 render_view_
->renderer_preferences_
4251 .browser_handles_all_top_level_requests
;
4254 if (browser_handles_request
) {
4255 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4256 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4260 // Use the frame's original request's URL rather than the document's URL for
4261 // subsequent checks. For a popup, the document's URL may become the opener
4262 // window's URL if the opener has called document.write().
4263 // See http://crbug.com/93517.
4264 GURL
old_url(info
.frame
->dataSource()->request().url());
4266 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4267 // an extension or app origin, leaving a WebUI page, etc). We only care about
4268 // top-level navigations (not iframes). But we sometimes navigate to
4269 // about:blank to clear a tab, and we want to still allow that.
4271 // Note: this is known to break POST submissions when crossing process
4272 // boundaries until http://crbug.com/101395 is fixed. This is better for
4273 // security than loading a WebUI, extension or app page in the wrong process.
4274 // POST requests don't work because this mechanism does not preserve form
4275 // POST data. We will need to send the request's httpBody data up to the
4276 // browser process, and issue a special POST navigation in WebKit (via
4277 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4278 // for examples of how to send the httpBody data.
4279 if (!info
.frame
->parent() && is_content_initiated
&&
4280 !url
.SchemeIs(url::kAboutScheme
)) {
4281 bool send_referrer
= false;
4283 // All navigations to or from WebUI URLs or within WebUI-enabled
4284 // RenderProcesses must be handled by the browser process so that the
4285 // correct bindings and data sources can be registered.
4286 // Similarly, navigations to view-source URLs or within ViewSource mode
4287 // must be handled by the browser process (except for reloads - those are
4288 // safe to leave within the renderer).
4289 // Lastly, access to file:// URLs from non-file:// URL pages must be
4290 // handled by the browser so that ordinary renderer processes don't get
4291 // blessed with file permissions.
4292 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4293 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4294 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4295 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4296 url
.SchemeIs(kViewSourceScheme
) ||
4297 (info
.frame
->isViewSourceModeEnabled() &&
4298 info
.navigationType
!= blink::WebNavigationTypeReload
);
4300 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4301 // Fork non-file to file opens. Check the opener URL if this is the
4302 // initial navigation in a newly opened window.
4303 GURL
source_url(old_url
);
4304 if (is_initial_navigation
&& source_url
.is_empty() &&
4305 info
.frame
->opener())
4306 source_url
= info
.frame
->opener()->top()->document().url();
4307 DCHECK(!source_url
.is_empty());
4308 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4312 // Give the embedder a chance.
4313 should_fork
= GetContentClient()->renderer()->ShouldFork(
4314 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4315 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4319 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4320 info
.defaultPolicy
);
4321 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4325 // Detect when a page is "forking" a new tab that can be safely rendered in
4326 // its own process. This is done by sites like Gmail that try to open links
4327 // in new windows without script connections back to the original page. We
4328 // treat such cases as browser navigations (in which we will create a new
4329 // renderer for a cross-site navigation), rather than WebKit navigations.
4331 // We use the following heuristic to decide whether to fork a new page in its
4333 // The parent page must open a new tab to about:blank, set the new tab's
4334 // window.opener to null, and then redirect the tab to a cross-site URL using
4337 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4340 // Must start from a tab showing about:blank, which is later redirected.
4341 old_url
== GURL(url::kAboutBlankURL
) &&
4342 // Must be the first real navigation of the tab.
4343 render_view_
->historyBackListCount() < 1 &&
4344 render_view_
->historyForwardListCount() < 1 &&
4345 // The parent page must have set the child's window.opener to null before
4346 // redirecting to the desired URL.
4347 info
.frame
->opener() == NULL
&&
4348 // Must be a top-level frame.
4349 info
.frame
->parent() == NULL
&&
4350 // Must not have issued the request from this page.
4351 is_content_initiated
&&
4352 // Must be targeted at the current tab.
4353 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4354 // Must be a JavaScript navigation, which appears as "other".
4355 info
.navigationType
== blink::WebNavigationTypeOther
;
4358 // Open the URL via the browser, not via WebKit.
4359 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4360 return blink::WebNavigationPolicyIgnore
;
4363 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4364 // This includes navigations with no request being sent to the network stack.
4365 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4366 switches::kEnableBrowserSideNavigation
) &&
4367 info
.urlRequest
.checkForBrowserSideNavigation() &&
4368 ShouldMakeNetworkRequestForURL(url
)) {
4369 BeginNavigation(&info
.urlRequest
);
4370 return blink::WebNavigationPolicyIgnore
;
4373 return info
.defaultPolicy
;
4376 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4378 const Referrer
& referrer
,
4379 WebNavigationPolicy policy
) {
4380 DCHECK_EQ(frame_
, frame
);
4382 FrameHostMsg_OpenURL_Params params
;
4384 params
.referrer
= referrer
;
4385 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4386 WebDataSource
* ds
= frame
->provisionalDataSource();
4388 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4389 NavigationStateImpl
* navigation_state
=
4390 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4391 if (navigation_state
->IsContentInitiated()) {
4392 params
.should_replace_current_entry
=
4393 ds
->replacesCurrentHistoryItem() &&
4394 render_view_
->history_list_length_
;
4396 // This is necessary to preserve the should_replace_current_entry value on
4397 // cross-process redirects, in the event it was set by a previous process.
4399 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4400 // NavigationState::should_replace_current_entry().
4401 params
.should_replace_current_entry
=
4402 navigation_state
->common_params().should_replace_current_entry
;
4405 params
.should_replace_current_entry
= false;
4407 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4408 if (GetContentClient()->renderer()->AllowPopup())
4409 params
.user_gesture
= true;
4411 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4412 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4413 policy
== blink::WebNavigationPolicyNewWindow
||
4414 policy
== blink::WebNavigationPolicyNewPopup
) {
4415 WebUserGestureIndicator::consumeUserGesture();
4418 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4421 void RenderFrameImpl::NavigateInternal(
4422 const CommonNavigationParams
& common_params
,
4423 const StartNavigationParams
& start_params
,
4424 const RequestNavigationParams
& request_params
,
4425 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4426 bool browser_side_navigation
=
4427 base::CommandLine::ForCurrentProcess()->HasSwitch(
4428 switches::kEnableBrowserSideNavigation
);
4429 bool is_reload
= IsReload(common_params
.navigation_type
);
4430 bool is_history_navigation
= request_params
.page_state
.IsValid();
4431 WebURLRequest::CachePolicy cache_policy
=
4432 WebURLRequest::UseProtocolCachePolicy
;
4433 RenderFrameImpl::PrepareRenderViewForNavigation(
4434 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4436 GetContentClient()->SetActiveURL(common_params
.url
);
4438 // If this frame isn't in the same process as the main frame, it may naively
4439 // assume that this is the first navigation in the iframe, but this may not
4440 // actually be the case. Inform the frame's state machine if this frame has
4441 // already committed other loads.
4442 if (request_params
.has_committed_real_load
&& frame_
->parent())
4443 frame_
->setCommittedFirstRealLoad();
4445 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4446 // We cannot reload if we do not have any history state. This happens, for
4447 // example, when recovering from a crash.
4449 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4452 pending_navigation_params_
.reset(
4453 new NavigationParams(common_params
, start_params
, request_params
));
4455 // Create parameters for a standard navigation.
4456 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4457 bool should_load_request
= false;
4458 WebHistoryItem item_for_history_navigation
;
4459 WebURLRequest request
= CreateURLRequestForNavigation(
4460 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4462 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4463 // navigation for this request (since it already went to the browser).
4464 if (browser_side_navigation
)
4465 request
.setCheckForBrowserSideNavigation(false);
4467 // If we are reloading, then use the history state of the current frame.
4468 // Otherwise, if we have history state, then we need to navigate to it, which
4469 // corresponds to a back/forward navigation event. Update the parameters
4470 // depending on the navigation type.
4472 bool ignore_cache
= (common_params
.navigation_type
==
4473 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4474 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4475 : blink::WebFrameLoadType::Reload
;
4477 if (!browser_side_navigation
) {
4478 const GURL override_url
=
4479 (common_params
.navigation_type
==
4480 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4483 request
= frame_
->requestForReload(load_type
, override_url
);
4485 should_load_request
= true;
4486 } else if (is_history_navigation
) {
4487 // We must know the page ID of the page we are navigating back to.
4488 DCHECK_NE(request_params
.page_id
, -1);
4489 // We must know the nav entry ID of the page we are navigating back to,
4490 // which should be the case because history navigations are routed via the
4492 DCHECK_NE(0, request_params
.nav_entry_id
);
4493 scoped_ptr
<HistoryEntry
> entry
=
4494 PageStateToHistoryEntry(request_params
.page_state
);
4496 // Ensure we didn't save the swapped out URL in UpdateState, since the
4497 // browser should never be telling us to navigate to swappedout://.
4498 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4500 if (!browser_side_navigation
) {
4501 scoped_ptr
<NavigationParams
> navigation_params(
4502 new NavigationParams(*pending_navigation_params_
.get()));
4503 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
4504 switches::kSitePerProcess
)) {
4505 // By default, tell the HistoryController to go the deserialized
4506 // HistoryEntry. This only works if all frames are in the same
4508 DCHECK(!frame_
->parent());
4509 render_view_
->history_controller()->GoToEntry(
4510 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4512 // In --site-per-process, the browser process sends a single
4513 // WebHistoryItem destined for this frame.
4514 // TODO(creis): Change PageState to FrameState. In the meantime, we
4515 // store the relevant frame's WebHistoryItem in the root of the
4517 SetPendingNavigationParams(navigation_params
.Pass());
4518 blink::WebHistoryItem history_item
= entry
->root();
4519 blink::WebHistoryLoadType load_type
=
4520 request_params
.is_same_document_history_load
4521 ? blink::WebHistorySameDocumentLoad
4522 : blink::WebHistoryDifferentDocumentLoad
;
4524 // Let the history controller know the provisional entry, since it is
4525 // used at commit time. Otherwise skip GoToEntry and navigate the
4527 // TODO(creis): Consider cloning the current entry to handle subframe
4528 // cases. Changes to SendUpdateState might affect this.
4529 render_view_
->history_controller()->set_provisional_entry(
4531 WebURLRequest request
=
4532 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4533 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4534 history_item
, load_type
);
4537 // TODO(clamy): this should be set to the HistoryItem sent by the
4538 // browser once the HistoryController has moved to the browser.
4539 // TODO(clamy): distinguish between different document and same document
4541 // TODO(clamy): update this for subframes history loads.
4542 item_for_history_navigation
=
4543 entry
->GetHistoryNodeForFrame(this)->item();
4544 load_type
= blink::WebFrameLoadType::BackForward
;
4545 should_load_request
= true;
4549 // Navigate to the given URL.
4550 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4551 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4552 start_params
.extra_headers
.end(),
4555 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4556 WebString::fromUTF8(i
.values()));
4560 if (start_params
.is_post
&& !browser_side_navigation
) {
4561 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4564 WebHTTPBody http_body
;
4565 http_body
.initialize();
4566 const char* data
= nullptr;
4567 if (start_params
.browser_initiated_post_data
.size()) {
4568 data
= reinterpret_cast<const char*>(
4569 &start_params
.browser_initiated_post_data
.front());
4571 http_body
.appendData(
4572 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4573 request
.setHTTPBody(http_body
);
4576 // A session history navigation should have been accompanied by state.
4577 CHECK_EQ(request_params
.page_id
, -1);
4579 should_load_request
= true;
4582 if (should_load_request
) {
4583 // Record this before starting the load. We need a lower bound of this
4584 // time to sanitize the navigationStart override set below.
4585 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4587 // Perform a navigation to a data url if needed.
4588 if (!common_params
.base_url_for_data_url
.is_empty() ||
4589 (browser_side_navigation
&&
4590 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4591 LoadDataURL(common_params
, frame_
);
4593 // Load the request.
4594 frame_
->toWebLocalFrame()->load(request
, load_type
,
4595 item_for_history_navigation
);
4598 if (load_type
== blink::WebFrameLoadType::Standard
) {
4599 UpdateFrameNavigationTiming(frame_
,
4600 request_params
.browser_navigation_start
,
4601 renderer_navigation_start
);
4605 // In case LoadRequest failed before didCreateDataSource was called.
4606 pending_navigation_params_
.reset();
4609 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4610 const std::string
& encoding_name
) {
4611 // Only update main frame's encoding_name.
4612 if (!frame
->parent())
4613 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4616 void RenderFrameImpl::SyncSelectionIfRequired() {
4617 base::string16 text
;
4620 #if defined(ENABLE_PLUGINS)
4621 if (render_view_
->focused_pepper_plugin_
) {
4622 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4623 offset
= 0; // Pepper API does not support offset reporting.
4624 // TODO(kinaba): cut as needed.
4628 size_t location
, length
;
4629 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4630 &location
, &length
)) {
4634 range
= gfx::Range(location
, location
+ length
);
4636 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4637 blink::WebTextInputTypeNone
) {
4638 // If current focused element is editable, we will send 100 more chars
4639 // before and after selection. It is for input method surrounding text
4641 if (location
> kExtraCharsBeforeAndAfterSelection
)
4642 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4645 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4646 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4647 if (!webrange
.isNull())
4648 text
= webrange
.toPlainText();
4651 text
= frame_
->selectionAsText();
4652 // http://crbug.com/101435
4653 // In some case, frame->selectionAsText() returned text's length is not
4654 // equal to the length returned from webwidget()->caretOrSelectionRange().
4655 // So we have to set the range according to text.length().
4656 range
.set_end(range
.start() + text
.length());
4660 // Sometimes we get repeated didChangeSelection calls from webkit when
4661 // the selection hasn't actually changed. We don't want to report these
4662 // because it will cause us to continually claim the X clipboard.
4663 if (selection_text_offset_
!= offset
||
4664 selection_range_
!= range
||
4665 selection_text_
!= text
) {
4666 selection_text_
= text
;
4667 selection_text_offset_
= offset
;
4668 selection_range_
= range
;
4669 SetSelectedText(text
, offset
, range
);
4671 GetRenderWidget()->UpdateSelectionBounds();
4674 void RenderFrameImpl::InitializeUserMediaClient() {
4675 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4678 #if defined(OS_ANDROID)
4679 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4680 switches::kDisableWebRTC
))
4684 #if defined(ENABLE_WEBRTC)
4685 DCHECK(!web_user_media_client_
);
4686 web_user_media_client_
= new UserMediaClientImpl(
4688 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4689 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4693 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4694 WebMediaPlayerClient
* client
) {
4695 #if defined(ENABLE_WEBRTC)
4696 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4698 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4699 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4700 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4701 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4702 new RenderMediaLog(),
4703 CreateRendererFactory());
4706 #endif // defined(ENABLE_WEBRTC)
4709 scoped_ptr
<MediaStreamRendererFactory
>
4710 RenderFrameImpl::CreateRendererFactory() {
4711 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4712 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4714 return factory
.Pass();
4715 #if defined(ENABLE_WEBRTC)
4716 return scoped_ptr
<MediaStreamRendererFactory
>(
4717 new MediaStreamRendererFactoryImpl());
4719 return scoped_ptr
<MediaStreamRendererFactory
>(
4720 static_cast<MediaStreamRendererFactory
*>(NULL
));
4724 void RenderFrameImpl::PrepareRenderViewForNavigation(
4726 const RequestNavigationParams
& request_params
,
4728 WebURLRequest::CachePolicy
* cache_policy
) {
4729 DCHECK(render_view_
->webview());
4731 MaybeHandleDebugURL(url
);
4734 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4736 render_view_
->history_list_offset_
=
4737 request_params
.current_history_list_offset
;
4738 render_view_
->history_list_length_
=
4739 request_params
.current_history_list_length
;
4740 if (request_params
.should_clear_history_list
) {
4741 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4742 CHECK_EQ(0, render_view_
->history_list_length_
);
4745 if (!is_swapped_out_
|| frame_
->parent())
4748 // This is a swapped out main frame, so swap the renderer back in.
4749 // We marked the view as hidden when swapping the view out, so be sure to
4750 // reset the visibility state before navigating to the new URL.
4751 render_view_
->webview()->setVisibilityState(
4752 render_view_
->visibilityState(), false);
4754 // If this is an attempt to reload while we are swapped out, we should not
4755 // reload swappedout://, but the previous page, which is stored in
4756 // params.state. Setting is_reload to false will treat this like a back
4757 // navigation to accomplish that.
4759 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4761 // We refresh timezone when a view is swapped in since timezone
4762 // can get out of sync when the system timezone is updated while
4763 // the view is swapped out.
4764 RenderThreadImpl::NotifyTimezoneChange();
4766 render_view_
->SetSwappedOut(false);
4767 is_swapped_out_
= false;
4771 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4772 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4773 switches::kEnableBrowserSideNavigation
));
4775 // TODO(clamy): Execute the beforeunload event.
4777 // Note: At this stage, the goal is to apply all the modifications the
4778 // renderer wants to make to the request, and then send it to the browser, so
4779 // that the actual network request can be started. Ideally, all such
4780 // modifications should take place in willSendRequest, and in the
4781 // implementation of willSendRequest for the various InspectorAgents
4784 // TODO(clamy): Apply devtools override.
4785 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4787 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4789 // TODO(clamy): Same-document navigations should not be sent back to the
4791 // TODO(clamy): Data urls should not be sent back to the browser either.
4792 bool should_replace_current_entry
= false;
4793 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4794 WebDataSource
* current_data_source
= frame_
->dataSource();
4795 WebDataSource
* data_source
=
4796 provisional_data_source
? provisional_data_source
: current_data_source
;
4798 // The current entry can only be replaced if there already is an entry in the
4800 if (data_source
&& render_view_
->history_list_length_
> 0) {
4801 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4803 Send(new FrameHostMsg_BeginNavigation(
4805 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4806 BeginNavigationParams(
4807 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4808 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4809 GetRequestBodyForWebURLRequest(*request
)));
4812 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4814 // A loadData request with a specified base URL.
4815 std::string mime_type
, charset
, data
;
4816 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4817 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4818 params
.url
: params
.base_url_for_data_url
;
4820 WebData(data
.c_str(), data
.length()),
4821 WebString::fromUTF8(mime_type
),
4822 WebString::fromUTF8(charset
),
4824 params
.history_url_for_data_url
,
4827 CHECK(false) << "Invalid URL passed: "
4828 << params
.url
.possibly_invalid_spec();
4832 void RenderFrameImpl::SendFailedProvisionalLoad(
4833 const blink::WebURLRequest
& request
,
4834 const blink::WebURLError
& error
,
4835 blink::WebLocalFrame
* frame
) {
4836 bool show_repost_interstitial
=
4837 (error
.reason
== net::ERR_CACHE_MISS
&&
4838 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4840 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4841 params
.error_code
= error
.reason
;
4842 GetContentClient()->renderer()->GetNavigationErrorStrings(
4843 render_view_
.get(), frame
, request
, error
, NULL
,
4844 ¶ms
.error_description
);
4845 params
.url
= error
.unreachableURL
;
4846 params
.showing_repost_interstitial
= show_repost_interstitial
;
4847 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4848 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4851 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4853 const GURL
& unreachable_url
) {
4854 // Don't display an error page if this is simply a cancelled load. Aside
4855 // from being dumb, Blink doesn't expect it and it will cause a crash.
4856 if (error_code
== net::ERR_ABORTED
)
4859 // Don't display "client blocked" error page if browser has asked us not to.
4860 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4861 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4865 // Allow the embedder to suppress an error page.
4866 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4867 this, unreachable_url
)) {
4871 if (RenderThreadImpl::current() &&
4872 RenderThreadImpl::current()->layout_test_mode()) {
4879 GURL
RenderFrameImpl::GetLoadingUrl() const {
4880 WebDataSource
* ds
= frame_
->dataSource();
4881 if (ds
->hasUnreachableURL())
4882 return ds
->unreachableURL();
4884 const WebURLRequest
& request
= ds
->request();
4885 return request
.url();
4888 void RenderFrameImpl::PopulateDocumentStateFromPending(
4889 DocumentState
* document_state
) {
4890 document_state
->set_request_time(
4891 pending_navigation_params_
->request_params
.request_time
);
4893 InternalDocumentStateData
* internal_data
=
4894 InternalDocumentStateData::FromDocumentState(document_state
);
4896 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4897 url::kJavaScriptScheme
) &&
4898 pending_navigation_params_
->common_params
.navigation_type
==
4899 FrameMsg_Navigate_Type::RESTORE
) {
4900 // We're doing a load of a page that was restored from the last session. By
4901 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4902 // can result in stale data for pages that are set to expire. We explicitly
4903 // override that by setting the policy here so that as necessary we load
4904 // from the network.
4906 // TODO(davidben): Remove this in favor of passing a cache policy to the
4907 // loadHistoryItem call in OnNavigate. That requires not overloading
4908 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4909 // policy based on load type, etc".
4910 internal_data
->set_cache_policy_override(
4911 WebURLRequest::UseProtocolCachePolicy
);
4914 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4915 document_state
->set_load_type(DocumentState::RELOAD
);
4916 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4917 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4919 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4921 internal_data
->set_is_overriding_user_agent(
4922 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4923 internal_data
->set_must_reset_scroll_and_scale_state(
4924 pending_navigation_params_
->common_params
.navigation_type
==
4925 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4926 document_state
->set_can_load_local_resources(
4927 pending_navigation_params_
->request_params
.can_load_local_resources
);
4930 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4931 // A navigation resulting from loading a javascript URL should not be treated
4932 // as a browser initiated event. Instead, we want it to look as if the page
4933 // initiated any load resulting from JS execution.
4934 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4935 url::kJavaScriptScheme
)) {
4936 return NavigationStateImpl::CreateBrowserInitiated(
4937 pending_navigation_params_
->common_params
,
4938 pending_navigation_params_
->start_params
,
4939 pending_navigation_params_
->request_params
);
4941 return NavigationStateImpl::CreateContentInitiated();
4944 #if defined(OS_ANDROID)
4946 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4947 WebMediaPlayerClient
* client
,
4948 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4949 media::MediaPermission
* media_permission
,
4950 WebContentDecryptionModule
* initial_cdm
) {
4951 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4952 if (SynchronousCompositorFactory
* factory
=
4953 SynchronousCompositorFactory::GetInstance()) {
4954 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4956 GpuChannelHost
* gpu_channel_host
=
4957 RenderThreadImpl::current()->EstablishGpuChannelSync(
4958 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4960 if (!gpu_channel_host
) {
4961 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4965 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4966 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4968 if (!context_provider
.get()) {
4969 LOG(ERROR
) << "Failed to get context3d for media player";
4973 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4974 context_provider
, gpu_channel_host
, routing_id_
);
4977 return new WebMediaPlayerAndroid(
4978 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
4979 GetMediaPlayerManager(), GetCdmFactory(), media_permission
, initial_cdm
,
4980 stream_texture_factory
,
4981 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4982 new RenderMediaLog());
4985 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4986 if (!media_player_manager_
)
4987 media_player_manager_
= new RendererMediaPlayerManager(this);
4988 return media_player_manager_
;
4991 #endif // defined(OS_ANDROID)
4993 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4994 if (!media_permission_dispatcher_
)
4995 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
4996 return media_permission_dispatcher_
;
4999 #if defined(ENABLE_MOJO_MEDIA)
5000 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5001 if (!media_service_factory_
) {
5002 mojo::InterfacePtr
<mojo::Shell
> shell_ptr
;
5003 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr
));
5005 mojo::ServiceProviderPtr service_provider
;
5006 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5007 request
->url
= mojo::String::From("mojo:media");
5008 shell_ptr
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5011 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5013 media_service_factory_
.set_connection_error_handler(
5014 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5015 base::Unretained(this)));
5018 return media_service_factory_
.get();
5021 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5022 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5023 // violation on the old |media_service_factory_| by outstanding
5024 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5026 // media_service_factory_.reset();
5030 bool RenderFrameImpl::AreSecureCodecsSupported() {
5031 #if defined(OS_ANDROID)
5032 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5033 return render_view_
->renderer_preferences_
5034 .use_video_overlay_for_embedded_encrypted_video
;
5037 #endif // defined(OS_ANDROID)
5040 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5041 #if defined(ENABLE_BROWSER_CDMS)
5043 cdm_manager_
= new RendererCdmManager(this);
5044 #endif // defined(ENABLE_BROWSER_CDMS)
5046 if (!cdm_factory_
) {
5049 #if defined(ENABLE_MOJO_MEDIA)
5050 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5052 cdm_factory_
.reset(new RenderCdmFactory(
5053 #if defined(ENABLE_PEPPER_CDMS)
5054 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5055 #elif defined(ENABLE_BROWSER_CDMS)
5059 #endif // defined(ENABLE_MOJO_MEDIA)
5062 return cdm_factory_
.get();
5065 void RenderFrameImpl::RegisterMojoServices() {
5066 // Only main frame have ImageDownloader service.
5067 if (!frame_
->parent()) {
5068 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5069 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5070 base::Unretained(this)));
5074 } // namespace content