1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/time/time.h"
22 #include "cc/base/switches.h"
23 #include "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/permissions/permission_dispatcher.h"
25 #include "content/child/plugin_messages.h"
26 #include "content/child/quota_dispatcher.h"
27 #include "content/child/request_extra_data.h"
28 #include "content/child/service_worker/service_worker_handle_reference.h"
29 #include "content/child/service_worker/service_worker_network_provider.h"
30 #include "content/child/service_worker/service_worker_provider_context.h"
31 #include "content/child/service_worker/web_service_worker_provider_impl.h"
32 #include "content/child/v8_value_converter_impl.h"
33 #include "content/child/web_url_loader_impl.h"
34 #include "content/child/web_url_request_util.h"
35 #include "content/child/webmessageportchannel_impl.h"
36 #include "content/child/websocket_bridge.h"
37 #include "content/child/weburlresponse_extradata_impl.h"
38 #include "content/common/accessibility_messages.h"
39 #include "content/common/clipboard_messages.h"
40 #include "content/common/frame_messages.h"
41 #include "content/common/frame_replication_state.h"
42 #include "content/common/input_messages.h"
43 #include "content/common/navigation_params.h"
44 #include "content/common/service_worker/service_worker_types.h"
45 #include "content/common/site_isolation_policy.h"
46 #include "content/common/swapped_out_messages.h"
47 #include "content/common/view_messages.h"
48 #include "content/public/common/bindings_policy.h"
49 #include "content/public/common/content_constants.h"
50 #include "content/public/common/content_switches.h"
51 #include "content/public/common/context_menu_params.h"
52 #include "content/public/common/isolated_world_ids.h"
53 #include "content/public/common/page_state.h"
54 #include "content/public/common/resource_response.h"
55 #include "content/public/common/url_constants.h"
56 #include "content/public/common/url_utils.h"
57 #include "content/public/renderer/browser_plugin_delegate.h"
58 #include "content/public/renderer/content_renderer_client.h"
59 #include "content/public/renderer/context_menu_client.h"
60 #include "content/public/renderer/document_state.h"
61 #include "content/public/renderer/navigation_state.h"
62 #include "content/public/renderer/render_frame_observer.h"
63 #include "content/public/renderer/renderer_ppapi_host.h"
64 #include "content/renderer/accessibility/renderer_accessibility.h"
65 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
66 #include "content/renderer/browser_plugin/browser_plugin.h"
67 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
68 #include "content/renderer/child_frame_compositing_helper.h"
69 #include "content/renderer/context_menu_params_builder.h"
70 #include "content/renderer/devtools/devtools_agent.h"
71 #include "content/renderer/dom_automation_controller.h"
72 #include "content/renderer/external_popup_menu.h"
73 #include "content/renderer/geolocation_dispatcher.h"
74 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
75 #include "content/renderer/history_controller.h"
76 #include "content/renderer/history_serialization.h"
77 #include "content/renderer/image_downloader/image_downloader_impl.h"
78 #include "content/renderer/ime_event_guard.h"
79 #include "content/renderer/internal_document_state_data.h"
80 #include "content/renderer/manifest/manifest_manager.h"
81 #include "content/renderer/media/audio_renderer_mixer_manager.h"
82 #include "content/renderer/media/crypto/render_cdm_factory.h"
83 #include "content/renderer/media/media_permission_dispatcher.h"
84 #include "content/renderer/media/media_stream_dispatcher.h"
85 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
86 #include "content/renderer/media/midi_dispatcher.h"
87 #include "content/renderer/media/render_media_log.h"
88 #include "content/renderer/media/user_media_client_impl.h"
89 #include "content/renderer/media/webmediaplayer_ms.h"
90 #include "content/renderer/memory_benchmarking_extension.h"
91 #include "content/renderer/mojo/service_registry_js_wrapper.h"
92 #include "content/renderer/navigation_state_impl.h"
93 #include "content/renderer/notification_permission_dispatcher.h"
94 #include "content/renderer/npapi/plugin_channel_host.h"
95 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
96 #include "content/renderer/presentation/presentation_dispatcher.h"
97 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
98 #include "content/renderer/render_frame_proxy.h"
99 #include "content/renderer/render_process.h"
100 #include "content/renderer/render_thread_impl.h"
101 #include "content/renderer/render_view_impl.h"
102 #include "content/renderer/render_widget_fullscreen_pepper.h"
103 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
104 #include "content/renderer/renderer_webcolorchooser_impl.h"
105 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
106 #include "content/renderer/shared_worker_repository.h"
107 #include "content/renderer/skia_benchmarking_extension.h"
108 #include "content/renderer/stats_collection_controller.h"
109 #include "content/renderer/web_ui_extension.h"
110 #include "content/renderer/websharedworker_proxy.h"
111 #include "gin/modules/module_registry.h"
112 #include "media/base/audio_renderer_mixer_input.h"
113 #include "media/base/media_log.h"
114 #include "media/blink/webencryptedmediaclient_impl.h"
115 #include "media/blink/webmediaplayer_impl.h"
116 #include "media/blink/webmediaplayer_params.h"
117 #include "media/renderers/gpu_video_accelerator_factories.h"
118 #include "net/base/data_url.h"
119 #include "net/base/net_errors.h"
120 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
121 #include "net/http/http_util.h"
122 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
123 #include "third_party/WebKit/public/platform/WebString.h"
124 #include "third_party/WebKit/public/platform/WebURL.h"
125 #include "third_party/WebKit/public/platform/WebURLError.h"
126 #include "third_party/WebKit/public/platform/WebURLResponse.h"
127 #include "third_party/WebKit/public/platform/WebVector.h"
128 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
129 #include "third_party/WebKit/public/web/WebDocument.h"
130 #include "third_party/WebKit/public/web/WebFrameWidget.h"
131 #include "third_party/WebKit/public/web/WebGlyphCache.h"
132 #include "third_party/WebKit/public/web/WebKit.h"
133 #include "third_party/WebKit/public/web/WebLocalFrame.h"
134 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
135 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
136 #include "third_party/WebKit/public/web/WebPlugin.h"
137 #include "third_party/WebKit/public/web/WebPluginParams.h"
138 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
139 #include "third_party/WebKit/public/web/WebRange.h"
140 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
141 #include "third_party/WebKit/public/web/WebScriptSource.h"
142 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
143 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
144 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
145 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
146 #include "third_party/WebKit/public/web/WebSettings.h"
147 #include "third_party/WebKit/public/web/WebSurroundingText.h"
148 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
149 #include "third_party/WebKit/public/web/WebView.h"
150 #include "third_party/mojo/src/mojo/edk/js/core.h"
151 #include "third_party/mojo/src/mojo/edk/js/support.h"
152 #include "url/url_util.h"
154 #if defined(ENABLE_PLUGINS)
155 #include "content/renderer/npapi/webplugin_impl.h"
156 #include "content/renderer/pepper/pepper_browser_connection.h"
157 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
158 #include "content/renderer/pepper/pepper_webplugin_impl.h"
159 #include "content/renderer/pepper/plugin_module.h"
162 #if defined(ENABLE_WEBRTC)
163 #include "content/renderer/media/rtc_peer_connection_handler.h"
166 #if defined(OS_ANDROID)
167 #include <cpu-features.h>
169 #include "content/common/gpu/client/context_provider_command_buffer.h"
170 #include "content/renderer/android/synchronous_compositor_factory.h"
171 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
172 #include "content/renderer/media/android/renderer_media_player_manager.h"
173 #include "content/renderer/media/android/stream_texture_factory_impl.h"
174 #include "content/renderer/media/android/webmediaplayer_android.h"
176 #include "cc/blink/context_provider_web_context.h"
179 #if defined(ENABLE_PEPPER_CDMS)
180 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
181 #elif defined(ENABLE_BROWSER_CDMS)
182 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
185 #if defined(ENABLE_MOJO_MEDIA)
186 #include "media/mojo/services/mojo_cdm_factory.h"
187 #include "media/mojo/services/mojo_renderer_factory.h"
188 #include "mojo/application/public/cpp/connect.h"
189 #include "mojo/application/public/interfaces/shell.mojom.h"
190 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
192 #include "media/renderers/default_renderer_factory.h"
195 #if defined(ENABLE_WEBVR)
196 #include "content/renderer/vr/vr_dispatcher.h"
199 using blink::WebContentDecryptionModule
;
200 using blink::WebContextMenuData
;
201 using blink::WebData
;
202 using blink::WebDataSource
;
203 using blink::WebDocument
;
204 using blink::WebDOMEvent
;
205 using blink::WebDOMMessageEvent
;
206 using blink::WebElement
;
207 using blink::WebExternalPopupMenu
;
208 using blink::WebExternalPopupMenuClient
;
209 using blink::WebFrame
;
210 using blink::WebHistoryItem
;
211 using blink::WebHTTPBody
;
212 using blink::WebLocalFrame
;
213 using blink::WebMediaPlayer
;
214 using blink::WebMediaPlayerClient
;
215 using blink::WebMediaPlayerEncryptedMediaClient
;
216 using blink::WebNavigationPolicy
;
217 using blink::WebNavigationType
;
218 using blink::WebNode
;
219 using blink::WebPluginParams
;
220 using blink::WebPopupMenuInfo
;
221 using blink::WebRange
;
222 using blink::WebReferrerPolicy
;
223 using blink::WebScriptSource
;
224 using blink::WebSearchableFormData
;
225 using blink::WebSecurityOrigin
;
226 using blink::WebSecurityPolicy
;
227 using blink::WebSerializedScriptValue
;
228 using blink::WebServiceWorkerProvider
;
229 using blink::WebSettings
;
230 using blink::WebStorageQuotaCallbacks
;
231 using blink::WebString
;
233 using blink::WebURLError
;
234 using blink::WebURLRequest
;
235 using blink::WebURLResponse
;
236 using blink::WebUserGestureIndicator
;
237 using blink::WebVector
;
238 using blink::WebView
;
240 using base::TimeDelta
;
246 const char kDefaultAcceptHeader
[] =
247 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
249 const char kAcceptHeader
[] = "Accept";
251 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
253 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
254 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
255 LAZY_INSTANCE_INITIALIZER
;
257 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
258 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
260 int64
ExtractPostId(HistoryEntry
* entry
) {
264 const WebHistoryItem
& item
= entry
->root();
265 if (item
.isNull() || item
.httpBody().isNull())
268 return item
.httpBody().identifier();
271 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
272 const WebURLResponse
& response
) {
273 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
276 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
277 // Replace any occurrences of swappedout:// with about:blank.
278 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
279 WebVector
<WebURL
> urls
;
280 ds
->redirectChain(urls
);
281 result
->reserve(urls
.size());
282 for (size_t i
= 0; i
< urls
.size(); ++i
) {
283 if (urls
[i
] != GURL(kSwappedOutURL
))
284 result
->push_back(urls
[i
]);
286 result
->push_back(blank_url
);
290 // Returns the original request url. If there is no redirect, the original
291 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
292 // frame was loaded by loadData, the original url will be ds->unreachableURL()
293 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
294 // WebDataSource has unreachable URL means that the frame is loaded through
295 // blink::WebFrame::loadData(), and the base URL will be in the redirect
296 // chain. However, we never visited the baseURL. So in this case, we should
297 // use the unreachable URL as the original URL.
298 if (ds
->hasUnreachableURL())
299 return ds
->unreachableURL();
301 std::vector
<GURL
> redirects
;
302 GetRedirectChain(ds
, &redirects
);
303 if (!redirects
.empty())
304 return redirects
.at(0);
306 return ds
->originalRequest().url();
309 NOINLINE
void CrashIntentionally() {
310 // NOTE(shess): Crash directly rather than using NOTREACHED() so
311 // that the signature is easier to triage in crash reports.
312 volatile int* zero
= NULL
;
316 NOINLINE
void BadCastCrashIntentionally() {
329 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
330 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
331 // NOTE(rogerm): We intentionally perform an invalid heap access here in
332 // order to trigger an Address Sanitizer (ASAN) error report.
333 const char kCrashDomain
[] = "crash";
334 const char kHeapOverflow
[] = "/heap-overflow";
335 const char kHeapUnderflow
[] = "/heap-underflow";
336 const char kUseAfterFree
[] = "/use-after-free";
337 #if defined(SYZYASAN)
338 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
339 const char kCorruptHeap
[] = "/corrupt-heap";
342 if (!url
.DomainIs(kCrashDomain
))
348 std::string
crash_type(url
.path());
349 if (crash_type
== kHeapOverflow
) {
350 base::debug::AsanHeapOverflow();
351 } else if (crash_type
== kHeapUnderflow
) {
352 base::debug::AsanHeapUnderflow();
353 } else if (crash_type
== kUseAfterFree
) {
354 base::debug::AsanHeapUseAfterFree();
355 #if defined(SYZYASAN)
356 } else if (crash_type
== kCorruptHeapBlock
) {
357 base::debug::AsanCorruptHeapBlock();
358 } else if (crash_type
== kCorruptHeap
) {
359 base::debug::AsanCorruptHeap();
363 #endif // ADDRESS_SANITIZER || SYZYASAN
365 void MaybeHandleDebugURL(const GURL
& url
) {
366 if (!url
.SchemeIs(kChromeUIScheme
))
368 if (url
== GURL(kChromeUIBadCastCrashURL
)) {
369 BadCastCrashIntentionally();
370 } else if (url
== GURL(kChromeUICrashURL
)) {
371 CrashIntentionally();
372 } else if (url
== GURL(kChromeUIDumpURL
)) {
373 // This URL will only correctly create a crash dump file if content is
374 // hosted in a process that has correctly called
375 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
376 // of base::debug::DumpWithoutCrashing for more details.
377 base::debug::DumpWithoutCrashing();
378 } else if (url
== GURL(kChromeUIKillURL
)) {
379 base::Process::Current().Terminate(1, false);
380 } else if (url
== GURL(kChromeUIHangURL
)) {
382 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
384 } else if (url
== GURL(kChromeUIShorthangURL
)) {
385 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
388 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
389 MaybeTriggerAsanError(url
);
390 #endif // ADDRESS_SANITIZER || SYZYASAN
393 // Returns false unless this is a top-level navigation.
394 bool IsTopLevelNavigation(WebFrame
* frame
) {
395 return frame
->parent() == NULL
;
398 // Returns false unless this is a top-level navigation that crosses origins.
399 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
401 WebNavigationType type
,
403 if (!IsTopLevelNavigation(frame
))
406 // Navigations initiated within Webkit are not sent out to the external host
407 // in the following cases.
408 // 1. The url scheme is not http/https
409 // 2. The origin of the url and the opener is the same in which case the
410 // opener relationship is maintained.
411 // 3. Reloads/form submits/back forward navigations
412 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
415 if (type
!= blink::WebNavigationTypeReload
&&
416 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
417 // The opener relationship between the new window and the parent allows the
418 // new window to script the parent and vice versa. This is not allowed if
419 // the origins of the two domains are different. This can be treated as a
420 // top level navigation and routed back to the host.
421 blink::WebFrame
* opener
= frame
->opener();
425 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
431 WebURLRequest
CreateURLRequestForNavigation(
432 const CommonNavigationParams
& common_params
,
433 scoped_ptr
<StreamOverrideParameters
> stream_override
,
434 bool is_view_source_mode_enabled
) {
435 WebURLRequest
request(common_params
.url
);
436 if (is_view_source_mode_enabled
)
437 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
439 if (common_params
.referrer
.url
.is_valid()) {
440 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
441 common_params
.referrer
.policy
,
443 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
444 if (!web_referrer
.isEmpty())
445 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
448 RequestExtraData
* extra_data
= new RequestExtraData();
449 extra_data
->set_stream_override(stream_override
.Pass());
450 request
.setExtraData(extra_data
);
452 // Set the ui timestamp for this navigation. Currently the timestamp here is
453 // only non empty when the navigation was triggered by an Android intent. The
454 // timestamp is converted to a double version supported by blink. It will be
455 // passed back to the browser in the DidCommitProvisionalLoad and the
456 // DocumentLoadComplete IPCs.
457 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
458 request
.setUiStartTime(ui_timestamp
.InSecondsF());
459 request
.setInputPerfMetricReportPolicy(
460 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
461 common_params
.report_type
));
465 void UpdateFrameNavigationTiming(WebFrame
* frame
,
466 base::TimeTicks browser_navigation_start
,
467 base::TimeTicks renderer_navigation_start
) {
468 // The browser provides the navigation_start time to bootstrap the
469 // Navigation Timing information for the browser-initiated navigations. In
470 // case of cross-process navigations, this carries over the time of
471 // finishing the onbeforeunload handler of the previous page.
472 DCHECK(!browser_navigation_start
.is_null());
473 if (frame
->provisionalDataSource()) {
474 // |browser_navigation_start| is likely before this process existed, so we
475 // can't use InterProcessTimeTicksConverter. We need at least to ensure
476 // that the browser-side navigation start we set is not later than the one
477 // on the renderer side.
478 base::TimeTicks navigation_start
= std::min(
479 browser_navigation_start
, renderer_navigation_start
);
480 double navigation_start_seconds
=
481 (navigation_start
- base::TimeTicks()).InSecondsF();
482 frame
->provisionalDataSource()->setNavigationStartTime(
483 navigation_start_seconds
);
484 // TODO(clamy): We need to provide additional timing values for the
485 // Navigation Timing API to work with browser-side navigations.
490 CommonNavigationParams
MakeCommonNavigationParams(
491 blink::WebURLRequest
* request
,
492 bool should_replace_current_entry
) {
493 const RequestExtraData kEmptyData
;
494 const RequestExtraData
* extra_data
=
495 static_cast<RequestExtraData
*>(request
->extraData());
497 extra_data
= &kEmptyData
;
499 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
500 request
->referrerPolicy());
502 // Set the ui timestamp for this navigation. Currently the timestamp here is
503 // only non empty when the navigation was triggered by an Android intent, or
504 // by the user clicking on a link. The timestamp is converted from a double
505 // version supported by blink. It will be passed back to the renderer in the
506 // CommitNavigation IPC, and then back to the browser again in the
507 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
508 base::TimeTicks ui_timestamp
=
509 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
510 FrameMsg_UILoadMetricsReportType::Value report_type
=
511 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
512 request
->inputPerfMetricReportPolicy());
513 return CommonNavigationParams(
514 request
->url(), referrer
, extra_data
->transition_type(),
515 FrameMsg_Navigate_Type::NORMAL
, true, should_replace_current_entry
,
516 ui_timestamp
, report_type
, GURL(), GURL());
519 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
520 media::Context3D
GetSharedMainThreadContext3D() {
521 cc::ContextProvider
* provider
=
522 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
524 return media::Context3D();
525 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
529 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
530 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
531 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
532 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
535 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
541 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
543 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
544 CreateParams
params(render_view
, routing_id
);
546 if (g_create_render_frame_impl
)
547 return g_create_render_frame_impl(params
);
549 return new RenderFrameImpl(params
);
553 RenderFrame
* RenderFrame::FromRoutingID(int routing_id
) {
554 return RenderFrameImpl::FromRoutingID(routing_id
);
558 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int routing_id
) {
559 RoutingIDFrameMap::iterator iter
=
560 g_routing_id_frame_map
.Get().find(routing_id
);
561 if (iter
!= g_routing_id_frame_map
.Get().end())
567 void RenderFrameImpl::CreateFrame(
569 int parent_routing_id
,
570 int previous_sibling_routing_id
,
571 int proxy_routing_id
,
572 const FrameReplicationState
& replicated_state
,
573 CompositorDependencies
* compositor_deps
,
574 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
575 blink::WebLocalFrame
* web_frame
;
576 RenderFrameImpl
* render_frame
;
577 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
578 RenderFrameProxy
* parent_proxy
=
579 RenderFrameProxy::FromRoutingID(parent_routing_id
);
580 // If the browser is sending a valid parent routing id, it should already
581 // be created and registered.
583 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
585 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
586 RenderFrameProxy
* previous_sibling_proxy
=
587 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
588 if (previous_sibling_proxy
)
589 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
591 // Create the RenderFrame and WebLocalFrame, linking the two.
593 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
594 web_frame
= parent_web_frame
->createLocalChild(
595 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
596 replicated_state
.sandbox_flags
, render_frame
,
597 previous_sibling_web_frame
);
599 RenderFrameProxy
* proxy
=
600 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
602 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
604 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
605 render_frame
->proxy_routing_id_
= proxy_routing_id
;
606 web_frame
->initializeToReplaceRemoteFrame(
607 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
608 replicated_state
.sandbox_flags
);
610 render_frame
->SetWebFrame(web_frame
);
611 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
613 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
614 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
615 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
616 widget_params
.routing_id
, widget_params
.surface_id
,
617 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
618 compositor_deps
, web_frame
);
619 // TODO(kenrb): Observing shouldn't be necessary when we sort out
620 // WasShown and WasHidden, separating page-level visibility from
621 // frame-level visibility.
622 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
625 render_frame
->Initialize();
629 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
630 return RenderFrameImpl::FromWebFrame(web_frame
);
634 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
635 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
636 if (iter
!= g_frame_map
.Get().end())
642 void RenderFrameImpl::InstallCreateHook(
643 CreateRenderFrameImplFunction create_render_frame_impl
) {
644 CHECK(!g_create_render_frame_impl
);
645 g_create_render_frame_impl
= create_render_frame_impl
;
648 // RenderFrameImpl ----------------------------------------------------------
649 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
652 is_local_root_(false),
653 render_view_(params
.render_view
->AsWeakPtr()),
654 routing_id_(params
.routing_id
),
655 is_swapped_out_(false),
656 render_frame_proxy_(NULL
),
657 is_detaching_(false),
658 proxy_routing_id_(MSG_ROUTING_NONE
),
659 #if defined(ENABLE_PLUGINS)
660 plugin_power_saver_helper_(NULL
),
663 selection_text_offset_(0),
664 selection_range_(gfx::Range::InvalidRange()),
665 handling_select_range_(false),
666 notification_permission_dispatcher_(NULL
),
667 web_user_media_client_(NULL
),
668 media_permission_dispatcher_(NULL
),
669 midi_dispatcher_(NULL
),
670 #if defined(OS_ANDROID)
671 media_player_manager_(NULL
),
673 #if defined(ENABLE_BROWSER_CDMS)
676 #if defined(VIDEO_HOLE)
677 contains_media_player_(false),
679 has_played_media_(false),
680 devtools_agent_(nullptr),
681 geolocation_dispatcher_(NULL
),
682 push_messaging_dispatcher_(NULL
),
683 presentation_dispatcher_(NULL
),
684 screen_orientation_dispatcher_(NULL
),
685 manifest_manager_(NULL
),
686 accessibility_mode_(AccessibilityModeOff
),
687 renderer_accessibility_(NULL
),
688 weak_factory_(this) {
689 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
690 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
691 CHECK(result
.second
) << "Inserting a duplicate item.";
693 RenderThread::Get()->AddRoute(routing_id_
, this);
695 render_view_
->RegisterRenderFrame(this);
697 // Everything below subclasses RenderFrameObserver and is automatically
698 // deleted when the RenderFrame gets deleted.
699 #if defined(OS_ANDROID)
700 new GinJavaBridgeDispatcher(this);
703 #if defined(ENABLE_PLUGINS)
704 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
707 manifest_manager_
= new ManifestManager(this);
710 RenderFrameImpl::~RenderFrameImpl() {
711 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
712 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
714 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
716 #if defined(VIDEO_HOLE)
717 if (contains_media_player_
)
718 render_view_
->UnregisterVideoHoleFrame(this);
722 // When using swapped out frames, RenderFrameProxy is owned by
723 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
724 // along with this object.
725 if (render_frame_proxy_
&&
726 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
727 // The following method calls back into this object and clears
728 // |render_frame_proxy_|.
729 render_frame_proxy_
->frameDetached(
730 blink::WebRemoteFrameClient::DetachType::Remove
);
733 // Ensure the RenderView doesn't point to this object, once it is destroyed.
734 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
735 // is |this|, once the object is no longer leaked.
736 // See https://crbug.com/464764.
737 render_view_
->main_render_frame_
= nullptr;
740 render_view_
->UnregisterRenderFrame(this);
741 g_routing_id_frame_map
.Get().erase(routing_id_
);
742 RenderThread::Get()->RemoveRoute(routing_id_
);
745 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
748 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
749 std::make_pair(web_frame
, this));
750 CHECK(result
.second
) << "Inserting a duplicate item.";
755 void RenderFrameImpl::Initialize() {
756 is_subframe_
= !!frame_
->parent();
757 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
759 #if defined(ENABLE_PLUGINS)
760 new PepperBrowserConnection(this);
762 new SharedWorkerRepository(this);
764 if (is_local_root_
&& !render_frame_proxy_
) {
765 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
766 // when |this| is deleted.
767 devtools_agent_
= new DevToolsAgent(this);
770 RegisterMojoServices();
772 // We delay calling this until we have the WebFrame so that any observer or
773 // embedder can call GetWebFrame on any RenderFrame.
774 GetContentClient()->renderer()->RenderFrameCreated(this);
777 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
778 return render_view_
.get();
781 #if defined(ENABLE_PLUGINS)
782 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
783 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
784 DidCreatePepperPlugin(host
));
785 if (host
->GetPluginName() == kFlashPluginName
) {
786 RenderThread::Get()->RecordAction(
787 base::UserMetricsAction("FrameLoadWithFlash"));
791 void RenderFrameImpl::PepperDidChangeCursor(
792 PepperPluginInstanceImpl
* instance
,
793 const blink::WebCursorInfo
& cursor
) {
794 // Update the cursor appearance immediately if the requesting plugin is the
795 // one which receives the last mouse event. Otherwise, the new cursor won't be
796 // picked up until the plugin gets the next input event. That is bad if, e.g.,
797 // the plugin would like to set an invisible cursor when there isn't any user
798 // input for a while.
799 if (instance
== render_view_
->pepper_last_mouse_event_target())
800 GetRenderWidget()->didChangeCursor(cursor
);
803 void RenderFrameImpl::PepperDidReceiveMouseEvent(
804 PepperPluginInstanceImpl
* instance
) {
805 render_view_
->set_pepper_last_mouse_event_target(instance
);
808 void RenderFrameImpl::PepperTextInputTypeChanged(
809 PepperPluginInstanceImpl
* instance
) {
810 if (instance
!= render_view_
->focused_pepper_plugin())
813 GetRenderWidget()->UpdateTextInputState(
814 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
816 FocusedNodeChangedForAccessibility(WebNode());
819 void RenderFrameImpl::PepperCaretPositionChanged(
820 PepperPluginInstanceImpl
* instance
) {
821 if (instance
!= render_view_
->focused_pepper_plugin())
823 GetRenderWidget()->UpdateSelectionBounds();
826 void RenderFrameImpl::PepperCancelComposition(
827 PepperPluginInstanceImpl
* instance
) {
828 if (instance
!= render_view_
->focused_pepper_plugin())
830 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
831 #if defined(OS_MACOSX) || defined(USE_AURA)
832 GetRenderWidget()->UpdateCompositionInfo(true);
836 void RenderFrameImpl::PepperSelectionChanged(
837 PepperPluginInstanceImpl
* instance
) {
838 if (instance
!= render_view_
->focused_pepper_plugin())
840 SyncSelectionIfRequired();
843 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
844 PepperPluginInstanceImpl
* plugin
) {
846 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
847 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
848 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
849 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
850 plugin
, active_url
, GetRenderWidget()->screenInfo());
851 widget
->show(blink::WebNavigationPolicyIgnore
);
855 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
856 if (!render_view_
->focused_pepper_plugin())
858 return render_view_
->focused_pepper_plugin()->
859 IsPluginAcceptingCompositionEvents();
862 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
863 base::ProcessId plugin_pid
) {
864 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
865 // routing_id_ as a result.
866 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
869 void RenderFrameImpl::SimulateImeSetComposition(
870 const base::string16
& text
,
871 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
874 render_view_
->OnImeSetComposition(
875 text
, underlines
, selection_start
, selection_end
);
878 void RenderFrameImpl::SimulateImeConfirmComposition(
879 const base::string16
& text
,
880 const gfx::Range
& replacement_range
) {
881 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
884 void RenderFrameImpl::OnImeSetComposition(
885 const base::string16
& text
,
886 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
889 // When a PPAPI plugin has focus, we bypass WebKit.
890 if (!IsPepperAcceptingCompositionEvents()) {
891 pepper_composition_text_
= text
;
893 // TODO(kinaba) currently all composition events are sent directly to
894 // plugins. Use DOM event mechanism after WebKit is made aware about
895 // plugins that support composition.
896 // The code below mimics the behavior of WebCore::Editor::setComposition.
898 // Empty -> nonempty: composition started.
899 if (pepper_composition_text_
.empty() && !text
.empty()) {
900 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
903 // Nonempty -> empty: composition canceled.
904 if (!pepper_composition_text_
.empty() && text
.empty()) {
905 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
908 pepper_composition_text_
= text
;
909 // Nonempty: composition is ongoing.
910 if (!pepper_composition_text_
.empty()) {
911 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
912 pepper_composition_text_
, underlines
, selection_start
,
918 void RenderFrameImpl::OnImeConfirmComposition(
919 const base::string16
& text
,
920 const gfx::Range
& replacement_range
,
921 bool keep_selection
) {
922 // When a PPAPI plugin has focus, we bypass WebKit.
923 // Here, text.empty() has a special meaning. It means to commit the last
924 // update of composition text (see
925 // RenderWidgetHost::ImeConfirmComposition()).
926 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
929 // last_text is empty only when both text and pepper_composition_text_ is.
931 if (last_text
.empty())
934 if (!IsPepperAcceptingCompositionEvents()) {
935 base::i18n::UTF16CharIterator
iterator(&last_text
);
937 while (iterator
.Advance()) {
938 blink::WebKeyboardEvent char_event
;
939 char_event
.type
= blink::WebInputEvent::Char
;
940 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
941 char_event
.modifiers
= 0;
942 char_event
.windowsKeyCode
= last_text
[i
];
943 char_event
.nativeKeyCode
= last_text
[i
];
945 const int32 char_start
= i
;
946 for (; i
< iterator
.array_pos(); ++i
) {
947 char_event
.text
[i
- char_start
] = last_text
[i
];
948 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
951 if (GetRenderWidget()->webwidget())
952 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
955 // Mimics the order of events sent by WebKit.
956 // See WebCore::Editor::setComposition() for the corresponding code.
957 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
958 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
960 pepper_composition_text_
.clear();
962 #endif // defined(ENABLE_PLUGINS)
964 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
965 if (!web_user_media_client_
)
966 InitializeUserMediaClient();
967 return web_user_media_client_
?
968 web_user_media_client_
->media_stream_dispatcher() : NULL
;
971 bool RenderFrameImpl::Send(IPC::Message
* message
) {
976 if (is_swapped_out_
) {
977 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
983 return RenderThread::Get()->Send(message
);
986 #if defined(OS_MACOSX) || defined(OS_ANDROID)
987 void RenderFrameImpl::DidHideExternalPopupMenu() {
988 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
989 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
990 external_popup_menu_
.reset();
994 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
995 // We may get here while detaching, when the WebFrame has been deleted. Do
996 // not process any messages in this state.
1000 // TODO(kenrb): document() should not be null, but as a transitional step
1001 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1002 // to this method. This happens for a top-level remote frame, where a
1003 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1004 // around and is still able to receive messages.
1005 if (!frame_
->document().isNull())
1006 GetContentClient()->SetActiveURL(frame_
->document().url());
1008 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
1009 RenderFrameObserver
* observer
;
1010 while ((observer
= it
.GetNext()) != NULL
) {
1011 if (observer
->OnMessageReceived(msg
))
1015 bool handled
= true;
1016 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1017 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1018 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1019 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1020 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1021 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1022 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1023 OnCustomContextMenuAction
)
1024 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1025 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1026 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1027 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1028 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1029 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1030 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1031 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1032 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1033 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1034 OnAdjustSelectionByCharacterOffset
)
1035 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1036 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1037 OnMoveRangeSelectionExtent
)
1038 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1039 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1040 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1041 OnExtendSelectionAndDelete
)
1042 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1043 OnSetCompositionFromExistingText
)
1044 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1045 OnExecuteNoValueEditCommand
)
1046 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1047 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1048 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1049 OnJavaScriptExecuteRequest
)
1050 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1051 OnJavaScriptExecuteRequestForTests
)
1052 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1053 OnJavaScriptExecuteRequestInIsolatedWorld
)
1054 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1055 OnVisualStateRequest
)
1056 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1057 OnSetEditableSelectionOffsets
)
1058 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1059 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1060 OnTextSurroundingSelectionRequest
)
1061 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1062 OnSetAccessibilityMode
)
1063 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1064 OnSnapshotAccessibilityTree
)
1065 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1066 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1067 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1068 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1069 OnTextTrackSettingsChanged
)
1070 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1071 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1072 #if defined(OS_ANDROID)
1073 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1074 #elif defined(OS_MACOSX)
1075 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1076 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1078 IPC_END_MESSAGE_MAP()
1083 void RenderFrameImpl::OnNavigate(
1084 const CommonNavigationParams
& common_params
,
1085 const StartNavigationParams
& start_params
,
1086 const RequestNavigationParams
& request_params
) {
1087 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1088 switches::kEnableBrowserSideNavigation
));
1089 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1090 "url", common_params
.url
.possibly_invalid_spec());
1091 NavigateInternal(common_params
, start_params
, request_params
,
1092 scoped_ptr
<StreamOverrideParameters
>());
1095 void RenderFrameImpl::NavigateToSwappedOutURL() {
1096 // We use loadRequest instead of loadHTMLString because the former commits
1097 // synchronously. Otherwise a new navigation can interrupt the navigation
1098 // to kSwappedOutURL. If that happens to be to the page we had been
1099 // showing, then WebKit will never send a commit and we'll be left spinning.
1100 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1101 // the navigation to swappedout:// is not announced to the browser side.
1102 is_swapped_out_
= true;
1103 GURL
swappedOutURL(kSwappedOutURL
);
1104 WebURLRequest
request(swappedOutURL
);
1105 frame_
->loadRequest(request
);
1108 void RenderFrameImpl::BindServiceRegistry(
1109 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1110 mojo::ServiceProviderPtr exposed_services
) {
1111 service_registry_
.Bind(services
.Pass());
1112 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1115 ManifestManager
* RenderFrameImpl::manifest_manager() {
1116 return manifest_manager_
;
1119 void RenderFrameImpl::SetPendingNavigationParams(
1120 scoped_ptr
<NavigationParams
> navigation_params
) {
1121 pending_navigation_params_
= navigation_params
.Pass();
1124 void RenderFrameImpl::OnBeforeUnload() {
1125 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1127 // TODO(creis): Right now, this is only called on the main frame. Make the
1128 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1130 CHECK(!frame_
->parent());
1132 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1133 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1134 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1135 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1136 before_unload_start_time
,
1137 before_unload_end_time
));
1140 void RenderFrameImpl::OnSwapOut(
1141 int proxy_routing_id
,
1143 const FrameReplicationState
& replicated_frame_state
) {
1144 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1145 RenderFrameProxy
* proxy
= NULL
;
1146 bool swapped_out_forbidden
=
1147 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1148 bool is_main_frame
= !frame_
->parent();
1150 // This codepath should only be hit for subframes when in --site-per-process.
1151 CHECK_IMPLIES(!is_main_frame
,
1152 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1154 // Only run unload if we're not swapped out yet, but send the ack either way.
1155 if (!is_swapped_out_
) {
1156 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1157 // a different process. This involves running the unload handler and
1158 // clearing the page. We also allow this process to exit if there are no
1159 // other active RenderFrames in it.
1161 // Send an UpdateState message before we get swapped out.
1162 render_view_
->SendUpdateState();
1164 // If we need a proxy to replace this, create it now so its routing id is
1165 // registered for receiving IPC messages.
1166 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1167 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1168 this, proxy_routing_id
, replicated_frame_state
.scope
);
1171 // Synchronously run the unload handler before sending the ACK.
1172 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1173 // unload on subframes as well.
1175 frame_
->dispatchUnloadEvent();
1177 // Swap out and stop sending any IPC messages that are not ACKs.
1179 render_view_
->SetSwappedOut(true);
1180 is_swapped_out_
= true;
1182 // Set the proxy here, since OnStop() below could cause an onload event
1183 // handler to execute, which could trigger code such as
1184 // willCheckAndDispatchMessageEvent() that needs the proxy.
1186 set_render_frame_proxy(proxy
);
1188 // Now that we're swapped out and filtering IPC messages, stop loading to
1189 // ensure that no other in-progress navigation continues. We do this here
1190 // to avoid sending a DidStopLoading message to the browser process.
1191 // TODO(creis): Should we be stopping all frames here and using
1192 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1194 if (!swapped_out_forbidden
)
1197 // Transfer settings such as initial drawing parameters to the remote frame,
1198 // if one is created, that will replace this frame.
1199 if (!is_main_frame
&& proxy
)
1200 proxy
->web_frame()->initializeFromFrame(frame_
);
1202 // Replace the page with a blank dummy URL. The unload handler will not be
1203 // run a second time, thanks to a check in FrameLoader::stopLoading.
1204 // TODO(creis): Need to add a better way to do this that avoids running the
1205 // beforeunload handler. For now, we just run it a second time silently.
1206 if (!swapped_out_forbidden
)
1207 NavigateToSwappedOutURL();
1209 // Let WebKit know that this view is hidden so it can drop resources and
1210 // stop compositing.
1211 // TODO(creis): Support this for subframes as well.
1212 if (is_main_frame
) {
1213 render_view_
->webview()->setVisibilityState(
1214 blink::WebPageVisibilityStateHidden
, false);
1218 // It is now safe to show modal dialogs again.
1219 // TODO(creis): Deal with modal dialogs from subframes.
1221 render_view_
->suppress_dialogs_until_swap_out_
= false;
1223 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1225 RenderViewImpl
* render_view
= render_view_
.get();
1227 // Now that all of the cleanup is complete and the browser side is notified,
1228 // start using the RenderFrameProxy, if one is created.
1229 if (proxy
&& swapped_out_forbidden
) {
1230 frame_
->swap(proxy
->web_frame());
1233 proxy
->OnDidStartLoading();
1236 // In --site-per-process, initialize the WebRemoteFrame with the replication
1237 // state passed by the process that is now rendering the frame.
1238 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1239 // in that case we leave the LocalFrame as the main frame visible to Blink
1240 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1241 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1242 // When we do an unconditional swap for all frames, we can remove
1243 // !is_main_frame below.
1244 if (proxy
&& swapped_out_forbidden
)
1245 proxy
->SetReplicatedState(replicated_frame_state
);
1247 // Safe to exit if no one else is using the process.
1248 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1249 // the process based on the lifetime of this RenderFrameImpl object.
1250 if (is_main_frame
) {
1251 render_view
->WasSwappedOut();
1255 void RenderFrameImpl::OnContextMenuClosed(
1256 const CustomContextMenuContext
& custom_context
) {
1257 if (custom_context
.request_id
) {
1258 // External request, should be in our map.
1259 ContextMenuClient
* client
=
1260 pending_context_menus_
.Lookup(custom_context
.request_id
);
1262 client
->OnMenuClosed(custom_context
.request_id
);
1263 pending_context_menus_
.Remove(custom_context
.request_id
);
1266 if (custom_context
.link_followed
.is_valid())
1267 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1268 // Internal request, forward to WebKit.
1269 context_menu_node_
.reset();
1273 void RenderFrameImpl::OnCustomContextMenuAction(
1274 const CustomContextMenuContext
& custom_context
,
1276 if (custom_context
.request_id
) {
1277 // External context menu request, look in our map.
1278 ContextMenuClient
* client
=
1279 pending_context_menus_
.Lookup(custom_context
.request_id
);
1281 client
->OnMenuAction(custom_context
.request_id
, action
);
1283 // Internal request, forward to WebKit.
1284 render_view_
->webview()->performCustomContextMenuAction(action
);
1288 void RenderFrameImpl::OnUndo() {
1289 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1292 void RenderFrameImpl::OnRedo() {
1293 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1296 void RenderFrameImpl::OnCut() {
1297 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1298 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1301 void RenderFrameImpl::OnCopy() {
1302 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1303 WebNode current_node
= context_menu_node_
.isNull() ?
1304 GetFocusedElement() : context_menu_node_
;
1305 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1308 void RenderFrameImpl::OnPaste() {
1309 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1310 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1313 void RenderFrameImpl::OnPasteAndMatchStyle() {
1314 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1315 frame_
->executeCommand(
1316 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1319 #if defined(OS_MACOSX)
1320 void RenderFrameImpl::OnCopyToFindPboard() {
1321 // Since the find pasteboard supports only plain text, this can be simpler
1322 // than the |OnCopy()| case.
1323 if (frame_
->hasSelection()) {
1324 base::string16 selection
= frame_
->selectionAsText();
1325 RenderThread::Get()->Send(
1326 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1331 void RenderFrameImpl::OnDelete() {
1332 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1335 void RenderFrameImpl::OnSelectAll() {
1336 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1337 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1340 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1341 const gfx::Point
& extent
) {
1342 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1343 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1345 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1346 frame_
->selectRange(base
, extent
);
1349 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1351 size_t start
, length
;
1352 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1357 // Sanity checks to disallow empty and out of range selections.
1358 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1359 || static_cast<int>(start
) + start_adjust
< 0) {
1363 // A negative adjust amount moves the selection towards the beginning of
1364 // the document, a positive amount moves the selection towards the end of
1366 start
+= start_adjust
;
1367 length
+= end_adjust
- start_adjust
;
1369 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1372 void RenderFrameImpl::OnUnselect() {
1373 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1374 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1377 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1378 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1379 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1380 GetRenderWidget()->routing_id()));
1382 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1383 frame_
->moveRangeSelectionExtent(point
);
1386 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1387 if (!frame_
->hasSelection())
1388 frame_
->selectWordAroundCaret();
1390 frame_
->replaceSelection(text
);
1393 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1394 if (!frame_
->hasSelection())
1397 frame_
->replaceMisspelledRange(text
);
1400 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1401 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1404 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1405 const std::string
& message
) {
1406 AddMessageToConsole(level
, message
);
1409 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1410 const base::string16
& jscript
,
1412 bool notify_result
) {
1413 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1414 TRACE_EVENT_SCOPE_THREAD
);
1416 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1417 v8::Local
<v8::Value
> result
=
1418 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1420 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1423 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1424 const base::string16
& jscript
,
1427 bool has_user_gesture
) {
1428 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1429 TRACE_EVENT_SCOPE_THREAD
);
1431 // A bunch of tests expect to run code in the context of a user gesture, which
1432 // can grant additional privileges (e.g. the ability to create popups).
1433 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1434 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1435 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1436 v8::Local
<v8::Value
> result
=
1437 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1439 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1442 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1443 const base::string16
& jscript
,
1447 TRACE_EVENT_INSTANT0("test_tracing",
1448 "OnJavaScriptExecuteRequestInIsolatedWorld",
1449 TRACE_EVENT_SCOPE_THREAD
);
1451 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1452 world_id
> ISOLATED_WORLD_ID_MAX
) {
1453 // Return if the world_id is not valid. world_id is passed as a plain int
1454 // over IPC and needs to be verified here, in the IPC endpoint.
1459 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1460 WebScriptSource script
= WebScriptSource(jscript
);
1461 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1462 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1463 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1467 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1471 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1473 notify_result_(notify_result
),
1474 routing_id_(routing_id
),
1475 render_frame_impl_(render_frame_impl
) {
1478 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1479 ~JavaScriptIsolatedWorldRequest() {
1482 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1483 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1484 if (!render_frame_impl_
.get()) {
1488 if (notify_result_
) {
1489 base::ListValue list
;
1490 if (!result
.isEmpty()) {
1491 // It's safe to always use the main world context when converting
1492 // here. V8ValueConverterImpl shouldn't actually care about the
1493 // context scope, and it switches to v8::Object's creation context
1494 // when encountered. (from extensions/renderer/script_injection.cc)
1495 v8::Local
<v8::Context
> context
=
1496 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1497 v8::Context::Scope
context_scope(context
);
1498 V8ValueConverterImpl converter
;
1499 converter
.SetDateAllowed(true);
1500 converter
.SetRegExpAllowed(true);
1501 for (const auto& value
: result
) {
1502 scoped_ptr
<base::Value
> result_value(
1503 converter
.FromV8Value(value
, context
));
1504 list
.Append(result_value
? result_value
.Pass()
1505 : base::Value::CreateNullValue());
1508 list
.Set(0, base::Value::CreateNullValue());
1510 render_frame_impl_
.get()->Send(
1511 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1517 void RenderFrameImpl::HandleJavascriptExecutionResult(
1518 const base::string16
& jscript
,
1521 v8::Local
<v8::Value
> result
) {
1522 if (notify_result
) {
1523 base::ListValue list
;
1524 if (!result
.IsEmpty()) {
1525 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1526 v8::Context::Scope
context_scope(context
);
1527 V8ValueConverterImpl converter
;
1528 converter
.SetDateAllowed(true);
1529 converter
.SetRegExpAllowed(true);
1530 scoped_ptr
<base::Value
> result_value(
1531 converter
.FromV8Value(result
, context
));
1532 list
.Set(0, result_value
? result_value
.Pass()
1533 : base::Value::CreateNullValue());
1535 list
.Set(0, base::Value::CreateNullValue());
1537 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1541 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1542 GetRenderWidget()->QueueMessage(
1543 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1544 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1547 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1548 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1549 if (!GetRenderWidget()->ShouldHandleImeEvent())
1551 ImeEventGuard
guard(GetRenderWidget());
1552 frame_
->setEditableSelectionOffsets(start
, end
);
1555 void RenderFrameImpl::OnSetCompositionFromExistingText(
1557 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1558 if (!GetRenderWidget()->ShouldHandleImeEvent())
1560 ImeEventGuard
guard(GetRenderWidget());
1561 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1564 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1565 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1568 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1569 if (!GetRenderWidget()->ShouldHandleImeEvent())
1572 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1574 ImeEventGuard
guard(GetRenderWidget());
1575 blink::WebScopedUserGesture gesture_indicator
;
1576 frame_
->extendSelectionAndDelete(before
, after
);
1579 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1580 if (accessibility_mode_
== new_mode
)
1582 accessibility_mode_
= new_mode
;
1583 if (renderer_accessibility_
) {
1584 // Note: this isn't called automatically by the destructor because
1585 // there'd be no point in calling it in frame teardown, only if there's
1586 // an accessibility mode change but the frame is persisting.
1587 renderer_accessibility_
->DisableAccessibility();
1589 delete renderer_accessibility_
;
1590 renderer_accessibility_
= NULL
;
1592 if (accessibility_mode_
== AccessibilityModeOff
)
1595 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1596 renderer_accessibility_
= new RendererAccessibility(this);
1599 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1600 ui::AXTreeUpdate
<AXContentNodeData
> response
;
1601 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1602 Send(new AccessibilityHostMsg_SnapshotResponse(
1603 routing_id_
, callback_id
, response
));
1606 void RenderFrameImpl::OnDisownOpener() {
1607 // TODO(creis): We should only see this for main frames for now. To support
1608 // disowning the opener on subframes, we will need to move WebContentsImpl's
1609 // opener_ to FrameTreeNode.
1610 CHECK(!frame_
->parent());
1612 if (frame_
->opener())
1613 frame_
->setOpener(NULL
);
1616 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1617 frame_
->setFrameOwnerSandboxFlags(flags
);
1620 void RenderFrameImpl::OnTextTrackSettingsChanged(
1621 const FrameMsg_TextTrackSettings_Params
& params
) {
1622 DCHECK(!frame_
->parent());
1623 if (!render_view_
->webview())
1626 if (params
.text_tracks_enabled
) {
1627 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1628 WebSettings::TextTrackKindUserPreference::Captions
);
1630 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1631 WebSettings::TextTrackKindUserPreference::Default
);
1633 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1634 WebString::fromUTF8(params
.text_track_background_color
));
1635 render_view_
->webview()->settings()->setTextTrackFontFamily(
1636 WebString::fromUTF8(params
.text_track_font_family
));
1637 render_view_
->webview()->settings()->setTextTrackFontStyle(
1638 WebString::fromUTF8(params
.text_track_font_style
));
1639 render_view_
->webview()->settings()->setTextTrackFontVariant(
1640 WebString::fromUTF8(params
.text_track_font_variant
));
1641 render_view_
->webview()->settings()->setTextTrackTextColor(
1642 WebString::fromUTF8(params
.text_track_text_color
));
1643 render_view_
->webview()->settings()->setTextTrackTextShadow(
1644 WebString::fromUTF8(params
.text_track_text_shadow
));
1645 render_view_
->webview()->settings()->setTextTrackTextSize(
1646 WebString::fromUTF8(params
.text_track_text_size
));
1649 void RenderFrameImpl::OnPostMessageEvent(
1650 const FrameMsg_PostMessage_Params
& params
) {
1651 // Find the source frame if it exists.
1652 WebFrame
* source_frame
= NULL
;
1653 if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1654 RenderFrameProxy
* source_proxy
=
1655 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1657 // Currently, navigating a top-level frame cross-process does not swap
1658 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1659 // WebRemoteFrame will not have an associated blink::Frame. If this is
1660 // the case for |source_proxy|, use the corresponding (swapped-out)
1661 // WebLocalFrame instead, so that event.source for this message can be
1662 // set and used properly.
1663 if (source_proxy
->IsMainFrameDetachedFromTree())
1664 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1666 source_frame
= source_proxy
->web_frame();
1670 // If the message contained MessagePorts, create the corresponding endpoints.
1671 blink::WebMessagePortChannelArray channels
=
1672 WebMessagePortChannelImpl::CreatePorts(
1673 params
.message_ports
, params
.new_routing_ids
,
1674 base::ThreadTaskRunnerHandle::Get().get());
1676 WebSerializedScriptValue serialized_script_value
;
1677 if (params
.is_data_raw_string
) {
1678 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1679 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1680 v8::Context::Scope
context_scope(context
);
1681 V8ValueConverterImpl converter
;
1682 converter
.SetDateAllowed(true);
1683 converter
.SetRegExpAllowed(true);
1684 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1685 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1687 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1689 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1692 // Create an event with the message. The next-to-last parameter to
1693 // initMessageEvent is the last event ID, which is not used with postMessage.
1694 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1695 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1696 msg_event
.initMessageEvent("message",
1697 // |canBubble| and |cancellable| are always false
1699 serialized_script_value
,
1700 params
.source_origin
, source_frame
,
1701 frame_
->document(), "", channels
);
1703 // We must pass in the target_origin to do the security check on this side,
1704 // since it may have changed since the original postMessage call was made.
1705 WebSecurityOrigin target_origin
;
1706 if (!params
.target_origin
.empty()) {
1708 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1710 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1713 #if defined(OS_ANDROID)
1714 void RenderFrameImpl::OnSelectPopupMenuItems(
1716 const std::vector
<int>& selected_indices
) {
1717 // It is possible to receive more than one of these calls if the user presses
1718 // a select faster than it takes for the show-select-popup IPC message to make
1719 // it to the browser UI thread. Ignore the extra-messages.
1720 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1721 if (!external_popup_menu_
)
1724 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1725 external_popup_menu_
.reset();
1729 #if defined(OS_MACOSX)
1730 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1731 if (external_popup_menu_
== NULL
)
1733 external_popup_menu_
->DidSelectItem(selected_index
);
1734 external_popup_menu_
.reset();
1738 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1739 frame_
->reload(ignore_cache
);
1742 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1743 blink::WebSurroundingText surroundingText
;
1744 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1746 if (surroundingText
.isNull()) {
1747 // |surroundingText| might not be correctly initialized, for example if
1748 // |frame_->selectionRange().isNull()|, in other words, if there was no
1750 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1751 routing_id_
, base::string16(), 0, 0));
1755 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1757 surroundingText
.textContent(),
1758 surroundingText
.startOffsetInTextContent(),
1759 surroundingText
.endOffsetInTextContent()));
1762 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1763 const base::string16
& message
,
1764 const base::string16
& default_value
,
1765 const GURL
& frame_url
,
1766 base::string16
* result
) {
1767 // Don't allow further dialogs if we are waiting to swap out, since the
1768 // PageGroupLoadDeferrer in our stack prevents it.
1769 if (render_view()->suppress_dialogs_until_swap_out_
)
1772 bool success
= false;
1773 base::string16 result_temp
;
1775 result
= &result_temp
;
1777 render_view()->SendAndRunNestedMessageLoop(
1778 new FrameHostMsg_RunJavaScriptMessage(
1779 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1784 void RenderFrameImpl::LoadNavigationErrorPage(
1785 const WebURLRequest
& failed_request
,
1786 const WebURLError
& error
,
1788 std::string error_html
;
1789 GetContentClient()->renderer()->GetNavigationErrorStrings(
1790 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1792 frame_
->loadHTMLString(error_html
,
1793 GURL(kUnreachableWebDataURL
),
1794 error
.unreachableURL
,
1798 void RenderFrameImpl::DidCommitCompositorFrame() {
1799 if (BrowserPluginManager::Get())
1800 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1802 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1805 RenderView
* RenderFrameImpl::GetRenderView() {
1806 return render_view_
.get();
1809 int RenderFrameImpl::GetRoutingID() {
1813 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1818 WebElement
RenderFrameImpl::GetFocusedElement() const {
1819 WebDocument doc
= frame_
->document();
1821 return doc
.focusedElement();
1823 return WebElement();
1826 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1827 return render_view_
->GetWebkitPreferences();
1830 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1831 const ContextMenuParams
& params
) {
1832 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1833 ContextMenuParams
our_params(params
);
1834 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1835 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1836 return our_params
.custom_context
.request_id
;
1839 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1840 DCHECK(pending_context_menus_
.Lookup(request_id
));
1841 pending_context_menus_
.Remove(request_id
);
1844 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1845 return context_menu_node_
;
1848 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1849 blink::WebFrame
* frame
,
1850 const WebPluginInfo
& info
,
1851 const blink::WebPluginParams
& params
,
1852 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1853 DCHECK_EQ(frame_
, frame
);
1854 #if defined(ENABLE_PLUGINS)
1855 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1856 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1857 this, GetContentClient()
1859 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1864 bool pepper_plugin_was_registered
= false;
1865 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1866 this, info
, &pepper_plugin_was_registered
));
1867 if (pepper_plugin_was_registered
) {
1868 if (pepper_module
.get()) {
1869 return new PepperWebPluginImpl(
1870 pepper_module
.get(), params
, this,
1872 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1875 #if defined(OS_CHROMEOS)
1876 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1878 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1879 // TODO(jam): change to take RenderFrame.
1880 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1887 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1888 const blink::WebURLRequest
& request
,
1889 blink::WebNavigationPolicy policy
) {
1890 DCHECK(!frame_
|| frame_
== frame
);
1891 loadURLExternally(frame
, request
, policy
, WebString());
1894 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1895 OnJavaScriptExecuteRequest(javascript
, 0, false);
1898 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1899 return &service_registry_
;
1902 #if defined(ENABLE_PLUGINS)
1903 void RenderFrameImpl::RegisterPeripheralPlugin(
1904 const GURL
& content_origin
,
1905 const base::Closure
& unthrottle_callback
) {
1906 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1907 content_origin
, unthrottle_callback
);
1909 #endif // defined(ENABLE_PLUGINS)
1911 bool RenderFrameImpl::IsFTPDirectoryListing() {
1912 WebURLResponseExtraDataImpl
* extra_data
=
1913 GetExtraDataFromResponse(frame_
->dataSource()->response());
1914 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1917 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1918 BrowserPluginManager::Get()->Attach(element_instance_id
);
1921 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1922 BrowserPluginManager::Get()->Detach(element_instance_id
);
1925 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1927 const gfx::Range
& range
) {
1928 // Use the routing id of Render Widget Host.
1929 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1935 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1936 v8::Isolate
* isolate
,
1937 v8::Local
<v8::Context
> context
) {
1938 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1939 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1942 v8::HandleScope
handle_scope(isolate
);
1943 registry
->AddBuiltinModule(
1944 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1945 registry
->AddBuiltinModule(isolate
,
1946 mojo::js::Support::kModuleName
,
1947 mojo::js::Support::GetModule(isolate
));
1948 registry
->AddBuiltinModule(
1950 ServiceRegistryJsWrapper::kModuleName
,
1951 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1954 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
1955 const std::string
& message
) {
1956 if (devtools_agent_
)
1957 devtools_agent_
->AddMessageToConsole(level
, message
);
1960 // blink::WebFrameClient implementation ----------------------------------------
1962 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1963 blink::WebLocalFrame
* frame
,
1964 const blink::WebPluginParams
& params
) {
1965 DCHECK_EQ(frame_
, frame
);
1966 return GetContentClient()
1968 ->CreatePluginPlaceholder(this, frame
, params
)
1972 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1973 blink::WebLocalFrame
* frame
,
1974 const blink::WebPluginParams
& params
) {
1975 DCHECK_EQ(frame_
, frame
);
1976 blink::WebPlugin
* plugin
= NULL
;
1977 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1978 this, frame
, params
, &plugin
)) {
1982 if (base::UTF16ToUTF8(base::StringPiece16(params
.mimeType
)) ==
1983 kBrowserPluginMimeType
) {
1984 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1985 this, GetContentClient()
1987 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
1992 #if defined(ENABLE_PLUGINS)
1994 std::string mime_type
;
1996 Send(new FrameHostMsg_GetPluginInfo(
1997 routing_id_
, params
.url
, frame
->top()->document().url(),
1998 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
2002 WebPluginParams params_to_use
= params
;
2003 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2004 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2007 #endif // defined(ENABLE_PLUGINS)
2010 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2011 blink::WebLocalFrame
* frame
,
2012 const blink::WebURL
& url
,
2013 WebMediaPlayerClient
* client
,
2014 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
2015 WebContentDecryptionModule
* initial_cdm
) {
2016 #if defined(VIDEO_HOLE)
2017 if (!contains_media_player_
) {
2018 render_view_
->RegisterVideoHoleFrame(this);
2019 contains_media_player_
= true;
2021 #endif // defined(VIDEO_HOLE)
2023 blink::WebMediaStream
web_stream(
2024 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2025 if (!web_stream
.isNull())
2026 return CreateWebMediaPlayerForMediaStream(client
);
2028 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2029 return CreateAndroidWebMediaPlayer(client
, encrypted_client
,
2030 GetMediaPermission(), initial_cdm
);
2032 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2034 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2035 media::WebMediaPlayerParams
params(
2036 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2037 base::Unretained(GetContentClient()->renderer()),
2038 static_cast<RenderFrame
*>(this), has_played_media_
),
2039 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2040 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2041 render_thread
->GetWorkerTaskRunner(),
2042 render_thread
->compositor_task_runner(),
2043 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2046 #if defined(ENABLE_MOJO_MEDIA)
2047 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2048 new media::MojoRendererFactory(GetMediaServiceFactory()));
2050 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2051 GetContentClient()->renderer()->CreateMediaRendererFactory(
2052 this, render_thread
->GetGpuFactories(), media_log
);
2054 if (!media_renderer_factory
.get()) {
2055 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2056 media_log
, render_thread
->GetGpuFactories(),
2057 *render_thread
->GetAudioHardwareConfig()));
2059 #endif // defined(ENABLE_MOJO_MEDIA)
2061 return new media::WebMediaPlayerImpl(
2062 frame
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
2063 media_renderer_factory
.Pass(), GetCdmFactory(), params
);
2064 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2067 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2068 blink::WebLocalFrame
* frame
,
2069 blink::WebApplicationCacheHostClient
* client
) {
2070 if (!frame
|| !frame
->view())
2072 DCHECK(!frame_
|| frame_
== frame
);
2073 return new RendererWebApplicationCacheHostImpl(
2074 RenderViewImpl::FromWebView(frame
->view()), client
,
2075 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2078 blink::WebWorkerContentSettingsClientProxy
*
2079 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2080 blink::WebLocalFrame
* frame
) {
2081 if (!frame
|| !frame
->view())
2083 DCHECK(!frame_
|| frame_
== frame
);
2084 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2088 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2089 const WebPopupMenuInfo
& popup_menu_info
,
2090 WebExternalPopupMenuClient
* popup_menu_client
) {
2091 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2092 // An IPC message is sent to the browser to build and display the actual
2093 // popup. The user could have time to click a different select by the time
2094 // the popup is shown. In that case external_popup_menu_ is non NULL.
2095 // By returning NULL in that case, we instruct Blink to cancel that new
2096 // popup. So from the user perspective, only the first one will show, and
2097 // will have to close the first one before another one can be shown.
2098 if (external_popup_menu_
)
2100 external_popup_menu_
.reset(
2101 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2102 if (render_view_
->screen_metrics_emulator_
) {
2103 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2104 external_popup_menu_
.get(),
2105 render_view_
->screen_metrics_emulator_
.get());
2107 return external_popup_menu_
.get();
2113 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2114 DCHECK(!frame_
|| frame_
== frame
);
2115 return &cookie_jar_
;
2118 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2119 blink::WebLocalFrame
* frame
) {
2120 DCHECK(!frame_
|| frame_
== frame
);
2121 // At this point we should have non-null data source.
2122 DCHECK(frame
->dataSource());
2123 if (!ChildThreadImpl::current())
2124 return NULL
; // May be null in some tests.
2125 ServiceWorkerNetworkProvider
* provider
=
2126 ServiceWorkerNetworkProvider::FromDocumentState(
2127 DocumentState::FromDataSource(frame
->dataSource()));
2129 return new WebServiceWorkerProviderImpl(
2130 ChildThreadImpl::current()->thread_safe_sender(),
2131 provider
->context());
2134 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2135 DCHECK(!frame_
|| frame_
== frame
);
2136 // If the request hasn't yet committed, notify the browser process that it is
2137 // no longer safe to show the pending URL of the main frame, since a URL spoof
2138 // is now possible. (If the request has committed, the browser already knows.)
2139 if (!frame
->parent()) {
2140 DocumentState
* document_state
=
2141 DocumentState::FromDataSource(frame
->dataSource());
2142 NavigationStateImpl
* navigation_state
=
2143 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2145 if (!navigation_state
->request_committed()) {
2146 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2151 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2152 blink::WebLocalFrame
* parent
,
2153 blink::WebTreeScopeType scope
,
2154 const blink::WebString
& name
,
2155 blink::WebSandboxFlags sandbox_flags
) {
2156 // Synchronously notify the browser of a child frame creation to get the
2157 // routing_id for the RenderFrame.
2158 int child_routing_id
= MSG_ROUTING_NONE
;
2159 Send(new FrameHostMsg_CreateChildFrame(
2161 base::UTF16ToUTF8(base::StringPiece16(name
)), sandbox_flags
,
2162 &child_routing_id
));
2164 // Allocation of routing id failed, so we can't create a child frame. This can
2165 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2166 // out state or synchronous IPC message above has failed.
2167 if (child_routing_id
== MSG_ROUTING_NONE
) {
2168 NOTREACHED() << "Failed to allocate routing id for child frame.";
2172 // Create the RenderFrame and WebLocalFrame, linking the two.
2173 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2174 render_view_
.get(), child_routing_id
);
2175 blink::WebLocalFrame
* web_frame
=
2176 WebLocalFrame::create(scope
, child_render_frame
);
2177 child_render_frame
->SetWebFrame(web_frame
);
2179 // Add the frame to the frame tree and initialize it.
2180 parent
->appendChild(web_frame
);
2181 child_render_frame
->Initialize();
2186 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2187 DCHECK(!frame_
|| frame_
== frame
);
2188 // We only need to notify the browser if the active, top-level frame clears
2189 // its opener. We can ignore cases where a swapped out frame clears its
2190 // opener after hearing about it from the browser, and the browser does not
2191 // (yet) care about subframe openers.
2192 if (is_swapped_out_
|| frame
->parent())
2195 // Notify WebContents and all its swapped out RenderViews.
2196 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2199 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2200 // NOTE: This function is called on the frame that is being detached and not
2201 // the parent frame. This is different from createChildFrame() which is
2202 // called on the parent frame.
2203 CHECK(!is_detaching_
);
2204 DCHECK(!frame_
|| frame_
== frame
);
2206 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2207 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2208 FrameDetached(frame
));
2210 // We only notify the browser process when the frame is being detached for
2211 // removal. If the frame is being detached for swap, we don't need to do this
2212 // since we are not modifiying the frame tree.
2213 if (type
== DetachType::Remove
)
2214 Send(new FrameHostMsg_Detach(routing_id_
));
2216 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2217 // sent before setting |is_detaching_| to true.
2218 is_detaching_
= true;
2220 // Clean up the associated RenderWidget for the frame, if there is one.
2221 if (render_widget_
) {
2222 render_widget_
->UnregisterRenderFrame(this);
2223 render_widget_
->CloseForFrame();
2226 // We need to clean up subframes by removing them from the map and deleting
2227 // the RenderFrameImpl. In contrast, the main frame is owned by its
2228 // containing RenderViewHost (so that they have the same lifetime), so only
2229 // removal from the map is needed and no deletion.
2230 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2231 CHECK(it
!= g_frame_map
.Get().end());
2232 CHECK_EQ(it
->second
, this);
2233 g_frame_map
.Get().erase(it
);
2235 // Only remove the frame from the renderer's frame tree if the frame is
2236 // being detached for removal. In the case of a swap, the frame needs to
2237 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2238 if (is_subframe_
&& type
== DetachType::Remove
)
2239 frame
->parent()->removeChild(frame
);
2241 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2242 // object may not be deleted immediately and other methods may try to access
2248 // Object is invalid after this point.
2251 void RenderFrameImpl::frameFocused() {
2252 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2255 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2256 DCHECK(!frame_
|| frame_
== frame
);
2258 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2259 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2260 FrameWillClose(frame
));
2263 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2264 const blink::WebString
& name
) {
2265 DCHECK(!frame_
|| frame_
== frame
);
2267 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2268 // updates may have performance implications for benchmarks like SunSpider.
2269 // For now, send these updates only for --site-per-process, which needs to
2270 // replicate frame names to frame proxies, and when
2271 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2272 // can be optimized further by only sending the update if there are any
2273 // remote frames in the frame tree, or delaying and batching up IPCs if
2274 // updates are happening too frequently.
2275 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2276 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2277 Send(new FrameHostMsg_DidChangeName(
2278 routing_id_
, base::UTF16ToUTF8(base::StringPiece16(name
))));
2282 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2283 blink::WebSandboxFlags flags
) {
2284 int frame_routing_id
= MSG_ROUTING_NONE
;
2285 if (child_frame
->isWebRemoteFrame()) {
2287 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2290 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2293 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2297 void RenderFrameImpl::didMatchCSS(
2298 blink::WebLocalFrame
* frame
,
2299 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2300 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2301 DCHECK(!frame_
|| frame_
== frame
);
2303 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2304 DidMatchCSS(newly_matching_selectors
,
2305 stopped_matching_selectors
));
2308 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2309 const blink::WebString
& source
) {
2310 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2314 void RenderFrameImpl::didAddMessageToConsole(
2315 const blink::WebConsoleMessage
& message
,
2316 const blink::WebString
& source_name
,
2317 unsigned source_line
,
2318 const blink::WebString
& stack_trace
) {
2319 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2320 switch (message
.level
) {
2321 case blink::WebConsoleMessage::LevelDebug
:
2322 log_severity
= logging::LOG_VERBOSE
;
2324 case blink::WebConsoleMessage::LevelLog
:
2325 case blink::WebConsoleMessage::LevelInfo
:
2326 log_severity
= logging::LOG_INFO
;
2328 case blink::WebConsoleMessage::LevelWarning
:
2329 log_severity
= logging::LOG_WARNING
;
2331 case blink::WebConsoleMessage::LevelError
:
2332 log_severity
= logging::LOG_ERROR
;
2335 log_severity
= logging::LOG_VERBOSE
;
2338 if (shouldReportDetailedMessageForSource(source_name
)) {
2340 RenderFrameObserver
, observers_
,
2341 DetailedConsoleMessageAdded(message
.text
,
2345 static_cast<int32
>(log_severity
)));
2348 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2349 static_cast<int32
>(log_severity
),
2351 static_cast<int32
>(source_line
),
2355 void RenderFrameImpl::loadURLExternally(
2356 blink::WebLocalFrame
* frame
,
2357 const blink::WebURLRequest
& request
,
2358 blink::WebNavigationPolicy policy
,
2359 const blink::WebString
& suggested_name
) {
2360 DCHECK(!frame_
|| frame_
== frame
);
2361 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2362 if (policy
== blink::WebNavigationPolicyDownload
) {
2363 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2364 request
.url(), referrer
,
2367 OpenURL(frame
, request
.url(), referrer
, policy
);
2371 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2372 const NavigationPolicyInfo
& info
) {
2373 DCHECK(!frame_
|| frame_
== info
.frame
);
2374 return DecidePolicyForNavigation(this, info
);
2377 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2378 blink::WebFrame
* frame
) {
2379 DCHECK(!frame_
|| frame_
== frame
);
2380 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2383 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2384 const blink::WebFormElement
& form
) {
2385 DCHECK(!frame_
|| frame_
== frame
);
2387 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2390 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2391 const blink::WebFormElement
& form
) {
2392 DCHECK(!frame_
|| frame_
== frame
);
2393 DocumentState
* document_state
=
2394 DocumentState::FromDataSource(frame
->provisionalDataSource());
2395 NavigationStateImpl
* navigation_state
=
2396 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2397 InternalDocumentStateData
* internal_data
=
2398 InternalDocumentStateData::FromDocumentState(document_state
);
2400 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2401 ui::PAGE_TRANSITION_LINK
)) {
2402 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2405 // Save these to be processed when the ensuing navigation is committed.
2406 WebSearchableFormData
web_searchable_form_data(form
);
2407 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2408 internal_data
->set_searchable_form_encoding(
2409 web_searchable_form_data
.encoding().utf8());
2411 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2414 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2415 blink::WebDataSource
* datasource
) {
2416 DCHECK(!frame_
|| frame_
== frame
);
2418 bool content_initiated
= !pending_navigation_params_
.get();
2420 // Make sure any previous redirect URLs end up in our new data source.
2421 if (pending_navigation_params_
.get()) {
2422 for (const auto& i
:
2423 pending_navigation_params_
->request_params
.redirects
) {
2424 datasource
->appendRedirect(i
);
2428 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2429 if (!document_state
) {
2430 document_state
= new DocumentState
;
2431 datasource
->setExtraData(document_state
);
2432 if (!content_initiated
)
2433 PopulateDocumentStateFromPending(document_state
);
2436 // Carry over the user agent override flag, if it exists.
2437 blink::WebView
* webview
= render_view_
->webview();
2438 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2439 webview
->mainFrame()->isWebLocalFrame() &&
2440 webview
->mainFrame()->dataSource()) {
2441 DocumentState
* old_document_state
=
2442 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2443 if (old_document_state
) {
2444 InternalDocumentStateData
* internal_data
=
2445 InternalDocumentStateData::FromDocumentState(document_state
);
2446 InternalDocumentStateData
* old_internal_data
=
2447 InternalDocumentStateData::FromDocumentState(old_document_state
);
2448 internal_data
->set_is_overriding_user_agent(
2449 old_internal_data
->is_overriding_user_agent());
2453 // The rest of RenderView assumes that a WebDataSource will always have a
2454 // non-null NavigationState.
2455 if (content_initiated
) {
2456 document_state
->set_navigation_state(
2457 NavigationStateImpl::CreateContentInitiated());
2459 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2460 pending_navigation_params_
.reset();
2463 // DocumentState::referred_by_prefetcher_ is true if we are
2464 // navigating from a page that used prefetching using a link on that
2465 // page. We are early enough in the request process here that we
2466 // can still see the DocumentState of the previous page and set
2467 // this value appropriately.
2468 // TODO(gavinp): catch the important case of navigation in a new
2469 // renderer process.
2471 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2472 const WebURLRequest
& original_request
= datasource
->originalRequest();
2473 const GURL
referrer(
2474 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2475 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2476 DocumentState::FromDataSource(old_frame
->dataSource())
2477 ->was_prefetcher()) {
2478 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2479 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2480 if (old_frame_datasource
&&
2481 referrer
== GURL(old_frame_datasource
->request().url())) {
2482 document_state
->set_was_referred_by_prefetcher(true);
2490 if (content_initiated
) {
2491 const WebURLRequest
& request
= datasource
->request();
2492 switch (request
.cachePolicy()) {
2493 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2494 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2496 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2497 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2498 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2500 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2501 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2503 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2504 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2511 // Create the serviceworker's per-document network observing object if it
2512 // does not exist (When navigation happens within a page, the provider already
2514 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2515 DocumentState::FromDataSource(datasource
))) {
2516 ServiceWorkerProviderType provider_type
=
2517 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2518 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2519 blink::WebSandboxFlags::Origin
) {
2520 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2522 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2523 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2524 ServiceWorkerNetworkProvider::AttachToDocumentState(
2525 DocumentState::FromDataSource(datasource
),
2526 network_provider
.Pass());
2530 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2531 double triggering_event_time
) {
2532 DCHECK(!frame_
|| frame_
== frame
);
2533 WebDataSource
* ds
= frame
->provisionalDataSource();
2535 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2536 // callback is invoked.
2540 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2541 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2542 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2544 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2545 CHECK_IMPLIES(ds
->request().url() == GURL(kSwappedOutURL
), is_swapped_out_
)
2546 << "Heard swappedout:// when not swapped out.";
2548 // Update the request time if WebKit has better knowledge of it.
2549 if (document_state
->request_time().is_null() &&
2550 triggering_event_time
!= 0.0) {
2551 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2554 // Start time is only set after request time.
2555 document_state
->set_start_load_time(Time::Now());
2557 bool is_top_most
= !frame
->parent();
2559 render_view_
->set_navigation_gesture(
2560 WebUserGestureIndicator::isProcessingUserGesture() ?
2561 NavigationGestureUser
: NavigationGestureAuto
);
2562 } else if (ds
->replacesCurrentHistoryItem()) {
2563 // Subframe navigations that don't add session history items must be
2564 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2565 // handle loading of error pages.
2566 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2567 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2570 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2571 DidStartProvisionalLoad(frame
));
2572 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2574 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2575 routing_id_
, ds
->request().url()));
2578 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2579 blink::WebLocalFrame
* frame
) {
2580 DCHECK(!frame_
|| frame_
== frame
);
2581 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2584 void RenderFrameImpl::didFailProvisionalLoad(
2585 blink::WebLocalFrame
* frame
,
2586 const blink::WebURLError
& error
,
2587 blink::WebHistoryCommitType commit_type
) {
2588 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2590 DCHECK(!frame_
|| frame_
== frame
);
2591 WebDataSource
* ds
= frame
->provisionalDataSource();
2594 const WebURLRequest
& failed_request
= ds
->request();
2596 // Notify the browser that we failed a provisional load with an error.
2598 // Note: It is important this notification occur before DidStopLoading so the
2599 // SSL manager can react to the provisional load failure before being
2600 // notified the load stopped.
2602 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2603 DidFailProvisionalLoad(frame
, error
));
2604 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2605 DidFailProvisionalLoad(error
));
2607 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2609 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2612 // Make sure we never show errors in view source mode.
2613 frame
->enableViewSourceMode(false);
2615 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2616 NavigationStateImpl
* navigation_state
=
2617 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2619 // If this is a failed back/forward/reload navigation, then we need to do a
2620 // 'replace' load. This is necessary to avoid messing up session history.
2621 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2622 // as session history is concerned.
2623 bool replace
= commit_type
!= blink::WebStandardCommit
;
2625 // If we failed on a browser initiated request, then make sure that our error
2626 // page load is regarded as the same browser initiated request.
2627 if (!navigation_state
->IsContentInitiated()) {
2628 pending_navigation_params_
.reset(new NavigationParams(
2629 navigation_state
->common_params(), navigation_state
->start_params(),
2630 navigation_state
->request_params()));
2631 pending_navigation_params_
->request_params
.request_time
=
2632 document_state
->request_time();
2635 // Load an error page.
2636 LoadNavigationErrorPage(failed_request
, error
, replace
);
2639 void RenderFrameImpl::didCommitProvisionalLoad(
2640 blink::WebLocalFrame
* frame
,
2641 const blink::WebHistoryItem
& item
,
2642 blink::WebHistoryCommitType commit_type
) {
2643 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2645 "url", GetLoadingUrl().possibly_invalid_spec());
2646 DCHECK(!frame_
|| frame_
== frame
);
2647 DocumentState
* document_state
=
2648 DocumentState::FromDataSource(frame
->dataSource());
2649 NavigationStateImpl
* navigation_state
=
2650 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2652 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2653 RenderFrameProxy
* proxy
=
2654 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2656 proxy
->web_frame()->swap(frame_
);
2657 proxy_routing_id_
= MSG_ROUTING_NONE
;
2659 // If this is the main frame going from a remote frame to a local frame,
2660 // it needs to set RenderViewImpl's pointer for the main frame to itself
2661 // and ensure RenderWidget is no longer in swapped out mode.
2662 if (!is_subframe_
) {
2663 CHECK(!render_view_
->main_render_frame_
);
2664 render_view_
->main_render_frame_
= this;
2665 if (render_view_
->is_swapped_out())
2666 render_view_
->SetSwappedOut(false);
2670 // When we perform a new navigation, we need to update the last committed
2671 // session history entry with state for the page we are leaving. Do this
2672 // before updating the HistoryController state.
2673 render_view_
->SendUpdateState();
2675 render_view_
->history_controller()->UpdateForCommit(
2676 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2678 InternalDocumentStateData
* internal_data
=
2679 InternalDocumentStateData::FromDocumentState(document_state
);
2681 if (document_state
->commit_load_time().is_null())
2682 document_state
->set_commit_load_time(Time::Now());
2684 if (internal_data
->must_reset_scroll_and_scale_state()) {
2685 render_view_
->webview()->resetScrollAndScaleState();
2686 internal_data
->set_must_reset_scroll_and_scale_state(false);
2689 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2690 if (is_new_navigation
) {
2691 // We bump our Page ID to correspond with the new session history entry.
2692 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2694 // Don't update history list values for kSwappedOutURL, since
2695 // we don't want to forget the entry that was there, and since we will
2696 // never come back to kSwappedOutURL. Note that we have to call
2697 // SendUpdateState and update page_id_ even in this case, so that
2698 // the current entry gets a state update and so that we don't send a
2699 // state update to the wrong entry when we swap back in.
2701 navigation_state
->common_params().should_replace_current_entry
,
2702 render_view_
->history_list_length_
> 0);
2703 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2704 !navigation_state
->common_params().should_replace_current_entry
) {
2705 // Advance our offset in session history, applying the length limit.
2706 // There is now no forward history.
2707 render_view_
->history_list_offset_
++;
2708 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2709 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2710 render_view_
->history_list_length_
=
2711 render_view_
->history_list_offset_
+ 1;
2714 const RequestNavigationParams
& request_params
=
2715 navigation_state
->request_params();
2716 if (request_params
.nav_entry_id
!= 0 &&
2717 !request_params
.intended_as_new_entry
) {
2718 // This is a successful session history navigation!
2719 render_view_
->page_id_
= request_params
.page_id
;
2721 render_view_
->history_list_offset_
=
2722 request_params
.pending_history_list_offset
;
2727 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2728 CHECK(sent
); // http://crbug.com/407376
2730 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2731 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2733 RenderFrameObserver
, observers_
,
2734 DidCommitProvisionalLoad(is_new_navigation
,
2735 navigation_state
->WasWithinSamePage()));
2737 if (!frame
->parent()) { // Only for top frames.
2738 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2739 if (render_thread_impl
) { // Can be NULL in tests.
2740 render_thread_impl
->histogram_customizer()->
2741 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2742 RenderView::GetRenderViewCount());
2746 // Remember that we've already processed this request, so we don't update
2747 // the session history again. We do this regardless of whether this is
2748 // a session history navigation, because if we attempted a session history
2749 // navigation without valid HistoryItem state, WebCore will think it is a
2751 navigation_state
->set_request_committed(true);
2753 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2755 // Check whether we have new encoding name.
2756 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2759 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2760 DCHECK(!frame_
|| frame_
== frame
);
2762 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2763 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2764 DidCreateNewDocument(frame
));
2767 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2768 DCHECK(!frame_
|| frame_
== frame
);
2770 int enabled_bindings
= render_view_
->GetEnabledBindings();
2772 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2773 WebUIExtension::Install(frame
);
2775 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2776 DomAutomationController::Install(this, frame
);
2778 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2779 StatsCollectionController::Install(frame
);
2781 const base::CommandLine
& command_line
=
2782 *base::CommandLine::ForCurrentProcess();
2784 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2785 GpuBenchmarking::Install(frame
);
2787 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2788 MemoryBenchmarkingExtension::Install(frame
);
2790 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2791 SkiaBenchmarking::Install(frame
);
2793 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2794 DidClearWindowObject(frame
));
2795 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2798 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2799 DCHECK(!frame_
|| frame_
== frame
);
2801 // Notify the browser about non-blank documents loading in the top frame.
2802 GURL url
= frame
->document().url();
2803 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2804 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2805 // frame->tree()->top().
2806 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2807 if (frame
== main_frame
) {
2808 // For now, don't remember plugin zoom values. We don't want to mix them
2809 // with normal web content (i.e. a fixed layout plugin would usually want
2811 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2812 render_view_
->GetRoutingID(),
2813 main_frame
->document().isPluginDocument()));
2817 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2818 DidCreateDocumentElement());
2819 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2820 DidCreateDocumentElement(frame
));
2823 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2824 const blink::WebString
& title
,
2825 blink::WebTextDirection direction
) {
2826 DCHECK(!frame_
|| frame_
== frame
);
2827 // Ignore all but top level navigations.
2828 if (!frame
->parent()) {
2829 base::string16 title16
= title
;
2830 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2831 routing_id_
, base::UTF16ToUTF8(title16
));
2833 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2834 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2835 shortened_title
, direction
));
2838 // Also check whether we have new encoding name.
2839 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2842 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2843 blink::WebIconURL::Type icon_type
) {
2844 DCHECK(!frame_
|| frame_
== frame
);
2845 // TODO(nasko): Investigate wheather implementation should move here.
2846 render_view_
->didChangeIcon(frame
, icon_type
);
2849 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
,
2850 bool document_is_empty
) {
2851 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2853 DCHECK(!frame_
|| frame_
== frame
);
2854 WebDataSource
* ds
= frame
->dataSource();
2855 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2856 document_state
->set_finish_document_load_time(Time::Now());
2858 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2860 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2861 DidFinishDocumentLoad(frame
));
2862 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2864 // Check whether we have new encoding name.
2865 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2867 // If this is an empty document with an http status code indicating an error,
2868 // we may want to display our own error page, so the user doesn't end up
2869 // with an unexplained blank page.
2870 if (!document_is_empty
)
2873 // Do not show error page when DevTools is attached.
2874 RenderFrameImpl
* localRoot
= this;
2875 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
2876 localRoot
->frame_
->parent()->isWebLocalFrame()) {
2877 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
2880 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
2883 // Display error page instead of a blank page, if appropriate.
2884 std::string error_domain
= "http";
2885 InternalDocumentStateData
* internal_data
=
2886 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2887 int http_status_code
= internal_data
->http_status_code();
2888 if (GetContentClient()->renderer()->HasErrorPage(http_status_code
,
2891 error
.unreachableURL
= frame
->document().url();
2892 error
.domain
= WebString::fromUTF8(error_domain
);
2893 error
.reason
= http_status_code
;
2894 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
2898 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2899 DCHECK(!frame_
|| frame_
== frame
);
2900 if (!frame
->parent()) {
2901 FrameMsg_UILoadMetricsReportType::Value report_type
=
2902 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2903 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2904 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2905 base::TimeDelta::FromSecondsD(
2906 frame
->dataSource()->request().uiStartTime());
2908 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2909 routing_id_
, report_type
, ui_timestamp
));
2913 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2914 const blink::WebURLError
& error
,
2915 blink::WebHistoryCommitType commit_type
) {
2916 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2918 DCHECK(!frame_
|| frame_
== frame
);
2919 // TODO(nasko): Move implementation here. No state needed.
2920 WebDataSource
* ds
= frame
->dataSource();
2923 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2924 DidFailLoad(frame
, error
));
2926 const WebURLRequest
& failed_request
= ds
->request();
2927 base::string16 error_description
;
2928 GetContentClient()->renderer()->GetNavigationErrorStrings(
2934 &error_description
);
2935 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2936 failed_request
.url(),
2939 error
.wasIgnoredByHandler
));
2942 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2943 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2945 DCHECK(!frame_
|| frame_
== frame
);
2946 WebDataSource
* ds
= frame
->dataSource();
2947 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2948 if (document_state
->finish_load_time().is_null()) {
2949 if (!frame
->parent()) {
2950 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2951 TRACE_EVENT_SCOPE_PROCESS
);
2953 document_state
->set_finish_load_time(Time::Now());
2956 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2957 DidFinishLoad(frame
));
2958 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2960 // Don't send this message while the frame is swapped out.
2961 if (is_swapped_out())
2964 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2965 ds
->request().url()));
2968 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2969 const blink::WebHistoryItem
& item
,
2970 blink::WebHistoryCommitType commit_type
) {
2971 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2973 DCHECK(!frame_
|| frame_
== frame
);
2974 // If this was a reference fragment navigation that we initiated, then we
2975 // could end up having a non-null pending navigation params. We just need to
2976 // update the ExtraData on the datasource so that others who read the
2977 // ExtraData will get the new NavigationState. Similarly, if we did not
2978 // initiate this navigation, then we need to take care to reset any pre-
2979 // existing navigation state to a content-initiated navigation state.
2980 // didCreateDataSource conveniently takes care of this for us.
2981 didCreateDataSource(frame
, frame
->dataSource());
2983 DocumentState
* document_state
=
2984 DocumentState::FromDataSource(frame
->dataSource());
2985 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2986 ->set_was_within_same_page(true);
2988 didCommitProvisionalLoad(frame
, item
, commit_type
);
2991 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2992 DCHECK(!frame_
|| frame_
== frame
);
2993 // TODO(nasko): Move implementation here. Needed methods:
2994 // * StartNavStateSyncTimerIfNecessary
2995 render_view_
->didUpdateCurrentHistoryItem(frame
);
2998 void RenderFrameImpl::didChangeThemeColor() {
2999 if (frame_
->parent())
3002 Send(new FrameHostMsg_DidChangeThemeColor(
3003 routing_id_
, frame_
->document().themeColor()));
3006 void RenderFrameImpl::dispatchLoad() {
3007 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
3010 void RenderFrameImpl::requestNotificationPermission(
3011 const blink::WebSecurityOrigin
& origin
,
3012 blink::WebNotificationPermissionCallback
* callback
) {
3013 if (!notification_permission_dispatcher_
) {
3014 notification_permission_dispatcher_
=
3015 new NotificationPermissionDispatcher(this);
3018 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3021 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3022 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3025 if (is_empty_selection
)
3026 selection_text_
.clear();
3028 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3029 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3030 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3031 // to notify the selection was changed. Focus change should be notified
3032 // before selection change.
3033 GetRenderWidget()->UpdateTextInputState(
3034 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
3035 SyncSelectionIfRequired();
3038 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3039 blink::WebColorChooserClient
* client
,
3040 const blink::WebColor
& initial_color
,
3041 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3042 RendererWebColorChooserImpl
* color_chooser
=
3043 new RendererWebColorChooserImpl(this, client
);
3044 std::vector
<ColorSuggestion
> color_suggestions
;
3045 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3046 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3048 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3049 return color_chooser
;
3052 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3053 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3056 frame_
->document().url(),
3060 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3061 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3064 frame_
->document().url(),
3068 bool RenderFrameImpl::runModalPromptDialog(
3069 const blink::WebString
& message
,
3070 const blink::WebString
& default_value
,
3071 blink::WebString
* actual_value
) {
3072 base::string16 result
;
3073 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3076 frame_
->document().url(),
3079 actual_value
->assign(result
);
3083 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3085 const blink::WebString
& message
) {
3086 // If we are swapping out, we have already run the beforeunload handler.
3087 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3088 // at all, to avoid running it twice.
3089 if (is_swapped_out_
)
3092 // Don't allow further dialogs if we are waiting to swap out, since the
3093 // PageGroupLoadDeferrer in our stack prevents it.
3094 if (render_view()->suppress_dialogs_until_swap_out_
)
3097 bool success
= false;
3098 // This is an ignored return value, but is included so we can accept the same
3099 // response as RunJavaScriptMessage.
3100 base::string16 ignored_result
;
3101 render_view()->SendAndRunNestedMessageLoop(
3102 new FrameHostMsg_RunBeforeUnloadConfirm(
3103 routing_id_
, frame_
->document().url(), message
, is_reload
,
3104 &success
, &ignored_result
));
3108 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3109 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3110 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3111 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3112 if (GetRenderWidget()->has_host_context_menu_location()) {
3113 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3114 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3117 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3118 // it. We replace it with an empty GURL so the appropriate items are disabled
3119 // in the context menu.
3120 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3121 // data encoded images. We should have a way to save them.
3122 if (params
.src_url
.spec().size() > GetMaxURLChars())
3123 params
.src_url
= GURL();
3124 context_menu_node_
= data
.node
;
3126 #if defined(OS_ANDROID)
3127 gfx::Rect start_rect
;
3129 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3130 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3131 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3134 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3137 void RenderFrameImpl::clearContextMenu() {
3138 context_menu_node_
.reset();
3141 void RenderFrameImpl::willSendRequest(
3142 blink::WebLocalFrame
* frame
,
3143 unsigned identifier
,
3144 blink::WebURLRequest
& request
,
3145 const blink::WebURLResponse
& redirect_response
) {
3146 DCHECK(!frame_
|| frame_
== frame
);
3147 // The request my be empty during tests.
3148 if (request
.url().isEmpty())
3151 // Set the first party for cookies url if it has not been set yet (new
3152 // requests). For redirects, it is updated by WebURLLoaderImpl.
3153 if (request
.firstPartyForCookies().isEmpty()) {
3154 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3155 request
.setFirstPartyForCookies(request
.url());
3157 // TODO(nasko): When the top-level frame is remote, there is no document.
3158 // This is broken and should be fixed to propagate the first party.
3159 WebFrame
* top
= frame
->top();
3160 if (top
->isWebLocalFrame()) {
3161 request
.setFirstPartyForCookies(
3162 frame
->top()->document().firstPartyForCookies());
3167 WebDataSource
* provisional_data_source
= frame
->provisionalDataSource();
3168 WebDataSource
* data_source
=
3169 provisional_data_source
? provisional_data_source
: frame
->dataSource();
3171 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3172 DCHECK(document_state
);
3173 InternalDocumentStateData
* internal_data
=
3174 InternalDocumentStateData::FromDocumentState(document_state
);
3175 NavigationStateImpl
* navigation_state
=
3176 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3177 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3178 if (provisional_data_source
&& provisional_data_source
->isClientRedirect()) {
3179 transition_type
= ui::PageTransitionFromInt(
3180 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3183 GURL
request_url(request
.url());
3185 if (GetContentClient()->renderer()->WillSendRequest(
3189 request
.firstPartyForCookies(),
3191 request
.setURL(WebURL(new_url
));
3194 if (internal_data
->is_cache_policy_override_set())
3195 request
.setCachePolicy(internal_data
->cache_policy_override());
3197 // The request's extra data may indicate that we should set a custom user
3198 // agent. This needs to be done here, after WebKit is through with setting the
3199 // user agent on its own. Similarly, it may indicate that we should set an
3200 // X-Requested-With header. This must be done here to avoid breaking CORS
3202 // PlzNavigate: there may also be a stream url associated with the request.
3203 WebString custom_user_agent
;
3204 WebString requested_with
;
3205 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3206 if (request
.extraData()) {
3207 RequestExtraData
* old_extra_data
=
3208 static_cast<RequestExtraData
*>(request
.extraData());
3210 custom_user_agent
= old_extra_data
->custom_user_agent();
3211 if (!custom_user_agent
.isNull()) {
3212 if (custom_user_agent
.isEmpty())
3213 request
.clearHTTPHeaderField("User-Agent");
3215 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3218 requested_with
= old_extra_data
->requested_with();
3219 if (!requested_with
.isNull()) {
3220 if (requested_with
.isEmpty())
3221 request
.clearHTTPHeaderField("X-Requested-With");
3223 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3225 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3228 // Add the default accept header for frame request if it has not been set
3230 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3231 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3232 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3233 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3234 WebString::fromUTF8(kDefaultAcceptHeader
));
3237 // Add an empty HTTP origin header for non GET methods if none is currently
3239 request
.addHTTPOriginIfNeeded(WebString());
3241 // Attach |should_replace_current_entry| state to requests so that, should
3242 // this navigation later require a request transfer, all state is preserved
3243 // when it is re-created in the new process.
3244 bool should_replace_current_entry
= false;
3245 if (navigation_state
->IsContentInitiated()) {
3246 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3248 // If the navigation is browser-initiated, the NavigationState contains the
3249 // correct value instead of the WebDataSource.
3251 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3252 // NavigationState::should_replace_current_entry().
3253 should_replace_current_entry
=
3254 navigation_state
->common_params().should_replace_current_entry
;
3257 int provider_id
= kInvalidServiceWorkerProviderId
;
3258 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3259 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3260 // |provisionalDataSource| may be null in some content::ResourceFetcher
3261 // use cases, we don't hook those requests.
3262 if (frame
->provisionalDataSource()) {
3263 ServiceWorkerNetworkProvider
* provider
=
3264 ServiceWorkerNetworkProvider::FromDocumentState(
3265 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3266 provider_id
= provider
->provider_id();
3268 } else if (frame
->dataSource()) {
3269 ServiceWorkerNetworkProvider
* provider
=
3270 ServiceWorkerNetworkProvider::FromDocumentState(
3271 DocumentState::FromDataSource(frame
->dataSource()));
3272 provider_id
= provider
->provider_id();
3275 WebFrame
* parent
= frame
->parent();
3276 int parent_routing_id
= MSG_ROUTING_NONE
;
3278 parent_routing_id
= -1;
3279 } else if (parent
->isWebLocalFrame()) {
3280 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3282 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3285 RequestExtraData
* extra_data
= new RequestExtraData();
3286 extra_data
->set_visibility_state(render_view_
->visibilityState());
3287 extra_data
->set_custom_user_agent(custom_user_agent
);
3288 extra_data
->set_requested_with(requested_with
);
3289 extra_data
->set_render_frame_id(routing_id_
);
3290 extra_data
->set_is_main_frame(!parent
);
3291 extra_data
->set_frame_origin(
3292 GURL(frame
->document().securityOrigin().toString()));
3293 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3294 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3295 extra_data
->set_allow_download(
3296 navigation_state
->common_params().allow_download
);
3297 extra_data
->set_transition_type(transition_type
);
3298 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3299 extra_data
->set_transferred_request_child_id(
3300 navigation_state
->start_params().transferred_request_child_id
);
3301 extra_data
->set_transferred_request_request_id(
3302 navigation_state
->start_params().transferred_request_request_id
);
3303 extra_data
->set_service_worker_provider_id(provider_id
);
3304 extra_data
->set_stream_override(stream_override
.Pass());
3305 request
.setExtraData(extra_data
);
3307 // TODO(creis): Update prefetching to work with out-of-process iframes.
3308 WebFrame
* top_frame
= frame
->top();
3309 if (top_frame
&& top_frame
->isWebLocalFrame()) {
3310 DocumentState
* top_document_state
=
3311 DocumentState::FromDataSource(top_frame
->dataSource());
3312 if (top_document_state
) {
3313 // TODO(gavinp): separate out prefetching and prerender field trials
3314 // if the rel=prerender rel type is sticking around.
3315 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3316 top_document_state
->set_was_prefetcher(true);
3320 // This is an instance where we embed a copy of the routing id
3321 // into the data portion of the message. This can cause problems if we
3322 // don't register this id on the browser side, since the download manager
3323 // expects to find a RenderViewHost based off the id.
3324 request
.setRequestorID(render_view_
->GetRoutingID());
3325 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3327 if (!navigation_state
->start_params().extra_headers
.empty()) {
3328 for (net::HttpUtil::HeadersIterator
i(
3329 navigation_state
->start_params().extra_headers
.begin(),
3330 navigation_state
->start_params().extra_headers
.end(), "\n");
3332 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3333 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3334 blink::WebReferrerPolicyDefault
,
3336 WebString::fromUTF8(i
.values()));
3337 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3339 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3340 WebString::fromUTF8(i
.values()));
3345 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3346 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3349 void RenderFrameImpl::didReceiveResponse(
3350 blink::WebLocalFrame
* frame
,
3351 unsigned identifier
,
3352 const blink::WebURLResponse
& response
) {
3353 DCHECK(!frame_
|| frame_
== frame
);
3354 // Only do this for responses that correspond to a provisional data source
3355 // of the top-most frame. If we have a provisional data source, then we
3356 // can't have any sub-resources yet, so we know that this response must
3357 // correspond to a frame load.
3358 if (!frame
->provisionalDataSource() || frame
->parent())
3361 // If we are in view source mode, then just let the user see the source of
3362 // the server's error page.
3363 if (frame
->isViewSourceModeEnabled())
3366 DocumentState
* document_state
=
3367 DocumentState::FromDataSource(frame
->provisionalDataSource());
3368 int http_status_code
= response
.httpStatusCode();
3370 // Record page load flags.
3371 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3373 document_state
->set_was_fetched_via_spdy(
3374 extra_data
->was_fetched_via_spdy());
3375 document_state
->set_was_npn_negotiated(
3376 extra_data
->was_npn_negotiated());
3377 document_state
->set_npn_negotiated_protocol(
3378 extra_data
->npn_negotiated_protocol());
3379 document_state
->set_was_alternate_protocol_available(
3380 extra_data
->was_alternate_protocol_available());
3381 document_state
->set_connection_info(
3382 extra_data
->connection_info());
3383 document_state
->set_was_fetched_via_proxy(
3384 extra_data
->was_fetched_via_proxy());
3385 document_state
->set_proxy_server(
3386 extra_data
->proxy_server());
3388 InternalDocumentStateData
* internal_data
=
3389 InternalDocumentStateData::FromDocumentState(document_state
);
3390 internal_data
->set_http_status_code(http_status_code
);
3393 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3394 blink::WebLocalFrame
* frame
,
3395 const blink::WebURLRequest
& request
,
3396 const blink::WebURLResponse
& response
) {
3397 DCHECK(!frame_
|| frame_
== frame
);
3398 // The recipients of this message have no use for data: URLs: they don't
3399 // affect the page's insecure content list and are not in the disk cache. To
3400 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3401 // filter them out here.
3402 GURL
url(request
.url());
3403 if (url
.SchemeIs(url::kDataScheme
))
3406 // Let the browser know we loaded a resource from the memory cache. This
3407 // message is needed to display the correct SSL indicators.
3408 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3409 render_view_
->GetRoutingID(),
3411 response
.securityInfo(),
3412 request
.httpMethod().utf8(),
3413 response
.mimeType().utf8(),
3414 WebURLRequestToResourceType(request
)));
3417 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3418 DCHECK(!frame_
|| frame_
== frame
);
3419 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3420 render_view_
->GetRoutingID()));
3423 void RenderFrameImpl::didRunInsecureContent(
3424 blink::WebLocalFrame
* frame
,
3425 const blink::WebSecurityOrigin
& origin
,
3426 const blink::WebURL
& target
) {
3427 DCHECK(!frame_
|| frame_
== frame
);
3428 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3429 render_view_
->GetRoutingID(),
3430 origin
.toString().utf8(),
3432 GetContentClient()->renderer()->RecordRapporURL(
3433 "ContentSettings.MixedScript.RanMixedScript",
3434 GURL(origin
.toString().utf8()));
3437 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3438 DCHECK(!frame_
|| frame_
== frame
);
3439 #if defined(ENABLE_PLUGINS)
3440 if (frame
!= render_view_
->webview()->mainFrame())
3442 PluginChannelHost::Broadcast(
3443 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3447 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3448 v8::Local
<v8::Context
> context
,
3449 int extension_group
,
3451 DCHECK(!frame_
|| frame_
== frame
);
3453 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3454 DidCreateScriptContext(context
, extension_group
, world_id
));
3457 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3458 v8::Local
<v8::Context
> context
,
3460 DCHECK(!frame_
|| frame_
== frame
);
3462 FOR_EACH_OBSERVER(RenderFrameObserver
,
3464 WillReleaseScriptContext(context
, world_id
));
3467 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3468 blink::WebLocalFrame
* frame
) {
3469 DCHECK(!frame_
|| frame_
== frame
);
3470 if (frame
->parent())
3473 InternalDocumentStateData
* data
=
3474 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3475 data
->set_did_first_visually_non_empty_layout(true);
3477 #if defined(OS_ANDROID)
3478 GetRenderWidget()->DidChangeBodyBackgroundColor(
3479 render_view_
->webwidget_
->backgroundColor());
3482 GetRenderWidget()->QueueMessage(
3483 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3484 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3487 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3488 DCHECK(!frame_
|| frame_
== frame
);
3489 // TODO(nasko): Move implementation here. Needed methods:
3490 // * StartNavStateSyncTimerIfNecessary
3491 render_view_
->didChangeScrollOffset(frame
);
3493 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3496 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3497 DCHECK(!frame_
|| frame_
== frame
);
3498 if (!frame
->parent()) {
3499 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3500 render_view_
->GetRoutingID()));
3504 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3506 bool final_update
) {
3507 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3509 active_match_ordinal
= 0;
3511 render_view_
->Send(new ViewHostMsg_Find_Reply(
3512 render_view_
->GetRoutingID(), request_id
, count
,
3513 gfx::Rect(), active_match_ordinal
, final_update
));
3516 void RenderFrameImpl::reportFindInPageSelection(
3518 int active_match_ordinal
,
3519 const blink::WebRect
& selection_rect
) {
3520 render_view_
->Send(new ViewHostMsg_Find_Reply(
3521 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3522 active_match_ordinal
, false));
3525 void RenderFrameImpl::requestStorageQuota(
3526 blink::WebLocalFrame
* frame
,
3527 blink::WebStorageQuotaType type
,
3528 unsigned long long requested_size
,
3529 blink::WebStorageQuotaCallbacks callbacks
) {
3530 DCHECK(!frame_
|| frame_
== frame
);
3531 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3532 if (origin
.isUnique()) {
3533 // Unique origins cannot store persistent state.
3534 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3537 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3538 render_view_
->GetRoutingID(),
3539 GURL(origin
.toString()),
3540 static_cast<storage::StorageType
>(type
),
3542 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3545 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3546 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3547 impl
->set_render_frame_id(routing_id_
);
3550 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3551 if (!geolocation_dispatcher_
)
3552 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3553 return geolocation_dispatcher_
;
3556 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3557 if (!presentation_dispatcher_
)
3558 presentation_dispatcher_
= new PresentationDispatcher(this);
3559 return presentation_dispatcher_
;
3562 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3563 if (!push_messaging_dispatcher_
)
3564 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3565 return push_messaging_dispatcher_
;
3568 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3569 blink::WebLocalFrame
* frame
,
3570 blink::WebRTCPeerConnectionHandler
* handler
) {
3571 DCHECK(!frame_
|| frame_
== frame
);
3572 #if defined(ENABLE_WEBRTC)
3573 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3577 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3578 if (!web_user_media_client_
)
3579 InitializeUserMediaClient();
3580 return web_user_media_client_
;
3583 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3584 if (!web_encrypted_media_client_
) {
3585 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3586 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3587 // is destructed before |this|, and does not give away ownership of the
3589 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3590 base::Unretained(this)),
3591 GetCdmFactory(), GetMediaPermission()));
3593 return web_encrypted_media_client_
.get();
3596 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3597 if (!midi_dispatcher_
)
3598 midi_dispatcher_
= new MidiDispatcher(this);
3599 return midi_dispatcher_
;
3602 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3603 blink::WebLocalFrame
* source_frame
,
3604 blink::WebFrame
* target_frame
,
3605 blink::WebSecurityOrigin target_origin
,
3606 blink::WebDOMMessageEvent event
) {
3607 DCHECK(!frame_
|| frame_
== target_frame
);
3609 // Currently, a postMessage that targets a cross-process frame can be plumbed
3610 // either through this function or RenderFrameProxy::postMessageEvent. This
3611 // function is used when the target cross-process frame is a top-level frame
3612 // which has been swapped out. In that case, the corresponding WebLocalFrame
3613 // currently remains in the frame tree even in site-per-process mode (see
3614 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3615 // --site-per-process mode for all other cases.
3617 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3618 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3619 // cross-process postMessages.
3620 if (!is_swapped_out_
)
3623 // It is possible to get here on a swapped-out frame without a
3624 // |render_frame_proxy_|. This happens when:
3625 // - This process only has one active RenderView and is about to go away
3626 // (e.g., due to cross-process navigation).
3627 // - The top frame has a subframe with an unload handler.
3628 // - The subframe sends a postMessage to the top-level frame in its unload
3630 // See https://crbug.com/475651 for details. We return false here, since we
3631 // don't want to deliver the message to the new process in this case.
3632 if (!render_frame_proxy_
)
3635 render_frame_proxy_
->postMessageEvent(
3636 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3640 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3641 const blink::WebURL
& url
) {
3642 DCHECK(!frame_
|| frame_
== frame
);
3643 std::string user_agent_override_for_url
=
3644 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3645 if (!user_agent_override_for_url
.empty())
3646 return WebString::fromUTF8(user_agent_override_for_url
);
3648 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3649 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3650 return blink::WebString();
3653 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3654 // associated with it, so the checks below are not valid. Temporarily
3655 // return early and fix properly as part of https://crbug.com/426555.
3656 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3657 return blink::WebString();
3659 // If we're in the middle of committing a load, the data source we need
3660 // will still be provisional.
3661 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3662 WebDataSource
* data_source
= NULL
;
3663 if (main_frame
->provisionalDataSource())
3664 data_source
= main_frame
->provisionalDataSource();
3666 data_source
= main_frame
->dataSource();
3668 InternalDocumentStateData
* internal_data
= data_source
?
3669 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3670 if (internal_data
&& internal_data
->is_overriding_user_agent())
3671 return WebString::fromUTF8(
3672 render_view_
->renderer_preferences_
.user_agent_override
);
3673 return blink::WebString();
3676 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3677 DCHECK(!frame_
|| frame_
== frame
);
3678 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3679 return WebString::fromUTF8("1");
3683 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3684 bool default_value
) {
3685 DCHECK(!frame_
|| frame_
== frame
);
3689 bool blocked
= true;
3690 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3691 render_view_
->GetRoutingID(),
3692 GURL(frame
->top()->securityOrigin().toString()),
3693 THREE_D_API_TYPE_WEBGL
,
3698 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3699 int arb_robustness_status_code
) {
3700 DCHECK(!frame_
|| frame_
== frame
);
3701 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3702 GURL(frame
->top()->securityOrigin().toString()),
3703 THREE_D_API_TYPE_WEBGL
,
3704 arb_robustness_status_code
));
3707 blink::WebScreenOrientationClient
*
3708 RenderFrameImpl::webScreenOrientationClient() {
3709 if (!screen_orientation_dispatcher_
)
3710 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3711 return screen_orientation_dispatcher_
;
3714 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3715 ServiceWorkerNetworkProvider
* provider
=
3716 ServiceWorkerNetworkProvider::FromDocumentState(
3717 DocumentState::FromDataSource(&data_source
));
3718 if (!provider
->context())
3720 return provider
->context()->controller_handle_id() !=
3721 kInvalidServiceWorkerHandleId
;
3724 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3725 ServiceWorkerNetworkProvider
* provider
=
3726 ServiceWorkerNetworkProvider::FromDocumentState(
3727 DocumentState::FromDataSource(&data_source
));
3728 if (provider
->context() && provider
->context()->controller())
3729 return provider
->context()->controller()->version_id();
3730 return kInvalidServiceWorkerVersionId
;
3733 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3734 blink::WebAXEvent event
) {
3735 HandleWebAccessibilityEvent(obj
, event
);
3738 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3741 const blink::WebAXObject
& start_object
,
3743 const blink::WebAXObject
& end_object
,
3745 if (renderer_accessibility_
) {
3746 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3747 identifier
, match_index
, start_object
, start_offset
,
3748 end_object
, end_offset
);
3752 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3753 DCHECK(!frame_
|| frame_
== frame
);
3755 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3758 bool RenderFrameImpl::enterFullscreen() {
3759 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3763 bool RenderFrameImpl::exitFullscreen() {
3764 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3768 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3769 if (!permission_client_
)
3770 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3772 return permission_client_
.get();
3775 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3776 if (!app_banner_client_
) {
3777 app_banner_client_
=
3778 GetContentClient()->renderer()->CreateAppBannerClient(this);
3781 return app_banner_client_
.get();
3784 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3786 const WebString
& title
) {
3787 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3788 Send(new FrameHostMsg_RegisterProtocolHandler(
3790 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3796 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3797 const WebURL
& url
) {
3798 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3799 Send(new FrameHostMsg_UnregisterProtocolHandler(
3801 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3806 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3808 bluetooth_
.reset(new WebBluetoothImpl(
3809 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3812 return bluetooth_
.get();
3815 #if defined(ENABLE_WEBVR)
3816 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3817 if (!vr_dispatcher_
)
3818 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3820 return vr_dispatcher_
.get();
3824 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3825 has_played_media_
= true;
3826 Send(new FrameHostMsg_MediaPlayingNotification(
3827 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3828 player
->hasAudio(), player
->isRemote()));
3831 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3832 Send(new FrameHostMsg_MediaPausedNotification(
3833 routing_id_
, reinterpret_cast<int64
>(player
)));
3836 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3840 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3841 observers_
.AddObserver(observer
);
3844 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3845 observer
->RenderFrameGone();
3846 observers_
.RemoveObserver(observer
);
3849 void RenderFrameImpl::OnStop() {
3851 frame_
->stopLoading();
3852 if (!frame_
->parent())
3853 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3855 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3858 void RenderFrameImpl::WasHidden() {
3859 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3862 void RenderFrameImpl::WasShown() {
3863 // TODO(kenrb): Need to figure out how to do this better. Should
3864 // VisibilityState remain a page-level concept or move to frames?
3865 // The semantics of 'Show' might have to change here.
3866 if (render_widget_
) {
3867 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3868 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3870 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3873 void RenderFrameImpl::WidgetWillClose() {
3874 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3877 bool RenderFrameImpl::IsHidden() {
3878 return GetRenderWidget()->is_hidden();
3881 // Tell the embedding application that the URL of the active page has changed.
3882 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3883 blink::WebFrame
* frame
,
3884 blink::WebHistoryCommitType commit_type
,
3885 const blink::WebHistoryItem
& item
) {
3886 DCHECK(!frame_
|| frame_
== frame
);
3887 WebDataSource
* ds
= frame
->dataSource();
3890 const WebURLRequest
& request
= ds
->request();
3891 const WebURLResponse
& response
= ds
->response();
3893 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3894 NavigationStateImpl
* navigation_state
=
3895 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3896 InternalDocumentStateData
* internal_data
=
3897 InternalDocumentStateData::FromDocumentState(document_state
);
3899 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3900 params
.http_status_code
= response
.httpStatusCode();
3901 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3902 params
.is_post
= false;
3903 params
.intended_as_new_entry
=
3904 navigation_state
->request_params().intended_as_new_entry
;
3905 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3906 params
.post_id
= -1;
3907 params
.page_id
= render_view_
->page_id_
;
3908 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3909 // We need to track the RenderViewHost routing_id because of downstream
3910 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3911 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3912 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3913 // based on the ID stored in the resource requests. Once those dependencies
3914 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3915 // client to be based on the routing_id of the RenderFrameHost.
3916 params
.render_view_routing_id
= render_view_
->routing_id();
3917 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3918 params
.socket_address
.set_port(response
.remotePort());
3919 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3921 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3922 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3923 params
.security_info
= response
.securityInfo();
3925 // Set the URL to be displayed in the browser UI to the user.
3926 params
.url
= GetLoadingUrl();
3927 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3929 // Set the origin of the frame. This will be replicated to the corresponding
3930 // RenderFrameProxies in other processes.
3931 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3932 // to https://crbug.com/439608 and will be replicated as unique origins.
3933 if (!is_swapped_out_
) {
3934 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3935 if (url::IsStandard(scheme
.c_str(),
3936 url::Component(0, static_cast<int>(scheme
.length())))) {
3937 params
.origin
= frame
->document().securityOrigin();
3941 if (frame
->document().baseURL() != params
.url
)
3942 params
.base_url
= frame
->document().baseURL();
3944 GetRedirectChain(ds
, ¶ms
.redirects
);
3945 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3946 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3948 params
.searchable_form_url
= internal_data
->searchable_form_url();
3949 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3951 params
.gesture
= render_view_
->navigation_gesture_
;
3952 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3954 // Make navigation state a part of the DidCommitProvisionalLoad message so
3955 // that committed entry has it at all times.
3956 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3957 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3959 params
.page_state
= HistoryEntryToPageState(entry
);
3961 params
.page_state
= PageState::CreateFromURL(request
.url());
3963 // In --site-per-process, just send a single HistoryItem for this frame,
3964 // rather than the whole tree. It will be stored in the corresponding
3965 // FrameNavigationEntry.
3966 params
.page_state
= SingleHistoryItemToPageState(item
);
3968 params
.item_sequence_number
= item
.itemSequenceNumber();
3969 params
.document_sequence_number
= item
.documentSequenceNumber();
3971 if (!frame
->parent()) {
3972 // Top-level navigation.
3974 // Reset the zoom limits in case a plugin had changed them previously. This
3975 // will also call us back which will cause us to send a message to
3976 // update WebContentsImpl.
3977 render_view_
->webview()->zoomLimitsChanged(
3978 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3979 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3981 // Set zoom level, but don't do it for full-page plugin since they don't use
3982 // the same zoom settings.
3983 HostZoomLevels::iterator host_zoom
=
3984 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3985 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3986 // Reset the zoom levels for plugins.
3987 render_view_
->webview()->setZoomLevel(0);
3989 // If the zoom level is not found, then do nothing. In-page navigation
3990 // relies on not changing the zoom level in this case.
3991 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3992 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3995 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3996 // This zoom level was merely recorded transiently for this load. We can
3997 // erase it now. If at some point we reload this page, the browser will
3998 // send us a new, up-to-date zoom level.
3999 render_view_
->host_zoom_levels_
.erase(host_zoom
);
4002 // Update contents MIME type for main frame.
4003 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4005 params
.transition
= navigation_state
->GetTransitionType();
4006 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4007 // If the main frame does a load, it should not be reported as a subframe
4008 // navigation. This can occur in the following case:
4009 // 1. You're on a site with frames.
4010 // 2. You do a subframe navigation. This is stored with transition type
4012 // 3. You navigate to some non-frame site, say, google.com.
4013 // 4. You navigate back to the page from step 2. Since it was initially
4014 // MANUAL_SUBFRAME, it will be that same transition type here.
4015 // We don't want that, because any navigation that changes the toplevel
4016 // frame should be tracked as a toplevel navigation (this allows us to
4017 // update the URL bar, etc).
4018 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4021 // If the page contained a client redirect (meta refresh, document.loc...),
4022 // set the referrer and transition appropriately.
4023 if (ds
->isClientRedirect()) {
4025 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4026 params
.transition
= ui::PageTransitionFromInt(
4027 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4029 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4030 frame
, ds
->request());
4033 base::string16 method
= request
.httpMethod();
4034 if (base::EqualsASCII(method
, "POST")) {
4035 params
.is_post
= true;
4036 params
.post_id
= ExtractPostId(entry
);
4039 // Send the user agent override back.
4040 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4042 // Track the URL of the original request. We use the first entry of the
4043 // redirect chain if it exists because the chain may have started in another
4045 params
.original_request_url
= GetOriginalRequestURL(ds
);
4047 params
.history_list_was_cleared
=
4048 navigation_state
->request_params().should_clear_history_list
;
4050 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4051 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4052 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4053 frame
->dataSource()->request().uiStartTime());
4055 // Save some histogram data so we can compute the average memory used per
4056 // page load of the glyphs.
4057 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4058 blink::WebGlyphCache::pageCount());
4060 // This message needs to be sent before any of allowScripts(),
4061 // allowImages(), allowPlugins() is called for the new page, so that when
4062 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4063 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4064 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4066 // Subframe navigation: the type depends on whether this navigation
4067 // generated a new session history entry. When they do generate a session
4068 // history entry, it means the user initiated the navigation and we should
4070 if (commit_type
== blink::WebStandardCommit
)
4071 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4073 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4075 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4076 params
.history_list_was_cleared
= false;
4077 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4079 // Don't send this message while the subframe is swapped out.
4080 if (!is_swapped_out())
4081 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4084 // If we end up reusing this WebRequest (for example, due to a #ref click),
4085 // we don't want the transition type to persist. Just clear it.
4086 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4089 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4090 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4092 render_view_
->FrameDidStartLoading(frame_
);
4093 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4096 void RenderFrameImpl::didStopLoading() {
4097 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4099 render_view_
->FrameDidStopLoading(frame_
);
4100 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4103 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4104 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4107 void RenderFrameImpl::HandleWebAccessibilityEvent(
4108 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4109 if (renderer_accessibility_
)
4110 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4113 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4114 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4117 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4118 if (renderer_accessibility())
4119 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4123 void RenderFrameImpl::OnCommitNavigation(
4124 const ResourceResponseHead
& response
,
4125 const GURL
& stream_url
,
4126 const CommonNavigationParams
& common_params
,
4127 const RequestNavigationParams
& request_params
) {
4128 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4129 switches::kEnableBrowserSideNavigation
));
4130 // This will override the url requested by the WebURLLoader, as well as
4131 // provide it with the response to the request.
4132 scoped_ptr
<StreamOverrideParameters
> stream_override(
4133 new StreamOverrideParameters());
4134 stream_override
->stream_url
= stream_url
;
4135 stream_override
->response
= response
;
4137 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4138 stream_override
.Pass());
4141 void RenderFrameImpl::OnFailedNavigation(
4142 const CommonNavigationParams
& common_params
,
4143 const RequestNavigationParams
& request_params
,
4144 bool has_stale_copy_in_cache
,
4146 bool is_reload
= IsReload(common_params
.navigation_type
);
4147 bool is_history_navigation
= request_params
.page_state
.IsValid();
4148 WebURLRequest::CachePolicy cache_policy
=
4149 WebURLRequest::UseProtocolCachePolicy
;
4150 RenderFrameImpl::PrepareRenderViewForNavigation(
4151 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4153 GetContentClient()->SetActiveURL(common_params
.url
);
4155 pending_navigation_params_
.reset(new NavigationParams(
4156 common_params
, StartNavigationParams(), request_params
));
4158 // Inform the browser of the start of the provisional load. This is needed so
4159 // that the load is properly tracked by the WebNavigation API.
4160 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4161 routing_id_
, common_params
.url
));
4163 // Send the provisional load failure.
4164 blink::WebURLError error
=
4165 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4166 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4167 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4168 frame_
->isViewSourceModeEnabled());
4169 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4171 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4172 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4173 // http://crbug.com/501960
4174 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4178 // Make sure errors are not shown in view source mode.
4179 frame_
->enableViewSourceMode(false);
4181 // Replace the current history entry in reloads, history navigations and loads
4182 // of the same url. This corresponds to Blink's notion of a standard
4184 // TODO(clamy): see if initial commits in subframes should be handled
4186 bool replace
= is_reload
|| is_history_navigation
||
4187 common_params
.url
== GetLoadingUrl();
4188 LoadNavigationErrorPage(failed_request
, error
, replace
);
4191 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4192 RenderFrame
* render_frame
,
4193 const NavigationPolicyInfo
& info
) {
4194 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4197 // TODO(nick): Is consulting |is_subframe_| here correct?
4198 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_
) {
4199 // There's no reason to ignore navigations on subframes, since the swap out
4200 // logic no longer applies.
4202 if (is_swapped_out_
) {
4203 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4204 // Targeted links may try to navigate a swapped out frame. Allow the
4205 // browser process to navigate the tab instead. Note that it is also
4206 // possible for non-targeted navigations (from this view) to arrive
4207 // here just after we are swapped out. It's ok to send them to the
4208 // browser, as long as they're for the top level frame.
4209 // TODO(creis): Ensure this supports targeted form submissions when
4210 // fixing http://crbug.com/101395.
4211 if (info
.frame
->parent() == NULL
) {
4212 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4213 info
.defaultPolicy
);
4214 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4217 // We should otherwise ignore in-process iframe navigations, if they
4218 // arrive just after we are swapped out.
4219 return blink::WebNavigationPolicyIgnore
;
4222 // Allow kSwappedOutURL to complete.
4223 return info
.defaultPolicy
;
4227 // Webkit is asking whether to navigate to a new URL.
4228 // This is fine normally, except if we're showing UI from one security
4229 // context and they're trying to navigate to a different context.
4230 const GURL
& url
= info
.urlRequest
.url();
4232 // A content initiated navigation may have originated from a link-click,
4233 // script, drag-n-drop operation, etc.
4234 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4235 bool is_content_initiated
=
4236 document_state
->navigation_state()->IsContentInitiated();
4238 // If the browser is interested, then give it a chance to look at the request.
4239 if (is_content_initiated
) {
4241 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4242 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4243 base::EqualsASCII(base::StringPiece16(info
.urlRequest
.httpMethod()),
4245 bool browser_handles_request
=
4246 render_view_
->renderer_preferences_
4247 .browser_handles_non_local_top_level_requests
4248 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4250 if (!browser_handles_request
) {
4251 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4252 render_view_
->renderer_preferences_
4253 .browser_handles_all_top_level_requests
;
4256 if (browser_handles_request
) {
4257 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4258 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4262 // Use the frame's original request's URL rather than the document's URL for
4263 // subsequent checks. For a popup, the document's URL may become the opener
4264 // window's URL if the opener has called document.write().
4265 // See http://crbug.com/93517.
4266 GURL
old_url(info
.frame
->dataSource()->request().url());
4268 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4269 // an extension or app origin, leaving a WebUI page, etc). We only care about
4270 // top-level navigations (not iframes). But we sometimes navigate to
4271 // about:blank to clear a tab, and we want to still allow that.
4273 // Note: this is known to break POST submissions when crossing process
4274 // boundaries until http://crbug.com/101395 is fixed. This is better for
4275 // security than loading a WebUI, extension or app page in the wrong process.
4276 // POST requests don't work because this mechanism does not preserve form
4277 // POST data. We will need to send the request's httpBody data up to the
4278 // browser process, and issue a special POST navigation in WebKit (via
4279 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4280 // for examples of how to send the httpBody data.
4281 if (!info
.frame
->parent() && is_content_initiated
&&
4282 !url
.SchemeIs(url::kAboutScheme
)) {
4283 bool send_referrer
= false;
4285 // All navigations to or from WebUI URLs or within WebUI-enabled
4286 // RenderProcesses must be handled by the browser process so that the
4287 // correct bindings and data sources can be registered.
4288 // Similarly, navigations to view-source URLs or within ViewSource mode
4289 // must be handled by the browser process (except for reloads - those are
4290 // safe to leave within the renderer).
4291 // Lastly, access to file:// URLs from non-file:// URL pages must be
4292 // handled by the browser so that ordinary renderer processes don't get
4293 // blessed with file permissions.
4294 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4295 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4296 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4297 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4298 url
.SchemeIs(kViewSourceScheme
) ||
4299 (info
.frame
->isViewSourceModeEnabled() &&
4300 info
.navigationType
!= blink::WebNavigationTypeReload
);
4302 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4303 // Fork non-file to file opens. Check the opener URL if this is the
4304 // initial navigation in a newly opened window.
4305 GURL
source_url(old_url
);
4306 if (is_initial_navigation
&& source_url
.is_empty() &&
4307 info
.frame
->opener())
4308 source_url
= info
.frame
->opener()->top()->document().url();
4309 DCHECK(!source_url
.is_empty());
4310 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4314 // Give the embedder a chance.
4315 should_fork
= GetContentClient()->renderer()->ShouldFork(
4316 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4317 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4321 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4322 info
.defaultPolicy
);
4323 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4327 // Detect when a page is "forking" a new tab that can be safely rendered in
4328 // its own process. This is done by sites like Gmail that try to open links
4329 // in new windows without script connections back to the original page. We
4330 // treat such cases as browser navigations (in which we will create a new
4331 // renderer for a cross-site navigation), rather than WebKit navigations.
4333 // We use the following heuristic to decide whether to fork a new page in its
4335 // The parent page must open a new tab to about:blank, set the new tab's
4336 // window.opener to null, and then redirect the tab to a cross-site URL using
4339 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4342 // Must start from a tab showing about:blank, which is later redirected.
4343 old_url
== GURL(url::kAboutBlankURL
) &&
4344 // Must be the first real navigation of the tab.
4345 render_view_
->historyBackListCount() < 1 &&
4346 render_view_
->historyForwardListCount() < 1 &&
4347 // The parent page must have set the child's window.opener to null before
4348 // redirecting to the desired URL.
4349 info
.frame
->opener() == NULL
&&
4350 // Must be a top-level frame.
4351 info
.frame
->parent() == NULL
&&
4352 // Must not have issued the request from this page.
4353 is_content_initiated
&&
4354 // Must be targeted at the current tab.
4355 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4356 // Must be a JavaScript navigation, which appears as "other".
4357 info
.navigationType
== blink::WebNavigationTypeOther
;
4360 // Open the URL via the browser, not via WebKit.
4361 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4362 return blink::WebNavigationPolicyIgnore
;
4365 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4366 // This includes navigations with no request being sent to the network stack.
4367 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4368 switches::kEnableBrowserSideNavigation
) &&
4369 info
.urlRequest
.checkForBrowserSideNavigation() &&
4370 ShouldMakeNetworkRequestForURL(url
)) {
4371 BeginNavigation(&info
.urlRequest
);
4372 return blink::WebNavigationPolicyIgnore
;
4375 return info
.defaultPolicy
;
4378 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4380 const Referrer
& referrer
,
4381 WebNavigationPolicy policy
) {
4382 DCHECK_EQ(frame_
, frame
);
4384 FrameHostMsg_OpenURL_Params params
;
4386 params
.referrer
= referrer
;
4387 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4388 WebDataSource
* ds
= frame
->provisionalDataSource();
4390 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4391 NavigationStateImpl
* navigation_state
=
4392 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4393 if (navigation_state
->IsContentInitiated()) {
4394 params
.should_replace_current_entry
=
4395 ds
->replacesCurrentHistoryItem() &&
4396 render_view_
->history_list_length_
;
4398 // This is necessary to preserve the should_replace_current_entry value on
4399 // cross-process redirects, in the event it was set by a previous process.
4401 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4402 // NavigationState::should_replace_current_entry().
4403 params
.should_replace_current_entry
=
4404 navigation_state
->common_params().should_replace_current_entry
;
4407 params
.should_replace_current_entry
= false;
4409 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4410 if (GetContentClient()->renderer()->AllowPopup())
4411 params
.user_gesture
= true;
4413 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4414 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4415 policy
== blink::WebNavigationPolicyNewWindow
||
4416 policy
== blink::WebNavigationPolicyNewPopup
) {
4417 WebUserGestureIndicator::consumeUserGesture();
4420 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4423 void RenderFrameImpl::NavigateInternal(
4424 const CommonNavigationParams
& common_params
,
4425 const StartNavigationParams
& start_params
,
4426 const RequestNavigationParams
& request_params
,
4427 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4428 bool browser_side_navigation
=
4429 base::CommandLine::ForCurrentProcess()->HasSwitch(
4430 switches::kEnableBrowserSideNavigation
);
4431 bool is_reload
= IsReload(common_params
.navigation_type
);
4432 bool is_history_navigation
= request_params
.page_state
.IsValid();
4433 WebURLRequest::CachePolicy cache_policy
=
4434 WebURLRequest::UseProtocolCachePolicy
;
4435 RenderFrameImpl::PrepareRenderViewForNavigation(
4436 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4438 GetContentClient()->SetActiveURL(common_params
.url
);
4440 // If this frame isn't in the same process as the main frame, it may naively
4441 // assume that this is the first navigation in the iframe, but this may not
4442 // actually be the case. Inform the frame's state machine if this frame has
4443 // already committed other loads.
4444 if (request_params
.has_committed_real_load
&& frame_
->parent())
4445 frame_
->setCommittedFirstRealLoad();
4447 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4448 // We cannot reload if we do not have any history state. This happens, for
4449 // example, when recovering from a crash.
4451 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4454 pending_navigation_params_
.reset(
4455 new NavigationParams(common_params
, start_params
, request_params
));
4457 // Create parameters for a standard navigation.
4458 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4459 bool should_load_request
= false;
4460 WebHistoryItem item_for_history_navigation
;
4461 WebURLRequest request
= CreateURLRequestForNavigation(
4462 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4463 #if defined(OS_ANDROID)
4464 request
.setHasUserGesture(start_params
.has_user_gesture
);
4467 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4468 // navigation for this request (since it already went to the browser).
4469 if (browser_side_navigation
)
4470 request
.setCheckForBrowserSideNavigation(false);
4472 // If we are reloading, then use the history state of the current frame.
4473 // Otherwise, if we have history state, then we need to navigate to it, which
4474 // corresponds to a back/forward navigation event. Update the parameters
4475 // depending on the navigation type.
4477 bool ignore_cache
= (common_params
.navigation_type
==
4478 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4479 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4480 : blink::WebFrameLoadType::Reload
;
4482 if (!browser_side_navigation
) {
4483 const GURL override_url
=
4484 (common_params
.navigation_type
==
4485 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4488 request
= frame_
->requestForReload(load_type
, override_url
);
4490 should_load_request
= true;
4491 } else if (is_history_navigation
) {
4492 // We must know the page ID of the page we are navigating back to.
4493 DCHECK_NE(request_params
.page_id
, -1);
4494 // We must know the nav entry ID of the page we are navigating back to,
4495 // which should be the case because history navigations are routed via the
4497 DCHECK_NE(0, request_params
.nav_entry_id
);
4498 scoped_ptr
<HistoryEntry
> entry
=
4499 PageStateToHistoryEntry(request_params
.page_state
);
4501 // Ensure we didn't save the swapped out URL in UpdateState, since the
4502 // browser should never be telling us to navigate to swappedout://.
4503 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4505 if (!browser_side_navigation
) {
4506 scoped_ptr
<NavigationParams
> navigation_params(
4507 new NavigationParams(*pending_navigation_params_
.get()));
4508 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4509 // By default, tell the HistoryController to go the deserialized
4510 // HistoryEntry. This only works if all frames are in the same
4512 DCHECK(!frame_
->parent());
4513 render_view_
->history_controller()->GoToEntry(
4514 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4516 // In --site-per-process, the browser process sends a single
4517 // WebHistoryItem destined for this frame.
4518 // TODO(creis): Change PageState to FrameState. In the meantime, we
4519 // store the relevant frame's WebHistoryItem in the root of the
4521 SetPendingNavigationParams(navigation_params
.Pass());
4522 blink::WebHistoryItem history_item
= entry
->root();
4523 blink::WebHistoryLoadType load_type
=
4524 request_params
.is_same_document_history_load
4525 ? blink::WebHistorySameDocumentLoad
4526 : blink::WebHistoryDifferentDocumentLoad
;
4528 // Let the history controller know the provisional entry, since it is
4529 // used at commit time. Otherwise skip GoToEntry and navigate the
4531 // TODO(creis): Consider cloning the current entry to handle subframe
4532 // cases. Changes to SendUpdateState might affect this.
4533 render_view_
->history_controller()->set_provisional_entry(
4535 WebURLRequest request
=
4536 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4537 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4538 history_item
, load_type
);
4541 // TODO(clamy): this should be set to the HistoryItem sent by the
4542 // browser once the HistoryController has moved to the browser.
4543 // TODO(clamy): distinguish between different document and same document
4545 // TODO(clamy): update this for subframes history loads.
4546 item_for_history_navigation
=
4547 entry
->GetHistoryNodeForFrame(this)->item();
4548 load_type
= blink::WebFrameLoadType::BackForward
;
4549 should_load_request
= true;
4553 // Navigate to the given URL.
4554 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4555 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4556 start_params
.extra_headers
.end(),
4559 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4560 WebString::fromUTF8(i
.values()));
4564 if (start_params
.is_post
&& !browser_side_navigation
) {
4565 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4568 WebHTTPBody http_body
;
4569 http_body
.initialize();
4570 const char* data
= nullptr;
4571 if (start_params
.browser_initiated_post_data
.size()) {
4572 data
= reinterpret_cast<const char*>(
4573 &start_params
.browser_initiated_post_data
.front());
4575 http_body
.appendData(
4576 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4577 request
.setHTTPBody(http_body
);
4580 // A session history navigation should have been accompanied by state.
4581 CHECK_EQ(request_params
.page_id
, -1);
4583 should_load_request
= true;
4586 if (should_load_request
) {
4587 // Record this before starting the load. We need a lower bound of this
4588 // time to sanitize the navigationStart override set below.
4589 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4591 // Perform a navigation to a data url if needed.
4592 if (!common_params
.base_url_for_data_url
.is_empty() ||
4593 (browser_side_navigation
&&
4594 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4595 LoadDataURL(common_params
, frame_
);
4597 // Load the request.
4598 frame_
->toWebLocalFrame()->load(request
, load_type
,
4599 item_for_history_navigation
);
4602 if (load_type
== blink::WebFrameLoadType::Standard
) {
4603 UpdateFrameNavigationTiming(frame_
,
4604 request_params
.browser_navigation_start
,
4605 renderer_navigation_start
);
4609 // In case LoadRequest failed before didCreateDataSource was called.
4610 pending_navigation_params_
.reset();
4613 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4614 const std::string
& encoding_name
) {
4615 // Only update main frame's encoding_name.
4616 if (!frame
->parent())
4617 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4620 void RenderFrameImpl::SyncSelectionIfRequired() {
4621 base::string16 text
;
4624 #if defined(ENABLE_PLUGINS)
4625 if (render_view_
->focused_pepper_plugin_
) {
4626 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4627 offset
= 0; // Pepper API does not support offset reporting.
4628 // TODO(kinaba): cut as needed.
4632 size_t location
, length
;
4633 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4634 &location
, &length
)) {
4638 range
= gfx::Range(location
, location
+ length
);
4640 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4641 blink::WebTextInputTypeNone
) {
4642 // If current focused element is editable, we will send 100 more chars
4643 // before and after selection. It is for input method surrounding text
4645 if (location
> kExtraCharsBeforeAndAfterSelection
)
4646 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4649 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4650 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4651 if (!webrange
.isNull())
4652 text
= webrange
.toPlainText();
4655 text
= frame_
->selectionAsText();
4656 // http://crbug.com/101435
4657 // In some case, frame->selectionAsText() returned text's length is not
4658 // equal to the length returned from webwidget()->caretOrSelectionRange().
4659 // So we have to set the range according to text.length().
4660 range
.set_end(range
.start() + text
.length());
4664 // Sometimes we get repeated didChangeSelection calls from webkit when
4665 // the selection hasn't actually changed. We don't want to report these
4666 // because it will cause us to continually claim the X clipboard.
4667 if (selection_text_offset_
!= offset
||
4668 selection_range_
!= range
||
4669 selection_text_
!= text
) {
4670 selection_text_
= text
;
4671 selection_text_offset_
= offset
;
4672 selection_range_
= range
;
4673 SetSelectedText(text
, offset
, range
);
4675 GetRenderWidget()->UpdateSelectionBounds();
4678 void RenderFrameImpl::InitializeUserMediaClient() {
4679 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4682 #if defined(OS_ANDROID)
4683 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4684 switches::kDisableWebRTC
))
4688 #if defined(ENABLE_WEBRTC)
4689 DCHECK(!web_user_media_client_
);
4690 web_user_media_client_
= new UserMediaClientImpl(
4692 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4693 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4697 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4698 WebMediaPlayerClient
* client
) {
4699 #if defined(ENABLE_WEBRTC)
4700 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4702 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4703 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4704 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4705 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4706 new RenderMediaLog(),
4707 CreateRendererFactory());
4710 #endif // defined(ENABLE_WEBRTC)
4713 scoped_ptr
<MediaStreamRendererFactory
>
4714 RenderFrameImpl::CreateRendererFactory() {
4715 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4716 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4718 return factory
.Pass();
4719 #if defined(ENABLE_WEBRTC)
4720 return scoped_ptr
<MediaStreamRendererFactory
>(
4721 new MediaStreamRendererFactoryImpl());
4723 return scoped_ptr
<MediaStreamRendererFactory
>(
4724 static_cast<MediaStreamRendererFactory
*>(NULL
));
4728 void RenderFrameImpl::PrepareRenderViewForNavigation(
4730 const RequestNavigationParams
& request_params
,
4732 WebURLRequest::CachePolicy
* cache_policy
) {
4733 DCHECK(render_view_
->webview());
4735 MaybeHandleDebugURL(url
);
4738 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4740 render_view_
->history_list_offset_
=
4741 request_params
.current_history_list_offset
;
4742 render_view_
->history_list_length_
=
4743 request_params
.current_history_list_length
;
4744 if (request_params
.should_clear_history_list
) {
4745 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4746 CHECK_EQ(0, render_view_
->history_list_length_
);
4749 if (!is_swapped_out_
|| frame_
->parent())
4752 // This is a swapped out main frame, so swap the renderer back in.
4753 // We marked the view as hidden when swapping the view out, so be sure to
4754 // reset the visibility state before navigating to the new URL.
4755 render_view_
->webview()->setVisibilityState(
4756 render_view_
->visibilityState(), false);
4758 // If this is an attempt to reload while we are swapped out, we should not
4759 // reload swappedout://, but the previous page, which is stored in
4760 // params.state. Setting is_reload to false will treat this like a back
4761 // navigation to accomplish that.
4763 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4765 // We refresh timezone when a view is swapped in since timezone
4766 // can get out of sync when the system timezone is updated while
4767 // the view is swapped out.
4768 RenderThreadImpl::NotifyTimezoneChange();
4770 render_view_
->SetSwappedOut(false);
4771 is_swapped_out_
= false;
4775 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4776 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4777 switches::kEnableBrowserSideNavigation
));
4779 // TODO(clamy): Execute the beforeunload event.
4781 // Note: At this stage, the goal is to apply all the modifications the
4782 // renderer wants to make to the request, and then send it to the browser, so
4783 // that the actual network request can be started. Ideally, all such
4784 // modifications should take place in willSendRequest, and in the
4785 // implementation of willSendRequest for the various InspectorAgents
4788 // TODO(clamy): Apply devtools override.
4789 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4791 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4793 // TODO(clamy): Same-document navigations should not be sent back to the
4795 // TODO(clamy): Data urls should not be sent back to the browser either.
4796 bool should_replace_current_entry
= false;
4797 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4798 WebDataSource
* current_data_source
= frame_
->dataSource();
4799 WebDataSource
* data_source
=
4800 provisional_data_source
? provisional_data_source
: current_data_source
;
4802 // The current entry can only be replaced if there already is an entry in the
4804 if (data_source
&& render_view_
->history_list_length_
> 0) {
4805 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4807 Send(new FrameHostMsg_BeginNavigation(
4809 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4810 BeginNavigationParams(
4811 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4812 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4813 GetRequestBodyForWebURLRequest(*request
)));
4816 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4818 // A loadData request with a specified base URL.
4819 std::string mime_type
, charset
, data
;
4820 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4821 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4822 params
.url
: params
.base_url_for_data_url
;
4824 WebData(data
.c_str(), data
.length()),
4825 WebString::fromUTF8(mime_type
),
4826 WebString::fromUTF8(charset
),
4828 params
.history_url_for_data_url
,
4831 CHECK(false) << "Invalid URL passed: "
4832 << params
.url
.possibly_invalid_spec();
4836 void RenderFrameImpl::SendFailedProvisionalLoad(
4837 const blink::WebURLRequest
& request
,
4838 const blink::WebURLError
& error
,
4839 blink::WebLocalFrame
* frame
) {
4840 bool show_repost_interstitial
=
4841 (error
.reason
== net::ERR_CACHE_MISS
&&
4842 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4844 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4845 params
.error_code
= error
.reason
;
4846 GetContentClient()->renderer()->GetNavigationErrorStrings(
4847 render_view_
.get(), frame
, request
, error
, NULL
,
4848 ¶ms
.error_description
);
4849 params
.url
= error
.unreachableURL
;
4850 params
.showing_repost_interstitial
= show_repost_interstitial
;
4851 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4852 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4855 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4857 const GURL
& unreachable_url
) {
4858 // Don't display an error page if this is simply a cancelled load. Aside
4859 // from being dumb, Blink doesn't expect it and it will cause a crash.
4860 if (error_code
== net::ERR_ABORTED
)
4863 // Don't display "client blocked" error page if browser has asked us not to.
4864 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4865 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4869 // Allow the embedder to suppress an error page.
4870 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4871 this, unreachable_url
)) {
4875 if (RenderThreadImpl::current() &&
4876 RenderThreadImpl::current()->layout_test_mode()) {
4883 GURL
RenderFrameImpl::GetLoadingUrl() const {
4884 WebDataSource
* ds
= frame_
->dataSource();
4885 if (ds
->hasUnreachableURL())
4886 return ds
->unreachableURL();
4888 const WebURLRequest
& request
= ds
->request();
4889 return request
.url();
4892 void RenderFrameImpl::PopulateDocumentStateFromPending(
4893 DocumentState
* document_state
) {
4894 document_state
->set_request_time(
4895 pending_navigation_params_
->request_params
.request_time
);
4897 InternalDocumentStateData
* internal_data
=
4898 InternalDocumentStateData::FromDocumentState(document_state
);
4900 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4901 url::kJavaScriptScheme
) &&
4902 pending_navigation_params_
->common_params
.navigation_type
==
4903 FrameMsg_Navigate_Type::RESTORE
) {
4904 // We're doing a load of a page that was restored from the last session. By
4905 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4906 // can result in stale data for pages that are set to expire. We explicitly
4907 // override that by setting the policy here so that as necessary we load
4908 // from the network.
4910 // TODO(davidben): Remove this in favor of passing a cache policy to the
4911 // loadHistoryItem call in OnNavigate. That requires not overloading
4912 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4913 // policy based on load type, etc".
4914 internal_data
->set_cache_policy_override(
4915 WebURLRequest::UseProtocolCachePolicy
);
4918 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4919 document_state
->set_load_type(DocumentState::RELOAD
);
4920 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4921 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4923 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4925 internal_data
->set_is_overriding_user_agent(
4926 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4927 internal_data
->set_must_reset_scroll_and_scale_state(
4928 pending_navigation_params_
->common_params
.navigation_type
==
4929 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4930 document_state
->set_can_load_local_resources(
4931 pending_navigation_params_
->request_params
.can_load_local_resources
);
4934 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4935 // A navigation resulting from loading a javascript URL should not be treated
4936 // as a browser initiated event. Instead, we want it to look as if the page
4937 // initiated any load resulting from JS execution.
4938 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4939 url::kJavaScriptScheme
)) {
4940 return NavigationStateImpl::CreateBrowserInitiated(
4941 pending_navigation_params_
->common_params
,
4942 pending_navigation_params_
->start_params
,
4943 pending_navigation_params_
->request_params
);
4945 return NavigationStateImpl::CreateContentInitiated();
4948 #if defined(OS_ANDROID)
4950 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4951 WebMediaPlayerClient
* client
,
4952 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4953 media::MediaPermission
* media_permission
,
4954 WebContentDecryptionModule
* initial_cdm
) {
4955 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4956 if (SynchronousCompositorFactory
* factory
=
4957 SynchronousCompositorFactory::GetInstance()) {
4958 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4960 GpuChannelHost
* gpu_channel_host
=
4961 RenderThreadImpl::current()->EstablishGpuChannelSync(
4962 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4964 if (!gpu_channel_host
) {
4965 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4969 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4970 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4972 if (!context_provider
.get()) {
4973 LOG(ERROR
) << "Failed to get context3d for media player";
4977 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4978 context_provider
, gpu_channel_host
, routing_id_
);
4981 return new WebMediaPlayerAndroid(
4982 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
4983 GetMediaPlayerManager(), GetCdmFactory(), media_permission
, initial_cdm
,
4984 stream_texture_factory
,
4985 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4986 new RenderMediaLog());
4989 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4990 if (!media_player_manager_
)
4991 media_player_manager_
= new RendererMediaPlayerManager(this);
4992 return media_player_manager_
;
4995 #endif // defined(OS_ANDROID)
4997 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4998 if (!media_permission_dispatcher_
)
4999 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
5000 return media_permission_dispatcher_
;
5003 #if defined(ENABLE_MOJO_MEDIA)
5004 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5005 if (!media_service_factory_
) {
5006 mojo::InterfacePtr
<mojo::Shell
> shell_ptr
;
5007 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr
));
5009 mojo::ServiceProviderPtr service_provider
;
5010 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5011 request
->url
= mojo::String::From("mojo:media");
5012 shell_ptr
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5015 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5017 media_service_factory_
.set_connection_error_handler(
5018 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5019 base::Unretained(this)));
5022 return media_service_factory_
.get();
5025 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5026 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5027 // violation on the old |media_service_factory_| by outstanding
5028 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5030 // media_service_factory_.reset();
5034 bool RenderFrameImpl::AreSecureCodecsSupported() {
5035 #if defined(OS_ANDROID)
5036 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5037 return render_view_
->renderer_preferences_
5038 .use_video_overlay_for_embedded_encrypted_video
;
5041 #endif // defined(OS_ANDROID)
5044 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5045 #if defined(ENABLE_BROWSER_CDMS)
5047 cdm_manager_
= new RendererCdmManager(this);
5048 #endif // defined(ENABLE_BROWSER_CDMS)
5050 if (!cdm_factory_
) {
5053 #if defined(ENABLE_MOJO_MEDIA)
5054 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5056 cdm_factory_
.reset(new RenderCdmFactory(
5057 #if defined(ENABLE_PEPPER_CDMS)
5058 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5059 #elif defined(ENABLE_BROWSER_CDMS)
5063 #endif // defined(ENABLE_MOJO_MEDIA)
5066 return cdm_factory_
.get();
5069 void RenderFrameImpl::RegisterMojoServices() {
5070 // Only main frame have ImageDownloader service.
5071 if (!frame_
->parent()) {
5072 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5073 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5074 base::Unretained(this)));
5078 } // namespace content