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::didChangePerformanceTiming() {
3486 FOR_EACH_OBSERVER(RenderFrameObserver
,
3488 DidChangePerformanceTiming());
3491 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3492 DCHECK(!frame_
|| frame_
== frame
);
3493 #if defined(ENABLE_PLUGINS)
3494 if (frame
!= render_view_
->webview()->mainFrame())
3496 PluginChannelHost::Broadcast(
3497 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3501 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3502 v8::Local
<v8::Context
> context
,
3503 int extension_group
,
3505 DCHECK(!frame_
|| frame_
== frame
);
3507 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3508 DidCreateScriptContext(context
, extension_group
, world_id
));
3511 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3512 v8::Local
<v8::Context
> context
,
3514 DCHECK(!frame_
|| frame_
== frame
);
3516 FOR_EACH_OBSERVER(RenderFrameObserver
,
3518 WillReleaseScriptContext(context
, world_id
));
3521 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3522 DCHECK(!frame_
|| frame_
== frame
);
3523 // TODO(nasko): Move implementation here. Needed methods:
3524 // * StartNavStateSyncTimerIfNecessary
3525 render_view_
->didChangeScrollOffset(frame
);
3527 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3530 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3531 DCHECK(!frame_
|| frame_
== frame
);
3532 if (!frame
->parent()) {
3533 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3534 render_view_
->GetRoutingID()));
3538 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3540 bool final_update
) {
3541 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3543 active_match_ordinal
= 0;
3545 render_view_
->Send(new ViewHostMsg_Find_Reply(
3546 render_view_
->GetRoutingID(), request_id
, count
,
3547 gfx::Rect(), active_match_ordinal
, final_update
));
3550 void RenderFrameImpl::reportFindInPageSelection(
3552 int active_match_ordinal
,
3553 const blink::WebRect
& selection_rect
) {
3554 render_view_
->Send(new ViewHostMsg_Find_Reply(
3555 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3556 active_match_ordinal
, false));
3559 void RenderFrameImpl::requestStorageQuota(
3560 blink::WebLocalFrame
* frame
,
3561 blink::WebStorageQuotaType type
,
3562 unsigned long long requested_size
,
3563 blink::WebStorageQuotaCallbacks callbacks
) {
3564 DCHECK(!frame_
|| frame_
== frame
);
3565 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3566 if (origin
.isUnique()) {
3567 // Unique origins cannot store persistent state.
3568 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3571 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3572 render_view_
->GetRoutingID(),
3573 GURL(origin
.toString()),
3574 static_cast<storage::StorageType
>(type
),
3576 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3579 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3580 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3581 impl
->set_render_frame_id(routing_id_
);
3584 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3585 if (!geolocation_dispatcher_
)
3586 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3587 return geolocation_dispatcher_
;
3590 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3591 if (!presentation_dispatcher_
)
3592 presentation_dispatcher_
= new PresentationDispatcher(this);
3593 return presentation_dispatcher_
;
3596 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3597 if (!push_messaging_dispatcher_
)
3598 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3599 return push_messaging_dispatcher_
;
3602 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3603 blink::WebLocalFrame
* frame
,
3604 blink::WebRTCPeerConnectionHandler
* handler
) {
3605 DCHECK(!frame_
|| frame_
== frame
);
3606 #if defined(ENABLE_WEBRTC)
3607 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3611 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3612 if (!web_user_media_client_
)
3613 InitializeUserMediaClient();
3614 return web_user_media_client_
;
3617 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3618 if (!web_encrypted_media_client_
) {
3619 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3620 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3621 // is destructed before |this|, and does not give away ownership of the
3623 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3624 base::Unretained(this)),
3625 GetCdmFactory(), GetMediaPermission()));
3627 return web_encrypted_media_client_
.get();
3630 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3631 if (!midi_dispatcher_
)
3632 midi_dispatcher_
= new MidiDispatcher(this);
3633 return midi_dispatcher_
;
3636 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3637 blink::WebLocalFrame
* source_frame
,
3638 blink::WebFrame
* target_frame
,
3639 blink::WebSecurityOrigin target_origin
,
3640 blink::WebDOMMessageEvent event
) {
3641 DCHECK(!frame_
|| frame_
== target_frame
);
3643 // Currently, a postMessage that targets a cross-process frame can be plumbed
3644 // either through this function or RenderFrameProxy::postMessageEvent. This
3645 // function is used when the target cross-process frame is a top-level frame
3646 // which has been swapped out. In that case, the corresponding WebLocalFrame
3647 // currently remains in the frame tree even in site-per-process mode (see
3648 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3649 // --site-per-process mode for all other cases.
3651 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3652 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3653 // cross-process postMessages.
3654 if (!is_swapped_out_
)
3657 // It is possible to get here on a swapped-out frame without a
3658 // |render_frame_proxy_|. This happens when:
3659 // - This process only has one active RenderView and is about to go away
3660 // (e.g., due to cross-process navigation).
3661 // - The top frame has a subframe with an unload handler.
3662 // - The subframe sends a postMessage to the top-level frame in its unload
3664 // See https://crbug.com/475651 for details. We return false here, since we
3665 // don't want to deliver the message to the new process in this case.
3666 if (!render_frame_proxy_
)
3669 render_frame_proxy_
->postMessageEvent(
3670 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3674 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3675 const blink::WebURL
& url
) {
3676 DCHECK(!frame_
|| frame_
== frame
);
3677 std::string user_agent_override_for_url
=
3678 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3679 if (!user_agent_override_for_url
.empty())
3680 return WebString::fromUTF8(user_agent_override_for_url
);
3682 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3683 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3684 return blink::WebString();
3687 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3688 // associated with it, so the checks below are not valid. Temporarily
3689 // return early and fix properly as part of https://crbug.com/426555.
3690 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3691 return blink::WebString();
3693 // If we're in the middle of committing a load, the data source we need
3694 // will still be provisional.
3695 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3696 WebDataSource
* data_source
= NULL
;
3697 if (main_frame
->provisionalDataSource())
3698 data_source
= main_frame
->provisionalDataSource();
3700 data_source
= main_frame
->dataSource();
3702 InternalDocumentStateData
* internal_data
= data_source
?
3703 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3704 if (internal_data
&& internal_data
->is_overriding_user_agent())
3705 return WebString::fromUTF8(
3706 render_view_
->renderer_preferences_
.user_agent_override
);
3707 return blink::WebString();
3710 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3711 DCHECK(!frame_
|| frame_
== frame
);
3712 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3713 return WebString::fromUTF8("1");
3717 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3718 bool default_value
) {
3719 DCHECK(!frame_
|| frame_
== frame
);
3723 bool blocked
= true;
3724 Send(new FrameHostMsg_Are3DAPIsBlocked(
3726 GURL(frame
->top()->securityOrigin().toString()),
3727 THREE_D_API_TYPE_WEBGL
,
3732 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3733 int arb_robustness_status_code
) {
3734 DCHECK(!frame_
|| frame_
== frame
);
3735 Send(new FrameHostMsg_DidLose3DContext(
3736 GURL(frame
->top()->securityOrigin().toString()),
3737 THREE_D_API_TYPE_WEBGL
,
3738 arb_robustness_status_code
));
3741 blink::WebScreenOrientationClient
*
3742 RenderFrameImpl::webScreenOrientationClient() {
3743 if (!screen_orientation_dispatcher_
)
3744 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3745 return screen_orientation_dispatcher_
;
3748 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3749 ServiceWorkerNetworkProvider
* provider
=
3750 ServiceWorkerNetworkProvider::FromDocumentState(
3751 DocumentState::FromDataSource(&data_source
));
3752 if (!provider
->context())
3754 return provider
->context()->controller_handle_id() !=
3755 kInvalidServiceWorkerHandleId
;
3758 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3759 ServiceWorkerNetworkProvider
* provider
=
3760 ServiceWorkerNetworkProvider::FromDocumentState(
3761 DocumentState::FromDataSource(&data_source
));
3762 if (provider
->context() && provider
->context()->controller())
3763 return provider
->context()->controller()->version_id();
3764 return kInvalidServiceWorkerVersionId
;
3767 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3768 blink::WebAXEvent event
) {
3769 HandleWebAccessibilityEvent(obj
, event
);
3772 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3775 const blink::WebAXObject
& start_object
,
3777 const blink::WebAXObject
& end_object
,
3779 if (renderer_accessibility_
) {
3780 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3781 identifier
, match_index
, start_object
, start_offset
,
3782 end_object
, end_offset
);
3786 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3787 DCHECK(!frame_
|| frame_
== frame
);
3789 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3792 bool RenderFrameImpl::enterFullscreen() {
3793 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3797 bool RenderFrameImpl::exitFullscreen() {
3798 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3802 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3803 if (!permission_client_
)
3804 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3806 return permission_client_
.get();
3809 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3810 if (!app_banner_client_
) {
3811 app_banner_client_
=
3812 GetContentClient()->renderer()->CreateAppBannerClient(this);
3815 return app_banner_client_
.get();
3818 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3820 const WebString
& title
) {
3821 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3822 Send(new FrameHostMsg_RegisterProtocolHandler(
3824 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3830 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3831 const WebURL
& url
) {
3832 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3833 Send(new FrameHostMsg_UnregisterProtocolHandler(
3835 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3840 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3842 bluetooth_
.reset(new WebBluetoothImpl(
3843 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3846 return bluetooth_
.get();
3849 blink::WebUSBClient
* RenderFrameImpl::usbClient() {
3850 #if !defined(OS_ANDROID)
3852 mojo::ServiceProviderPtr device_services
=
3853 ConnectToApplication(GURL(device::kDevicesMojoAppUrl
));
3854 usb_client_
.reset(new WebUSBClientImpl(device_services
.Pass()));
3857 return usb_client_
.get();
3860 #if defined(ENABLE_WEBVR)
3861 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3862 if (!vr_dispatcher_
)
3863 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3865 return vr_dispatcher_
.get();
3869 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3870 has_played_media_
= true;
3871 Send(new FrameHostMsg_MediaPlayingNotification(
3872 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3873 player
->hasAudio(), player
->isRemote()));
3876 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3877 Send(new FrameHostMsg_MediaPausedNotification(
3878 routing_id_
, reinterpret_cast<int64
>(player
)));
3881 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3885 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3886 observers_
.AddObserver(observer
);
3889 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3890 observer
->RenderFrameGone();
3891 observers_
.RemoveObserver(observer
);
3894 void RenderFrameImpl::OnStop() {
3896 frame_
->stopLoading();
3897 if (!frame_
->parent())
3898 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3900 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3903 void RenderFrameImpl::WasHidden() {
3904 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3907 void RenderFrameImpl::WasShown() {
3908 // TODO(kenrb): Need to figure out how to do this better. Should
3909 // VisibilityState remain a page-level concept or move to frames?
3910 // The semantics of 'Show' might have to change here.
3911 if (render_widget_
) {
3912 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3913 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3915 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3918 void RenderFrameImpl::WidgetWillClose() {
3919 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3922 bool RenderFrameImpl::IsHidden() {
3923 return GetRenderWidget()->is_hidden();
3926 // Tell the embedding application that the URL of the active page has changed.
3927 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3928 blink::WebFrame
* frame
,
3929 blink::WebHistoryCommitType commit_type
,
3930 const blink::WebHistoryItem
& item
) {
3931 DCHECK(!frame_
|| frame_
== frame
);
3932 WebDataSource
* ds
= frame
->dataSource();
3935 const WebURLRequest
& request
= ds
->request();
3936 const WebURLResponse
& response
= ds
->response();
3938 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3939 NavigationStateImpl
* navigation_state
=
3940 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3941 InternalDocumentStateData
* internal_data
=
3942 InternalDocumentStateData::FromDocumentState(document_state
);
3944 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3945 params
.http_status_code
= response
.httpStatusCode();
3946 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3947 params
.is_post
= false;
3948 params
.intended_as_new_entry
=
3949 navigation_state
->request_params().intended_as_new_entry
;
3950 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3951 params
.post_id
= -1;
3952 params
.page_id
= render_view_
->page_id_
;
3953 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3954 // We need to track the RenderViewHost routing_id because of downstream
3955 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3956 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3957 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3958 // based on the ID stored in the resource requests. Once those dependencies
3959 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3960 // client to be based on the routing_id of the RenderFrameHost.
3961 params
.render_view_routing_id
= render_view_
->routing_id();
3962 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3963 params
.socket_address
.set_port(response
.remotePort());
3964 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3966 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3967 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3968 params
.security_info
= response
.securityInfo();
3970 // Set the URL to be displayed in the browser UI to the user.
3971 params
.url
= GetLoadingUrl();
3972 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3974 // Set the origin of the frame. This will be replicated to the corresponding
3975 // RenderFrameProxies in other processes.
3976 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3977 // to https://crbug.com/439608 and will be replicated as unique origins.
3978 if (!is_swapped_out_
) {
3979 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3980 if (url::IsStandard(scheme
.c_str(),
3981 url::Component(0, static_cast<int>(scheme
.length())))) {
3982 params
.origin
= frame
->document().securityOrigin();
3986 if (frame
->document().baseURL() != params
.url
)
3987 params
.base_url
= frame
->document().baseURL();
3989 GetRedirectChain(ds
, ¶ms
.redirects
);
3990 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3991 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3993 params
.searchable_form_url
= internal_data
->searchable_form_url();
3994 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3996 params
.gesture
= render_view_
->navigation_gesture_
;
3997 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3999 // Make navigation state a part of the DidCommitProvisionalLoad message so
4000 // that committed entry has it at all times.
4001 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
4002 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4004 params
.page_state
= HistoryEntryToPageState(entry
);
4006 params
.page_state
= PageState::CreateFromURL(request
.url());
4008 // In --site-per-process, just send a single HistoryItem for this frame,
4009 // rather than the whole tree. It will be stored in the corresponding
4010 // FrameNavigationEntry.
4011 params
.page_state
= SingleHistoryItemToPageState(item
);
4013 params
.item_sequence_number
= item
.itemSequenceNumber();
4014 params
.document_sequence_number
= item
.documentSequenceNumber();
4016 if (!frame
->parent()) {
4017 // Top-level navigation.
4019 // Reset the zoom limits in case a plugin had changed them previously. This
4020 // will also call us back which will cause us to send a message to
4021 // update WebContentsImpl.
4022 render_view_
->webview()->zoomLimitsChanged(
4023 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
4024 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
4026 // Set zoom level, but don't do it for full-page plugin since they don't use
4027 // the same zoom settings.
4028 HostZoomLevels::iterator host_zoom
=
4029 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
4030 if (render_view_
->webview()->mainFrame()->isWebLocalFrame() &&
4031 render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
4032 // Reset the zoom levels for plugins.
4033 render_view_
->webview()->setZoomLevel(0);
4035 // If the zoom level is not found, then do nothing. In-page navigation
4036 // relies on not changing the zoom level in this case.
4037 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
4038 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
4041 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
4042 // This zoom level was merely recorded transiently for this load. We can
4043 // erase it now. If at some point we reload this page, the browser will
4044 // send us a new, up-to-date zoom level.
4045 render_view_
->host_zoom_levels_
.erase(host_zoom
);
4048 // Update contents MIME type for main frame.
4049 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4051 params
.transition
= navigation_state
->GetTransitionType();
4052 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4053 // If the main frame does a load, it should not be reported as a subframe
4054 // navigation. This can occur in the following case:
4055 // 1. You're on a site with frames.
4056 // 2. You do a subframe navigation. This is stored with transition type
4058 // 3. You navigate to some non-frame site, say, google.com.
4059 // 4. You navigate back to the page from step 2. Since it was initially
4060 // MANUAL_SUBFRAME, it will be that same transition type here.
4061 // We don't want that, because any navigation that changes the toplevel
4062 // frame should be tracked as a toplevel navigation (this allows us to
4063 // update the URL bar, etc).
4064 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4067 // If the page contained a client redirect (meta refresh, document.loc...),
4068 // set the referrer and transition appropriately.
4069 if (ds
->isClientRedirect()) {
4071 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4072 params
.transition
= ui::PageTransitionFromInt(
4073 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4075 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4076 frame
, ds
->request());
4079 base::string16 method
= request
.httpMethod();
4080 if (base::EqualsASCII(method
, "POST")) {
4081 params
.is_post
= true;
4082 params
.post_id
= ExtractPostId(entry
);
4085 // Send the user agent override back.
4086 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4088 // Track the URL of the original request. We use the first entry of the
4089 // redirect chain if it exists because the chain may have started in another
4091 params
.original_request_url
= GetOriginalRequestURL(ds
);
4093 params
.history_list_was_cleared
=
4094 navigation_state
->request_params().should_clear_history_list
;
4096 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4097 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4098 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4099 frame
->dataSource()->request().uiStartTime());
4101 // Save some histogram data so we can compute the average memory used per
4102 // page load of the glyphs.
4103 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4104 blink::WebGlyphCache::pageCount());
4106 // This message needs to be sent before any of allowScripts(),
4107 // allowImages(), allowPlugins() is called for the new page, so that when
4108 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4109 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4110 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4112 // Subframe navigation: the type depends on whether this navigation
4113 // generated a new session history entry. When they do generate a session
4114 // history entry, it means the user initiated the navigation and we should
4116 if (commit_type
== blink::WebStandardCommit
)
4117 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4119 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4121 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4122 params
.history_list_was_cleared
= false;
4123 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4125 // Don't send this message while the subframe is swapped out.
4126 if (!is_swapped_out())
4127 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4130 // If we end up reusing this WebRequest (for example, due to a #ref click),
4131 // we don't want the transition type to persist. Just clear it.
4132 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4135 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4136 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4138 render_view_
->FrameDidStartLoading(frame_
);
4139 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4142 void RenderFrameImpl::didStopLoading() {
4143 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4145 render_view_
->FrameDidStopLoading(frame_
);
4146 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4149 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4150 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4153 void RenderFrameImpl::HandleWebAccessibilityEvent(
4154 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4155 if (renderer_accessibility_
)
4156 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4159 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4160 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4163 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4164 if (renderer_accessibility())
4165 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4169 void RenderFrameImpl::OnCommitNavigation(
4170 const ResourceResponseHead
& response
,
4171 const GURL
& stream_url
,
4172 const CommonNavigationParams
& common_params
,
4173 const RequestNavigationParams
& request_params
) {
4174 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4175 switches::kEnableBrowserSideNavigation
));
4176 // This will override the url requested by the WebURLLoader, as well as
4177 // provide it with the response to the request.
4178 scoped_ptr
<StreamOverrideParameters
> stream_override(
4179 new StreamOverrideParameters());
4180 stream_override
->stream_url
= stream_url
;
4181 stream_override
->response
= response
;
4183 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4184 stream_override
.Pass());
4187 void RenderFrameImpl::OnFailedNavigation(
4188 const CommonNavigationParams
& common_params
,
4189 const RequestNavigationParams
& request_params
,
4190 bool has_stale_copy_in_cache
,
4192 bool is_reload
= IsReload(common_params
.navigation_type
);
4193 bool is_history_navigation
= request_params
.page_state
.IsValid();
4194 WebURLRequest::CachePolicy cache_policy
=
4195 WebURLRequest::UseProtocolCachePolicy
;
4196 RenderFrameImpl::PrepareRenderViewForNavigation(
4197 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4199 GetContentClient()->SetActiveURL(common_params
.url
);
4201 pending_navigation_params_
.reset(new NavigationParams(
4202 common_params
, StartNavigationParams(), request_params
));
4204 // Inform the browser of the start of the provisional load. This is needed so
4205 // that the load is properly tracked by the WebNavigation API.
4206 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4207 routing_id_
, common_params
.url
));
4209 // Send the provisional load failure.
4210 blink::WebURLError error
=
4211 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4212 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4213 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4214 frame_
->isViewSourceModeEnabled());
4215 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4217 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4218 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4219 // http://crbug.com/501960
4220 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4224 // Make sure errors are not shown in view source mode.
4225 frame_
->enableViewSourceMode(false);
4227 // Replace the current history entry in reloads, history navigations and loads
4228 // of the same url. This corresponds to Blink's notion of a standard
4230 // TODO(clamy): see if initial commits in subframes should be handled
4232 bool replace
= is_reload
|| is_history_navigation
||
4233 common_params
.url
== GetLoadingUrl();
4234 LoadNavigationErrorPage(failed_request
, error
, replace
);
4237 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4238 RenderFrame
* render_frame
,
4239 const NavigationPolicyInfo
& info
) {
4240 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4243 // TODO(nick): Is consulting |is_subframe_| here correct?
4244 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_
) {
4245 // There's no reason to ignore navigations on subframes, since the swap out
4246 // logic no longer applies.
4248 if (is_swapped_out_
) {
4249 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4250 // Targeted links may try to navigate a swapped out frame. Allow the
4251 // browser process to navigate the tab instead. Note that it is also
4252 // possible for non-targeted navigations (from this view) to arrive
4253 // here just after we are swapped out. It's ok to send them to the
4254 // browser, as long as they're for the top level frame.
4255 // TODO(creis): Ensure this supports targeted form submissions when
4256 // fixing http://crbug.com/101395.
4257 if (info
.frame
->parent() == NULL
) {
4258 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4259 info
.defaultPolicy
);
4260 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4263 // We should otherwise ignore in-process iframe navigations, if they
4264 // arrive just after we are swapped out.
4265 return blink::WebNavigationPolicyIgnore
;
4268 // Allow kSwappedOutURL to complete.
4269 return info
.defaultPolicy
;
4273 // Webkit is asking whether to navigate to a new URL.
4274 // This is fine normally, except if we're showing UI from one security
4275 // context and they're trying to navigate to a different context.
4276 const GURL
& url
= info
.urlRequest
.url();
4278 // A content initiated navigation may have originated from a link-click,
4279 // script, drag-n-drop operation, etc.
4280 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4281 bool is_content_initiated
=
4282 document_state
->navigation_state()->IsContentInitiated();
4284 // If the browser is interested, then give it a chance to look at the request.
4285 if (is_content_initiated
) {
4287 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4288 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4289 base::EqualsASCII(base::StringPiece16(info
.urlRequest
.httpMethod()),
4291 bool browser_handles_request
=
4292 render_view_
->renderer_preferences_
4293 .browser_handles_non_local_top_level_requests
4294 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4296 if (!browser_handles_request
) {
4297 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4298 render_view_
->renderer_preferences_
4299 .browser_handles_all_top_level_requests
;
4302 if (browser_handles_request
) {
4303 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4304 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4308 // Use the frame's original request's URL rather than the document's URL for
4309 // subsequent checks. For a popup, the document's URL may become the opener
4310 // window's URL if the opener has called document.write().
4311 // See http://crbug.com/93517.
4312 GURL
old_url(info
.frame
->dataSource()->request().url());
4314 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4315 // an extension or app origin, leaving a WebUI page, etc). We only care about
4316 // top-level navigations (not iframes). But we sometimes navigate to
4317 // about:blank to clear a tab, and we want to still allow that.
4319 // Note: this is known to break POST submissions when crossing process
4320 // boundaries until http://crbug.com/101395 is fixed. This is better for
4321 // security than loading a WebUI, extension or app page in the wrong process.
4322 // POST requests don't work because this mechanism does not preserve form
4323 // POST data. We will need to send the request's httpBody data up to the
4324 // browser process, and issue a special POST navigation in WebKit (via
4325 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4326 // for examples of how to send the httpBody data.
4327 if (!info
.frame
->parent() && is_content_initiated
&&
4328 !url
.SchemeIs(url::kAboutScheme
)) {
4329 bool send_referrer
= false;
4331 // All navigations to or from WebUI URLs or within WebUI-enabled
4332 // RenderProcesses must be handled by the browser process so that the
4333 // correct bindings and data sources can be registered.
4334 // Similarly, navigations to view-source URLs or within ViewSource mode
4335 // must be handled by the browser process (except for reloads - those are
4336 // safe to leave within the renderer).
4337 // Lastly, access to file:// URLs from non-file:// URL pages must be
4338 // handled by the browser so that ordinary renderer processes don't get
4339 // blessed with file permissions.
4340 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4341 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4342 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4343 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4344 url
.SchemeIs(kViewSourceScheme
) ||
4345 (info
.frame
->isViewSourceModeEnabled() &&
4346 info
.navigationType
!= blink::WebNavigationTypeReload
);
4348 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4349 // Fork non-file to file opens. Check the opener URL if this is the
4350 // initial navigation in a newly opened window.
4351 GURL
source_url(old_url
);
4352 if (is_initial_navigation
&& source_url
.is_empty() &&
4353 info
.frame
->opener())
4354 source_url
= info
.frame
->opener()->top()->document().url();
4355 DCHECK(!source_url
.is_empty());
4356 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4360 // Give the embedder a chance.
4361 should_fork
= GetContentClient()->renderer()->ShouldFork(
4362 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4363 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4367 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4368 info
.defaultPolicy
);
4369 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4373 // Detect when a page is "forking" a new tab that can be safely rendered in
4374 // its own process. This is done by sites like Gmail that try to open links
4375 // in new windows without script connections back to the original page. We
4376 // treat such cases as browser navigations (in which we will create a new
4377 // renderer for a cross-site navigation), rather than WebKit navigations.
4379 // We use the following heuristic to decide whether to fork a new page in its
4381 // The parent page must open a new tab to about:blank, set the new tab's
4382 // window.opener to null, and then redirect the tab to a cross-site URL using
4385 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4388 // Must start from a tab showing about:blank, which is later redirected.
4389 old_url
== GURL(url::kAboutBlankURL
) &&
4390 // Must be the first real navigation of the tab.
4391 render_view_
->historyBackListCount() < 1 &&
4392 render_view_
->historyForwardListCount() < 1 &&
4393 // The parent page must have set the child's window.opener to null before
4394 // redirecting to the desired URL.
4395 info
.frame
->opener() == NULL
&&
4396 // Must be a top-level frame.
4397 info
.frame
->parent() == NULL
&&
4398 // Must not have issued the request from this page.
4399 is_content_initiated
&&
4400 // Must be targeted at the current tab.
4401 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4402 // Must be a JavaScript navigation, which appears as "other".
4403 info
.navigationType
== blink::WebNavigationTypeOther
;
4406 // Open the URL via the browser, not via WebKit.
4407 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4408 return blink::WebNavigationPolicyIgnore
;
4411 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4412 // This includes navigations with no request being sent to the network stack.
4413 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4414 switches::kEnableBrowserSideNavigation
) &&
4415 info
.urlRequest
.checkForBrowserSideNavigation() &&
4416 ShouldMakeNetworkRequestForURL(url
)) {
4417 BeginNavigation(&info
.urlRequest
);
4418 return blink::WebNavigationPolicyIgnore
;
4421 return info
.defaultPolicy
;
4424 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4426 const Referrer
& referrer
,
4427 WebNavigationPolicy policy
) {
4428 DCHECK_EQ(frame_
, frame
);
4430 FrameHostMsg_OpenURL_Params params
;
4432 params
.referrer
= referrer
;
4433 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4434 WebDataSource
* ds
= frame
->provisionalDataSource();
4436 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4437 NavigationStateImpl
* navigation_state
=
4438 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4439 if (navigation_state
->IsContentInitiated()) {
4440 params
.should_replace_current_entry
=
4441 ds
->replacesCurrentHistoryItem() &&
4442 render_view_
->history_list_length_
;
4444 // This is necessary to preserve the should_replace_current_entry value on
4445 // cross-process redirects, in the event it was set by a previous process.
4447 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4448 // NavigationState::should_replace_current_entry().
4449 params
.should_replace_current_entry
=
4450 navigation_state
->common_params().should_replace_current_entry
;
4453 params
.should_replace_current_entry
= false;
4455 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4456 if (GetContentClient()->renderer()->AllowPopup())
4457 params
.user_gesture
= true;
4459 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4460 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4461 policy
== blink::WebNavigationPolicyNewWindow
||
4462 policy
== blink::WebNavigationPolicyNewPopup
) {
4463 WebUserGestureIndicator::consumeUserGesture();
4466 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4469 void RenderFrameImpl::NavigateInternal(
4470 const CommonNavigationParams
& common_params
,
4471 const StartNavigationParams
& start_params
,
4472 const RequestNavigationParams
& request_params
,
4473 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4474 bool browser_side_navigation
=
4475 base::CommandLine::ForCurrentProcess()->HasSwitch(
4476 switches::kEnableBrowserSideNavigation
);
4477 bool is_reload
= IsReload(common_params
.navigation_type
);
4478 bool is_history_navigation
= request_params
.page_state
.IsValid();
4479 WebURLRequest::CachePolicy cache_policy
=
4480 WebURLRequest::UseProtocolCachePolicy
;
4481 RenderFrameImpl::PrepareRenderViewForNavigation(
4482 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4484 GetContentClient()->SetActiveURL(common_params
.url
);
4486 // If this frame isn't in the same process as the main frame, it may naively
4487 // assume that this is the first navigation in the iframe, but this may not
4488 // actually be the case. Inform the frame's state machine if this frame has
4489 // already committed other loads.
4490 if (request_params
.has_committed_real_load
&& frame_
->parent())
4491 frame_
->setCommittedFirstRealLoad();
4493 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4494 // We cannot reload if we do not have any history state. This happens, for
4495 // example, when recovering from a crash.
4497 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4500 pending_navigation_params_
.reset(
4501 new NavigationParams(common_params
, start_params
, request_params
));
4503 // Create parameters for a standard navigation.
4504 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4505 bool should_load_request
= false;
4506 WebHistoryItem item_for_history_navigation
;
4507 WebURLRequest request
= CreateURLRequestForNavigation(
4508 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4509 #if defined(OS_ANDROID)
4510 request
.setHasUserGesture(start_params
.has_user_gesture
);
4513 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4514 // navigation for this request (since it already went to the browser).
4515 if (browser_side_navigation
)
4516 request
.setCheckForBrowserSideNavigation(false);
4518 // If we are reloading, then use the history state of the current frame.
4519 // Otherwise, if we have history state, then we need to navigate to it, which
4520 // corresponds to a back/forward navigation event. Update the parameters
4521 // depending on the navigation type.
4523 bool ignore_cache
= (common_params
.navigation_type
==
4524 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4525 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4526 : blink::WebFrameLoadType::Reload
;
4528 if (!browser_side_navigation
) {
4529 const GURL override_url
=
4530 (common_params
.navigation_type
==
4531 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4534 request
= frame_
->requestForReload(load_type
, override_url
);
4536 should_load_request
= true;
4537 } else if (is_history_navigation
) {
4538 // We must know the page ID of the page we are navigating back to.
4539 DCHECK_NE(request_params
.page_id
, -1);
4540 // We must know the nav entry ID of the page we are navigating back to,
4541 // which should be the case because history navigations are routed via the
4543 DCHECK_NE(0, request_params
.nav_entry_id
);
4544 scoped_ptr
<HistoryEntry
> entry
=
4545 PageStateToHistoryEntry(request_params
.page_state
);
4547 // Ensure we didn't save the swapped out URL in UpdateState, since the
4548 // browser should never be telling us to navigate to swappedout://.
4549 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4551 if (!browser_side_navigation
) {
4552 scoped_ptr
<NavigationParams
> navigation_params(
4553 new NavigationParams(*pending_navigation_params_
.get()));
4554 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4555 // By default, tell the HistoryController to go the deserialized
4556 // HistoryEntry. This only works if all frames are in the same
4558 DCHECK(!frame_
->parent());
4559 render_view_
->history_controller()->GoToEntry(
4560 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4562 // In --site-per-process, the browser process sends a single
4563 // WebHistoryItem destined for this frame.
4564 // TODO(creis): Change PageState to FrameState. In the meantime, we
4565 // store the relevant frame's WebHistoryItem in the root of the
4567 SetPendingNavigationParams(navigation_params
.Pass());
4568 blink::WebHistoryItem history_item
= entry
->root();
4569 blink::WebHistoryLoadType load_type
=
4570 request_params
.is_same_document_history_load
4571 ? blink::WebHistorySameDocumentLoad
4572 : blink::WebHistoryDifferentDocumentLoad
;
4574 // Let the history controller know the provisional entry, since it is
4575 // used at commit time. Otherwise skip GoToEntry and navigate the
4577 // TODO(creis): Consider cloning the current entry to handle subframe
4578 // cases. Changes to SendUpdateState might affect this.
4579 render_view_
->history_controller()->set_provisional_entry(
4581 WebURLRequest request
=
4582 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4583 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4584 history_item
, load_type
);
4587 // TODO(clamy): this should be set to the HistoryItem sent by the
4588 // browser once the HistoryController has moved to the browser.
4589 // TODO(clamy): distinguish between different document and same document
4591 // TODO(clamy): update this for subframes history loads.
4592 item_for_history_navigation
=
4593 entry
->GetHistoryNodeForFrame(this)->item();
4594 load_type
= blink::WebFrameLoadType::BackForward
;
4595 should_load_request
= true;
4599 // Navigate to the given URL.
4600 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4601 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4602 start_params
.extra_headers
.end(),
4605 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4606 WebString::fromUTF8(i
.values()));
4610 if (start_params
.is_post
&& !browser_side_navigation
) {
4611 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4614 WebHTTPBody http_body
;
4615 http_body
.initialize();
4616 const char* data
= nullptr;
4617 if (start_params
.browser_initiated_post_data
.size()) {
4618 data
= reinterpret_cast<const char*>(
4619 &start_params
.browser_initiated_post_data
.front());
4621 http_body
.appendData(
4622 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4623 request
.setHTTPBody(http_body
);
4626 // A session history navigation should have been accompanied by state.
4627 CHECK_EQ(request_params
.page_id
, -1);
4629 should_load_request
= true;
4632 if (should_load_request
) {
4633 // Record this before starting the load. We need a lower bound of this
4634 // time to sanitize the navigationStart override set below.
4635 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4637 // Perform a navigation to a data url if needed.
4638 if (!common_params
.base_url_for_data_url
.is_empty() ||
4639 (browser_side_navigation
&&
4640 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4641 LoadDataURL(common_params
, frame_
);
4643 // Load the request.
4644 frame_
->toWebLocalFrame()->load(request
, load_type
,
4645 item_for_history_navigation
);
4648 if (load_type
== blink::WebFrameLoadType::Standard
) {
4649 UpdateFrameNavigationTiming(frame_
,
4650 request_params
.browser_navigation_start
,
4651 renderer_navigation_start
);
4655 // In case LoadRequest failed before didCreateDataSource was called.
4656 pending_navigation_params_
.reset();
4659 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4660 const std::string
& encoding_name
) {
4661 // Only update main frame's encoding_name.
4662 if (!frame
->parent())
4663 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4666 void RenderFrameImpl::SyncSelectionIfRequired() {
4667 base::string16 text
;
4670 #if defined(ENABLE_PLUGINS)
4671 if (render_view_
->focused_pepper_plugin_
) {
4672 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4673 offset
= 0; // Pepper API does not support offset reporting.
4674 // TODO(kinaba): cut as needed.
4678 size_t location
, length
;
4679 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4680 &location
, &length
)) {
4684 range
= gfx::Range(location
, location
+ length
);
4686 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4687 blink::WebTextInputTypeNone
) {
4688 // If current focused element is editable, we will send 100 more chars
4689 // before and after selection. It is for input method surrounding text
4691 if (location
> kExtraCharsBeforeAndAfterSelection
)
4692 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4695 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4696 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4697 if (!webrange
.isNull())
4698 text
= webrange
.toPlainText();
4701 text
= frame_
->selectionAsText();
4702 // http://crbug.com/101435
4703 // In some case, frame->selectionAsText() returned text's length is not
4704 // equal to the length returned from webwidget()->caretOrSelectionRange().
4705 // So we have to set the range according to text.length().
4706 range
.set_end(range
.start() + text
.length());
4710 // Sometimes we get repeated didChangeSelection calls from webkit when
4711 // the selection hasn't actually changed. We don't want to report these
4712 // because it will cause us to continually claim the X clipboard.
4713 if (selection_text_offset_
!= offset
||
4714 selection_range_
!= range
||
4715 selection_text_
!= text
) {
4716 selection_text_
= text
;
4717 selection_text_offset_
= offset
;
4718 selection_range_
= range
;
4719 SetSelectedText(text
, offset
, range
);
4721 GetRenderWidget()->UpdateSelectionBounds();
4724 void RenderFrameImpl::InitializeUserMediaClient() {
4725 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4728 #if defined(ENABLE_WEBRTC)
4729 DCHECK(!web_user_media_client_
);
4730 web_user_media_client_
= new UserMediaClientImpl(
4732 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4733 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4737 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4738 WebMediaPlayerClient
* client
) {
4739 #if defined(ENABLE_WEBRTC)
4740 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4742 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4743 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4744 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4745 scoped_refptr
<base::SingleThreadTaskRunner
> compositor_task_runner
=
4746 RenderThreadImpl::current()->compositor_task_runner();
4747 if (!compositor_task_runner
.get())
4748 compositor_task_runner
= base::MessageLoop::current()->task_runner();
4749 return new WebMediaPlayerMS(
4750 frame_
, client
, weak_factory_
.GetWeakPtr(), new RenderMediaLog(),
4751 CreateRendererFactory(),
4752 compositor_task_runner
);
4755 #endif // defined(ENABLE_WEBRTC)
4758 scoped_ptr
<MediaStreamRendererFactory
>
4759 RenderFrameImpl::CreateRendererFactory() {
4760 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4761 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4763 return factory
.Pass();
4764 #if defined(ENABLE_WEBRTC)
4765 return scoped_ptr
<MediaStreamRendererFactory
>(
4766 new MediaStreamRendererFactoryImpl());
4768 return scoped_ptr
<MediaStreamRendererFactory
>(
4769 static_cast<MediaStreamRendererFactory
*>(NULL
));
4773 void RenderFrameImpl::PrepareRenderViewForNavigation(
4775 const RequestNavigationParams
& request_params
,
4777 WebURLRequest::CachePolicy
* cache_policy
) {
4778 DCHECK(render_view_
->webview());
4780 MaybeHandleDebugURL(url
);
4783 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4785 render_view_
->history_list_offset_
=
4786 request_params
.current_history_list_offset
;
4787 render_view_
->history_list_length_
=
4788 request_params
.current_history_list_length
;
4789 if (request_params
.should_clear_history_list
) {
4790 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4791 CHECK_EQ(0, render_view_
->history_list_length_
);
4794 if (!is_swapped_out_
|| frame_
->parent())
4797 // This is a swapped out main frame, so swap the renderer back in.
4798 // We marked the view as hidden when swapping the view out, so be sure to
4799 // reset the visibility state before navigating to the new URL.
4800 render_view_
->webview()->setVisibilityState(
4801 render_view_
->visibilityState(), false);
4803 // If this is an attempt to reload while we are swapped out, we should not
4804 // reload swappedout://, but the previous page, which is stored in
4805 // params.state. Setting is_reload to false will treat this like a back
4806 // navigation to accomplish that.
4808 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4810 // We refresh timezone when a view is swapped in since timezone
4811 // can get out of sync when the system timezone is updated while
4812 // the view is swapped out.
4813 RenderThreadImpl::NotifyTimezoneChange();
4815 render_view_
->SetSwappedOut(false);
4816 is_swapped_out_
= false;
4820 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4821 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4822 switches::kEnableBrowserSideNavigation
));
4824 // TODO(clamy): Execute the beforeunload event.
4826 // Note: At this stage, the goal is to apply all the modifications the
4827 // renderer wants to make to the request, and then send it to the browser, so
4828 // that the actual network request can be started. Ideally, all such
4829 // modifications should take place in willSendRequest, and in the
4830 // implementation of willSendRequest for the various InspectorAgents
4833 // TODO(clamy): Apply devtools override.
4834 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4836 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4838 // TODO(clamy): Same-document navigations should not be sent back to the
4840 // TODO(clamy): Data urls should not be sent back to the browser either.
4841 bool should_replace_current_entry
= false;
4842 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4843 WebDataSource
* current_data_source
= frame_
->dataSource();
4844 WebDataSource
* data_source
=
4845 provisional_data_source
? provisional_data_source
: current_data_source
;
4847 // The current entry can only be replaced if there already is an entry in the
4849 if (data_source
&& render_view_
->history_list_length_
> 0) {
4850 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4852 Send(new FrameHostMsg_BeginNavigation(
4854 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4855 BeginNavigationParams(
4856 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4857 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4858 GetRequestBodyForWebURLRequest(*request
)));
4861 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4863 // A loadData request with a specified base URL.
4864 std::string mime_type
, charset
, data
;
4865 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4866 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4867 params
.url
: params
.base_url_for_data_url
;
4869 WebData(data
.c_str(), data
.length()),
4870 WebString::fromUTF8(mime_type
),
4871 WebString::fromUTF8(charset
),
4873 params
.history_url_for_data_url
,
4876 CHECK(false) << "Invalid URL passed: "
4877 << params
.url
.possibly_invalid_spec();
4881 void RenderFrameImpl::SendFailedProvisionalLoad(
4882 const blink::WebURLRequest
& request
,
4883 const blink::WebURLError
& error
,
4884 blink::WebLocalFrame
* frame
) {
4885 bool show_repost_interstitial
=
4886 (error
.reason
== net::ERR_CACHE_MISS
&&
4887 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4889 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4890 params
.error_code
= error
.reason
;
4891 GetContentClient()->renderer()->GetNavigationErrorStrings(
4892 render_view_
.get(), frame
, request
, error
, NULL
,
4893 ¶ms
.error_description
);
4894 params
.url
= error
.unreachableURL
;
4895 params
.showing_repost_interstitial
= show_repost_interstitial
;
4896 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4897 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4900 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4902 const GURL
& unreachable_url
) {
4903 // Don't display an error page if this is simply a cancelled load. Aside
4904 // from being dumb, Blink doesn't expect it and it will cause a crash.
4905 if (error_code
== net::ERR_ABORTED
)
4908 // Don't display "client blocked" error page if browser has asked us not to.
4909 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4910 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4914 // Allow the embedder to suppress an error page.
4915 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4916 this, unreachable_url
)) {
4920 if (RenderThreadImpl::current() &&
4921 RenderThreadImpl::current()->layout_test_mode()) {
4928 GURL
RenderFrameImpl::GetLoadingUrl() const {
4929 WebDataSource
* ds
= frame_
->dataSource();
4930 if (ds
->hasUnreachableURL())
4931 return ds
->unreachableURL();
4933 const WebURLRequest
& request
= ds
->request();
4934 return request
.url();
4937 void RenderFrameImpl::PopulateDocumentStateFromPending(
4938 DocumentState
* document_state
) {
4939 document_state
->set_request_time(
4940 pending_navigation_params_
->request_params
.request_time
);
4942 InternalDocumentStateData
* internal_data
=
4943 InternalDocumentStateData::FromDocumentState(document_state
);
4945 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4946 url::kJavaScriptScheme
) &&
4947 pending_navigation_params_
->common_params
.navigation_type
==
4948 FrameMsg_Navigate_Type::RESTORE
) {
4949 // We're doing a load of a page that was restored from the last session. By
4950 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4951 // can result in stale data for pages that are set to expire. We explicitly
4952 // override that by setting the policy here so that as necessary we load
4953 // from the network.
4955 // TODO(davidben): Remove this in favor of passing a cache policy to the
4956 // loadHistoryItem call in OnNavigate. That requires not overloading
4957 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4958 // policy based on load type, etc".
4959 internal_data
->set_cache_policy_override(
4960 WebURLRequest::UseProtocolCachePolicy
);
4963 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4964 document_state
->set_load_type(DocumentState::RELOAD
);
4965 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4966 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4968 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4970 internal_data
->set_is_overriding_user_agent(
4971 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4972 internal_data
->set_must_reset_scroll_and_scale_state(
4973 pending_navigation_params_
->common_params
.navigation_type
==
4974 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4975 document_state
->set_can_load_local_resources(
4976 pending_navigation_params_
->request_params
.can_load_local_resources
);
4979 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4980 // A navigation resulting from loading a javascript URL should not be treated
4981 // as a browser initiated event. Instead, we want it to look as if the page
4982 // initiated any load resulting from JS execution.
4983 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4984 url::kJavaScriptScheme
)) {
4985 return NavigationStateImpl::CreateBrowserInitiated(
4986 pending_navigation_params_
->common_params
,
4987 pending_navigation_params_
->start_params
,
4988 pending_navigation_params_
->request_params
);
4990 return NavigationStateImpl::CreateContentInitiated();
4993 #if defined(OS_ANDROID)
4994 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4995 WebMediaPlayerClient
* client
,
4996 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4997 const media::WebMediaPlayerParams
& params
) {
4998 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4999 if (SynchronousCompositorFactory
* factory
=
5000 SynchronousCompositorFactory::GetInstance()) {
5001 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
5003 GpuChannelHost
* gpu_channel_host
=
5004 RenderThreadImpl::current()->EstablishGpuChannelSync(
5005 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
5007 if (!gpu_channel_host
) {
5008 LOG(ERROR
) << "Failed to establish GPU channel for media player";
5012 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
5013 RenderThreadImpl::current()->SharedMainThreadContextProvider();
5015 if (!context_provider
.get()) {
5016 LOG(ERROR
) << "Failed to get context3d for media player";
5020 stream_texture_factory
= StreamTextureFactoryImpl::Create(
5021 context_provider
, gpu_channel_host
, routing_id_
);
5024 return new WebMediaPlayerAndroid(
5025 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
5026 GetMediaPlayerManager(), GetCdmFactory(), stream_texture_factory
, params
);
5029 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
5030 if (!media_player_manager_
)
5031 media_player_manager_
= new RendererMediaPlayerManager(this);
5032 return media_player_manager_
;
5034 #endif // defined(OS_ANDROID)
5036 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
5037 if (!media_permission_dispatcher_
)
5038 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
5039 return media_permission_dispatcher_
;
5042 #if defined(ENABLE_MOJO_MEDIA)
5043 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5044 if (!media_service_factory_
) {
5045 mojo::ServiceProviderPtr service_provider
=
5046 ConnectToApplication(GURL("mojo:media"));
5047 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5048 media_service_factory_
.set_connection_error_handler(
5049 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5050 base::Unretained(this)));
5053 return media_service_factory_
.get();
5056 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5057 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5058 // violation on the old |media_service_factory_| by outstanding
5059 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5061 // media_service_factory_.reset();
5065 bool RenderFrameImpl::AreSecureCodecsSupported() {
5066 #if defined(OS_ANDROID)
5067 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5068 return render_view_
->renderer_preferences_
5069 .use_video_overlay_for_embedded_encrypted_video
;
5072 #endif // defined(OS_ANDROID)
5075 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5076 #if defined(ENABLE_BROWSER_CDMS)
5078 cdm_manager_
= new RendererCdmManager(this);
5079 #endif // defined(ENABLE_BROWSER_CDMS)
5081 if (!cdm_factory_
) {
5084 #if defined(ENABLE_MOJO_MEDIA)
5085 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5087 cdm_factory_
.reset(new RenderCdmFactory(
5088 #if defined(ENABLE_PEPPER_CDMS)
5089 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5090 #elif defined(ENABLE_BROWSER_CDMS)
5094 #endif // defined(ENABLE_MOJO_MEDIA)
5097 return cdm_factory_
.get();
5100 void RenderFrameImpl::RegisterMojoServices() {
5101 // Only main frame have ImageDownloader service.
5102 if (!frame_
->parent()) {
5103 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5104 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5105 base::Unretained(this)));
5109 mojo::ServiceProviderPtr
RenderFrameImpl::ConnectToApplication(
5111 DCHECK(mojo_shell_
);
5112 mojo::ServiceProviderPtr service_provider
;
5113 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5114 request
->url
= mojo::String::From(url
);
5115 mojo_shell_
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5117 base::Bind(&OnGotContentHandlerID
));
5118 return service_provider
.Pass();
5121 } // namespace content