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/renderers/gpu_video_accelerator_factories.h"
117 #include "mojo/common/url_type_converters.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/platform/modules/webusb/WebUSBClient.h"
129 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
130 #include "third_party/WebKit/public/web/WebDocument.h"
131 #include "third_party/WebKit/public/web/WebFrameWidget.h"
132 #include "third_party/WebKit/public/web/WebGlyphCache.h"
133 #include "third_party/WebKit/public/web/WebKit.h"
134 #include "third_party/WebKit/public/web/WebLocalFrame.h"
135 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
136 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
137 #include "third_party/WebKit/public/web/WebPlugin.h"
138 #include "third_party/WebKit/public/web/WebPluginParams.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"
177 #include "content/renderer/usb/web_usb_client_impl.h"
178 #include "device/devices_app/public/cpp/constants.h"
181 #if defined(ENABLE_PEPPER_CDMS)
182 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
183 #elif defined(ENABLE_BROWSER_CDMS)
184 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
187 #if defined(ENABLE_MOJO_MEDIA)
188 #include "media/mojo/services/mojo_cdm_factory.h"
189 #include "media/mojo/services/mojo_renderer_factory.h"
190 #include "mojo/application/public/cpp/connect.h"
191 #include "mojo/application/public/interfaces/shell.mojom.h"
192 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
194 #include "media/renderers/default_renderer_factory.h"
197 #if defined(ENABLE_WEBVR)
198 #include "content/renderer/vr/vr_dispatcher.h"
201 using blink::WebContentDecryptionModule
;
202 using blink::WebContextMenuData
;
203 using blink::WebData
;
204 using blink::WebDataSource
;
205 using blink::WebDocument
;
206 using blink::WebDOMEvent
;
207 using blink::WebDOMMessageEvent
;
208 using blink::WebElement
;
209 using blink::WebExternalPopupMenu
;
210 using blink::WebExternalPopupMenuClient
;
211 using blink::WebFrame
;
212 using blink::WebHistoryItem
;
213 using blink::WebHTTPBody
;
214 using blink::WebLocalFrame
;
215 using blink::WebMediaPlayer
;
216 using blink::WebMediaPlayerClient
;
217 using blink::WebMediaPlayerEncryptedMediaClient
;
218 using blink::WebNavigationPolicy
;
219 using blink::WebNavigationType
;
220 using blink::WebNode
;
221 using blink::WebPluginParams
;
222 using blink::WebPopupMenuInfo
;
223 using blink::WebRange
;
224 using blink::WebReferrerPolicy
;
225 using blink::WebScriptSource
;
226 using blink::WebSearchableFormData
;
227 using blink::WebSecurityOrigin
;
228 using blink::WebSecurityPolicy
;
229 using blink::WebSerializedScriptValue
;
230 using blink::WebServiceWorkerProvider
;
231 using blink::WebSettings
;
232 using blink::WebStorageQuotaCallbacks
;
233 using blink::WebString
;
235 using blink::WebURLError
;
236 using blink::WebURLRequest
;
237 using blink::WebURLResponse
;
238 using blink::WebUserGestureIndicator
;
239 using blink::WebVector
;
240 using blink::WebView
;
242 using base::TimeDelta
;
248 const char kDefaultAcceptHeader
[] =
249 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
251 const char kAcceptHeader
[] = "Accept";
253 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
255 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
256 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
257 LAZY_INSTANCE_INITIALIZER
;
259 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
260 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
262 int64
ExtractPostId(HistoryEntry
* entry
) {
266 const WebHistoryItem
& item
= entry
->root();
267 if (item
.isNull() || item
.httpBody().isNull())
270 return item
.httpBody().identifier();
273 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
274 const WebURLResponse
& response
) {
275 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
278 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
279 // Replace any occurrences of swappedout:// with about:blank.
280 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
281 WebVector
<WebURL
> urls
;
282 ds
->redirectChain(urls
);
283 result
->reserve(urls
.size());
284 for (size_t i
= 0; i
< urls
.size(); ++i
) {
285 if (urls
[i
] != GURL(kSwappedOutURL
))
286 result
->push_back(urls
[i
]);
288 result
->push_back(blank_url
);
292 // Returns the original request url. If there is no redirect, the original
293 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
294 // frame was loaded by loadData, the original url will be ds->unreachableURL()
295 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
296 // WebDataSource has unreachable URL means that the frame is loaded through
297 // blink::WebFrame::loadData(), and the base URL will be in the redirect
298 // chain. However, we never visited the baseURL. So in this case, we should
299 // use the unreachable URL as the original URL.
300 if (ds
->hasUnreachableURL())
301 return ds
->unreachableURL();
303 std::vector
<GURL
> redirects
;
304 GetRedirectChain(ds
, &redirects
);
305 if (!redirects
.empty())
306 return redirects
.at(0);
308 return ds
->originalRequest().url();
311 NOINLINE
void CrashIntentionally() {
312 // NOTE(shess): Crash directly rather than using NOTREACHED() so
313 // that the signature is easier to triage in crash reports.
314 volatile int* zero
= NULL
;
318 NOINLINE
void BadCastCrashIntentionally() {
331 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
332 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
333 // NOTE(rogerm): We intentionally perform an invalid heap access here in
334 // order to trigger an Address Sanitizer (ASAN) error report.
335 const char kCrashDomain
[] = "crash";
336 const char kHeapOverflow
[] = "/heap-overflow";
337 const char kHeapUnderflow
[] = "/heap-underflow";
338 const char kUseAfterFree
[] = "/use-after-free";
339 #if defined(SYZYASAN)
340 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
341 const char kCorruptHeap
[] = "/corrupt-heap";
344 if (!url
.DomainIs(kCrashDomain
))
350 std::string
crash_type(url
.path());
351 if (crash_type
== kHeapOverflow
) {
352 base::debug::AsanHeapOverflow();
353 } else if (crash_type
== kHeapUnderflow
) {
354 base::debug::AsanHeapUnderflow();
355 } else if (crash_type
== kUseAfterFree
) {
356 base::debug::AsanHeapUseAfterFree();
357 #if defined(SYZYASAN)
358 } else if (crash_type
== kCorruptHeapBlock
) {
359 base::debug::AsanCorruptHeapBlock();
360 } else if (crash_type
== kCorruptHeap
) {
361 base::debug::AsanCorruptHeap();
365 #endif // ADDRESS_SANITIZER || SYZYASAN
367 void MaybeHandleDebugURL(const GURL
& url
) {
368 if (!url
.SchemeIs(kChromeUIScheme
))
370 if (url
== GURL(kChromeUIBadCastCrashURL
)) {
371 BadCastCrashIntentionally();
372 } else if (url
== GURL(kChromeUICrashURL
)) {
373 CrashIntentionally();
374 } else if (url
== GURL(kChromeUIDumpURL
)) {
375 // This URL will only correctly create a crash dump file if content is
376 // hosted in a process that has correctly called
377 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
378 // of base::debug::DumpWithoutCrashing for more details.
379 base::debug::DumpWithoutCrashing();
380 } else if (url
== GURL(kChromeUIKillURL
)) {
381 base::Process::Current().Terminate(1, false);
382 } else if (url
== GURL(kChromeUIHangURL
)) {
384 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
386 } else if (url
== GURL(kChromeUIShorthangURL
)) {
387 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
390 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
391 MaybeTriggerAsanError(url
);
392 #endif // ADDRESS_SANITIZER || SYZYASAN
395 // Returns false unless this is a top-level navigation.
396 bool IsTopLevelNavigation(WebFrame
* frame
) {
397 return frame
->parent() == NULL
;
400 // Returns false unless this is a top-level navigation that crosses origins.
401 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
403 WebNavigationType type
,
405 if (!IsTopLevelNavigation(frame
))
408 // Navigations initiated within Webkit are not sent out to the external host
409 // in the following cases.
410 // 1. The url scheme is not http/https
411 // 2. The origin of the url and the opener is the same in which case the
412 // opener relationship is maintained.
413 // 3. Reloads/form submits/back forward navigations
414 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
417 if (type
!= blink::WebNavigationTypeReload
&&
418 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
419 // The opener relationship between the new window and the parent allows the
420 // new window to script the parent and vice versa. This is not allowed if
421 // the origins of the two domains are different. This can be treated as a
422 // top level navigation and routed back to the host.
423 blink::WebFrame
* opener
= frame
->opener();
427 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
433 WebURLRequest
CreateURLRequestForNavigation(
434 const CommonNavigationParams
& common_params
,
435 scoped_ptr
<StreamOverrideParameters
> stream_override
,
436 bool is_view_source_mode_enabled
) {
437 WebURLRequest
request(common_params
.url
);
438 if (is_view_source_mode_enabled
)
439 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
441 if (common_params
.referrer
.url
.is_valid()) {
442 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
443 common_params
.referrer
.policy
,
445 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
446 if (!web_referrer
.isEmpty())
447 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
450 RequestExtraData
* extra_data
= new RequestExtraData();
451 extra_data
->set_stream_override(stream_override
.Pass());
452 request
.setExtraData(extra_data
);
454 // Set the ui timestamp for this navigation. Currently the timestamp here is
455 // only non empty when the navigation was triggered by an Android intent. The
456 // timestamp is converted to a double version supported by blink. It will be
457 // passed back to the browser in the DidCommitProvisionalLoad and the
458 // DocumentLoadComplete IPCs.
459 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
460 request
.setUiStartTime(ui_timestamp
.InSecondsF());
461 request
.setInputPerfMetricReportPolicy(
462 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
463 common_params
.report_type
));
467 void UpdateFrameNavigationTiming(WebFrame
* frame
,
468 base::TimeTicks browser_navigation_start
,
469 base::TimeTicks renderer_navigation_start
) {
470 // The browser provides the navigation_start time to bootstrap the
471 // Navigation Timing information for the browser-initiated navigations. In
472 // case of cross-process navigations, this carries over the time of
473 // finishing the onbeforeunload handler of the previous page.
474 DCHECK(!browser_navigation_start
.is_null());
475 if (frame
->provisionalDataSource()) {
476 // |browser_navigation_start| is likely before this process existed, so we
477 // can't use InterProcessTimeTicksConverter. We need at least to ensure
478 // that the browser-side navigation start we set is not later than the one
479 // on the renderer side.
480 base::TimeTicks navigation_start
= std::min(
481 browser_navigation_start
, renderer_navigation_start
);
482 double navigation_start_seconds
=
483 (navigation_start
- base::TimeTicks()).InSecondsF();
484 frame
->provisionalDataSource()->setNavigationStartTime(
485 navigation_start_seconds
);
486 // TODO(clamy): We need to provide additional timing values for the
487 // Navigation Timing API to work with browser-side navigations.
492 CommonNavigationParams
MakeCommonNavigationParams(
493 blink::WebURLRequest
* request
,
494 bool should_replace_current_entry
) {
495 const RequestExtraData kEmptyData
;
496 const RequestExtraData
* extra_data
=
497 static_cast<RequestExtraData
*>(request
->extraData());
499 extra_data
= &kEmptyData
;
501 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
502 request
->referrerPolicy());
504 // Set the ui timestamp for this navigation. Currently the timestamp here is
505 // only non empty when the navigation was triggered by an Android intent, or
506 // by the user clicking on a link. The timestamp is converted from a double
507 // version supported by blink. It will be passed back to the renderer in the
508 // CommitNavigation IPC, and then back to the browser again in the
509 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
510 base::TimeTicks ui_timestamp
=
511 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
512 FrameMsg_UILoadMetricsReportType::Value report_type
=
513 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
514 request
->inputPerfMetricReportPolicy());
515 return CommonNavigationParams(
516 request
->url(), referrer
, extra_data
->transition_type(),
517 FrameMsg_Navigate_Type::NORMAL
, true, should_replace_current_entry
,
518 ui_timestamp
, report_type
, GURL(), GURL());
521 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
522 media::Context3D
GetSharedMainThreadContext3D() {
523 cc::ContextProvider
* provider
=
524 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
526 return media::Context3D();
527 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
531 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
532 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
533 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
534 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
537 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
540 void OnGotContentHandlerID(uint32_t content_handler_id
) {}
545 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
547 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
548 CreateParams
params(render_view
, routing_id
);
550 if (g_create_render_frame_impl
)
551 return g_create_render_frame_impl(params
);
553 return new RenderFrameImpl(params
);
557 RenderFrame
* RenderFrame::FromRoutingID(int routing_id
) {
558 return RenderFrameImpl::FromRoutingID(routing_id
);
562 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int routing_id
) {
563 RoutingIDFrameMap::iterator iter
=
564 g_routing_id_frame_map
.Get().find(routing_id
);
565 if (iter
!= g_routing_id_frame_map
.Get().end())
571 RenderFrameImpl
* RenderFrameImpl::CreateMainFrame(RenderViewImpl
* render_view
,
573 RenderFrameImpl
* render_frame
=
574 RenderFrameImpl::Create(render_view
, routing_id
);
575 WebLocalFrame
* web_frame
=
576 WebLocalFrame::create(blink::WebTreeScopeType::Document
, render_frame
);
577 render_frame
->SetWebFrame(web_frame
);
578 render_view
->webview()->setMainFrame(web_frame
);
583 void RenderFrameImpl::CreateFrame(
585 int proxy_routing_id
,
586 int opener_routing_id
,
587 int parent_routing_id
,
588 int previous_sibling_routing_id
,
589 const FrameReplicationState
& replicated_state
,
590 CompositorDependencies
* compositor_deps
,
591 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
592 blink::WebLocalFrame
* web_frame
;
593 RenderFrameImpl
* render_frame
;
594 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
595 RenderFrameProxy
* parent_proxy
=
596 RenderFrameProxy::FromRoutingID(parent_routing_id
);
597 // If the browser is sending a valid parent routing id, it should already
598 // be created and registered.
600 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
602 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
603 RenderFrameProxy
* previous_sibling_proxy
=
604 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
605 if (previous_sibling_proxy
)
606 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
608 // Create the RenderFrame and WebLocalFrame, linking the two.
610 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
611 web_frame
= parent_web_frame
->createLocalChild(
612 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
613 replicated_state
.sandbox_flags
, render_frame
,
614 previous_sibling_web_frame
);
616 RenderFrameProxy
* proxy
=
617 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
619 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
621 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
622 render_frame
->proxy_routing_id_
= proxy_routing_id
;
623 web_frame
->initializeToReplaceRemoteFrame(
624 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
625 replicated_state
.sandbox_flags
);
627 render_frame
->SetWebFrame(web_frame
);
628 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
630 WebFrame
* opener
= ResolveOpener(opener_routing_id
, nullptr);
631 web_frame
->setOpener(opener
);
633 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
634 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
635 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
636 widget_params
.routing_id
, widget_params
.surface_id
,
637 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
638 compositor_deps
, web_frame
);
639 // TODO(kenrb): Observing shouldn't be necessary when we sort out
640 // WasShown and WasHidden, separating page-level visibility from
641 // frame-level visibility.
642 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
645 render_frame
->Initialize();
649 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
650 return RenderFrameImpl::FromWebFrame(web_frame
);
654 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
655 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
656 if (iter
!= g_frame_map
.Get().end())
662 void RenderFrameImpl::InstallCreateHook(
663 CreateRenderFrameImplFunction create_render_frame_impl
) {
664 CHECK(!g_create_render_frame_impl
);
665 g_create_render_frame_impl
= create_render_frame_impl
;
669 blink::WebFrame
* RenderFrameImpl::ResolveOpener(int opener_frame_routing_id
,
670 int* opener_view_routing_id
) {
671 if (opener_view_routing_id
)
672 *opener_view_routing_id
= MSG_ROUTING_NONE
;
674 if (opener_frame_routing_id
== MSG_ROUTING_NONE
)
677 // Opener routing ID could refer to either a RenderFrameProxy or a
678 // RenderFrame, so need to check both.
679 RenderFrameProxy
* opener_proxy
=
680 RenderFrameProxy::FromRoutingID(opener_frame_routing_id
);
682 if (opener_view_routing_id
)
683 *opener_view_routing_id
= opener_proxy
->render_view()->GetRoutingID();
685 // TODO(nasko,alexmos): This check won't be needed once swappedout:// is
687 if (opener_proxy
->IsMainFrameDetachedFromTree()) {
688 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
689 return opener_proxy
->render_view()->webview()->mainFrame();
691 return opener_proxy
->web_frame();
695 RenderFrameImpl
* opener_frame
=
696 RenderFrameImpl::FromRoutingID(opener_frame_routing_id
);
698 if (opener_view_routing_id
)
699 *opener_view_routing_id
= opener_frame
->render_view()->GetRoutingID();
700 return opener_frame
->GetWebFrame();
706 // RenderFrameImpl ----------------------------------------------------------
707 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
710 is_local_root_(false),
711 render_view_(params
.render_view
->AsWeakPtr()),
712 routing_id_(params
.routing_id
),
713 is_swapped_out_(false),
714 render_frame_proxy_(NULL
),
715 is_detaching_(false),
716 proxy_routing_id_(MSG_ROUTING_NONE
),
717 #if defined(ENABLE_PLUGINS)
718 plugin_power_saver_helper_(NULL
),
721 selection_text_offset_(0),
722 selection_range_(gfx::Range::InvalidRange()),
723 handling_select_range_(false),
724 notification_permission_dispatcher_(NULL
),
725 web_user_media_client_(NULL
),
726 media_permission_dispatcher_(NULL
),
727 midi_dispatcher_(NULL
),
728 #if defined(OS_ANDROID)
729 media_player_manager_(NULL
),
731 #if defined(ENABLE_BROWSER_CDMS)
734 #if defined(VIDEO_HOLE)
735 contains_media_player_(false),
737 has_played_media_(false),
738 devtools_agent_(nullptr),
739 geolocation_dispatcher_(NULL
),
740 push_messaging_dispatcher_(NULL
),
741 presentation_dispatcher_(NULL
),
742 screen_orientation_dispatcher_(NULL
),
743 manifest_manager_(NULL
),
744 accessibility_mode_(AccessibilityModeOff
),
745 renderer_accessibility_(NULL
),
746 weak_factory_(this) {
747 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
748 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
749 CHECK(result
.second
) << "Inserting a duplicate item.";
751 RenderThread::Get()->AddRoute(routing_id_
, this);
753 render_view_
->RegisterRenderFrame(this);
755 // Everything below subclasses RenderFrameObserver and is automatically
756 // deleted when the RenderFrame gets deleted.
757 #if defined(OS_ANDROID)
758 new GinJavaBridgeDispatcher(this);
761 #if defined(ENABLE_PLUGINS)
762 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
765 manifest_manager_
= new ManifestManager(this);
767 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_
));
770 RenderFrameImpl::~RenderFrameImpl() {
771 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
772 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
774 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
776 #if defined(VIDEO_HOLE)
777 if (contains_media_player_
)
778 render_view_
->UnregisterVideoHoleFrame(this);
782 // When using swapped out frames, RenderFrameProxy is owned by
783 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
784 // along with this object.
785 if (render_frame_proxy_
&&
786 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
787 // The following method calls back into this object and clears
788 // |render_frame_proxy_|.
789 render_frame_proxy_
->frameDetached(
790 blink::WebRemoteFrameClient::DetachType::Remove
);
793 // Ensure the RenderView doesn't point to this object, once it is destroyed.
794 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
795 // is |this|, once the object is no longer leaked.
796 // See https://crbug.com/464764.
797 render_view_
->main_render_frame_
= nullptr;
800 render_view_
->UnregisterRenderFrame(this);
801 g_routing_id_frame_map
.Get().erase(routing_id_
);
802 RenderThread::Get()->RemoveRoute(routing_id_
);
805 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
808 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
809 std::make_pair(web_frame
, this));
810 CHECK(result
.second
) << "Inserting a duplicate item.";
815 void RenderFrameImpl::Initialize() {
816 is_subframe_
= !!frame_
->parent();
817 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
819 #if defined(ENABLE_PLUGINS)
820 new PepperBrowserConnection(this);
822 new SharedWorkerRepository(this);
824 if (is_local_root_
&& !render_frame_proxy_
) {
825 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
826 // when |this| is deleted.
827 devtools_agent_
= new DevToolsAgent(this);
830 RegisterMojoServices();
832 // We delay calling this until we have the WebFrame so that any observer or
833 // embedder can call GetWebFrame on any RenderFrame.
834 GetContentClient()->renderer()->RenderFrameCreated(this);
837 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
838 return render_view_
.get();
841 #if defined(ENABLE_PLUGINS)
842 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
843 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
844 DidCreatePepperPlugin(host
));
845 if (host
->GetPluginName() == kFlashPluginName
) {
846 RenderThread::Get()->RecordAction(
847 base::UserMetricsAction("FrameLoadWithFlash"));
851 void RenderFrameImpl::PepperDidChangeCursor(
852 PepperPluginInstanceImpl
* instance
,
853 const blink::WebCursorInfo
& cursor
) {
854 // Update the cursor appearance immediately if the requesting plugin is the
855 // one which receives the last mouse event. Otherwise, the new cursor won't be
856 // picked up until the plugin gets the next input event. That is bad if, e.g.,
857 // the plugin would like to set an invisible cursor when there isn't any user
858 // input for a while.
859 if (instance
== render_view_
->pepper_last_mouse_event_target())
860 GetRenderWidget()->didChangeCursor(cursor
);
863 void RenderFrameImpl::PepperDidReceiveMouseEvent(
864 PepperPluginInstanceImpl
* instance
) {
865 render_view_
->set_pepper_last_mouse_event_target(instance
);
868 void RenderFrameImpl::PepperTextInputTypeChanged(
869 PepperPluginInstanceImpl
* instance
) {
870 if (instance
!= render_view_
->focused_pepper_plugin())
873 GetRenderWidget()->UpdateTextInputState(
874 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
876 FocusedNodeChangedForAccessibility(WebNode());
879 void RenderFrameImpl::PepperCaretPositionChanged(
880 PepperPluginInstanceImpl
* instance
) {
881 if (instance
!= render_view_
->focused_pepper_plugin())
883 GetRenderWidget()->UpdateSelectionBounds();
886 void RenderFrameImpl::PepperCancelComposition(
887 PepperPluginInstanceImpl
* instance
) {
888 if (instance
!= render_view_
->focused_pepper_plugin())
890 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
891 #if defined(OS_MACOSX) || defined(USE_AURA)
892 GetRenderWidget()->UpdateCompositionInfo(true);
896 void RenderFrameImpl::PepperSelectionChanged(
897 PepperPluginInstanceImpl
* instance
) {
898 if (instance
!= render_view_
->focused_pepper_plugin())
900 SyncSelectionIfRequired();
903 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
904 PepperPluginInstanceImpl
* plugin
) {
906 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
907 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
908 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
909 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
910 plugin
, active_url
, GetRenderWidget()->screenInfo());
911 widget
->show(blink::WebNavigationPolicyIgnore
);
915 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
916 if (!render_view_
->focused_pepper_plugin())
918 return render_view_
->focused_pepper_plugin()->
919 IsPluginAcceptingCompositionEvents();
922 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
923 base::ProcessId plugin_pid
) {
924 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
925 // routing_id_ as a result.
926 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
929 void RenderFrameImpl::SimulateImeSetComposition(
930 const base::string16
& text
,
931 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
934 render_view_
->OnImeSetComposition(
935 text
, underlines
, selection_start
, selection_end
);
938 void RenderFrameImpl::SimulateImeConfirmComposition(
939 const base::string16
& text
,
940 const gfx::Range
& replacement_range
) {
941 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
944 void RenderFrameImpl::OnImeSetComposition(
945 const base::string16
& text
,
946 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
949 // When a PPAPI plugin has focus, we bypass WebKit.
950 if (!IsPepperAcceptingCompositionEvents()) {
951 pepper_composition_text_
= text
;
953 // TODO(kinaba) currently all composition events are sent directly to
954 // plugins. Use DOM event mechanism after WebKit is made aware about
955 // plugins that support composition.
956 // The code below mimics the behavior of WebCore::Editor::setComposition.
958 // Empty -> nonempty: composition started.
959 if (pepper_composition_text_
.empty() && !text
.empty()) {
960 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
963 // Nonempty -> empty: composition canceled.
964 if (!pepper_composition_text_
.empty() && text
.empty()) {
965 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
968 pepper_composition_text_
= text
;
969 // Nonempty: composition is ongoing.
970 if (!pepper_composition_text_
.empty()) {
971 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
972 pepper_composition_text_
, underlines
, selection_start
,
978 void RenderFrameImpl::OnImeConfirmComposition(
979 const base::string16
& text
,
980 const gfx::Range
& replacement_range
,
981 bool keep_selection
) {
982 // When a PPAPI plugin has focus, we bypass WebKit.
983 // Here, text.empty() has a special meaning. It means to commit the last
984 // update of composition text (see
985 // RenderWidgetHost::ImeConfirmComposition()).
986 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
989 // last_text is empty only when both text and pepper_composition_text_ is.
991 if (last_text
.empty())
994 if (!IsPepperAcceptingCompositionEvents()) {
995 base::i18n::UTF16CharIterator
iterator(&last_text
);
997 while (iterator
.Advance()) {
998 blink::WebKeyboardEvent char_event
;
999 char_event
.type
= blink::WebInputEvent::Char
;
1000 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
1001 char_event
.modifiers
= 0;
1002 char_event
.windowsKeyCode
= last_text
[i
];
1003 char_event
.nativeKeyCode
= last_text
[i
];
1005 const int32 char_start
= i
;
1006 for (; i
< iterator
.array_pos(); ++i
) {
1007 char_event
.text
[i
- char_start
] = last_text
[i
];
1008 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
1011 if (GetRenderWidget()->webwidget())
1012 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
1015 // Mimics the order of events sent by WebKit.
1016 // See WebCore::Editor::setComposition() for the corresponding code.
1017 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
1018 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
1020 pepper_composition_text_
.clear();
1022 #endif // defined(ENABLE_PLUGINS)
1024 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
1025 if (!web_user_media_client_
)
1026 InitializeUserMediaClient();
1027 return web_user_media_client_
?
1028 web_user_media_client_
->media_stream_dispatcher() : NULL
;
1031 bool RenderFrameImpl::Send(IPC::Message
* message
) {
1032 if (is_detaching_
) {
1036 if (is_swapped_out_
) {
1037 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
1043 return RenderThread::Get()->Send(message
);
1046 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1047 void RenderFrameImpl::DidHideExternalPopupMenu() {
1048 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
1049 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
1050 external_popup_menu_
.reset();
1054 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
1055 // We may get here while detaching, when the WebFrame has been deleted. Do
1056 // not process any messages in this state.
1060 // TODO(kenrb): document() should not be null, but as a transitional step
1061 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1062 // to this method. This happens for a top-level remote frame, where a
1063 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1064 // around and is still able to receive messages.
1065 if (!frame_
->document().isNull())
1066 GetContentClient()->SetActiveURL(frame_
->document().url());
1068 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
1069 RenderFrameObserver
* observer
;
1070 while ((observer
= it
.GetNext()) != NULL
) {
1071 if (observer
->OnMessageReceived(msg
))
1075 bool handled
= true;
1076 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1077 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1078 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1079 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1080 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1081 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1082 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1083 OnCustomContextMenuAction
)
1084 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1085 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1086 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1087 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1088 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1089 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1090 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1091 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1092 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1093 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1094 OnAdjustSelectionByCharacterOffset
)
1095 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1096 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1097 OnMoveRangeSelectionExtent
)
1098 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1099 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1100 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1101 OnExtendSelectionAndDelete
)
1102 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1103 OnSetCompositionFromExistingText
)
1104 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1105 OnExecuteNoValueEditCommand
)
1106 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1107 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1108 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1109 OnJavaScriptExecuteRequest
)
1110 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1111 OnJavaScriptExecuteRequestForTests
)
1112 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1113 OnJavaScriptExecuteRequestInIsolatedWorld
)
1114 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1115 OnVisualStateRequest
)
1116 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1117 OnSetEditableSelectionOffsets
)
1118 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1119 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1120 OnTextSurroundingSelectionRequest
)
1121 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1122 OnSetAccessibilityMode
)
1123 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1124 OnSnapshotAccessibilityTree
)
1125 IPC_MESSAGE_HANDLER(FrameMsg_UpdateOpener
, OnUpdateOpener
)
1126 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1127 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1128 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1129 OnTextTrackSettingsChanged
)
1130 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1131 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1132 #if defined(OS_ANDROID)
1133 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1134 #elif defined(OS_MACOSX)
1135 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1136 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1138 IPC_END_MESSAGE_MAP()
1143 void RenderFrameImpl::OnNavigate(
1144 const CommonNavigationParams
& common_params
,
1145 const StartNavigationParams
& start_params
,
1146 const RequestNavigationParams
& request_params
) {
1147 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1148 switches::kEnableBrowserSideNavigation
));
1149 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1150 "url", common_params
.url
.possibly_invalid_spec());
1151 NavigateInternal(common_params
, start_params
, request_params
,
1152 scoped_ptr
<StreamOverrideParameters
>());
1155 void RenderFrameImpl::NavigateToSwappedOutURL() {
1156 // We use loadRequest instead of loadHTMLString because the former commits
1157 // synchronously. Otherwise a new navigation can interrupt the navigation
1158 // to kSwappedOutURL. If that happens to be to the page we had been
1159 // showing, then WebKit will never send a commit and we'll be left spinning.
1160 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1161 // the navigation to swappedout:// is not announced to the browser side.
1162 is_swapped_out_
= true;
1163 GURL
swappedOutURL(kSwappedOutURL
);
1164 WebURLRequest
request(swappedOutURL
);
1165 frame_
->loadRequest(request
);
1168 void RenderFrameImpl::BindServiceRegistry(
1169 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1170 mojo::ServiceProviderPtr exposed_services
) {
1171 service_registry_
.Bind(services
.Pass());
1172 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1175 ManifestManager
* RenderFrameImpl::manifest_manager() {
1176 return manifest_manager_
;
1179 void RenderFrameImpl::SetPendingNavigationParams(
1180 scoped_ptr
<NavigationParams
> navigation_params
) {
1181 pending_navigation_params_
= navigation_params
.Pass();
1184 void RenderFrameImpl::OnBeforeUnload() {
1185 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1187 // TODO(creis): Right now, this is only called on the main frame. Make the
1188 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1190 CHECK(!frame_
->parent());
1192 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1193 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1194 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1195 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1196 before_unload_start_time
,
1197 before_unload_end_time
));
1200 void RenderFrameImpl::OnSwapOut(
1201 int proxy_routing_id
,
1203 const FrameReplicationState
& replicated_frame_state
) {
1204 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1205 RenderFrameProxy
* proxy
= NULL
;
1206 bool swapped_out_forbidden
=
1207 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1208 bool is_main_frame
= !frame_
->parent();
1210 // This codepath should only be hit for subframes when in --site-per-process.
1211 CHECK_IMPLIES(!is_main_frame
,
1212 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1214 // Only run unload if we're not swapped out yet, but send the ack either way.
1215 if (!is_swapped_out_
) {
1216 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1217 // a different process. This involves running the unload handler and
1218 // clearing the page. We also allow this process to exit if there are no
1219 // other active RenderFrames in it.
1221 // Send an UpdateState message before we get swapped out.
1222 render_view_
->SendUpdateState();
1224 // If we need a proxy to replace this, create it now so its routing id is
1225 // registered for receiving IPC messages.
1226 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1227 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1228 this, proxy_routing_id
, replicated_frame_state
.scope
);
1231 // Synchronously run the unload handler before sending the ACK.
1232 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1233 // unload on subframes as well.
1235 frame_
->dispatchUnloadEvent();
1237 // Swap out and stop sending any IPC messages that are not ACKs.
1239 render_view_
->SetSwappedOut(true);
1240 is_swapped_out_
= true;
1242 // Set the proxy here, since OnStop() below could cause an onload event
1243 // handler to execute, which could trigger code such as
1244 // willCheckAndDispatchMessageEvent() that needs the proxy.
1246 set_render_frame_proxy(proxy
);
1248 // Now that we're swapped out and filtering IPC messages, stop loading to
1249 // ensure that no other in-progress navigation continues. We do this here
1250 // to avoid sending a DidStopLoading message to the browser process.
1251 // TODO(creis): Should we be stopping all frames here and using
1252 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1254 if (!swapped_out_forbidden
)
1257 // Transfer settings such as initial drawing parameters to the remote frame,
1258 // if one is created, that will replace this frame.
1259 if (!is_main_frame
&& proxy
)
1260 proxy
->web_frame()->initializeFromFrame(frame_
);
1262 // Replace the page with a blank dummy URL. The unload handler will not be
1263 // run a second time, thanks to a check in FrameLoader::stopLoading.
1264 // TODO(creis): Need to add a better way to do this that avoids running the
1265 // beforeunload handler. For now, we just run it a second time silently.
1266 if (!swapped_out_forbidden
)
1267 NavigateToSwappedOutURL();
1269 // Let WebKit know that this view is hidden so it can drop resources and
1270 // stop compositing.
1271 // TODO(creis): Support this for subframes as well.
1272 if (is_main_frame
) {
1273 render_view_
->webview()->setVisibilityState(
1274 blink::WebPageVisibilityStateHidden
, false);
1278 // It is now safe to show modal dialogs again.
1279 // TODO(creis): Deal with modal dialogs from subframes.
1281 render_view_
->suppress_dialogs_until_swap_out_
= false;
1283 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1285 RenderViewImpl
* render_view
= render_view_
.get();
1287 // Now that all of the cleanup is complete and the browser side is notified,
1288 // start using the RenderFrameProxy, if one is created.
1289 if (proxy
&& swapped_out_forbidden
) {
1290 frame_
->swap(proxy
->web_frame());
1293 proxy
->OnDidStartLoading();
1296 // In --site-per-process, initialize the WebRemoteFrame with the replication
1297 // state passed by the process that is now rendering the frame.
1298 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1299 // in that case we leave the LocalFrame as the main frame visible to Blink
1300 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1301 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1302 // When we do an unconditional swap for all frames, we can remove
1303 // !is_main_frame below.
1304 if (proxy
&& swapped_out_forbidden
)
1305 proxy
->SetReplicatedState(replicated_frame_state
);
1307 // Safe to exit if no one else is using the process.
1308 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1309 // the process based on the lifetime of this RenderFrameImpl object.
1310 if (is_main_frame
) {
1311 render_view
->WasSwappedOut();
1315 void RenderFrameImpl::OnContextMenuClosed(
1316 const CustomContextMenuContext
& custom_context
) {
1317 if (custom_context
.request_id
) {
1318 // External request, should be in our map.
1319 ContextMenuClient
* client
=
1320 pending_context_menus_
.Lookup(custom_context
.request_id
);
1322 client
->OnMenuClosed(custom_context
.request_id
);
1323 pending_context_menus_
.Remove(custom_context
.request_id
);
1326 if (custom_context
.link_followed
.is_valid())
1327 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1328 // Internal request, forward to WebKit.
1329 context_menu_node_
.reset();
1333 void RenderFrameImpl::OnCustomContextMenuAction(
1334 const CustomContextMenuContext
& custom_context
,
1336 if (custom_context
.request_id
) {
1337 // External context menu request, look in our map.
1338 ContextMenuClient
* client
=
1339 pending_context_menus_
.Lookup(custom_context
.request_id
);
1341 client
->OnMenuAction(custom_context
.request_id
, action
);
1343 // Internal request, forward to WebKit.
1344 render_view_
->webview()->performCustomContextMenuAction(action
);
1348 void RenderFrameImpl::OnUndo() {
1349 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1352 void RenderFrameImpl::OnRedo() {
1353 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1356 void RenderFrameImpl::OnCut() {
1357 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1358 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1361 void RenderFrameImpl::OnCopy() {
1362 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1363 WebNode current_node
= context_menu_node_
.isNull() ?
1364 GetFocusedElement() : context_menu_node_
;
1365 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1368 void RenderFrameImpl::OnPaste() {
1369 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1370 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1373 void RenderFrameImpl::OnPasteAndMatchStyle() {
1374 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1375 frame_
->executeCommand(
1376 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1379 #if defined(OS_MACOSX)
1380 void RenderFrameImpl::OnCopyToFindPboard() {
1381 // Since the find pasteboard supports only plain text, this can be simpler
1382 // than the |OnCopy()| case.
1383 if (frame_
->hasSelection()) {
1384 base::string16 selection
= frame_
->selectionAsText();
1385 RenderThread::Get()->Send(
1386 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1391 void RenderFrameImpl::OnDelete() {
1392 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1395 void RenderFrameImpl::OnSelectAll() {
1396 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1397 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1400 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1401 const gfx::Point
& extent
) {
1402 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1403 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1405 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1406 frame_
->selectRange(base
, extent
);
1409 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1411 size_t start
, length
;
1412 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1417 // Sanity checks to disallow empty and out of range selections.
1418 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1419 || static_cast<int>(start
) + start_adjust
< 0) {
1423 // A negative adjust amount moves the selection towards the beginning of
1424 // the document, a positive amount moves the selection towards the end of
1426 start
+= start_adjust
;
1427 length
+= end_adjust
- start_adjust
;
1429 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1432 void RenderFrameImpl::OnUnselect() {
1433 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1434 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1437 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1438 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1439 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1440 GetRenderWidget()->routing_id()));
1442 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1443 frame_
->moveRangeSelectionExtent(point
);
1446 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1447 if (!frame_
->hasSelection())
1448 frame_
->selectWordAroundCaret();
1450 frame_
->replaceSelection(text
);
1453 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1454 if (!frame_
->hasSelection())
1457 frame_
->replaceMisspelledRange(text
);
1460 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1461 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1464 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1465 const std::string
& message
) {
1466 AddMessageToConsole(level
, message
);
1469 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1470 const base::string16
& jscript
,
1472 bool notify_result
) {
1473 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1474 TRACE_EVENT_SCOPE_THREAD
);
1476 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1477 v8::Local
<v8::Value
> result
=
1478 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1480 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1483 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1484 const base::string16
& jscript
,
1487 bool has_user_gesture
) {
1488 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1489 TRACE_EVENT_SCOPE_THREAD
);
1491 // A bunch of tests expect to run code in the context of a user gesture, which
1492 // can grant additional privileges (e.g. the ability to create popups).
1493 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1494 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1495 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1496 v8::Local
<v8::Value
> result
=
1497 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1499 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1502 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1503 const base::string16
& jscript
,
1507 TRACE_EVENT_INSTANT0("test_tracing",
1508 "OnJavaScriptExecuteRequestInIsolatedWorld",
1509 TRACE_EVENT_SCOPE_THREAD
);
1511 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1512 world_id
> ISOLATED_WORLD_ID_MAX
) {
1513 // Return if the world_id is not valid. world_id is passed as a plain int
1514 // over IPC and needs to be verified here, in the IPC endpoint.
1519 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1520 WebScriptSource script
= WebScriptSource(jscript
);
1521 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1522 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1523 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1527 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1531 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1533 notify_result_(notify_result
),
1534 routing_id_(routing_id
),
1535 render_frame_impl_(render_frame_impl
) {
1538 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1539 ~JavaScriptIsolatedWorldRequest() {
1542 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1543 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1544 if (!render_frame_impl_
.get()) {
1548 if (notify_result_
) {
1549 base::ListValue list
;
1550 if (!result
.isEmpty()) {
1551 // It's safe to always use the main world context when converting
1552 // here. V8ValueConverterImpl shouldn't actually care about the
1553 // context scope, and it switches to v8::Object's creation context
1554 // when encountered. (from extensions/renderer/script_injection.cc)
1555 v8::Local
<v8::Context
> context
=
1556 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1557 v8::Context::Scope
context_scope(context
);
1558 V8ValueConverterImpl converter
;
1559 converter
.SetDateAllowed(true);
1560 converter
.SetRegExpAllowed(true);
1561 for (const auto& value
: result
) {
1562 scoped_ptr
<base::Value
> result_value(
1563 converter
.FromV8Value(value
, context
));
1564 list
.Append(result_value
? result_value
.Pass()
1565 : base::Value::CreateNullValue());
1568 list
.Set(0, base::Value::CreateNullValue());
1570 render_frame_impl_
.get()->Send(
1571 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1577 void RenderFrameImpl::HandleJavascriptExecutionResult(
1578 const base::string16
& jscript
,
1581 v8::Local
<v8::Value
> result
) {
1582 if (notify_result
) {
1583 base::ListValue list
;
1584 if (!result
.IsEmpty()) {
1585 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1586 v8::Context::Scope
context_scope(context
);
1587 V8ValueConverterImpl converter
;
1588 converter
.SetDateAllowed(true);
1589 converter
.SetRegExpAllowed(true);
1590 scoped_ptr
<base::Value
> result_value(
1591 converter
.FromV8Value(result
, context
));
1592 list
.Set(0, result_value
? result_value
.Pass()
1593 : base::Value::CreateNullValue());
1595 list
.Set(0, base::Value::CreateNullValue());
1597 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1601 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1602 GetRenderWidget()->QueueMessage(
1603 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1604 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1607 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1608 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1609 if (!GetRenderWidget()->ShouldHandleImeEvent())
1611 ImeEventGuard
guard(GetRenderWidget());
1612 frame_
->setEditableSelectionOffsets(start
, end
);
1615 void RenderFrameImpl::OnSetCompositionFromExistingText(
1617 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1618 if (!GetRenderWidget()->ShouldHandleImeEvent())
1620 ImeEventGuard
guard(GetRenderWidget());
1621 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1624 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1625 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1628 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1629 if (!GetRenderWidget()->ShouldHandleImeEvent())
1632 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1634 ImeEventGuard
guard(GetRenderWidget());
1635 blink::WebScopedUserGesture gesture_indicator
;
1636 frame_
->extendSelectionAndDelete(before
, after
);
1639 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1640 if (accessibility_mode_
== new_mode
)
1642 accessibility_mode_
= new_mode
;
1643 if (renderer_accessibility_
) {
1644 // Note: this isn't called automatically by the destructor because
1645 // there'd be no point in calling it in frame teardown, only if there's
1646 // an accessibility mode change but the frame is persisting.
1647 renderer_accessibility_
->DisableAccessibility();
1649 delete renderer_accessibility_
;
1650 renderer_accessibility_
= NULL
;
1652 if (accessibility_mode_
== AccessibilityModeOff
)
1655 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1656 renderer_accessibility_
= new RendererAccessibility(this);
1659 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1660 ui::AXTreeUpdate
<AXContentNodeData
> response
;
1661 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1662 Send(new AccessibilityHostMsg_SnapshotResponse(
1663 routing_id_
, callback_id
, response
));
1666 void RenderFrameImpl::OnUpdateOpener(int opener_routing_id
) {
1667 WebFrame
* opener
= ResolveOpener(opener_routing_id
, nullptr);
1668 frame_
->setOpener(opener
);
1671 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1672 frame_
->setFrameOwnerSandboxFlags(flags
);
1675 void RenderFrameImpl::OnTextTrackSettingsChanged(
1676 const FrameMsg_TextTrackSettings_Params
& params
) {
1677 DCHECK(!frame_
->parent());
1678 if (!render_view_
->webview())
1681 if (params
.text_tracks_enabled
) {
1682 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1683 WebSettings::TextTrackKindUserPreference::Captions
);
1685 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1686 WebSettings::TextTrackKindUserPreference::Default
);
1688 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1689 WebString::fromUTF8(params
.text_track_background_color
));
1690 render_view_
->webview()->settings()->setTextTrackFontFamily(
1691 WebString::fromUTF8(params
.text_track_font_family
));
1692 render_view_
->webview()->settings()->setTextTrackFontStyle(
1693 WebString::fromUTF8(params
.text_track_font_style
));
1694 render_view_
->webview()->settings()->setTextTrackFontVariant(
1695 WebString::fromUTF8(params
.text_track_font_variant
));
1696 render_view_
->webview()->settings()->setTextTrackTextColor(
1697 WebString::fromUTF8(params
.text_track_text_color
));
1698 render_view_
->webview()->settings()->setTextTrackTextShadow(
1699 WebString::fromUTF8(params
.text_track_text_shadow
));
1700 render_view_
->webview()->settings()->setTextTrackTextSize(
1701 WebString::fromUTF8(params
.text_track_text_size
));
1704 void RenderFrameImpl::OnPostMessageEvent(
1705 const FrameMsg_PostMessage_Params
& params
) {
1706 // Find the source frame if it exists.
1707 WebFrame
* source_frame
= NULL
;
1708 if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1709 RenderFrameProxy
* source_proxy
=
1710 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1712 // Currently, navigating a top-level frame cross-process does not swap
1713 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1714 // WebRemoteFrame will not have an associated blink::Frame. If this is
1715 // the case for |source_proxy|, use the corresponding (swapped-out)
1716 // WebLocalFrame instead, so that event.source for this message can be
1717 // set and used properly.
1718 if (source_proxy
->IsMainFrameDetachedFromTree())
1719 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1721 source_frame
= source_proxy
->web_frame();
1725 // If the message contained MessagePorts, create the corresponding endpoints.
1726 blink::WebMessagePortChannelArray channels
=
1727 WebMessagePortChannelImpl::CreatePorts(
1728 params
.message_ports
, params
.new_routing_ids
,
1729 base::ThreadTaskRunnerHandle::Get().get());
1731 WebSerializedScriptValue serialized_script_value
;
1732 if (params
.is_data_raw_string
) {
1733 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1734 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1735 v8::Context::Scope
context_scope(context
);
1736 V8ValueConverterImpl converter
;
1737 converter
.SetDateAllowed(true);
1738 converter
.SetRegExpAllowed(true);
1739 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1740 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1742 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1744 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1747 // Create an event with the message. The next-to-last parameter to
1748 // initMessageEvent is the last event ID, which is not used with postMessage.
1749 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1750 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1751 msg_event
.initMessageEvent("message",
1752 // |canBubble| and |cancellable| are always false
1754 serialized_script_value
,
1755 params
.source_origin
, source_frame
,
1756 frame_
->document(), "", channels
);
1758 // We must pass in the target_origin to do the security check on this side,
1759 // since it may have changed since the original postMessage call was made.
1760 WebSecurityOrigin target_origin
;
1761 if (!params
.target_origin
.empty()) {
1763 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1765 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1768 #if defined(OS_ANDROID)
1769 void RenderFrameImpl::OnSelectPopupMenuItems(
1771 const std::vector
<int>& selected_indices
) {
1772 // It is possible to receive more than one of these calls if the user presses
1773 // a select faster than it takes for the show-select-popup IPC message to make
1774 // it to the browser UI thread. Ignore the extra-messages.
1775 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1776 if (!external_popup_menu_
)
1779 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1780 external_popup_menu_
.reset();
1784 #if defined(OS_MACOSX)
1785 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1786 if (external_popup_menu_
== NULL
)
1788 external_popup_menu_
->DidSelectItem(selected_index
);
1789 external_popup_menu_
.reset();
1793 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1794 frame_
->reload(ignore_cache
);
1797 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1798 blink::WebSurroundingText surroundingText
;
1799 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1801 if (surroundingText
.isNull()) {
1802 // |surroundingText| might not be correctly initialized, for example if
1803 // |frame_->selectionRange().isNull()|, in other words, if there was no
1805 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1806 routing_id_
, base::string16(), 0, 0));
1810 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1812 surroundingText
.textContent(),
1813 surroundingText
.startOffsetInTextContent(),
1814 surroundingText
.endOffsetInTextContent()));
1817 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1818 const base::string16
& message
,
1819 const base::string16
& default_value
,
1820 const GURL
& frame_url
,
1821 base::string16
* result
) {
1822 // Don't allow further dialogs if we are waiting to swap out, since the
1823 // PageGroupLoadDeferrer in our stack prevents it.
1824 if (render_view()->suppress_dialogs_until_swap_out_
)
1827 bool success
= false;
1828 base::string16 result_temp
;
1830 result
= &result_temp
;
1832 render_view()->SendAndRunNestedMessageLoop(
1833 new FrameHostMsg_RunJavaScriptMessage(
1834 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1839 void RenderFrameImpl::LoadNavigationErrorPage(
1840 const WebURLRequest
& failed_request
,
1841 const WebURLError
& error
,
1843 std::string error_html
;
1844 GetContentClient()->renderer()->GetNavigationErrorStrings(
1845 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1847 frame_
->loadHTMLString(error_html
,
1848 GURL(kUnreachableWebDataURL
),
1849 error
.unreachableURL
,
1853 void RenderFrameImpl::DidCommitCompositorFrame() {
1854 if (BrowserPluginManager::Get())
1855 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1857 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1860 RenderView
* RenderFrameImpl::GetRenderView() {
1861 return render_view_
.get();
1864 int RenderFrameImpl::GetRoutingID() {
1868 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1873 WebElement
RenderFrameImpl::GetFocusedElement() const {
1874 WebDocument doc
= frame_
->document();
1876 return doc
.focusedElement();
1878 return WebElement();
1881 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1882 return render_view_
->GetWebkitPreferences();
1885 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1886 const ContextMenuParams
& params
) {
1887 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1888 ContextMenuParams
our_params(params
);
1889 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1890 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1891 return our_params
.custom_context
.request_id
;
1894 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1895 DCHECK(pending_context_menus_
.Lookup(request_id
));
1896 pending_context_menus_
.Remove(request_id
);
1899 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1900 return context_menu_node_
;
1903 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1904 blink::WebFrame
* frame
,
1905 const WebPluginInfo
& info
,
1906 const blink::WebPluginParams
& params
,
1907 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1908 DCHECK_EQ(frame_
, frame
);
1909 #if defined(ENABLE_PLUGINS)
1910 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1911 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1912 this, GetContentClient()
1914 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1919 bool pepper_plugin_was_registered
= false;
1920 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1921 this, info
, &pepper_plugin_was_registered
));
1922 if (pepper_plugin_was_registered
) {
1923 if (pepper_module
.get()) {
1924 return new PepperWebPluginImpl(
1925 pepper_module
.get(), params
, this,
1927 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1930 #if defined(OS_CHROMEOS)
1931 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1933 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1934 // TODO(jam): change to take RenderFrame.
1935 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1942 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1943 const blink::WebURLRequest
& request
,
1944 blink::WebNavigationPolicy policy
) {
1945 DCHECK(!frame_
|| frame_
== frame
);
1946 loadURLExternally(frame
, request
, policy
, WebString());
1949 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1950 OnJavaScriptExecuteRequest(javascript
, 0, false);
1953 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1954 return &service_registry_
;
1957 #if defined(ENABLE_PLUGINS)
1958 void RenderFrameImpl::RegisterPeripheralPlugin(
1959 const GURL
& content_origin
,
1960 const base::Closure
& unthrottle_callback
) {
1961 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1962 content_origin
, unthrottle_callback
);
1964 #endif // defined(ENABLE_PLUGINS)
1966 bool RenderFrameImpl::IsFTPDirectoryListing() {
1967 WebURLResponseExtraDataImpl
* extra_data
=
1968 GetExtraDataFromResponse(frame_
->dataSource()->response());
1969 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1972 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1973 BrowserPluginManager::Get()->Attach(element_instance_id
);
1976 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1977 BrowserPluginManager::Get()->Detach(element_instance_id
);
1980 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1982 const gfx::Range
& range
) {
1983 // Use the routing id of Render Widget Host.
1984 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1990 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1991 v8::Isolate
* isolate
,
1992 v8::Local
<v8::Context
> context
) {
1993 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1994 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1997 v8::HandleScope
handle_scope(isolate
);
1998 registry
->AddBuiltinModule(
1999 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
2000 registry
->AddBuiltinModule(isolate
,
2001 mojo::js::Support::kModuleName
,
2002 mojo::js::Support::GetModule(isolate
));
2003 registry
->AddBuiltinModule(
2005 ServiceRegistryJsWrapper::kModuleName
,
2006 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
2009 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
2010 const std::string
& message
) {
2011 if (devtools_agent_
)
2012 devtools_agent_
->AddMessageToConsole(level
, message
);
2015 // blink::WebFrameClient implementation ----------------------------------------
2017 blink::WebPlugin
* RenderFrameImpl::createPlugin(
2018 blink::WebLocalFrame
* frame
,
2019 const blink::WebPluginParams
& params
) {
2020 DCHECK_EQ(frame_
, frame
);
2021 blink::WebPlugin
* plugin
= NULL
;
2022 if (GetContentClient()->renderer()->OverrideCreatePlugin(
2023 this, frame
, params
, &plugin
)) {
2027 if (base::UTF16ToUTF8(base::StringPiece16(params
.mimeType
)) ==
2028 kBrowserPluginMimeType
) {
2029 return BrowserPluginManager::Get()->CreateBrowserPlugin(
2030 this, GetContentClient()
2032 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
2037 #if defined(ENABLE_PLUGINS)
2039 std::string mime_type
;
2041 WebString top_origin
= frame
->top()->securityOrigin().toString();
2042 Send(new FrameHostMsg_GetPluginInfo(routing_id_
, params
.url
, GURL(top_origin
),
2043 params
.mimeType
.utf8(), &found
, &info
,
2048 WebPluginParams params_to_use
= params
;
2049 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2050 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2053 #endif // defined(ENABLE_PLUGINS)
2056 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2057 blink::WebLocalFrame
* frame
,
2058 const blink::WebURL
& url
,
2059 WebMediaPlayerClient
* client
,
2060 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
2061 WebContentDecryptionModule
* initial_cdm
) {
2062 #if defined(VIDEO_HOLE)
2063 if (!contains_media_player_
) {
2064 render_view_
->RegisterVideoHoleFrame(this);
2065 contains_media_player_
= true;
2067 #endif // defined(VIDEO_HOLE)
2069 blink::WebMediaStream
web_stream(
2070 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2071 if (!web_stream
.isNull())
2072 return CreateWebMediaPlayerForMediaStream(client
);
2074 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2076 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2077 scoped_refptr
<media::AudioRendererSink
> audio_renderer_sink
;
2078 media::WebMediaPlayerParams::Context3DCB context_3d_cb
;
2080 scoped_refptr
<media::AudioRendererSink
> audio_renderer_sink
=
2081 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
);
2082 media::WebMediaPlayerParams::Context3DCB context_3d_cb
=
2083 base::Bind(&GetSharedMainThreadContext3D
);
2084 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2086 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2087 media::WebMediaPlayerParams
params(
2088 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2089 base::Unretained(GetContentClient()->renderer()),
2090 static_cast<RenderFrame
*>(this), has_played_media_
),
2091 audio_renderer_sink
, media_log
, render_thread
->GetMediaThreadTaskRunner(),
2092 render_thread
->GetWorkerTaskRunner(),
2093 render_thread
->compositor_task_runner(), context_3d_cb
,
2094 GetMediaPermission(), initial_cdm
);
2096 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2097 return CreateAndroidWebMediaPlayer(client
, encrypted_client
, params
);
2099 #if defined(ENABLE_MOJO_MEDIA)
2100 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2101 new media::MojoRendererFactory(GetMediaServiceFactory()));
2103 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2104 GetContentClient()->renderer()->CreateMediaRendererFactory(
2105 this, render_thread
->GetGpuFactories(), media_log
);
2107 if (!media_renderer_factory
.get()) {
2108 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2109 media_log
, render_thread
->GetGpuFactories(),
2110 *render_thread
->GetAudioHardwareConfig()));
2112 #endif // defined(ENABLE_MOJO_MEDIA)
2114 return new media::WebMediaPlayerImpl(
2115 frame
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
2116 media_renderer_factory
.Pass(), GetCdmFactory(), params
);
2117 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2120 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2121 blink::WebLocalFrame
* frame
,
2122 blink::WebApplicationCacheHostClient
* client
) {
2123 if (!frame
|| !frame
->view())
2125 DCHECK(!frame_
|| frame_
== frame
);
2126 return new RendererWebApplicationCacheHostImpl(
2127 RenderViewImpl::FromWebView(frame
->view()), client
,
2128 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2131 blink::WebWorkerContentSettingsClientProxy
*
2132 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2133 blink::WebLocalFrame
* frame
) {
2134 if (!frame
|| !frame
->view())
2136 DCHECK(!frame_
|| frame_
== frame
);
2137 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2141 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2142 const WebPopupMenuInfo
& popup_menu_info
,
2143 WebExternalPopupMenuClient
* popup_menu_client
) {
2144 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2145 // An IPC message is sent to the browser to build and display the actual
2146 // popup. The user could have time to click a different select by the time
2147 // the popup is shown. In that case external_popup_menu_ is non NULL.
2148 // By returning NULL in that case, we instruct Blink to cancel that new
2149 // popup. So from the user perspective, only the first one will show, and
2150 // will have to close the first one before another one can be shown.
2151 if (external_popup_menu_
)
2153 external_popup_menu_
.reset(
2154 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2155 if (render_view_
->screen_metrics_emulator_
) {
2156 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2157 external_popup_menu_
.get(),
2158 render_view_
->screen_metrics_emulator_
.get());
2160 return external_popup_menu_
.get();
2166 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2167 DCHECK(!frame_
|| frame_
== frame
);
2168 return &cookie_jar_
;
2171 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2172 blink::WebLocalFrame
* frame
) {
2173 DCHECK(!frame_
|| frame_
== frame
);
2174 // At this point we should have non-null data source.
2175 DCHECK(frame
->dataSource());
2176 if (!ChildThreadImpl::current())
2177 return NULL
; // May be null in some tests.
2178 ServiceWorkerNetworkProvider
* provider
=
2179 ServiceWorkerNetworkProvider::FromDocumentState(
2180 DocumentState::FromDataSource(frame
->dataSource()));
2182 return new WebServiceWorkerProviderImpl(
2183 ChildThreadImpl::current()->thread_safe_sender(),
2184 provider
->context());
2187 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2188 DCHECK(!frame_
|| frame_
== frame
);
2189 // If the request hasn't yet committed, notify the browser process that it is
2190 // no longer safe to show the pending URL of the main frame, since a URL spoof
2191 // is now possible. (If the request has committed, the browser already knows.)
2192 if (!frame
->parent()) {
2193 DocumentState
* document_state
=
2194 DocumentState::FromDataSource(frame
->dataSource());
2195 NavigationStateImpl
* navigation_state
=
2196 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2198 if (!navigation_state
->request_committed()) {
2199 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2204 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2205 blink::WebLocalFrame
* parent
,
2206 blink::WebTreeScopeType scope
,
2207 const blink::WebString
& name
,
2208 blink::WebSandboxFlags sandbox_flags
) {
2209 // Synchronously notify the browser of a child frame creation to get the
2210 // routing_id for the RenderFrame.
2211 int child_routing_id
= MSG_ROUTING_NONE
;
2212 Send(new FrameHostMsg_CreateChildFrame(
2214 base::UTF16ToUTF8(base::StringPiece16(name
)), sandbox_flags
,
2215 &child_routing_id
));
2217 // Allocation of routing id failed, so we can't create a child frame. This can
2218 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2219 // out state or synchronous IPC message above has failed.
2220 if (child_routing_id
== MSG_ROUTING_NONE
) {
2221 NOTREACHED() << "Failed to allocate routing id for child frame.";
2225 // Create the RenderFrame and WebLocalFrame, linking the two.
2226 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2227 render_view_
.get(), child_routing_id
);
2228 blink::WebLocalFrame
* web_frame
=
2229 WebLocalFrame::create(scope
, child_render_frame
);
2230 child_render_frame
->SetWebFrame(web_frame
);
2232 // Add the frame to the frame tree and initialize it.
2233 parent
->appendChild(web_frame
);
2234 child_render_frame
->Initialize();
2239 void RenderFrameImpl::didChangeOpener(blink::WebFrame
* opener
) {
2240 // Only active frames are able to disown their opener.
2241 if (!opener
&& is_swapped_out_
)
2244 // Only a local frame should be able to update another frame's opener.
2245 DCHECK(!opener
|| opener
->isWebLocalFrame());
2247 int opener_routing_id
= opener
?
2248 RenderFrameImpl::FromWebFrame(opener
->toWebLocalFrame())->GetRoutingID() :
2250 Send(new FrameHostMsg_DidChangeOpener(routing_id_
, opener_routing_id
));
2253 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2254 // NOTE: This function is called on the frame that is being detached and not
2255 // the parent frame. This is different from createChildFrame() which is
2256 // called on the parent frame.
2257 CHECK(!is_detaching_
);
2258 DCHECK(!frame_
|| frame_
== frame
);
2260 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2261 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2262 FrameDetached(frame
));
2264 // We only notify the browser process when the frame is being detached for
2265 // removal. If the frame is being detached for swap, we don't need to do this
2266 // since we are not modifiying the frame tree.
2267 if (type
== DetachType::Remove
)
2268 Send(new FrameHostMsg_Detach(routing_id_
));
2270 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2271 // sent before setting |is_detaching_| to true.
2272 is_detaching_
= true;
2274 // Clean up the associated RenderWidget for the frame, if there is one.
2275 if (render_widget_
) {
2276 render_widget_
->UnregisterRenderFrame(this);
2277 render_widget_
->CloseForFrame();
2280 // We need to clean up subframes by removing them from the map and deleting
2281 // the RenderFrameImpl. In contrast, the main frame is owned by its
2282 // containing RenderViewHost (so that they have the same lifetime), so only
2283 // removal from the map is needed and no deletion.
2284 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2285 CHECK(it
!= g_frame_map
.Get().end());
2286 CHECK_EQ(it
->second
, this);
2287 g_frame_map
.Get().erase(it
);
2289 // Only remove the frame from the renderer's frame tree if the frame is
2290 // being detached for removal. In the case of a swap, the frame needs to
2291 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2292 if (is_subframe_
&& type
== DetachType::Remove
)
2293 frame
->parent()->removeChild(frame
);
2295 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2296 // object may not be deleted immediately and other methods may try to access
2302 // Object is invalid after this point.
2305 void RenderFrameImpl::frameFocused() {
2306 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2309 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2310 DCHECK(!frame_
|| frame_
== frame
);
2312 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2313 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2314 FrameWillClose(frame
));
2317 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2318 const blink::WebString
& name
) {
2319 DCHECK(!frame_
|| frame_
== frame
);
2321 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2322 // updates may have performance implications for benchmarks like SunSpider.
2323 // For now, send these updates only for --site-per-process, which needs to
2324 // replicate frame names to frame proxies, and when
2325 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2326 // can be optimized further by only sending the update if there are any
2327 // remote frames in the frame tree, or delaying and batching up IPCs if
2328 // updates are happening too frequently.
2329 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2330 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2331 Send(new FrameHostMsg_DidChangeName(
2332 routing_id_
, base::UTF16ToUTF8(base::StringPiece16(name
))));
2336 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2337 blink::WebSandboxFlags flags
) {
2338 int frame_routing_id
= MSG_ROUTING_NONE
;
2339 if (child_frame
->isWebRemoteFrame()) {
2341 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2344 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2347 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2351 void RenderFrameImpl::didMatchCSS(
2352 blink::WebLocalFrame
* frame
,
2353 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2354 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2355 DCHECK(!frame_
|| frame_
== frame
);
2357 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2358 DidMatchCSS(newly_matching_selectors
,
2359 stopped_matching_selectors
));
2362 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2363 const blink::WebString
& source
) {
2364 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2368 void RenderFrameImpl::didAddMessageToConsole(
2369 const blink::WebConsoleMessage
& message
,
2370 const blink::WebString
& source_name
,
2371 unsigned source_line
,
2372 const blink::WebString
& stack_trace
) {
2373 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2374 switch (message
.level
) {
2375 case blink::WebConsoleMessage::LevelDebug
:
2376 log_severity
= logging::LOG_VERBOSE
;
2378 case blink::WebConsoleMessage::LevelLog
:
2379 case blink::WebConsoleMessage::LevelInfo
:
2380 log_severity
= logging::LOG_INFO
;
2382 case blink::WebConsoleMessage::LevelWarning
:
2383 log_severity
= logging::LOG_WARNING
;
2385 case blink::WebConsoleMessage::LevelError
:
2386 log_severity
= logging::LOG_ERROR
;
2389 log_severity
= logging::LOG_VERBOSE
;
2392 if (shouldReportDetailedMessageForSource(source_name
)) {
2394 RenderFrameObserver
, observers_
,
2395 DetailedConsoleMessageAdded(message
.text
,
2399 static_cast<int32
>(log_severity
)));
2402 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2403 static_cast<int32
>(log_severity
),
2405 static_cast<int32
>(source_line
),
2409 void RenderFrameImpl::loadURLExternally(
2410 blink::WebLocalFrame
* frame
,
2411 const blink::WebURLRequest
& request
,
2412 blink::WebNavigationPolicy policy
,
2413 const blink::WebString
& suggested_name
) {
2414 DCHECK(!frame_
|| frame_
== frame
);
2415 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2416 if (policy
== blink::WebNavigationPolicyDownload
) {
2417 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2419 request
.url(), referrer
,
2422 OpenURL(frame
, request
.url(), referrer
, policy
);
2426 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2427 const NavigationPolicyInfo
& info
) {
2428 DCHECK(!frame_
|| frame_
== info
.frame
);
2429 return DecidePolicyForNavigation(this, info
);
2432 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2433 blink::WebFrame
* frame
) {
2434 DCHECK(!frame_
|| frame_
== frame
);
2435 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2438 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2439 const blink::WebFormElement
& form
) {
2440 DCHECK(!frame_
|| frame_
== frame
);
2442 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2445 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2446 const blink::WebFormElement
& form
) {
2447 DCHECK(!frame_
|| frame_
== frame
);
2448 DocumentState
* document_state
=
2449 DocumentState::FromDataSource(frame
->provisionalDataSource());
2450 NavigationStateImpl
* navigation_state
=
2451 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2452 InternalDocumentStateData
* internal_data
=
2453 InternalDocumentStateData::FromDocumentState(document_state
);
2455 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2456 ui::PAGE_TRANSITION_LINK
)) {
2457 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2460 // Save these to be processed when the ensuing navigation is committed.
2461 WebSearchableFormData
web_searchable_form_data(form
);
2462 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2463 internal_data
->set_searchable_form_encoding(
2464 web_searchable_form_data
.encoding().utf8());
2466 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2469 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2470 blink::WebDataSource
* datasource
) {
2471 DCHECK(!frame_
|| frame_
== frame
);
2473 bool content_initiated
= !pending_navigation_params_
.get();
2475 // Make sure any previous redirect URLs end up in our new data source.
2476 if (pending_navigation_params_
.get()) {
2477 for (const auto& i
:
2478 pending_navigation_params_
->request_params
.redirects
) {
2479 datasource
->appendRedirect(i
);
2483 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2484 if (!document_state
) {
2485 document_state
= new DocumentState
;
2486 datasource
->setExtraData(document_state
);
2487 if (!content_initiated
)
2488 PopulateDocumentStateFromPending(document_state
);
2491 // Carry over the user agent override flag, if it exists.
2492 blink::WebView
* webview
= render_view_
->webview();
2493 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2494 webview
->mainFrame()->isWebLocalFrame() &&
2495 webview
->mainFrame()->dataSource()) {
2496 DocumentState
* old_document_state
=
2497 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2498 if (old_document_state
) {
2499 InternalDocumentStateData
* internal_data
=
2500 InternalDocumentStateData::FromDocumentState(document_state
);
2501 InternalDocumentStateData
* old_internal_data
=
2502 InternalDocumentStateData::FromDocumentState(old_document_state
);
2503 internal_data
->set_is_overriding_user_agent(
2504 old_internal_data
->is_overriding_user_agent());
2508 // The rest of RenderView assumes that a WebDataSource will always have a
2509 // non-null NavigationState.
2510 if (content_initiated
) {
2511 document_state
->set_navigation_state(
2512 NavigationStateImpl::CreateContentInitiated());
2514 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2515 pending_navigation_params_
.reset();
2518 // DocumentState::referred_by_prefetcher_ is true if we are
2519 // navigating from a page that used prefetching using a link on that
2520 // page. We are early enough in the request process here that we
2521 // can still see the DocumentState of the previous page and set
2522 // this value appropriately.
2523 // TODO(gavinp): catch the important case of navigation in a new
2524 // renderer process.
2526 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2527 const WebURLRequest
& original_request
= datasource
->originalRequest();
2528 const GURL
referrer(
2529 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2530 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2531 DocumentState::FromDataSource(old_frame
->dataSource())
2532 ->was_prefetcher()) {
2533 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2534 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2535 if (old_frame_datasource
&&
2536 referrer
== GURL(old_frame_datasource
->request().url())) {
2537 document_state
->set_was_referred_by_prefetcher(true);
2545 if (content_initiated
) {
2546 const WebURLRequest
& request
= datasource
->request();
2547 switch (request
.cachePolicy()) {
2548 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2549 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2551 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2552 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2553 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2555 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2556 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2558 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2559 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2566 // Create the serviceworker's per-document network observing object if it
2567 // does not exist (When navigation happens within a page, the provider already
2569 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2570 DocumentState::FromDataSource(datasource
))) {
2571 ServiceWorkerProviderType provider_type
=
2572 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2573 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2574 blink::WebSandboxFlags::Origin
) {
2575 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2577 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2578 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2579 ServiceWorkerNetworkProvider::AttachToDocumentState(
2580 DocumentState::FromDataSource(datasource
),
2581 network_provider
.Pass());
2585 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2586 double triggering_event_time
) {
2587 DCHECK(!frame_
|| frame_
== frame
);
2588 WebDataSource
* ds
= frame
->provisionalDataSource();
2590 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2591 // callback is invoked.
2595 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2596 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2597 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2599 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2600 CHECK_IMPLIES(ds
->request().url() == GURL(kSwappedOutURL
), is_swapped_out_
)
2601 << "Heard swappedout:// when not swapped out.";
2603 // Update the request time if WebKit has better knowledge of it.
2604 if (document_state
->request_time().is_null() &&
2605 triggering_event_time
!= 0.0) {
2606 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2609 // Start time is only set after request time.
2610 document_state
->set_start_load_time(Time::Now());
2612 bool is_top_most
= !frame
->parent();
2614 render_view_
->set_navigation_gesture(
2615 WebUserGestureIndicator::isProcessingUserGesture() ?
2616 NavigationGestureUser
: NavigationGestureAuto
);
2617 } else if (ds
->replacesCurrentHistoryItem()) {
2618 // Subframe navigations that don't add session history items must be
2619 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2620 // handle loading of error pages.
2621 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2622 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2625 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2626 DidStartProvisionalLoad(frame
));
2627 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2629 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2630 routing_id_
, ds
->request().url()));
2633 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2634 blink::WebLocalFrame
* frame
) {
2635 DCHECK(!frame_
|| frame_
== frame
);
2636 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2639 void RenderFrameImpl::didFailProvisionalLoad(
2640 blink::WebLocalFrame
* frame
,
2641 const blink::WebURLError
& error
,
2642 blink::WebHistoryCommitType commit_type
) {
2643 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2645 DCHECK(!frame_
|| frame_
== frame
);
2646 WebDataSource
* ds
= frame
->provisionalDataSource();
2649 const WebURLRequest
& failed_request
= ds
->request();
2651 // Notify the browser that we failed a provisional load with an error.
2653 // Note: It is important this notification occur before DidStopLoading so the
2654 // SSL manager can react to the provisional load failure before being
2655 // notified the load stopped.
2657 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2658 DidFailProvisionalLoad(frame
, error
));
2659 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2660 DidFailProvisionalLoad(error
));
2662 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2664 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2667 // Make sure we never show errors in view source mode.
2668 frame
->enableViewSourceMode(false);
2670 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2671 NavigationStateImpl
* navigation_state
=
2672 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2674 // If this is a failed back/forward/reload navigation, then we need to do a
2675 // 'replace' load. This is necessary to avoid messing up session history.
2676 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2677 // as session history is concerned.
2678 bool replace
= commit_type
!= blink::WebStandardCommit
;
2680 // If we failed on a browser initiated request, then make sure that our error
2681 // page load is regarded as the same browser initiated request.
2682 if (!navigation_state
->IsContentInitiated()) {
2683 pending_navigation_params_
.reset(new NavigationParams(
2684 navigation_state
->common_params(), navigation_state
->start_params(),
2685 navigation_state
->request_params()));
2686 pending_navigation_params_
->request_params
.request_time
=
2687 document_state
->request_time();
2690 // Load an error page.
2691 LoadNavigationErrorPage(failed_request
, error
, replace
);
2694 void RenderFrameImpl::didCommitProvisionalLoad(
2695 blink::WebLocalFrame
* frame
,
2696 const blink::WebHistoryItem
& item
,
2697 blink::WebHistoryCommitType commit_type
) {
2698 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2700 "url", GetLoadingUrl().possibly_invalid_spec());
2701 DCHECK(!frame_
|| frame_
== frame
);
2702 DocumentState
* document_state
=
2703 DocumentState::FromDataSource(frame
->dataSource());
2704 NavigationStateImpl
* navigation_state
=
2705 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2707 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2708 RenderFrameProxy
* proxy
=
2709 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2711 proxy
->web_frame()->swap(frame_
);
2712 proxy_routing_id_
= MSG_ROUTING_NONE
;
2714 // If this is the main frame going from a remote frame to a local frame,
2715 // it needs to set RenderViewImpl's pointer for the main frame to itself
2716 // and ensure RenderWidget is no longer in swapped out mode.
2717 if (!is_subframe_
) {
2718 CHECK(!render_view_
->main_render_frame_
);
2719 render_view_
->main_render_frame_
= this;
2720 if (render_view_
->is_swapped_out())
2721 render_view_
->SetSwappedOut(false);
2725 // When we perform a new navigation, we need to update the last committed
2726 // session history entry with state for the page we are leaving. Do this
2727 // before updating the HistoryController state.
2728 render_view_
->SendUpdateState();
2730 render_view_
->history_controller()->UpdateForCommit(
2731 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2733 InternalDocumentStateData
* internal_data
=
2734 InternalDocumentStateData::FromDocumentState(document_state
);
2736 if (document_state
->commit_load_time().is_null())
2737 document_state
->set_commit_load_time(Time::Now());
2739 if (internal_data
->must_reset_scroll_and_scale_state()) {
2740 render_view_
->webview()->resetScrollAndScaleState();
2741 internal_data
->set_must_reset_scroll_and_scale_state(false);
2744 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2745 if (is_new_navigation
) {
2746 // We bump our Page ID to correspond with the new session history entry.
2747 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2749 // Don't update history list values for kSwappedOutURL, since
2750 // we don't want to forget the entry that was there, and since we will
2751 // never come back to kSwappedOutURL. Note that we have to call
2752 // SendUpdateState and update page_id_ even in this case, so that
2753 // the current entry gets a state update and so that we don't send a
2754 // state update to the wrong entry when we swap back in.
2756 navigation_state
->common_params().should_replace_current_entry
,
2757 render_view_
->history_list_length_
> 0);
2758 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2759 !navigation_state
->common_params().should_replace_current_entry
) {
2760 // Advance our offset in session history, applying the length limit.
2761 // There is now no forward history.
2762 render_view_
->history_list_offset_
++;
2763 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2764 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2765 render_view_
->history_list_length_
=
2766 render_view_
->history_list_offset_
+ 1;
2769 const RequestNavigationParams
& request_params
=
2770 navigation_state
->request_params();
2771 if (request_params
.nav_entry_id
!= 0 &&
2772 !request_params
.intended_as_new_entry
) {
2773 // This is a successful session history navigation!
2774 render_view_
->page_id_
= request_params
.page_id
;
2776 render_view_
->history_list_offset_
=
2777 request_params
.pending_history_list_offset
;
2782 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2783 CHECK(sent
); // http://crbug.com/407376
2785 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2786 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2788 RenderFrameObserver
, observers_
,
2789 DidCommitProvisionalLoad(is_new_navigation
,
2790 navigation_state
->WasWithinSamePage()));
2792 if (!frame
->parent()) { // Only for top frames.
2793 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2794 if (render_thread_impl
) { // Can be NULL in tests.
2795 render_thread_impl
->histogram_customizer()->
2796 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2797 RenderView::GetRenderViewCount());
2801 // Remember that we've already processed this request, so we don't update
2802 // the session history again. We do this regardless of whether this is
2803 // a session history navigation, because if we attempted a session history
2804 // navigation without valid HistoryItem state, WebCore will think it is a
2806 navigation_state
->set_request_committed(true);
2808 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2810 // Check whether we have new encoding name.
2811 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2814 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2815 DCHECK(!frame_
|| frame_
== frame
);
2817 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2818 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2819 DidCreateNewDocument(frame
));
2822 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2823 DCHECK(!frame_
|| frame_
== frame
);
2825 int enabled_bindings
= render_view_
->GetEnabledBindings();
2827 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2828 WebUIExtension::Install(frame
);
2830 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2831 DomAutomationController::Install(this, frame
);
2833 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2834 StatsCollectionController::Install(frame
);
2836 const base::CommandLine
& command_line
=
2837 *base::CommandLine::ForCurrentProcess();
2839 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2840 GpuBenchmarking::Install(frame
);
2842 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2843 MemoryBenchmarkingExtension::Install(frame
);
2845 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2846 SkiaBenchmarking::Install(frame
);
2848 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2849 DidClearWindowObject(frame
));
2850 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2853 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2854 DCHECK(!frame_
|| frame_
== frame
);
2856 // Notify the browser about non-blank documents loading in the top frame.
2857 GURL url
= frame
->document().url();
2858 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2859 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2860 // frame->tree()->top().
2861 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2862 if (frame
== main_frame
) {
2863 // For now, don't remember plugin zoom values. We don't want to mix them
2864 // with normal web content (i.e. a fixed layout plugin would usually want
2866 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2867 render_view_
->GetRoutingID(),
2868 main_frame
->document().isPluginDocument()));
2872 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2873 DidCreateDocumentElement());
2874 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2875 DidCreateDocumentElement(frame
));
2878 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2879 const blink::WebString
& title
,
2880 blink::WebTextDirection direction
) {
2881 DCHECK(!frame_
|| frame_
== frame
);
2882 // Ignore all but top level navigations.
2883 if (!frame
->parent()) {
2884 base::string16 title16
= title
;
2885 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2886 routing_id_
, base::UTF16ToUTF8(title16
));
2888 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2889 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2890 shortened_title
, direction
));
2893 // Also check whether we have new encoding name.
2894 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2897 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2898 blink::WebIconURL::Type icon_type
) {
2899 DCHECK(!frame_
|| frame_
== frame
);
2900 // TODO(nasko): Investigate wheather implementation should move here.
2901 render_view_
->didChangeIcon(frame
, icon_type
);
2904 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
,
2905 bool document_is_empty
) {
2906 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2908 DCHECK(!frame_
|| frame_
== frame
);
2909 WebDataSource
* ds
= frame
->dataSource();
2910 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2911 document_state
->set_finish_document_load_time(Time::Now());
2913 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2915 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2916 DidFinishDocumentLoad(frame
));
2917 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2919 // Check whether we have new encoding name.
2920 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2922 // If this is an empty document with an http status code indicating an error,
2923 // we may want to display our own error page, so the user doesn't end up
2924 // with an unexplained blank page.
2925 if (!document_is_empty
)
2928 // Do not show error page when DevTools is attached.
2929 RenderFrameImpl
* localRoot
= this;
2930 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
2931 localRoot
->frame_
->parent()->isWebLocalFrame()) {
2932 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
2935 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
2938 // Display error page instead of a blank page, if appropriate.
2939 std::string error_domain
= "http";
2940 InternalDocumentStateData
* internal_data
=
2941 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2942 int http_status_code
= internal_data
->http_status_code();
2943 if (GetContentClient()->renderer()->HasErrorPage(http_status_code
,
2946 error
.unreachableURL
= frame
->document().url();
2947 error
.domain
= WebString::fromUTF8(error_domain
);
2948 error
.reason
= http_status_code
;
2949 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
2953 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2954 DCHECK(!frame_
|| frame_
== frame
);
2955 if (!frame
->parent()) {
2956 FrameMsg_UILoadMetricsReportType::Value report_type
=
2957 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2958 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2959 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2960 base::TimeDelta::FromSecondsD(
2961 frame
->dataSource()->request().uiStartTime());
2963 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2964 routing_id_
, report_type
, ui_timestamp
));
2968 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2969 const blink::WebURLError
& error
,
2970 blink::WebHistoryCommitType commit_type
) {
2971 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2973 DCHECK(!frame_
|| frame_
== frame
);
2974 // TODO(nasko): Move implementation here. No state needed.
2975 WebDataSource
* ds
= frame
->dataSource();
2978 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2979 DidFailLoad(frame
, error
));
2981 const WebURLRequest
& failed_request
= ds
->request();
2982 base::string16 error_description
;
2983 GetContentClient()->renderer()->GetNavigationErrorStrings(
2989 &error_description
);
2990 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2991 failed_request
.url(),
2994 error
.wasIgnoredByHandler
));
2997 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2998 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
3000 DCHECK(!frame_
|| frame_
== frame
);
3001 WebDataSource
* ds
= frame
->dataSource();
3002 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3003 if (document_state
->finish_load_time().is_null()) {
3004 if (!frame
->parent()) {
3005 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
3006 TRACE_EVENT_SCOPE_PROCESS
);
3008 document_state
->set_finish_load_time(Time::Now());
3011 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
3012 DidFinishLoad(frame
));
3013 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
3015 // Don't send this message while the frame is swapped out.
3016 if (is_swapped_out())
3019 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
3020 ds
->request().url()));
3023 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
3024 const blink::WebHistoryItem
& item
,
3025 blink::WebHistoryCommitType commit_type
) {
3026 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
3028 DCHECK(!frame_
|| frame_
== frame
);
3029 // If this was a reference fragment navigation that we initiated, then we
3030 // could end up having a non-null pending navigation params. We just need to
3031 // update the ExtraData on the datasource so that others who read the
3032 // ExtraData will get the new NavigationState. Similarly, if we did not
3033 // initiate this navigation, then we need to take care to reset any pre-
3034 // existing navigation state to a content-initiated navigation state.
3035 // didCreateDataSource conveniently takes care of this for us.
3036 didCreateDataSource(frame
, frame
->dataSource());
3038 DocumentState
* document_state
=
3039 DocumentState::FromDataSource(frame
->dataSource());
3040 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
3041 ->set_was_within_same_page(true);
3043 didCommitProvisionalLoad(frame
, item
, commit_type
);
3046 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
3047 DCHECK(!frame_
|| frame_
== frame
);
3048 // TODO(nasko): Move implementation here. Needed methods:
3049 // * StartNavStateSyncTimerIfNecessary
3050 render_view_
->didUpdateCurrentHistoryItem(frame
);
3053 void RenderFrameImpl::didChangeThemeColor() {
3054 if (frame_
->parent())
3057 Send(new FrameHostMsg_DidChangeThemeColor(
3058 routing_id_
, frame_
->document().themeColor()));
3061 void RenderFrameImpl::dispatchLoad() {
3062 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
3065 void RenderFrameImpl::requestNotificationPermission(
3066 const blink::WebSecurityOrigin
& origin
,
3067 blink::WebNotificationPermissionCallback
* callback
) {
3068 if (!notification_permission_dispatcher_
) {
3069 notification_permission_dispatcher_
=
3070 new NotificationPermissionDispatcher(this);
3073 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3076 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3077 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3080 if (is_empty_selection
)
3081 selection_text_
.clear();
3083 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3084 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3085 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3086 // to notify the selection was changed. Focus change should be notified
3087 // before selection change.
3088 GetRenderWidget()->UpdateTextInputState(
3089 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
3090 SyncSelectionIfRequired();
3093 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3094 blink::WebColorChooserClient
* client
,
3095 const blink::WebColor
& initial_color
,
3096 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3097 RendererWebColorChooserImpl
* color_chooser
=
3098 new RendererWebColorChooserImpl(this, client
);
3099 std::vector
<ColorSuggestion
> color_suggestions
;
3100 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3101 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3103 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3104 return color_chooser
;
3107 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3108 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3111 frame_
->document().url(),
3115 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3116 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3119 frame_
->document().url(),
3123 bool RenderFrameImpl::runModalPromptDialog(
3124 const blink::WebString
& message
,
3125 const blink::WebString
& default_value
,
3126 blink::WebString
* actual_value
) {
3127 base::string16 result
;
3128 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3131 frame_
->document().url(),
3134 actual_value
->assign(result
);
3138 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3140 const blink::WebString
& message
) {
3141 // If we are swapping out, we have already run the beforeunload handler.
3142 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3143 // at all, to avoid running it twice.
3144 if (is_swapped_out_
)
3147 // Don't allow further dialogs if we are waiting to swap out, since the
3148 // PageGroupLoadDeferrer in our stack prevents it.
3149 if (render_view()->suppress_dialogs_until_swap_out_
)
3152 bool success
= false;
3153 // This is an ignored return value, but is included so we can accept the same
3154 // response as RunJavaScriptMessage.
3155 base::string16 ignored_result
;
3156 render_view()->SendAndRunNestedMessageLoop(
3157 new FrameHostMsg_RunBeforeUnloadConfirm(
3158 routing_id_
, frame_
->document().url(), message
, is_reload
,
3159 &success
, &ignored_result
));
3163 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3164 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3165 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3166 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3167 if (GetRenderWidget()->has_host_context_menu_location()) {
3168 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3169 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3172 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3173 // it. We replace it with an empty GURL so the appropriate items are disabled
3174 // in the context menu.
3175 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3176 // data encoded images. We should have a way to save them.
3177 if (params
.src_url
.spec().size() > GetMaxURLChars())
3178 params
.src_url
= GURL();
3179 context_menu_node_
= data
.node
;
3181 #if defined(OS_ANDROID)
3182 gfx::Rect start_rect
;
3184 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3185 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3186 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3189 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3192 void RenderFrameImpl::clearContextMenu() {
3193 context_menu_node_
.reset();
3196 void RenderFrameImpl::willSendRequest(
3197 blink::WebLocalFrame
* frame
,
3198 unsigned identifier
,
3199 blink::WebURLRequest
& request
,
3200 const blink::WebURLResponse
& redirect_response
) {
3201 DCHECK(!frame_
|| frame_
== frame
);
3202 // The request my be empty during tests.
3203 if (request
.url().isEmpty())
3206 // Set the first party for cookies url if it has not been set yet (new
3207 // requests). For redirects, it is updated by WebURLLoaderImpl.
3208 if (request
.firstPartyForCookies().isEmpty()) {
3209 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3210 request
.setFirstPartyForCookies(request
.url());
3212 // TODO(nasko): When the top-level frame is remote, there is no document.
3213 // This is broken and should be fixed to propagate the first party.
3214 WebFrame
* top
= frame
->top();
3215 if (top
->isWebLocalFrame()) {
3216 request
.setFirstPartyForCookies(
3217 frame
->top()->document().firstPartyForCookies());
3222 WebDataSource
* provisional_data_source
= frame
->provisionalDataSource();
3223 WebDataSource
* data_source
=
3224 provisional_data_source
? provisional_data_source
: frame
->dataSource();
3226 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3227 DCHECK(document_state
);
3228 InternalDocumentStateData
* internal_data
=
3229 InternalDocumentStateData::FromDocumentState(document_state
);
3230 NavigationStateImpl
* navigation_state
=
3231 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3232 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3233 if (provisional_data_source
&& provisional_data_source
->isClientRedirect()) {
3234 transition_type
= ui::PageTransitionFromInt(
3235 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3238 GURL
request_url(request
.url());
3240 if (GetContentClient()->renderer()->WillSendRequest(
3244 request
.firstPartyForCookies(),
3246 request
.setURL(WebURL(new_url
));
3249 if (internal_data
->is_cache_policy_override_set())
3250 request
.setCachePolicy(internal_data
->cache_policy_override());
3252 // The request's extra data may indicate that we should set a custom user
3253 // agent. This needs to be done here, after WebKit is through with setting the
3254 // user agent on its own. Similarly, it may indicate that we should set an
3255 // X-Requested-With header. This must be done here to avoid breaking CORS
3257 // PlzNavigate: there may also be a stream url associated with the request.
3258 WebString custom_user_agent
;
3259 WebString requested_with
;
3260 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3261 if (request
.extraData()) {
3262 RequestExtraData
* old_extra_data
=
3263 static_cast<RequestExtraData
*>(request
.extraData());
3265 custom_user_agent
= old_extra_data
->custom_user_agent();
3266 if (!custom_user_agent
.isNull()) {
3267 if (custom_user_agent
.isEmpty())
3268 request
.clearHTTPHeaderField("User-Agent");
3270 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3273 requested_with
= old_extra_data
->requested_with();
3274 if (!requested_with
.isNull()) {
3275 if (requested_with
.isEmpty())
3276 request
.clearHTTPHeaderField("X-Requested-With");
3278 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3280 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3283 // Add the default accept header for frame request if it has not been set
3285 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3286 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3287 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3288 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3289 WebString::fromUTF8(kDefaultAcceptHeader
));
3292 // Add an empty HTTP origin header for non GET methods if none is currently
3294 request
.addHTTPOriginIfNeeded(WebString());
3296 // Attach |should_replace_current_entry| state to requests so that, should
3297 // this navigation later require a request transfer, all state is preserved
3298 // when it is re-created in the new process.
3299 bool should_replace_current_entry
= false;
3300 if (navigation_state
->IsContentInitiated()) {
3301 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3303 // If the navigation is browser-initiated, the NavigationState contains the
3304 // correct value instead of the WebDataSource.
3306 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3307 // NavigationState::should_replace_current_entry().
3308 should_replace_current_entry
=
3309 navigation_state
->common_params().should_replace_current_entry
;
3312 int provider_id
= kInvalidServiceWorkerProviderId
;
3313 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3314 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3315 // |provisionalDataSource| may be null in some content::ResourceFetcher
3316 // use cases, we don't hook those requests.
3317 if (frame
->provisionalDataSource()) {
3318 ServiceWorkerNetworkProvider
* provider
=
3319 ServiceWorkerNetworkProvider::FromDocumentState(
3320 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3321 provider_id
= provider
->provider_id();
3323 } else if (frame
->dataSource()) {
3324 ServiceWorkerNetworkProvider
* provider
=
3325 ServiceWorkerNetworkProvider::FromDocumentState(
3326 DocumentState::FromDataSource(frame
->dataSource()));
3327 provider_id
= provider
->provider_id();
3330 WebFrame
* parent
= frame
->parent();
3331 int parent_routing_id
= MSG_ROUTING_NONE
;
3333 parent_routing_id
= -1;
3334 } else if (parent
->isWebLocalFrame()) {
3335 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3337 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3340 RequestExtraData
* extra_data
= new RequestExtraData();
3341 extra_data
->set_visibility_state(render_view_
->visibilityState());
3342 extra_data
->set_custom_user_agent(custom_user_agent
);
3343 extra_data
->set_requested_with(requested_with
);
3344 extra_data
->set_render_frame_id(routing_id_
);
3345 extra_data
->set_is_main_frame(!parent
);
3346 extra_data
->set_frame_origin(
3347 GURL(frame
->document().securityOrigin().toString()));
3348 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3349 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3350 extra_data
->set_allow_download(
3351 navigation_state
->common_params().allow_download
);
3352 extra_data
->set_transition_type(transition_type
);
3353 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3354 extra_data
->set_transferred_request_child_id(
3355 navigation_state
->start_params().transferred_request_child_id
);
3356 extra_data
->set_transferred_request_request_id(
3357 navigation_state
->start_params().transferred_request_request_id
);
3358 extra_data
->set_service_worker_provider_id(provider_id
);
3359 extra_data
->set_stream_override(stream_override
.Pass());
3360 request
.setExtraData(extra_data
);
3362 // TODO(creis): Update prefetching to work with out-of-process iframes.
3363 WebFrame
* top_frame
= frame
->top();
3364 if (top_frame
&& top_frame
->isWebLocalFrame()) {
3365 DocumentState
* top_document_state
=
3366 DocumentState::FromDataSource(top_frame
->dataSource());
3367 if (top_document_state
) {
3368 // TODO(gavinp): separate out prefetching and prerender field trials
3369 // if the rel=prerender rel type is sticking around.
3370 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3371 top_document_state
->set_was_prefetcher(true);
3375 // This is an instance where we embed a copy of the routing id
3376 // into the data portion of the message. This can cause problems if we
3377 // don't register this id on the browser side, since the download manager
3378 // expects to find a RenderViewHost based off the id.
3379 request
.setRequestorID(render_view_
->GetRoutingID());
3380 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3382 if (!navigation_state
->start_params().extra_headers
.empty()) {
3383 for (net::HttpUtil::HeadersIterator
i(
3384 navigation_state
->start_params().extra_headers
.begin(),
3385 navigation_state
->start_params().extra_headers
.end(), "\n");
3387 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3388 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3389 blink::WebReferrerPolicyDefault
,
3391 WebString::fromUTF8(i
.values()));
3392 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3394 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3395 WebString::fromUTF8(i
.values()));
3400 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3401 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3404 void RenderFrameImpl::didReceiveResponse(
3405 blink::WebLocalFrame
* frame
,
3406 unsigned identifier
,
3407 const blink::WebURLResponse
& response
) {
3408 DCHECK(!frame_
|| frame_
== frame
);
3409 // Only do this for responses that correspond to a provisional data source
3410 // of the top-most frame. If we have a provisional data source, then we
3411 // can't have any sub-resources yet, so we know that this response must
3412 // correspond to a frame load.
3413 if (!frame
->provisionalDataSource() || frame
->parent())
3416 // If we are in view source mode, then just let the user see the source of
3417 // the server's error page.
3418 if (frame
->isViewSourceModeEnabled())
3421 DocumentState
* document_state
=
3422 DocumentState::FromDataSource(frame
->provisionalDataSource());
3423 int http_status_code
= response
.httpStatusCode();
3425 // Record page load flags.
3426 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3428 document_state
->set_was_fetched_via_spdy(
3429 extra_data
->was_fetched_via_spdy());
3430 document_state
->set_was_npn_negotiated(
3431 extra_data
->was_npn_negotiated());
3432 document_state
->set_npn_negotiated_protocol(
3433 extra_data
->npn_negotiated_protocol());
3434 document_state
->set_was_alternate_protocol_available(
3435 extra_data
->was_alternate_protocol_available());
3436 document_state
->set_connection_info(
3437 extra_data
->connection_info());
3438 document_state
->set_was_fetched_via_proxy(
3439 extra_data
->was_fetched_via_proxy());
3440 document_state
->set_proxy_server(
3441 extra_data
->proxy_server());
3443 InternalDocumentStateData
* internal_data
=
3444 InternalDocumentStateData::FromDocumentState(document_state
);
3445 internal_data
->set_http_status_code(http_status_code
);
3448 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3449 blink::WebLocalFrame
* frame
,
3450 const blink::WebURLRequest
& request
,
3451 const blink::WebURLResponse
& response
) {
3452 DCHECK(!frame_
|| frame_
== frame
);
3453 // The recipients of this message have no use for data: URLs: they don't
3454 // affect the page's insecure content list and are not in the disk cache. To
3455 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3456 // filter them out here.
3457 GURL
url(request
.url());
3458 if (url
.SchemeIs(url::kDataScheme
))
3461 // Let the browser know we loaded a resource from the memory cache. This
3462 // message is needed to display the correct SSL indicators.
3463 Send(new FrameHostMsg_DidLoadResourceFromMemoryCache(
3464 routing_id_
, url
, response
.securityInfo(), request
.httpMethod().utf8(),
3465 response
.mimeType().utf8(), WebURLRequestToResourceType(request
)));
3468 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3469 DCHECK(!frame_
|| frame_
== frame
);
3470 Send(new FrameHostMsg_DidDisplayInsecureContent(routing_id_
));
3473 void RenderFrameImpl::didRunInsecureContent(
3474 blink::WebLocalFrame
* frame
,
3475 const blink::WebSecurityOrigin
& origin
,
3476 const blink::WebURL
& target
) {
3477 DCHECK(!frame_
|| frame_
== frame
);
3478 Send(new FrameHostMsg_DidRunInsecureContent(
3479 routing_id_
, origin
.toString().utf8(), target
));
3480 GetContentClient()->renderer()->RecordRapporURL(
3481 "ContentSettings.MixedScript.RanMixedScript",
3482 GURL(origin
.toString().utf8()));
3485 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3486 DCHECK(!frame_
|| frame_
== frame
);
3487 #if defined(ENABLE_PLUGINS)
3488 if (frame
!= render_view_
->webview()->mainFrame())
3490 PluginChannelHost::Broadcast(
3491 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3495 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3496 v8::Local
<v8::Context
> context
,
3497 int extension_group
,
3499 DCHECK(!frame_
|| frame_
== frame
);
3501 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3502 DidCreateScriptContext(context
, extension_group
, world_id
));
3505 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3506 v8::Local
<v8::Context
> context
,
3508 DCHECK(!frame_
|| frame_
== frame
);
3510 FOR_EACH_OBSERVER(RenderFrameObserver
,
3512 WillReleaseScriptContext(context
, world_id
));
3515 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3516 DCHECK(!frame_
|| frame_
== frame
);
3517 // TODO(nasko): Move implementation here. Needed methods:
3518 // * StartNavStateSyncTimerIfNecessary
3519 render_view_
->didChangeScrollOffset(frame
);
3521 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3524 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3525 DCHECK(!frame_
|| frame_
== frame
);
3526 if (!frame
->parent()) {
3527 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3528 render_view_
->GetRoutingID()));
3532 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3534 bool final_update
) {
3535 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3537 active_match_ordinal
= 0;
3539 render_view_
->Send(new ViewHostMsg_Find_Reply(
3540 render_view_
->GetRoutingID(), request_id
, count
,
3541 gfx::Rect(), active_match_ordinal
, final_update
));
3544 void RenderFrameImpl::reportFindInPageSelection(
3546 int active_match_ordinal
,
3547 const blink::WebRect
& selection_rect
) {
3548 render_view_
->Send(new ViewHostMsg_Find_Reply(
3549 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3550 active_match_ordinal
, false));
3553 void RenderFrameImpl::requestStorageQuota(
3554 blink::WebLocalFrame
* frame
,
3555 blink::WebStorageQuotaType type
,
3556 unsigned long long requested_size
,
3557 blink::WebStorageQuotaCallbacks callbacks
) {
3558 DCHECK(!frame_
|| frame_
== frame
);
3559 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3560 if (origin
.isUnique()) {
3561 // Unique origins cannot store persistent state.
3562 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3565 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3566 render_view_
->GetRoutingID(),
3567 GURL(origin
.toString()),
3568 static_cast<storage::StorageType
>(type
),
3570 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3573 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3574 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3575 impl
->set_render_frame_id(routing_id_
);
3578 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3579 if (!geolocation_dispatcher_
)
3580 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3581 return geolocation_dispatcher_
;
3584 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3585 if (!presentation_dispatcher_
)
3586 presentation_dispatcher_
= new PresentationDispatcher(this);
3587 return presentation_dispatcher_
;
3590 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3591 if (!push_messaging_dispatcher_
)
3592 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3593 return push_messaging_dispatcher_
;
3596 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3597 blink::WebLocalFrame
* frame
,
3598 blink::WebRTCPeerConnectionHandler
* handler
) {
3599 DCHECK(!frame_
|| frame_
== frame
);
3600 #if defined(ENABLE_WEBRTC)
3601 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3605 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3606 if (!web_user_media_client_
)
3607 InitializeUserMediaClient();
3608 return web_user_media_client_
;
3611 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3612 if (!web_encrypted_media_client_
) {
3613 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3614 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3615 // is destructed before |this|, and does not give away ownership of the
3617 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3618 base::Unretained(this)),
3619 GetCdmFactory(), GetMediaPermission()));
3621 return web_encrypted_media_client_
.get();
3624 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3625 if (!midi_dispatcher_
)
3626 midi_dispatcher_
= new MidiDispatcher(this);
3627 return midi_dispatcher_
;
3630 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3631 blink::WebLocalFrame
* source_frame
,
3632 blink::WebFrame
* target_frame
,
3633 blink::WebSecurityOrigin target_origin
,
3634 blink::WebDOMMessageEvent event
) {
3635 DCHECK(!frame_
|| frame_
== target_frame
);
3637 // Currently, a postMessage that targets a cross-process frame can be plumbed
3638 // either through this function or RenderFrameProxy::postMessageEvent. This
3639 // function is used when the target cross-process frame is a top-level frame
3640 // which has been swapped out. In that case, the corresponding WebLocalFrame
3641 // currently remains in the frame tree even in site-per-process mode (see
3642 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3643 // --site-per-process mode for all other cases.
3645 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3646 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3647 // cross-process postMessages.
3648 if (!is_swapped_out_
)
3651 // It is possible to get here on a swapped-out frame without a
3652 // |render_frame_proxy_|. This happens when:
3653 // - This process only has one active RenderView and is about to go away
3654 // (e.g., due to cross-process navigation).
3655 // - The top frame has a subframe with an unload handler.
3656 // - The subframe sends a postMessage to the top-level frame in its unload
3658 // See https://crbug.com/475651 for details. We return false here, since we
3659 // don't want to deliver the message to the new process in this case.
3660 if (!render_frame_proxy_
)
3663 render_frame_proxy_
->postMessageEvent(
3664 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3668 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3669 const blink::WebURL
& url
) {
3670 DCHECK(!frame_
|| frame_
== frame
);
3671 std::string user_agent_override_for_url
=
3672 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3673 if (!user_agent_override_for_url
.empty())
3674 return WebString::fromUTF8(user_agent_override_for_url
);
3676 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3677 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3678 return blink::WebString();
3681 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3682 // associated with it, so the checks below are not valid. Temporarily
3683 // return early and fix properly as part of https://crbug.com/426555.
3684 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3685 return blink::WebString();
3687 // If we're in the middle of committing a load, the data source we need
3688 // will still be provisional.
3689 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3690 WebDataSource
* data_source
= NULL
;
3691 if (main_frame
->provisionalDataSource())
3692 data_source
= main_frame
->provisionalDataSource();
3694 data_source
= main_frame
->dataSource();
3696 InternalDocumentStateData
* internal_data
= data_source
?
3697 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3698 if (internal_data
&& internal_data
->is_overriding_user_agent())
3699 return WebString::fromUTF8(
3700 render_view_
->renderer_preferences_
.user_agent_override
);
3701 return blink::WebString();
3704 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3705 DCHECK(!frame_
|| frame_
== frame
);
3706 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3707 return WebString::fromUTF8("1");
3711 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3712 bool default_value
) {
3713 DCHECK(!frame_
|| frame_
== frame
);
3717 bool blocked
= true;
3718 Send(new FrameHostMsg_Are3DAPIsBlocked(
3720 GURL(frame
->top()->securityOrigin().toString()),
3721 THREE_D_API_TYPE_WEBGL
,
3726 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3727 int arb_robustness_status_code
) {
3728 DCHECK(!frame_
|| frame_
== frame
);
3729 Send(new FrameHostMsg_DidLose3DContext(
3730 GURL(frame
->top()->securityOrigin().toString()),
3731 THREE_D_API_TYPE_WEBGL
,
3732 arb_robustness_status_code
));
3735 blink::WebScreenOrientationClient
*
3736 RenderFrameImpl::webScreenOrientationClient() {
3737 if (!screen_orientation_dispatcher_
)
3738 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3739 return screen_orientation_dispatcher_
;
3742 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3743 ServiceWorkerNetworkProvider
* provider
=
3744 ServiceWorkerNetworkProvider::FromDocumentState(
3745 DocumentState::FromDataSource(&data_source
));
3746 if (!provider
->context())
3748 return provider
->context()->controller_handle_id() !=
3749 kInvalidServiceWorkerHandleId
;
3752 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3753 ServiceWorkerNetworkProvider
* provider
=
3754 ServiceWorkerNetworkProvider::FromDocumentState(
3755 DocumentState::FromDataSource(&data_source
));
3756 if (provider
->context() && provider
->context()->controller())
3757 return provider
->context()->controller()->version_id();
3758 return kInvalidServiceWorkerVersionId
;
3761 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3762 blink::WebAXEvent event
) {
3763 HandleWebAccessibilityEvent(obj
, event
);
3766 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3769 const blink::WebAXObject
& start_object
,
3771 const blink::WebAXObject
& end_object
,
3773 if (renderer_accessibility_
) {
3774 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3775 identifier
, match_index
, start_object
, start_offset
,
3776 end_object
, end_offset
);
3780 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3781 DCHECK(!frame_
|| frame_
== frame
);
3783 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3786 bool RenderFrameImpl::enterFullscreen() {
3787 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3791 bool RenderFrameImpl::exitFullscreen() {
3792 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3796 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3797 if (!permission_client_
)
3798 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3800 return permission_client_
.get();
3803 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3804 if (!app_banner_client_
) {
3805 app_banner_client_
=
3806 GetContentClient()->renderer()->CreateAppBannerClient(this);
3809 return app_banner_client_
.get();
3812 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3814 const WebString
& title
) {
3815 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3816 Send(new FrameHostMsg_RegisterProtocolHandler(
3818 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3824 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3825 const WebURL
& url
) {
3826 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3827 Send(new FrameHostMsg_UnregisterProtocolHandler(
3829 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3834 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3836 bluetooth_
.reset(new WebBluetoothImpl(
3837 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3840 return bluetooth_
.get();
3843 blink::WebUSBClient
* RenderFrameImpl::usbClient() {
3844 #if !defined(OS_ANDROID)
3846 mojo::ServiceProviderPtr device_services
=
3847 ConnectToApplication(GURL(device::kDevicesMojoAppUrl
));
3848 usb_client_
.reset(new WebUSBClientImpl(device_services
.Pass()));
3851 return usb_client_
.get();
3854 #if defined(ENABLE_WEBVR)
3855 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3856 if (!vr_dispatcher_
)
3857 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3859 return vr_dispatcher_
.get();
3863 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3864 has_played_media_
= true;
3865 Send(new FrameHostMsg_MediaPlayingNotification(
3866 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3867 player
->hasAudio(), player
->isRemote()));
3870 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3871 Send(new FrameHostMsg_MediaPausedNotification(
3872 routing_id_
, reinterpret_cast<int64
>(player
)));
3875 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3879 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3880 observers_
.AddObserver(observer
);
3883 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3884 observer
->RenderFrameGone();
3885 observers_
.RemoveObserver(observer
);
3888 void RenderFrameImpl::OnStop() {
3890 frame_
->stopLoading();
3891 if (!frame_
->parent())
3892 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3894 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3897 void RenderFrameImpl::WasHidden() {
3898 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3901 void RenderFrameImpl::WasShown() {
3902 // TODO(kenrb): Need to figure out how to do this better. Should
3903 // VisibilityState remain a page-level concept or move to frames?
3904 // The semantics of 'Show' might have to change here.
3905 if (render_widget_
) {
3906 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3907 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3909 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3912 void RenderFrameImpl::WidgetWillClose() {
3913 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3916 bool RenderFrameImpl::IsHidden() {
3917 return GetRenderWidget()->is_hidden();
3920 // Tell the embedding application that the URL of the active page has changed.
3921 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3922 blink::WebFrame
* frame
,
3923 blink::WebHistoryCommitType commit_type
,
3924 const blink::WebHistoryItem
& item
) {
3925 DCHECK(!frame_
|| frame_
== frame
);
3926 WebDataSource
* ds
= frame
->dataSource();
3929 const WebURLRequest
& request
= ds
->request();
3930 const WebURLResponse
& response
= ds
->response();
3932 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3933 NavigationStateImpl
* navigation_state
=
3934 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3935 InternalDocumentStateData
* internal_data
=
3936 InternalDocumentStateData::FromDocumentState(document_state
);
3938 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3939 params
.http_status_code
= response
.httpStatusCode();
3940 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3941 params
.is_post
= false;
3942 params
.intended_as_new_entry
=
3943 navigation_state
->request_params().intended_as_new_entry
;
3944 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3945 params
.post_id
= -1;
3946 params
.page_id
= render_view_
->page_id_
;
3947 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3948 // We need to track the RenderViewHost routing_id because of downstream
3949 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3950 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3951 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3952 // based on the ID stored in the resource requests. Once those dependencies
3953 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3954 // client to be based on the routing_id of the RenderFrameHost.
3955 params
.render_view_routing_id
= render_view_
->routing_id();
3956 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3957 params
.socket_address
.set_port(response
.remotePort());
3958 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3960 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3961 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3962 params
.security_info
= response
.securityInfo();
3964 // Set the URL to be displayed in the browser UI to the user.
3965 params
.url
= GetLoadingUrl();
3966 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3968 // Set the origin of the frame. This will be replicated to the corresponding
3969 // RenderFrameProxies in other processes.
3970 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3971 // to https://crbug.com/439608 and will be replicated as unique origins.
3972 if (!is_swapped_out_
) {
3973 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3974 if (url::IsStandard(scheme
.c_str(),
3975 url::Component(0, static_cast<int>(scheme
.length())))) {
3976 params
.origin
= frame
->document().securityOrigin();
3980 if (frame
->document().baseURL() != params
.url
)
3981 params
.base_url
= frame
->document().baseURL();
3983 GetRedirectChain(ds
, ¶ms
.redirects
);
3984 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3985 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3987 params
.searchable_form_url
= internal_data
->searchable_form_url();
3988 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3990 params
.gesture
= render_view_
->navigation_gesture_
;
3991 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3993 // Make navigation state a part of the DidCommitProvisionalLoad message so
3994 // that committed entry has it at all times.
3995 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3996 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3998 params
.page_state
= HistoryEntryToPageState(entry
);
4000 params
.page_state
= PageState::CreateFromURL(request
.url());
4002 // In --site-per-process, just send a single HistoryItem for this frame,
4003 // rather than the whole tree. It will be stored in the corresponding
4004 // FrameNavigationEntry.
4005 params
.page_state
= SingleHistoryItemToPageState(item
);
4007 params
.item_sequence_number
= item
.itemSequenceNumber();
4008 params
.document_sequence_number
= item
.documentSequenceNumber();
4010 if (!frame
->parent()) {
4011 // Top-level navigation.
4013 // Reset the zoom limits in case a plugin had changed them previously. This
4014 // will also call us back which will cause us to send a message to
4015 // update WebContentsImpl.
4016 render_view_
->webview()->zoomLimitsChanged(
4017 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
4018 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
4020 // Set zoom level, but don't do it for full-page plugin since they don't use
4021 // the same zoom settings.
4022 HostZoomLevels::iterator host_zoom
=
4023 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
4024 if (render_view_
->webview()->mainFrame()->isWebLocalFrame() &&
4025 render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
4026 // Reset the zoom levels for plugins.
4027 render_view_
->webview()->setZoomLevel(0);
4029 // If the zoom level is not found, then do nothing. In-page navigation
4030 // relies on not changing the zoom level in this case.
4031 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
4032 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
4035 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
4036 // This zoom level was merely recorded transiently for this load. We can
4037 // erase it now. If at some point we reload this page, the browser will
4038 // send us a new, up-to-date zoom level.
4039 render_view_
->host_zoom_levels_
.erase(host_zoom
);
4042 // Update contents MIME type for main frame.
4043 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4045 params
.transition
= navigation_state
->GetTransitionType();
4046 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4047 // If the main frame does a load, it should not be reported as a subframe
4048 // navigation. This can occur in the following case:
4049 // 1. You're on a site with frames.
4050 // 2. You do a subframe navigation. This is stored with transition type
4052 // 3. You navigate to some non-frame site, say, google.com.
4053 // 4. You navigate back to the page from step 2. Since it was initially
4054 // MANUAL_SUBFRAME, it will be that same transition type here.
4055 // We don't want that, because any navigation that changes the toplevel
4056 // frame should be tracked as a toplevel navigation (this allows us to
4057 // update the URL bar, etc).
4058 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4061 // If the page contained a client redirect (meta refresh, document.loc...),
4062 // set the referrer and transition appropriately.
4063 if (ds
->isClientRedirect()) {
4065 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4066 params
.transition
= ui::PageTransitionFromInt(
4067 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4069 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4070 frame
, ds
->request());
4073 base::string16 method
= request
.httpMethod();
4074 if (base::EqualsASCII(method
, "POST")) {
4075 params
.is_post
= true;
4076 params
.post_id
= ExtractPostId(entry
);
4079 // Send the user agent override back.
4080 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4082 // Track the URL of the original request. We use the first entry of the
4083 // redirect chain if it exists because the chain may have started in another
4085 params
.original_request_url
= GetOriginalRequestURL(ds
);
4087 params
.history_list_was_cleared
=
4088 navigation_state
->request_params().should_clear_history_list
;
4090 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4091 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4092 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4093 frame
->dataSource()->request().uiStartTime());
4095 // Save some histogram data so we can compute the average memory used per
4096 // page load of the glyphs.
4097 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4098 blink::WebGlyphCache::pageCount());
4100 // This message needs to be sent before any of allowScripts(),
4101 // allowImages(), allowPlugins() is called for the new page, so that when
4102 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4103 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4104 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4106 // Subframe navigation: the type depends on whether this navigation
4107 // generated a new session history entry. When they do generate a session
4108 // history entry, it means the user initiated the navigation and we should
4110 if (commit_type
== blink::WebStandardCommit
)
4111 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4113 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4115 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4116 params
.history_list_was_cleared
= false;
4117 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4119 // Don't send this message while the subframe is swapped out.
4120 if (!is_swapped_out())
4121 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4124 // If we end up reusing this WebRequest (for example, due to a #ref click),
4125 // we don't want the transition type to persist. Just clear it.
4126 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4129 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4130 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4132 render_view_
->FrameDidStartLoading(frame_
);
4133 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4136 void RenderFrameImpl::didStopLoading() {
4137 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4139 render_view_
->FrameDidStopLoading(frame_
);
4140 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4143 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4144 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4147 void RenderFrameImpl::HandleWebAccessibilityEvent(
4148 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4149 if (renderer_accessibility_
)
4150 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4153 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4154 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4157 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4158 if (renderer_accessibility())
4159 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4163 void RenderFrameImpl::OnCommitNavigation(
4164 const ResourceResponseHead
& response
,
4165 const GURL
& stream_url
,
4166 const CommonNavigationParams
& common_params
,
4167 const RequestNavigationParams
& request_params
) {
4168 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4169 switches::kEnableBrowserSideNavigation
));
4170 // This will override the url requested by the WebURLLoader, as well as
4171 // provide it with the response to the request.
4172 scoped_ptr
<StreamOverrideParameters
> stream_override(
4173 new StreamOverrideParameters());
4174 stream_override
->stream_url
= stream_url
;
4175 stream_override
->response
= response
;
4177 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4178 stream_override
.Pass());
4181 void RenderFrameImpl::OnFailedNavigation(
4182 const CommonNavigationParams
& common_params
,
4183 const RequestNavigationParams
& request_params
,
4184 bool has_stale_copy_in_cache
,
4186 bool is_reload
= IsReload(common_params
.navigation_type
);
4187 bool is_history_navigation
= request_params
.page_state
.IsValid();
4188 WebURLRequest::CachePolicy cache_policy
=
4189 WebURLRequest::UseProtocolCachePolicy
;
4190 RenderFrameImpl::PrepareRenderViewForNavigation(
4191 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4193 GetContentClient()->SetActiveURL(common_params
.url
);
4195 pending_navigation_params_
.reset(new NavigationParams(
4196 common_params
, StartNavigationParams(), request_params
));
4198 // Inform the browser of the start of the provisional load. This is needed so
4199 // that the load is properly tracked by the WebNavigation API.
4200 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4201 routing_id_
, common_params
.url
));
4203 // Send the provisional load failure.
4204 blink::WebURLError error
=
4205 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4206 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4207 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4208 frame_
->isViewSourceModeEnabled());
4209 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4211 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4212 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4213 // http://crbug.com/501960
4214 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4218 // Make sure errors are not shown in view source mode.
4219 frame_
->enableViewSourceMode(false);
4221 // Replace the current history entry in reloads, history navigations and loads
4222 // of the same url. This corresponds to Blink's notion of a standard
4224 // TODO(clamy): see if initial commits in subframes should be handled
4226 bool replace
= is_reload
|| is_history_navigation
||
4227 common_params
.url
== GetLoadingUrl();
4228 LoadNavigationErrorPage(failed_request
, error
, replace
);
4231 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4232 RenderFrame
* render_frame
,
4233 const NavigationPolicyInfo
& info
) {
4234 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4237 // TODO(nick): Is consulting |is_subframe_| here correct?
4238 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_
) {
4239 // There's no reason to ignore navigations on subframes, since the swap out
4240 // logic no longer applies.
4242 if (is_swapped_out_
) {
4243 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4244 // Targeted links may try to navigate a swapped out frame. Allow the
4245 // browser process to navigate the tab instead. Note that it is also
4246 // possible for non-targeted navigations (from this view) to arrive
4247 // here just after we are swapped out. It's ok to send them to the
4248 // browser, as long as they're for the top level frame.
4249 // TODO(creis): Ensure this supports targeted form submissions when
4250 // fixing http://crbug.com/101395.
4251 if (info
.frame
->parent() == NULL
) {
4252 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4253 info
.defaultPolicy
);
4254 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4257 // We should otherwise ignore in-process iframe navigations, if they
4258 // arrive just after we are swapped out.
4259 return blink::WebNavigationPolicyIgnore
;
4262 // Allow kSwappedOutURL to complete.
4263 return info
.defaultPolicy
;
4267 // Webkit is asking whether to navigate to a new URL.
4268 // This is fine normally, except if we're showing UI from one security
4269 // context and they're trying to navigate to a different context.
4270 const GURL
& url
= info
.urlRequest
.url();
4272 // A content initiated navigation may have originated from a link-click,
4273 // script, drag-n-drop operation, etc.
4274 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4275 bool is_content_initiated
=
4276 document_state
->navigation_state()->IsContentInitiated();
4278 // If the browser is interested, then give it a chance to look at the request.
4279 if (is_content_initiated
) {
4281 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4282 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4283 base::EqualsASCII(base::StringPiece16(info
.urlRequest
.httpMethod()),
4285 bool browser_handles_request
=
4286 render_view_
->renderer_preferences_
4287 .browser_handles_non_local_top_level_requests
4288 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4290 if (!browser_handles_request
) {
4291 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4292 render_view_
->renderer_preferences_
4293 .browser_handles_all_top_level_requests
;
4296 if (browser_handles_request
) {
4297 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4298 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4302 // Use the frame's original request's URL rather than the document's URL for
4303 // subsequent checks. For a popup, the document's URL may become the opener
4304 // window's URL if the opener has called document.write().
4305 // See http://crbug.com/93517.
4306 GURL
old_url(info
.frame
->dataSource()->request().url());
4308 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4309 // an extension or app origin, leaving a WebUI page, etc). We only care about
4310 // top-level navigations (not iframes). But we sometimes navigate to
4311 // about:blank to clear a tab, and we want to still allow that.
4313 // Note: this is known to break POST submissions when crossing process
4314 // boundaries until http://crbug.com/101395 is fixed. This is better for
4315 // security than loading a WebUI, extension or app page in the wrong process.
4316 // POST requests don't work because this mechanism does not preserve form
4317 // POST data. We will need to send the request's httpBody data up to the
4318 // browser process, and issue a special POST navigation in WebKit (via
4319 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4320 // for examples of how to send the httpBody data.
4321 if (!info
.frame
->parent() && is_content_initiated
&&
4322 !url
.SchemeIs(url::kAboutScheme
)) {
4323 bool send_referrer
= false;
4325 // All navigations to or from WebUI URLs or within WebUI-enabled
4326 // RenderProcesses must be handled by the browser process so that the
4327 // correct bindings and data sources can be registered.
4328 // Similarly, navigations to view-source URLs or within ViewSource mode
4329 // must be handled by the browser process (except for reloads - those are
4330 // safe to leave within the renderer).
4331 // Lastly, access to file:// URLs from non-file:// URL pages must be
4332 // handled by the browser so that ordinary renderer processes don't get
4333 // blessed with file permissions.
4334 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4335 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4336 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4337 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4338 url
.SchemeIs(kViewSourceScheme
) ||
4339 (info
.frame
->isViewSourceModeEnabled() &&
4340 info
.navigationType
!= blink::WebNavigationTypeReload
);
4342 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4343 // Fork non-file to file opens. Check the opener URL if this is the
4344 // initial navigation in a newly opened window.
4345 GURL
source_url(old_url
);
4346 if (is_initial_navigation
&& source_url
.is_empty() &&
4347 info
.frame
->opener())
4348 source_url
= info
.frame
->opener()->top()->document().url();
4349 DCHECK(!source_url
.is_empty());
4350 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4354 // Give the embedder a chance.
4355 should_fork
= GetContentClient()->renderer()->ShouldFork(
4356 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4357 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4361 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4362 info
.defaultPolicy
);
4363 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4367 // Detect when a page is "forking" a new tab that can be safely rendered in
4368 // its own process. This is done by sites like Gmail that try to open links
4369 // in new windows without script connections back to the original page. We
4370 // treat such cases as browser navigations (in which we will create a new
4371 // renderer for a cross-site navigation), rather than WebKit navigations.
4373 // We use the following heuristic to decide whether to fork a new page in its
4375 // The parent page must open a new tab to about:blank, set the new tab's
4376 // window.opener to null, and then redirect the tab to a cross-site URL using
4379 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4382 // Must start from a tab showing about:blank, which is later redirected.
4383 old_url
== GURL(url::kAboutBlankURL
) &&
4384 // Must be the first real navigation of the tab.
4385 render_view_
->historyBackListCount() < 1 &&
4386 render_view_
->historyForwardListCount() < 1 &&
4387 // The parent page must have set the child's window.opener to null before
4388 // redirecting to the desired URL.
4389 info
.frame
->opener() == NULL
&&
4390 // Must be a top-level frame.
4391 info
.frame
->parent() == NULL
&&
4392 // Must not have issued the request from this page.
4393 is_content_initiated
&&
4394 // Must be targeted at the current tab.
4395 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4396 // Must be a JavaScript navigation, which appears as "other".
4397 info
.navigationType
== blink::WebNavigationTypeOther
;
4400 // Open the URL via the browser, not via WebKit.
4401 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4402 return blink::WebNavigationPolicyIgnore
;
4405 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4406 // This includes navigations with no request being sent to the network stack.
4407 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4408 switches::kEnableBrowserSideNavigation
) &&
4409 info
.urlRequest
.checkForBrowserSideNavigation() &&
4410 ShouldMakeNetworkRequestForURL(url
)) {
4411 BeginNavigation(&info
.urlRequest
);
4412 return blink::WebNavigationPolicyIgnore
;
4415 return info
.defaultPolicy
;
4418 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4420 const Referrer
& referrer
,
4421 WebNavigationPolicy policy
) {
4422 DCHECK_EQ(frame_
, frame
);
4424 FrameHostMsg_OpenURL_Params params
;
4426 params
.referrer
= referrer
;
4427 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4428 WebDataSource
* ds
= frame
->provisionalDataSource();
4430 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4431 NavigationStateImpl
* navigation_state
=
4432 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4433 if (navigation_state
->IsContentInitiated()) {
4434 params
.should_replace_current_entry
=
4435 ds
->replacesCurrentHistoryItem() &&
4436 render_view_
->history_list_length_
;
4438 // This is necessary to preserve the should_replace_current_entry value on
4439 // cross-process redirects, in the event it was set by a previous process.
4441 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4442 // NavigationState::should_replace_current_entry().
4443 params
.should_replace_current_entry
=
4444 navigation_state
->common_params().should_replace_current_entry
;
4447 params
.should_replace_current_entry
= false;
4449 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4450 if (GetContentClient()->renderer()->AllowPopup())
4451 params
.user_gesture
= true;
4453 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4454 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4455 policy
== blink::WebNavigationPolicyNewWindow
||
4456 policy
== blink::WebNavigationPolicyNewPopup
) {
4457 WebUserGestureIndicator::consumeUserGesture();
4460 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4463 void RenderFrameImpl::NavigateInternal(
4464 const CommonNavigationParams
& common_params
,
4465 const StartNavigationParams
& start_params
,
4466 const RequestNavigationParams
& request_params
,
4467 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4468 bool browser_side_navigation
=
4469 base::CommandLine::ForCurrentProcess()->HasSwitch(
4470 switches::kEnableBrowserSideNavigation
);
4471 bool is_reload
= IsReload(common_params
.navigation_type
);
4472 bool is_history_navigation
= request_params
.page_state
.IsValid();
4473 WebURLRequest::CachePolicy cache_policy
=
4474 WebURLRequest::UseProtocolCachePolicy
;
4475 RenderFrameImpl::PrepareRenderViewForNavigation(
4476 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4478 GetContentClient()->SetActiveURL(common_params
.url
);
4480 // If this frame isn't in the same process as the main frame, it may naively
4481 // assume that this is the first navigation in the iframe, but this may not
4482 // actually be the case. Inform the frame's state machine if this frame has
4483 // already committed other loads.
4484 if (request_params
.has_committed_real_load
&& frame_
->parent())
4485 frame_
->setCommittedFirstRealLoad();
4487 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4488 // We cannot reload if we do not have any history state. This happens, for
4489 // example, when recovering from a crash.
4491 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4494 pending_navigation_params_
.reset(
4495 new NavigationParams(common_params
, start_params
, request_params
));
4497 // Create parameters for a standard navigation.
4498 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4499 bool should_load_request
= false;
4500 WebHistoryItem item_for_history_navigation
;
4501 WebURLRequest request
= CreateURLRequestForNavigation(
4502 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4503 #if defined(OS_ANDROID)
4504 request
.setHasUserGesture(start_params
.has_user_gesture
);
4507 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4508 // navigation for this request (since it already went to the browser).
4509 if (browser_side_navigation
)
4510 request
.setCheckForBrowserSideNavigation(false);
4512 // If we are reloading, then use the history state of the current frame.
4513 // Otherwise, if we have history state, then we need to navigate to it, which
4514 // corresponds to a back/forward navigation event. Update the parameters
4515 // depending on the navigation type.
4517 bool ignore_cache
= (common_params
.navigation_type
==
4518 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4519 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4520 : blink::WebFrameLoadType::Reload
;
4522 if (!browser_side_navigation
) {
4523 const GURL override_url
=
4524 (common_params
.navigation_type
==
4525 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4528 request
= frame_
->requestForReload(load_type
, override_url
);
4530 should_load_request
= true;
4531 } else if (is_history_navigation
) {
4532 // We must know the page ID of the page we are navigating back to.
4533 DCHECK_NE(request_params
.page_id
, -1);
4534 // We must know the nav entry ID of the page we are navigating back to,
4535 // which should be the case because history navigations are routed via the
4537 DCHECK_NE(0, request_params
.nav_entry_id
);
4538 scoped_ptr
<HistoryEntry
> entry
=
4539 PageStateToHistoryEntry(request_params
.page_state
);
4541 // Ensure we didn't save the swapped out URL in UpdateState, since the
4542 // browser should never be telling us to navigate to swappedout://.
4543 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4545 if (!browser_side_navigation
) {
4546 scoped_ptr
<NavigationParams
> navigation_params(
4547 new NavigationParams(*pending_navigation_params_
.get()));
4548 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4549 // By default, tell the HistoryController to go the deserialized
4550 // HistoryEntry. This only works if all frames are in the same
4552 DCHECK(!frame_
->parent());
4553 render_view_
->history_controller()->GoToEntry(
4554 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4556 // In --site-per-process, the browser process sends a single
4557 // WebHistoryItem destined for this frame.
4558 // TODO(creis): Change PageState to FrameState. In the meantime, we
4559 // store the relevant frame's WebHistoryItem in the root of the
4561 SetPendingNavigationParams(navigation_params
.Pass());
4562 blink::WebHistoryItem history_item
= entry
->root();
4563 blink::WebHistoryLoadType load_type
=
4564 request_params
.is_same_document_history_load
4565 ? blink::WebHistorySameDocumentLoad
4566 : blink::WebHistoryDifferentDocumentLoad
;
4568 // Let the history controller know the provisional entry, since it is
4569 // used at commit time. Otherwise skip GoToEntry and navigate the
4571 // TODO(creis): Consider cloning the current entry to handle subframe
4572 // cases. Changes to SendUpdateState might affect this.
4573 render_view_
->history_controller()->set_provisional_entry(
4575 WebURLRequest request
=
4576 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4577 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4578 history_item
, load_type
);
4581 // TODO(clamy): this should be set to the HistoryItem sent by the
4582 // browser once the HistoryController has moved to the browser.
4583 // TODO(clamy): distinguish between different document and same document
4585 // TODO(clamy): update this for subframes history loads.
4586 item_for_history_navigation
=
4587 entry
->GetHistoryNodeForFrame(this)->item();
4588 load_type
= blink::WebFrameLoadType::BackForward
;
4589 should_load_request
= true;
4593 // Navigate to the given URL.
4594 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4595 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4596 start_params
.extra_headers
.end(),
4599 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4600 WebString::fromUTF8(i
.values()));
4604 if (start_params
.is_post
&& !browser_side_navigation
) {
4605 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4608 WebHTTPBody http_body
;
4609 http_body
.initialize();
4610 const char* data
= nullptr;
4611 if (start_params
.browser_initiated_post_data
.size()) {
4612 data
= reinterpret_cast<const char*>(
4613 &start_params
.browser_initiated_post_data
.front());
4615 http_body
.appendData(
4616 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4617 request
.setHTTPBody(http_body
);
4620 // A session history navigation should have been accompanied by state.
4621 CHECK_EQ(request_params
.page_id
, -1);
4623 should_load_request
= true;
4626 if (should_load_request
) {
4627 // Record this before starting the load. We need a lower bound of this
4628 // time to sanitize the navigationStart override set below.
4629 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4631 // Perform a navigation to a data url if needed.
4632 if (!common_params
.base_url_for_data_url
.is_empty() ||
4633 (browser_side_navigation
&&
4634 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4635 LoadDataURL(common_params
, frame_
);
4637 // Load the request.
4638 frame_
->toWebLocalFrame()->load(request
, load_type
,
4639 item_for_history_navigation
);
4642 if (load_type
== blink::WebFrameLoadType::Standard
) {
4643 UpdateFrameNavigationTiming(frame_
,
4644 request_params
.browser_navigation_start
,
4645 renderer_navigation_start
);
4649 // In case LoadRequest failed before didCreateDataSource was called.
4650 pending_navigation_params_
.reset();
4653 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4654 const std::string
& encoding_name
) {
4655 // Only update main frame's encoding_name.
4656 if (!frame
->parent())
4657 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4660 void RenderFrameImpl::SyncSelectionIfRequired() {
4661 base::string16 text
;
4664 #if defined(ENABLE_PLUGINS)
4665 if (render_view_
->focused_pepper_plugin_
) {
4666 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4667 offset
= 0; // Pepper API does not support offset reporting.
4668 // TODO(kinaba): cut as needed.
4672 size_t location
, length
;
4673 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4674 &location
, &length
)) {
4678 range
= gfx::Range(location
, location
+ length
);
4680 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4681 blink::WebTextInputTypeNone
) {
4682 // If current focused element is editable, we will send 100 more chars
4683 // before and after selection. It is for input method surrounding text
4685 if (location
> kExtraCharsBeforeAndAfterSelection
)
4686 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4689 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4690 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4691 if (!webrange
.isNull())
4692 text
= webrange
.toPlainText();
4695 text
= frame_
->selectionAsText();
4696 // http://crbug.com/101435
4697 // In some case, frame->selectionAsText() returned text's length is not
4698 // equal to the length returned from webwidget()->caretOrSelectionRange().
4699 // So we have to set the range according to text.length().
4700 range
.set_end(range
.start() + text
.length());
4704 // Sometimes we get repeated didChangeSelection calls from webkit when
4705 // the selection hasn't actually changed. We don't want to report these
4706 // because it will cause us to continually claim the X clipboard.
4707 if (selection_text_offset_
!= offset
||
4708 selection_range_
!= range
||
4709 selection_text_
!= text
) {
4710 selection_text_
= text
;
4711 selection_text_offset_
= offset
;
4712 selection_range_
= range
;
4713 SetSelectedText(text
, offset
, range
);
4715 GetRenderWidget()->UpdateSelectionBounds();
4718 void RenderFrameImpl::InitializeUserMediaClient() {
4719 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4722 #if defined(ENABLE_WEBRTC)
4723 DCHECK(!web_user_media_client_
);
4724 web_user_media_client_
= new UserMediaClientImpl(
4726 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4727 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4731 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4732 WebMediaPlayerClient
* client
) {
4733 #if defined(ENABLE_WEBRTC)
4734 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4736 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4737 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4738 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4739 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4740 new RenderMediaLog(),
4741 CreateRendererFactory());
4744 #endif // defined(ENABLE_WEBRTC)
4747 scoped_ptr
<MediaStreamRendererFactory
>
4748 RenderFrameImpl::CreateRendererFactory() {
4749 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4750 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4752 return factory
.Pass();
4753 #if defined(ENABLE_WEBRTC)
4754 return scoped_ptr
<MediaStreamRendererFactory
>(
4755 new MediaStreamRendererFactoryImpl());
4757 return scoped_ptr
<MediaStreamRendererFactory
>(
4758 static_cast<MediaStreamRendererFactory
*>(NULL
));
4762 void RenderFrameImpl::PrepareRenderViewForNavigation(
4764 const RequestNavigationParams
& request_params
,
4766 WebURLRequest::CachePolicy
* cache_policy
) {
4767 DCHECK(render_view_
->webview());
4769 MaybeHandleDebugURL(url
);
4772 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4774 render_view_
->history_list_offset_
=
4775 request_params
.current_history_list_offset
;
4776 render_view_
->history_list_length_
=
4777 request_params
.current_history_list_length
;
4778 if (request_params
.should_clear_history_list
) {
4779 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4780 CHECK_EQ(0, render_view_
->history_list_length_
);
4783 if (!is_swapped_out_
|| frame_
->parent())
4786 // This is a swapped out main frame, so swap the renderer back in.
4787 // We marked the view as hidden when swapping the view out, so be sure to
4788 // reset the visibility state before navigating to the new URL.
4789 render_view_
->webview()->setVisibilityState(
4790 render_view_
->visibilityState(), false);
4792 // If this is an attempt to reload while we are swapped out, we should not
4793 // reload swappedout://, but the previous page, which is stored in
4794 // params.state. Setting is_reload to false will treat this like a back
4795 // navigation to accomplish that.
4797 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4799 // We refresh timezone when a view is swapped in since timezone
4800 // can get out of sync when the system timezone is updated while
4801 // the view is swapped out.
4802 RenderThreadImpl::NotifyTimezoneChange();
4804 render_view_
->SetSwappedOut(false);
4805 is_swapped_out_
= false;
4809 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4810 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4811 switches::kEnableBrowserSideNavigation
));
4813 // TODO(clamy): Execute the beforeunload event.
4815 // Note: At this stage, the goal is to apply all the modifications the
4816 // renderer wants to make to the request, and then send it to the browser, so
4817 // that the actual network request can be started. Ideally, all such
4818 // modifications should take place in willSendRequest, and in the
4819 // implementation of willSendRequest for the various InspectorAgents
4822 // TODO(clamy): Apply devtools override.
4823 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4825 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4827 // TODO(clamy): Same-document navigations should not be sent back to the
4829 // TODO(clamy): Data urls should not be sent back to the browser either.
4830 bool should_replace_current_entry
= false;
4831 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4832 WebDataSource
* current_data_source
= frame_
->dataSource();
4833 WebDataSource
* data_source
=
4834 provisional_data_source
? provisional_data_source
: current_data_source
;
4836 // The current entry can only be replaced if there already is an entry in the
4838 if (data_source
&& render_view_
->history_list_length_
> 0) {
4839 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4841 Send(new FrameHostMsg_BeginNavigation(
4843 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4844 BeginNavigationParams(
4845 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4846 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4847 GetRequestBodyForWebURLRequest(*request
)));
4850 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4852 // A loadData request with a specified base URL.
4853 std::string mime_type
, charset
, data
;
4854 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4855 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4856 params
.url
: params
.base_url_for_data_url
;
4858 WebData(data
.c_str(), data
.length()),
4859 WebString::fromUTF8(mime_type
),
4860 WebString::fromUTF8(charset
),
4862 params
.history_url_for_data_url
,
4865 CHECK(false) << "Invalid URL passed: "
4866 << params
.url
.possibly_invalid_spec();
4870 void RenderFrameImpl::SendFailedProvisionalLoad(
4871 const blink::WebURLRequest
& request
,
4872 const blink::WebURLError
& error
,
4873 blink::WebLocalFrame
* frame
) {
4874 bool show_repost_interstitial
=
4875 (error
.reason
== net::ERR_CACHE_MISS
&&
4876 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4878 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4879 params
.error_code
= error
.reason
;
4880 GetContentClient()->renderer()->GetNavigationErrorStrings(
4881 render_view_
.get(), frame
, request
, error
, NULL
,
4882 ¶ms
.error_description
);
4883 params
.url
= error
.unreachableURL
;
4884 params
.showing_repost_interstitial
= show_repost_interstitial
;
4885 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4886 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4889 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4891 const GURL
& unreachable_url
) {
4892 // Don't display an error page if this is simply a cancelled load. Aside
4893 // from being dumb, Blink doesn't expect it and it will cause a crash.
4894 if (error_code
== net::ERR_ABORTED
)
4897 // Don't display "client blocked" error page if browser has asked us not to.
4898 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4899 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4903 // Allow the embedder to suppress an error page.
4904 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4905 this, unreachable_url
)) {
4909 if (RenderThreadImpl::current() &&
4910 RenderThreadImpl::current()->layout_test_mode()) {
4917 GURL
RenderFrameImpl::GetLoadingUrl() const {
4918 WebDataSource
* ds
= frame_
->dataSource();
4919 if (ds
->hasUnreachableURL())
4920 return ds
->unreachableURL();
4922 const WebURLRequest
& request
= ds
->request();
4923 return request
.url();
4926 void RenderFrameImpl::PopulateDocumentStateFromPending(
4927 DocumentState
* document_state
) {
4928 document_state
->set_request_time(
4929 pending_navigation_params_
->request_params
.request_time
);
4931 InternalDocumentStateData
* internal_data
=
4932 InternalDocumentStateData::FromDocumentState(document_state
);
4934 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4935 url::kJavaScriptScheme
) &&
4936 pending_navigation_params_
->common_params
.navigation_type
==
4937 FrameMsg_Navigate_Type::RESTORE
) {
4938 // We're doing a load of a page that was restored from the last session. By
4939 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4940 // can result in stale data for pages that are set to expire. We explicitly
4941 // override that by setting the policy here so that as necessary we load
4942 // from the network.
4944 // TODO(davidben): Remove this in favor of passing a cache policy to the
4945 // loadHistoryItem call in OnNavigate. That requires not overloading
4946 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4947 // policy based on load type, etc".
4948 internal_data
->set_cache_policy_override(
4949 WebURLRequest::UseProtocolCachePolicy
);
4952 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4953 document_state
->set_load_type(DocumentState::RELOAD
);
4954 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4955 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4957 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4959 internal_data
->set_is_overriding_user_agent(
4960 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4961 internal_data
->set_must_reset_scroll_and_scale_state(
4962 pending_navigation_params_
->common_params
.navigation_type
==
4963 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4964 document_state
->set_can_load_local_resources(
4965 pending_navigation_params_
->request_params
.can_load_local_resources
);
4968 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4969 // A navigation resulting from loading a javascript URL should not be treated
4970 // as a browser initiated event. Instead, we want it to look as if the page
4971 // initiated any load resulting from JS execution.
4972 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4973 url::kJavaScriptScheme
)) {
4974 return NavigationStateImpl::CreateBrowserInitiated(
4975 pending_navigation_params_
->common_params
,
4976 pending_navigation_params_
->start_params
,
4977 pending_navigation_params_
->request_params
);
4979 return NavigationStateImpl::CreateContentInitiated();
4982 #if defined(OS_ANDROID)
4983 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4984 WebMediaPlayerClient
* client
,
4985 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4986 const media::WebMediaPlayerParams
& params
) {
4987 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4988 if (SynchronousCompositorFactory
* factory
=
4989 SynchronousCompositorFactory::GetInstance()) {
4990 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4992 GpuChannelHost
* gpu_channel_host
=
4993 RenderThreadImpl::current()->EstablishGpuChannelSync(
4994 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4996 if (!gpu_channel_host
) {
4997 LOG(ERROR
) << "Failed to establish GPU channel for media player";
5001 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
5002 RenderThreadImpl::current()->SharedMainThreadContextProvider();
5004 if (!context_provider
.get()) {
5005 LOG(ERROR
) << "Failed to get context3d for media player";
5009 stream_texture_factory
= StreamTextureFactoryImpl::Create(
5010 context_provider
, gpu_channel_host
, routing_id_
);
5013 return new WebMediaPlayerAndroid(
5014 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
5015 GetMediaPlayerManager(), GetCdmFactory(), stream_texture_factory
, params
);
5018 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
5019 if (!media_player_manager_
)
5020 media_player_manager_
= new RendererMediaPlayerManager(this);
5021 return media_player_manager_
;
5023 #endif // defined(OS_ANDROID)
5025 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
5026 if (!media_permission_dispatcher_
)
5027 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
5028 return media_permission_dispatcher_
;
5031 #if defined(ENABLE_MOJO_MEDIA)
5032 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5033 if (!media_service_factory_
) {
5034 mojo::ServiceProviderPtr service_provider
=
5035 ConnectToApplication(GURL("mojo:media"));
5036 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5037 media_service_factory_
.set_connection_error_handler(
5038 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5039 base::Unretained(this)));
5042 return media_service_factory_
.get();
5045 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5046 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5047 // violation on the old |media_service_factory_| by outstanding
5048 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5050 // media_service_factory_.reset();
5054 bool RenderFrameImpl::AreSecureCodecsSupported() {
5055 #if defined(OS_ANDROID)
5056 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5057 return render_view_
->renderer_preferences_
5058 .use_video_overlay_for_embedded_encrypted_video
;
5061 #endif // defined(OS_ANDROID)
5064 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5065 #if defined(ENABLE_BROWSER_CDMS)
5067 cdm_manager_
= new RendererCdmManager(this);
5068 #endif // defined(ENABLE_BROWSER_CDMS)
5070 if (!cdm_factory_
) {
5073 #if defined(ENABLE_MOJO_MEDIA)
5074 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5076 cdm_factory_
.reset(new RenderCdmFactory(
5077 #if defined(ENABLE_PEPPER_CDMS)
5078 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5079 #elif defined(ENABLE_BROWSER_CDMS)
5083 #endif // defined(ENABLE_MOJO_MEDIA)
5086 return cdm_factory_
.get();
5089 void RenderFrameImpl::RegisterMojoServices() {
5090 // Only main frame have ImageDownloader service.
5091 if (!frame_
->parent()) {
5092 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5093 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5094 base::Unretained(this)));
5098 mojo::ServiceProviderPtr
RenderFrameImpl::ConnectToApplication(
5100 DCHECK(mojo_shell_
);
5101 mojo::ServiceProviderPtr service_provider
;
5102 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5103 request
->url
= mojo::String::From(url
);
5104 mojo_shell_
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5106 base::Bind(&OnGotContentHandlerID
));
5107 return service_provider
.Pass();
5110 } // namespace content