1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/time/time.h"
22 #include "cc/base/switches.h"
23 #include "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/permissions/permission_dispatcher.h"
25 #include "content/child/plugin_messages.h"
26 #include "content/child/quota_dispatcher.h"
27 #include "content/child/request_extra_data.h"
28 #include "content/child/service_worker/service_worker_handle_reference.h"
29 #include "content/child/service_worker/service_worker_network_provider.h"
30 #include "content/child/service_worker/service_worker_provider_context.h"
31 #include "content/child/service_worker/web_service_worker_provider_impl.h"
32 #include "content/child/v8_value_converter_impl.h"
33 #include "content/child/web_url_loader_impl.h"
34 #include "content/child/web_url_request_util.h"
35 #include "content/child/webmessageportchannel_impl.h"
36 #include "content/child/websocket_bridge.h"
37 #include "content/child/weburlresponse_extradata_impl.h"
38 #include "content/common/accessibility_messages.h"
39 #include "content/common/clipboard_messages.h"
40 #include "content/common/frame_messages.h"
41 #include "content/common/frame_replication_state.h"
42 #include "content/common/input_messages.h"
43 #include "content/common/navigation_params.h"
44 #include "content/common/service_worker/service_worker_types.h"
45 #include "content/common/site_isolation_policy.h"
46 #include "content/common/swapped_out_messages.h"
47 #include "content/common/view_messages.h"
48 #include "content/public/common/bindings_policy.h"
49 #include "content/public/common/content_constants.h"
50 #include "content/public/common/content_switches.h"
51 #include "content/public/common/context_menu_params.h"
52 #include "content/public/common/isolated_world_ids.h"
53 #include "content/public/common/page_state.h"
54 #include "content/public/common/resource_response.h"
55 #include "content/public/common/url_constants.h"
56 #include "content/public/common/url_utils.h"
57 #include "content/public/renderer/browser_plugin_delegate.h"
58 #include "content/public/renderer/content_renderer_client.h"
59 #include "content/public/renderer/context_menu_client.h"
60 #include "content/public/renderer/document_state.h"
61 #include "content/public/renderer/navigation_state.h"
62 #include "content/public/renderer/render_frame_observer.h"
63 #include "content/public/renderer/renderer_ppapi_host.h"
64 #include "content/renderer/accessibility/renderer_accessibility.h"
65 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
66 #include "content/renderer/browser_plugin/browser_plugin.h"
67 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
68 #include "content/renderer/child_frame_compositing_helper.h"
69 #include "content/renderer/context_menu_params_builder.h"
70 #include "content/renderer/devtools/devtools_agent.h"
71 #include "content/renderer/dom_automation_controller.h"
72 #include "content/renderer/external_popup_menu.h"
73 #include "content/renderer/geolocation_dispatcher.h"
74 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
75 #include "content/renderer/history_controller.h"
76 #include "content/renderer/history_serialization.h"
77 #include "content/renderer/image_downloader/image_downloader_impl.h"
78 #include "content/renderer/ime_event_guard.h"
79 #include "content/renderer/internal_document_state_data.h"
80 #include "content/renderer/manifest/manifest_manager.h"
81 #include "content/renderer/media/audio_renderer_mixer_manager.h"
82 #include "content/renderer/media/crypto/render_cdm_factory.h"
83 #include "content/renderer/media/media_permission_dispatcher.h"
84 #include "content/renderer/media/media_stream_dispatcher.h"
85 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
86 #include "content/renderer/media/midi_dispatcher.h"
87 #include "content/renderer/media/render_media_log.h"
88 #include "content/renderer/media/user_media_client_impl.h"
89 #include "content/renderer/media/webmediaplayer_ms.h"
90 #include "content/renderer/memory_benchmarking_extension.h"
91 #include "content/renderer/mojo/service_registry_js_wrapper.h"
92 #include "content/renderer/navigation_state_impl.h"
93 #include "content/renderer/notification_permission_dispatcher.h"
94 #include "content/renderer/npapi/plugin_channel_host.h"
95 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
96 #include "content/renderer/presentation/presentation_dispatcher.h"
97 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
98 #include "content/renderer/render_frame_proxy.h"
99 #include "content/renderer/render_process.h"
100 #include "content/renderer/render_thread_impl.h"
101 #include "content/renderer/render_view_impl.h"
102 #include "content/renderer/render_widget_fullscreen_pepper.h"
103 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
104 #include "content/renderer/renderer_webcolorchooser_impl.h"
105 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
106 #include "content/renderer/shared_worker_repository.h"
107 #include "content/renderer/skia_benchmarking_extension.h"
108 #include "content/renderer/stats_collection_controller.h"
109 #include "content/renderer/web_ui_extension.h"
110 #include "content/renderer/websharedworker_proxy.h"
111 #include "gin/modules/module_registry.h"
112 #include "media/base/audio_renderer_mixer_input.h"
113 #include "media/base/media_log.h"
114 #include "media/blink/webencryptedmediaclient_impl.h"
115 #include "media/blink/webmediaplayer_impl.h"
116 #include "media/blink/webmediaplayer_params.h"
117 #include "media/renderers/gpu_video_accelerator_factories.h"
118 #include "mojo/common/url_type_converters.h"
119 #include "net/base/data_url.h"
120 #include "net/base/net_errors.h"
121 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
122 #include "net/http/http_util.h"
123 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
124 #include "third_party/WebKit/public/platform/WebString.h"
125 #include "third_party/WebKit/public/platform/WebURL.h"
126 #include "third_party/WebKit/public/platform/WebURLError.h"
127 #include "third_party/WebKit/public/platform/WebURLResponse.h"
128 #include "third_party/WebKit/public/platform/WebVector.h"
129 #include "third_party/WebKit/public/platform/modules/webusb/WebUSBClient.h"
130 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
131 #include "third_party/WebKit/public/web/WebDocument.h"
132 #include "third_party/WebKit/public/web/WebFrameWidget.h"
133 #include "third_party/WebKit/public/web/WebGlyphCache.h"
134 #include "third_party/WebKit/public/web/WebKit.h"
135 #include "third_party/WebKit/public/web/WebLocalFrame.h"
136 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
137 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
138 #include "third_party/WebKit/public/web/WebPlugin.h"
139 #include "third_party/WebKit/public/web/WebPluginParams.h"
140 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
141 #include "third_party/WebKit/public/web/WebRange.h"
142 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
143 #include "third_party/WebKit/public/web/WebScriptSource.h"
144 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
145 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
146 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
147 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
148 #include "third_party/WebKit/public/web/WebSettings.h"
149 #include "third_party/WebKit/public/web/WebSurroundingText.h"
150 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
151 #include "third_party/WebKit/public/web/WebView.h"
152 #include "third_party/mojo/src/mojo/edk/js/core.h"
153 #include "third_party/mojo/src/mojo/edk/js/support.h"
154 #include "url/url_util.h"
156 #if defined(ENABLE_PLUGINS)
157 #include "content/renderer/npapi/webplugin_impl.h"
158 #include "content/renderer/pepper/pepper_browser_connection.h"
159 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
160 #include "content/renderer/pepper/pepper_webplugin_impl.h"
161 #include "content/renderer/pepper/plugin_module.h"
164 #if defined(ENABLE_WEBRTC)
165 #include "content/renderer/media/rtc_peer_connection_handler.h"
168 #if defined(OS_ANDROID)
169 #include <cpu-features.h>
171 #include "content/common/gpu/client/context_provider_command_buffer.h"
172 #include "content/renderer/android/synchronous_compositor_factory.h"
173 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
174 #include "content/renderer/media/android/renderer_media_player_manager.h"
175 #include "content/renderer/media/android/stream_texture_factory_impl.h"
176 #include "content/renderer/media/android/webmediaplayer_android.h"
178 #include "cc/blink/context_provider_web_context.h"
179 #include "content/renderer/usb/web_usb_client_impl.h"
180 #include "device/devices_app/public/cpp/constants.h"
183 #if defined(ENABLE_PEPPER_CDMS)
184 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
185 #elif defined(ENABLE_BROWSER_CDMS)
186 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
189 #if defined(ENABLE_MOJO_MEDIA)
190 #include "media/mojo/services/mojo_cdm_factory.h"
191 #include "media/mojo/services/mojo_renderer_factory.h"
192 #include "mojo/application/public/cpp/connect.h"
193 #include "mojo/application/public/interfaces/shell.mojom.h"
194 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
196 #include "media/renderers/default_renderer_factory.h"
199 #if defined(ENABLE_WEBVR)
200 #include "content/renderer/vr/vr_dispatcher.h"
203 using blink::WebContentDecryptionModule
;
204 using blink::WebContextMenuData
;
205 using blink::WebData
;
206 using blink::WebDataSource
;
207 using blink::WebDocument
;
208 using blink::WebDOMEvent
;
209 using blink::WebDOMMessageEvent
;
210 using blink::WebElement
;
211 using blink::WebExternalPopupMenu
;
212 using blink::WebExternalPopupMenuClient
;
213 using blink::WebFrame
;
214 using blink::WebHistoryItem
;
215 using blink::WebHTTPBody
;
216 using blink::WebLocalFrame
;
217 using blink::WebMediaPlayer
;
218 using blink::WebMediaPlayerClient
;
219 using blink::WebMediaPlayerEncryptedMediaClient
;
220 using blink::WebNavigationPolicy
;
221 using blink::WebNavigationType
;
222 using blink::WebNode
;
223 using blink::WebPluginParams
;
224 using blink::WebPopupMenuInfo
;
225 using blink::WebRange
;
226 using blink::WebReferrerPolicy
;
227 using blink::WebScriptSource
;
228 using blink::WebSearchableFormData
;
229 using blink::WebSecurityOrigin
;
230 using blink::WebSecurityPolicy
;
231 using blink::WebSerializedScriptValue
;
232 using blink::WebServiceWorkerProvider
;
233 using blink::WebSettings
;
234 using blink::WebStorageQuotaCallbacks
;
235 using blink::WebString
;
237 using blink::WebURLError
;
238 using blink::WebURLRequest
;
239 using blink::WebURLResponse
;
240 using blink::WebUserGestureIndicator
;
241 using blink::WebVector
;
242 using blink::WebView
;
244 using base::TimeDelta
;
250 const char kDefaultAcceptHeader
[] =
251 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
253 const char kAcceptHeader
[] = "Accept";
255 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
257 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
258 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
259 LAZY_INSTANCE_INITIALIZER
;
261 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
262 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
264 int64
ExtractPostId(HistoryEntry
* entry
) {
268 const WebHistoryItem
& item
= entry
->root();
269 if (item
.isNull() || item
.httpBody().isNull())
272 return item
.httpBody().identifier();
275 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
276 const WebURLResponse
& response
) {
277 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
280 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
281 // Replace any occurrences of swappedout:// with about:blank.
282 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
283 WebVector
<WebURL
> urls
;
284 ds
->redirectChain(urls
);
285 result
->reserve(urls
.size());
286 for (size_t i
= 0; i
< urls
.size(); ++i
) {
287 if (urls
[i
] != GURL(kSwappedOutURL
))
288 result
->push_back(urls
[i
]);
290 result
->push_back(blank_url
);
294 // Returns the original request url. If there is no redirect, the original
295 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
296 // frame was loaded by loadData, the original url will be ds->unreachableURL()
297 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
298 // WebDataSource has unreachable URL means that the frame is loaded through
299 // blink::WebFrame::loadData(), and the base URL will be in the redirect
300 // chain. However, we never visited the baseURL. So in this case, we should
301 // use the unreachable URL as the original URL.
302 if (ds
->hasUnreachableURL())
303 return ds
->unreachableURL();
305 std::vector
<GURL
> redirects
;
306 GetRedirectChain(ds
, &redirects
);
307 if (!redirects
.empty())
308 return redirects
.at(0);
310 return ds
->originalRequest().url();
313 NOINLINE
void CrashIntentionally() {
314 // NOTE(shess): Crash directly rather than using NOTREACHED() so
315 // that the signature is easier to triage in crash reports.
316 volatile int* zero
= NULL
;
320 NOINLINE
void BadCastCrashIntentionally() {
333 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
334 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
335 // NOTE(rogerm): We intentionally perform an invalid heap access here in
336 // order to trigger an Address Sanitizer (ASAN) error report.
337 const char kCrashDomain
[] = "crash";
338 const char kHeapOverflow
[] = "/heap-overflow";
339 const char kHeapUnderflow
[] = "/heap-underflow";
340 const char kUseAfterFree
[] = "/use-after-free";
341 #if defined(SYZYASAN)
342 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
343 const char kCorruptHeap
[] = "/corrupt-heap";
346 if (!url
.DomainIs(kCrashDomain
))
352 std::string
crash_type(url
.path());
353 if (crash_type
== kHeapOverflow
) {
354 base::debug::AsanHeapOverflow();
355 } else if (crash_type
== kHeapUnderflow
) {
356 base::debug::AsanHeapUnderflow();
357 } else if (crash_type
== kUseAfterFree
) {
358 base::debug::AsanHeapUseAfterFree();
359 #if defined(SYZYASAN)
360 } else if (crash_type
== kCorruptHeapBlock
) {
361 base::debug::AsanCorruptHeapBlock();
362 } else if (crash_type
== kCorruptHeap
) {
363 base::debug::AsanCorruptHeap();
367 #endif // ADDRESS_SANITIZER || SYZYASAN
369 void MaybeHandleDebugURL(const GURL
& url
) {
370 if (!url
.SchemeIs(kChromeUIScheme
))
372 if (url
== GURL(kChromeUIBadCastCrashURL
)) {
373 BadCastCrashIntentionally();
374 } else if (url
== GURL(kChromeUICrashURL
)) {
375 CrashIntentionally();
376 } else if (url
== GURL(kChromeUIDumpURL
)) {
377 // This URL will only correctly create a crash dump file if content is
378 // hosted in a process that has correctly called
379 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
380 // of base::debug::DumpWithoutCrashing for more details.
381 base::debug::DumpWithoutCrashing();
382 } else if (url
== GURL(kChromeUIKillURL
)) {
383 base::Process::Current().Terminate(1, false);
384 } else if (url
== GURL(kChromeUIHangURL
)) {
386 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
388 } else if (url
== GURL(kChromeUIShorthangURL
)) {
389 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
392 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
393 MaybeTriggerAsanError(url
);
394 #endif // ADDRESS_SANITIZER || SYZYASAN
397 // Returns false unless this is a top-level navigation.
398 bool IsTopLevelNavigation(WebFrame
* frame
) {
399 return frame
->parent() == NULL
;
402 // Returns false unless this is a top-level navigation that crosses origins.
403 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
405 WebNavigationType type
,
407 if (!IsTopLevelNavigation(frame
))
410 // Navigations initiated within Webkit are not sent out to the external host
411 // in the following cases.
412 // 1. The url scheme is not http/https
413 // 2. The origin of the url and the opener is the same in which case the
414 // opener relationship is maintained.
415 // 3. Reloads/form submits/back forward navigations
416 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
419 if (type
!= blink::WebNavigationTypeReload
&&
420 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
421 // The opener relationship between the new window and the parent allows the
422 // new window to script the parent and vice versa. This is not allowed if
423 // the origins of the two domains are different. This can be treated as a
424 // top level navigation and routed back to the host.
425 blink::WebFrame
* opener
= frame
->opener();
429 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
435 WebURLRequest
CreateURLRequestForNavigation(
436 const CommonNavigationParams
& common_params
,
437 scoped_ptr
<StreamOverrideParameters
> stream_override
,
438 bool is_view_source_mode_enabled
) {
439 WebURLRequest
request(common_params
.url
);
440 if (is_view_source_mode_enabled
)
441 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
443 if (common_params
.referrer
.url
.is_valid()) {
444 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
445 common_params
.referrer
.policy
,
447 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
448 if (!web_referrer
.isEmpty())
449 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
452 RequestExtraData
* extra_data
= new RequestExtraData();
453 extra_data
->set_stream_override(stream_override
.Pass());
454 request
.setExtraData(extra_data
);
456 // Set the ui timestamp for this navigation. Currently the timestamp here is
457 // only non empty when the navigation was triggered by an Android intent. The
458 // timestamp is converted to a double version supported by blink. It will be
459 // passed back to the browser in the DidCommitProvisionalLoad and the
460 // DocumentLoadComplete IPCs.
461 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
462 request
.setUiStartTime(ui_timestamp
.InSecondsF());
463 request
.setInputPerfMetricReportPolicy(
464 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
465 common_params
.report_type
));
469 void UpdateFrameNavigationTiming(WebFrame
* frame
,
470 base::TimeTicks browser_navigation_start
,
471 base::TimeTicks renderer_navigation_start
) {
472 // The browser provides the navigation_start time to bootstrap the
473 // Navigation Timing information for the browser-initiated navigations. In
474 // case of cross-process navigations, this carries over the time of
475 // finishing the onbeforeunload handler of the previous page.
476 DCHECK(!browser_navigation_start
.is_null());
477 if (frame
->provisionalDataSource()) {
478 // |browser_navigation_start| is likely before this process existed, so we
479 // can't use InterProcessTimeTicksConverter. We need at least to ensure
480 // that the browser-side navigation start we set is not later than the one
481 // on the renderer side.
482 base::TimeTicks navigation_start
= std::min(
483 browser_navigation_start
, renderer_navigation_start
);
484 double navigation_start_seconds
=
485 (navigation_start
- base::TimeTicks()).InSecondsF();
486 frame
->provisionalDataSource()->setNavigationStartTime(
487 navigation_start_seconds
);
488 // TODO(clamy): We need to provide additional timing values for the
489 // Navigation Timing API to work with browser-side navigations.
494 CommonNavigationParams
MakeCommonNavigationParams(
495 blink::WebURLRequest
* request
,
496 bool should_replace_current_entry
) {
497 const RequestExtraData kEmptyData
;
498 const RequestExtraData
* extra_data
=
499 static_cast<RequestExtraData
*>(request
->extraData());
501 extra_data
= &kEmptyData
;
503 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
504 request
->referrerPolicy());
506 // Set the ui timestamp for this navigation. Currently the timestamp here is
507 // only non empty when the navigation was triggered by an Android intent, or
508 // by the user clicking on a link. The timestamp is converted from a double
509 // version supported by blink. It will be passed back to the renderer in the
510 // CommitNavigation IPC, and then back to the browser again in the
511 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
512 base::TimeTicks ui_timestamp
=
513 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
514 FrameMsg_UILoadMetricsReportType::Value report_type
=
515 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
516 request
->inputPerfMetricReportPolicy());
517 return CommonNavigationParams(
518 request
->url(), referrer
, extra_data
->transition_type(),
519 FrameMsg_Navigate_Type::NORMAL
, true, should_replace_current_entry
,
520 ui_timestamp
, report_type
, GURL(), GURL());
523 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
524 media::Context3D
GetSharedMainThreadContext3D() {
525 cc::ContextProvider
* provider
=
526 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
528 return media::Context3D();
529 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
533 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
534 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
535 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
536 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
539 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
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 void RenderFrameImpl::CreateFrame(
573 int parent_routing_id
,
574 int previous_sibling_routing_id
,
575 int proxy_routing_id
,
576 const FrameReplicationState
& replicated_state
,
577 CompositorDependencies
* compositor_deps
,
578 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
579 blink::WebLocalFrame
* web_frame
;
580 RenderFrameImpl
* render_frame
;
581 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
582 RenderFrameProxy
* parent_proxy
=
583 RenderFrameProxy::FromRoutingID(parent_routing_id
);
584 // If the browser is sending a valid parent routing id, it should already
585 // be created and registered.
587 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
589 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
590 RenderFrameProxy
* previous_sibling_proxy
=
591 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
592 if (previous_sibling_proxy
)
593 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
595 // Create the RenderFrame and WebLocalFrame, linking the two.
597 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
598 web_frame
= parent_web_frame
->createLocalChild(
599 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
600 replicated_state
.sandbox_flags
, render_frame
,
601 previous_sibling_web_frame
);
603 RenderFrameProxy
* proxy
=
604 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
606 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
608 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
609 render_frame
->proxy_routing_id_
= proxy_routing_id
;
610 web_frame
->initializeToReplaceRemoteFrame(
611 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
612 replicated_state
.sandbox_flags
);
614 render_frame
->SetWebFrame(web_frame
);
615 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
617 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
618 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
619 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
620 widget_params
.routing_id
, widget_params
.surface_id
,
621 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
622 compositor_deps
, web_frame
);
623 // TODO(kenrb): Observing shouldn't be necessary when we sort out
624 // WasShown and WasHidden, separating page-level visibility from
625 // frame-level visibility.
626 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
629 render_frame
->Initialize();
633 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
634 return RenderFrameImpl::FromWebFrame(web_frame
);
638 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
639 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
640 if (iter
!= g_frame_map
.Get().end())
646 void RenderFrameImpl::InstallCreateHook(
647 CreateRenderFrameImplFunction create_render_frame_impl
) {
648 CHECK(!g_create_render_frame_impl
);
649 g_create_render_frame_impl
= create_render_frame_impl
;
652 // RenderFrameImpl ----------------------------------------------------------
653 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
656 is_local_root_(false),
657 render_view_(params
.render_view
->AsWeakPtr()),
658 routing_id_(params
.routing_id
),
659 is_swapped_out_(false),
660 render_frame_proxy_(NULL
),
661 is_detaching_(false),
662 proxy_routing_id_(MSG_ROUTING_NONE
),
663 #if defined(ENABLE_PLUGINS)
664 plugin_power_saver_helper_(NULL
),
667 selection_text_offset_(0),
668 selection_range_(gfx::Range::InvalidRange()),
669 handling_select_range_(false),
670 notification_permission_dispatcher_(NULL
),
671 web_user_media_client_(NULL
),
672 media_permission_dispatcher_(NULL
),
673 midi_dispatcher_(NULL
),
674 #if defined(OS_ANDROID)
675 media_player_manager_(NULL
),
677 #if defined(ENABLE_BROWSER_CDMS)
680 #if defined(VIDEO_HOLE)
681 contains_media_player_(false),
683 has_played_media_(false),
684 devtools_agent_(nullptr),
685 geolocation_dispatcher_(NULL
),
686 push_messaging_dispatcher_(NULL
),
687 presentation_dispatcher_(NULL
),
688 screen_orientation_dispatcher_(NULL
),
689 manifest_manager_(NULL
),
690 accessibility_mode_(AccessibilityModeOff
),
691 renderer_accessibility_(NULL
),
692 weak_factory_(this) {
693 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
694 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
695 CHECK(result
.second
) << "Inserting a duplicate item.";
697 RenderThread::Get()->AddRoute(routing_id_
, this);
699 render_view_
->RegisterRenderFrame(this);
701 // Everything below subclasses RenderFrameObserver and is automatically
702 // deleted when the RenderFrame gets deleted.
703 #if defined(OS_ANDROID)
704 new GinJavaBridgeDispatcher(this);
707 #if defined(ENABLE_PLUGINS)
708 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
711 manifest_manager_
= new ManifestManager(this);
713 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_
));
716 RenderFrameImpl::~RenderFrameImpl() {
717 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
718 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
720 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
722 #if defined(VIDEO_HOLE)
723 if (contains_media_player_
)
724 render_view_
->UnregisterVideoHoleFrame(this);
728 // When using swapped out frames, RenderFrameProxy is owned by
729 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
730 // along with this object.
731 if (render_frame_proxy_
&&
732 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
733 // The following method calls back into this object and clears
734 // |render_frame_proxy_|.
735 render_frame_proxy_
->frameDetached(
736 blink::WebRemoteFrameClient::DetachType::Remove
);
739 // Ensure the RenderView doesn't point to this object, once it is destroyed.
740 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
741 // is |this|, once the object is no longer leaked.
742 // See https://crbug.com/464764.
743 render_view_
->main_render_frame_
= nullptr;
746 render_view_
->UnregisterRenderFrame(this);
747 g_routing_id_frame_map
.Get().erase(routing_id_
);
748 RenderThread::Get()->RemoveRoute(routing_id_
);
751 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
754 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
755 std::make_pair(web_frame
, this));
756 CHECK(result
.second
) << "Inserting a duplicate item.";
761 void RenderFrameImpl::Initialize() {
762 is_subframe_
= !!frame_
->parent();
763 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
765 #if defined(ENABLE_PLUGINS)
766 new PepperBrowserConnection(this);
768 new SharedWorkerRepository(this);
770 if (is_local_root_
&& !render_frame_proxy_
) {
771 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
772 // when |this| is deleted.
773 devtools_agent_
= new DevToolsAgent(this);
776 RegisterMojoServices();
778 // We delay calling this until we have the WebFrame so that any observer or
779 // embedder can call GetWebFrame on any RenderFrame.
780 GetContentClient()->renderer()->RenderFrameCreated(this);
783 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
784 return render_view_
.get();
787 #if defined(ENABLE_PLUGINS)
788 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
789 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
790 DidCreatePepperPlugin(host
));
791 if (host
->GetPluginName() == kFlashPluginName
) {
792 RenderThread::Get()->RecordAction(
793 base::UserMetricsAction("FrameLoadWithFlash"));
797 void RenderFrameImpl::PepperDidChangeCursor(
798 PepperPluginInstanceImpl
* instance
,
799 const blink::WebCursorInfo
& cursor
) {
800 // Update the cursor appearance immediately if the requesting plugin is the
801 // one which receives the last mouse event. Otherwise, the new cursor won't be
802 // picked up until the plugin gets the next input event. That is bad if, e.g.,
803 // the plugin would like to set an invisible cursor when there isn't any user
804 // input for a while.
805 if (instance
== render_view_
->pepper_last_mouse_event_target())
806 GetRenderWidget()->didChangeCursor(cursor
);
809 void RenderFrameImpl::PepperDidReceiveMouseEvent(
810 PepperPluginInstanceImpl
* instance
) {
811 render_view_
->set_pepper_last_mouse_event_target(instance
);
814 void RenderFrameImpl::PepperTextInputTypeChanged(
815 PepperPluginInstanceImpl
* instance
) {
816 if (instance
!= render_view_
->focused_pepper_plugin())
819 GetRenderWidget()->UpdateTextInputState(
820 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
822 FocusedNodeChangedForAccessibility(WebNode());
825 void RenderFrameImpl::PepperCaretPositionChanged(
826 PepperPluginInstanceImpl
* instance
) {
827 if (instance
!= render_view_
->focused_pepper_plugin())
829 GetRenderWidget()->UpdateSelectionBounds();
832 void RenderFrameImpl::PepperCancelComposition(
833 PepperPluginInstanceImpl
* instance
) {
834 if (instance
!= render_view_
->focused_pepper_plugin())
836 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
837 #if defined(OS_MACOSX) || defined(USE_AURA)
838 GetRenderWidget()->UpdateCompositionInfo(true);
842 void RenderFrameImpl::PepperSelectionChanged(
843 PepperPluginInstanceImpl
* instance
) {
844 if (instance
!= render_view_
->focused_pepper_plugin())
846 SyncSelectionIfRequired();
849 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
850 PepperPluginInstanceImpl
* plugin
) {
852 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
853 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
854 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
855 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
856 plugin
, active_url
, GetRenderWidget()->screenInfo());
857 widget
->show(blink::WebNavigationPolicyIgnore
);
861 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
862 if (!render_view_
->focused_pepper_plugin())
864 return render_view_
->focused_pepper_plugin()->
865 IsPluginAcceptingCompositionEvents();
868 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
869 base::ProcessId plugin_pid
) {
870 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
871 // routing_id_ as a result.
872 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
875 void RenderFrameImpl::SimulateImeSetComposition(
876 const base::string16
& text
,
877 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
880 render_view_
->OnImeSetComposition(
881 text
, underlines
, selection_start
, selection_end
);
884 void RenderFrameImpl::SimulateImeConfirmComposition(
885 const base::string16
& text
,
886 const gfx::Range
& replacement_range
) {
887 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
890 void RenderFrameImpl::OnImeSetComposition(
891 const base::string16
& text
,
892 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
895 // When a PPAPI plugin has focus, we bypass WebKit.
896 if (!IsPepperAcceptingCompositionEvents()) {
897 pepper_composition_text_
= text
;
899 // TODO(kinaba) currently all composition events are sent directly to
900 // plugins. Use DOM event mechanism after WebKit is made aware about
901 // plugins that support composition.
902 // The code below mimics the behavior of WebCore::Editor::setComposition.
904 // Empty -> nonempty: composition started.
905 if (pepper_composition_text_
.empty() && !text
.empty()) {
906 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
909 // Nonempty -> empty: composition canceled.
910 if (!pepper_composition_text_
.empty() && text
.empty()) {
911 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
914 pepper_composition_text_
= text
;
915 // Nonempty: composition is ongoing.
916 if (!pepper_composition_text_
.empty()) {
917 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
918 pepper_composition_text_
, underlines
, selection_start
,
924 void RenderFrameImpl::OnImeConfirmComposition(
925 const base::string16
& text
,
926 const gfx::Range
& replacement_range
,
927 bool keep_selection
) {
928 // When a PPAPI plugin has focus, we bypass WebKit.
929 // Here, text.empty() has a special meaning. It means to commit the last
930 // update of composition text (see
931 // RenderWidgetHost::ImeConfirmComposition()).
932 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
935 // last_text is empty only when both text and pepper_composition_text_ is.
937 if (last_text
.empty())
940 if (!IsPepperAcceptingCompositionEvents()) {
941 base::i18n::UTF16CharIterator
iterator(&last_text
);
943 while (iterator
.Advance()) {
944 blink::WebKeyboardEvent char_event
;
945 char_event
.type
= blink::WebInputEvent::Char
;
946 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
947 char_event
.modifiers
= 0;
948 char_event
.windowsKeyCode
= last_text
[i
];
949 char_event
.nativeKeyCode
= last_text
[i
];
951 const int32 char_start
= i
;
952 for (; i
< iterator
.array_pos(); ++i
) {
953 char_event
.text
[i
- char_start
] = last_text
[i
];
954 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
957 if (GetRenderWidget()->webwidget())
958 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
961 // Mimics the order of events sent by WebKit.
962 // See WebCore::Editor::setComposition() for the corresponding code.
963 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
964 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
966 pepper_composition_text_
.clear();
968 #endif // defined(ENABLE_PLUGINS)
970 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
971 if (!web_user_media_client_
)
972 InitializeUserMediaClient();
973 return web_user_media_client_
?
974 web_user_media_client_
->media_stream_dispatcher() : NULL
;
977 bool RenderFrameImpl::Send(IPC::Message
* message
) {
982 if (is_swapped_out_
) {
983 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
989 return RenderThread::Get()->Send(message
);
992 #if defined(OS_MACOSX) || defined(OS_ANDROID)
993 void RenderFrameImpl::DidHideExternalPopupMenu() {
994 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
995 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
996 external_popup_menu_
.reset();
1000 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
1001 // We may get here while detaching, when the WebFrame has been deleted. Do
1002 // not process any messages in this state.
1006 // TODO(kenrb): document() should not be null, but as a transitional step
1007 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1008 // to this method. This happens for a top-level remote frame, where a
1009 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1010 // around and is still able to receive messages.
1011 if (!frame_
->document().isNull())
1012 GetContentClient()->SetActiveURL(frame_
->document().url());
1014 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
1015 RenderFrameObserver
* observer
;
1016 while ((observer
= it
.GetNext()) != NULL
) {
1017 if (observer
->OnMessageReceived(msg
))
1021 bool handled
= true;
1022 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1023 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1024 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1025 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1026 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1027 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1028 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1029 OnCustomContextMenuAction
)
1030 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1031 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1032 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1033 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1034 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1035 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1036 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1037 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1038 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1039 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1040 OnAdjustSelectionByCharacterOffset
)
1041 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1042 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1043 OnMoveRangeSelectionExtent
)
1044 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1045 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1046 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1047 OnExtendSelectionAndDelete
)
1048 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1049 OnSetCompositionFromExistingText
)
1050 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1051 OnExecuteNoValueEditCommand
)
1052 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1053 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1054 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1055 OnJavaScriptExecuteRequest
)
1056 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1057 OnJavaScriptExecuteRequestForTests
)
1058 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1059 OnJavaScriptExecuteRequestInIsolatedWorld
)
1060 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1061 OnVisualStateRequest
)
1062 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1063 OnSetEditableSelectionOffsets
)
1064 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1065 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1066 OnTextSurroundingSelectionRequest
)
1067 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1068 OnSetAccessibilityMode
)
1069 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1070 OnSnapshotAccessibilityTree
)
1071 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1072 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1073 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1074 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1075 OnTextTrackSettingsChanged
)
1076 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1077 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1078 #if defined(OS_ANDROID)
1079 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1080 #elif defined(OS_MACOSX)
1081 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1082 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1084 IPC_END_MESSAGE_MAP()
1089 void RenderFrameImpl::OnNavigate(
1090 const CommonNavigationParams
& common_params
,
1091 const StartNavigationParams
& start_params
,
1092 const RequestNavigationParams
& request_params
) {
1093 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1094 switches::kEnableBrowserSideNavigation
));
1095 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1096 "url", common_params
.url
.possibly_invalid_spec());
1097 NavigateInternal(common_params
, start_params
, request_params
,
1098 scoped_ptr
<StreamOverrideParameters
>());
1101 void RenderFrameImpl::NavigateToSwappedOutURL() {
1102 // We use loadRequest instead of loadHTMLString because the former commits
1103 // synchronously. Otherwise a new navigation can interrupt the navigation
1104 // to kSwappedOutURL. If that happens to be to the page we had been
1105 // showing, then WebKit will never send a commit and we'll be left spinning.
1106 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1107 // the navigation to swappedout:// is not announced to the browser side.
1108 is_swapped_out_
= true;
1109 GURL
swappedOutURL(kSwappedOutURL
);
1110 WebURLRequest
request(swappedOutURL
);
1111 frame_
->loadRequest(request
);
1114 void RenderFrameImpl::BindServiceRegistry(
1115 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1116 mojo::ServiceProviderPtr exposed_services
) {
1117 service_registry_
.Bind(services
.Pass());
1118 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1121 ManifestManager
* RenderFrameImpl::manifest_manager() {
1122 return manifest_manager_
;
1125 void RenderFrameImpl::SetPendingNavigationParams(
1126 scoped_ptr
<NavigationParams
> navigation_params
) {
1127 pending_navigation_params_
= navigation_params
.Pass();
1130 void RenderFrameImpl::OnBeforeUnload() {
1131 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1133 // TODO(creis): Right now, this is only called on the main frame. Make the
1134 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1136 CHECK(!frame_
->parent());
1138 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1139 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1140 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1141 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1142 before_unload_start_time
,
1143 before_unload_end_time
));
1146 void RenderFrameImpl::OnSwapOut(
1147 int proxy_routing_id
,
1149 const FrameReplicationState
& replicated_frame_state
) {
1150 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1151 RenderFrameProxy
* proxy
= NULL
;
1152 bool swapped_out_forbidden
=
1153 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1154 bool is_main_frame
= !frame_
->parent();
1156 // This codepath should only be hit for subframes when in --site-per-process.
1157 CHECK_IMPLIES(!is_main_frame
,
1158 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1160 // Only run unload if we're not swapped out yet, but send the ack either way.
1161 if (!is_swapped_out_
) {
1162 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1163 // a different process. This involves running the unload handler and
1164 // clearing the page. We also allow this process to exit if there are no
1165 // other active RenderFrames in it.
1167 // Send an UpdateState message before we get swapped out.
1168 render_view_
->SendUpdateState();
1170 // If we need a proxy to replace this, create it now so its routing id is
1171 // registered for receiving IPC messages.
1172 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1173 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1174 this, proxy_routing_id
, replicated_frame_state
.scope
);
1177 // Synchronously run the unload handler before sending the ACK.
1178 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1179 // unload on subframes as well.
1181 frame_
->dispatchUnloadEvent();
1183 // Swap out and stop sending any IPC messages that are not ACKs.
1185 render_view_
->SetSwappedOut(true);
1186 is_swapped_out_
= true;
1188 // Set the proxy here, since OnStop() below could cause an onload event
1189 // handler to execute, which could trigger code such as
1190 // willCheckAndDispatchMessageEvent() that needs the proxy.
1192 set_render_frame_proxy(proxy
);
1194 // Now that we're swapped out and filtering IPC messages, stop loading to
1195 // ensure that no other in-progress navigation continues. We do this here
1196 // to avoid sending a DidStopLoading message to the browser process.
1197 // TODO(creis): Should we be stopping all frames here and using
1198 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1200 if (!swapped_out_forbidden
)
1203 // Transfer settings such as initial drawing parameters to the remote frame,
1204 // if one is created, that will replace this frame.
1205 if (!is_main_frame
&& proxy
)
1206 proxy
->web_frame()->initializeFromFrame(frame_
);
1208 // Replace the page with a blank dummy URL. The unload handler will not be
1209 // run a second time, thanks to a check in FrameLoader::stopLoading.
1210 // TODO(creis): Need to add a better way to do this that avoids running the
1211 // beforeunload handler. For now, we just run it a second time silently.
1212 if (!swapped_out_forbidden
)
1213 NavigateToSwappedOutURL();
1215 // Let WebKit know that this view is hidden so it can drop resources and
1216 // stop compositing.
1217 // TODO(creis): Support this for subframes as well.
1218 if (is_main_frame
) {
1219 render_view_
->webview()->setVisibilityState(
1220 blink::WebPageVisibilityStateHidden
, false);
1224 // It is now safe to show modal dialogs again.
1225 // TODO(creis): Deal with modal dialogs from subframes.
1227 render_view_
->suppress_dialogs_until_swap_out_
= false;
1229 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1231 RenderViewImpl
* render_view
= render_view_
.get();
1233 // Now that all of the cleanup is complete and the browser side is notified,
1234 // start using the RenderFrameProxy, if one is created.
1235 if (proxy
&& swapped_out_forbidden
) {
1236 frame_
->swap(proxy
->web_frame());
1239 proxy
->OnDidStartLoading();
1242 // In --site-per-process, initialize the WebRemoteFrame with the replication
1243 // state passed by the process that is now rendering the frame.
1244 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1245 // in that case we leave the LocalFrame as the main frame visible to Blink
1246 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1247 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1248 // When we do an unconditional swap for all frames, we can remove
1249 // !is_main_frame below.
1250 if (proxy
&& swapped_out_forbidden
)
1251 proxy
->SetReplicatedState(replicated_frame_state
);
1253 // Safe to exit if no one else is using the process.
1254 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1255 // the process based on the lifetime of this RenderFrameImpl object.
1256 if (is_main_frame
) {
1257 render_view
->WasSwappedOut();
1261 void RenderFrameImpl::OnContextMenuClosed(
1262 const CustomContextMenuContext
& custom_context
) {
1263 if (custom_context
.request_id
) {
1264 // External request, should be in our map.
1265 ContextMenuClient
* client
=
1266 pending_context_menus_
.Lookup(custom_context
.request_id
);
1268 client
->OnMenuClosed(custom_context
.request_id
);
1269 pending_context_menus_
.Remove(custom_context
.request_id
);
1272 if (custom_context
.link_followed
.is_valid())
1273 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1274 // Internal request, forward to WebKit.
1275 context_menu_node_
.reset();
1279 void RenderFrameImpl::OnCustomContextMenuAction(
1280 const CustomContextMenuContext
& custom_context
,
1282 if (custom_context
.request_id
) {
1283 // External context menu request, look in our map.
1284 ContextMenuClient
* client
=
1285 pending_context_menus_
.Lookup(custom_context
.request_id
);
1287 client
->OnMenuAction(custom_context
.request_id
, action
);
1289 // Internal request, forward to WebKit.
1290 render_view_
->webview()->performCustomContextMenuAction(action
);
1294 void RenderFrameImpl::OnUndo() {
1295 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1298 void RenderFrameImpl::OnRedo() {
1299 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1302 void RenderFrameImpl::OnCut() {
1303 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1304 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1307 void RenderFrameImpl::OnCopy() {
1308 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1309 WebNode current_node
= context_menu_node_
.isNull() ?
1310 GetFocusedElement() : context_menu_node_
;
1311 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1314 void RenderFrameImpl::OnPaste() {
1315 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1316 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1319 void RenderFrameImpl::OnPasteAndMatchStyle() {
1320 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1321 frame_
->executeCommand(
1322 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1325 #if defined(OS_MACOSX)
1326 void RenderFrameImpl::OnCopyToFindPboard() {
1327 // Since the find pasteboard supports only plain text, this can be simpler
1328 // than the |OnCopy()| case.
1329 if (frame_
->hasSelection()) {
1330 base::string16 selection
= frame_
->selectionAsText();
1331 RenderThread::Get()->Send(
1332 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1337 void RenderFrameImpl::OnDelete() {
1338 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1341 void RenderFrameImpl::OnSelectAll() {
1342 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1343 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1346 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1347 const gfx::Point
& extent
) {
1348 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1349 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1351 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1352 frame_
->selectRange(base
, extent
);
1355 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1357 size_t start
, length
;
1358 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1363 // Sanity checks to disallow empty and out of range selections.
1364 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1365 || static_cast<int>(start
) + start_adjust
< 0) {
1369 // A negative adjust amount moves the selection towards the beginning of
1370 // the document, a positive amount moves the selection towards the end of
1372 start
+= start_adjust
;
1373 length
+= end_adjust
- start_adjust
;
1375 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1378 void RenderFrameImpl::OnUnselect() {
1379 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1380 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1383 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1384 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1385 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1386 GetRenderWidget()->routing_id()));
1388 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1389 frame_
->moveRangeSelectionExtent(point
);
1392 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1393 if (!frame_
->hasSelection())
1394 frame_
->selectWordAroundCaret();
1396 frame_
->replaceSelection(text
);
1399 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1400 if (!frame_
->hasSelection())
1403 frame_
->replaceMisspelledRange(text
);
1406 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1407 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1410 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1411 const std::string
& message
) {
1412 AddMessageToConsole(level
, message
);
1415 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1416 const base::string16
& jscript
,
1418 bool notify_result
) {
1419 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1420 TRACE_EVENT_SCOPE_THREAD
);
1422 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1423 v8::Local
<v8::Value
> result
=
1424 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1426 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1429 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1430 const base::string16
& jscript
,
1433 bool has_user_gesture
) {
1434 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1435 TRACE_EVENT_SCOPE_THREAD
);
1437 // A bunch of tests expect to run code in the context of a user gesture, which
1438 // can grant additional privileges (e.g. the ability to create popups).
1439 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1440 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1441 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1442 v8::Local
<v8::Value
> result
=
1443 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1445 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1448 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1449 const base::string16
& jscript
,
1453 TRACE_EVENT_INSTANT0("test_tracing",
1454 "OnJavaScriptExecuteRequestInIsolatedWorld",
1455 TRACE_EVENT_SCOPE_THREAD
);
1457 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1458 world_id
> ISOLATED_WORLD_ID_MAX
) {
1459 // Return if the world_id is not valid. world_id is passed as a plain int
1460 // over IPC and needs to be verified here, in the IPC endpoint.
1465 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1466 WebScriptSource script
= WebScriptSource(jscript
);
1467 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1468 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1469 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1473 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1477 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1479 notify_result_(notify_result
),
1480 routing_id_(routing_id
),
1481 render_frame_impl_(render_frame_impl
) {
1484 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1485 ~JavaScriptIsolatedWorldRequest() {
1488 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1489 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1490 if (!render_frame_impl_
.get()) {
1494 if (notify_result_
) {
1495 base::ListValue list
;
1496 if (!result
.isEmpty()) {
1497 // It's safe to always use the main world context when converting
1498 // here. V8ValueConverterImpl shouldn't actually care about the
1499 // context scope, and it switches to v8::Object's creation context
1500 // when encountered. (from extensions/renderer/script_injection.cc)
1501 v8::Local
<v8::Context
> context
=
1502 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1503 v8::Context::Scope
context_scope(context
);
1504 V8ValueConverterImpl converter
;
1505 converter
.SetDateAllowed(true);
1506 converter
.SetRegExpAllowed(true);
1507 for (const auto& value
: result
) {
1508 scoped_ptr
<base::Value
> result_value(
1509 converter
.FromV8Value(value
, context
));
1510 list
.Append(result_value
? result_value
.Pass()
1511 : base::Value::CreateNullValue());
1514 list
.Set(0, base::Value::CreateNullValue());
1516 render_frame_impl_
.get()->Send(
1517 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1523 void RenderFrameImpl::HandleJavascriptExecutionResult(
1524 const base::string16
& jscript
,
1527 v8::Local
<v8::Value
> result
) {
1528 if (notify_result
) {
1529 base::ListValue list
;
1530 if (!result
.IsEmpty()) {
1531 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1532 v8::Context::Scope
context_scope(context
);
1533 V8ValueConverterImpl converter
;
1534 converter
.SetDateAllowed(true);
1535 converter
.SetRegExpAllowed(true);
1536 scoped_ptr
<base::Value
> result_value(
1537 converter
.FromV8Value(result
, context
));
1538 list
.Set(0, result_value
? result_value
.Pass()
1539 : base::Value::CreateNullValue());
1541 list
.Set(0, base::Value::CreateNullValue());
1543 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1547 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1548 GetRenderWidget()->QueueMessage(
1549 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1550 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1553 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1554 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1555 if (!GetRenderWidget()->ShouldHandleImeEvent())
1557 ImeEventGuard
guard(GetRenderWidget());
1558 frame_
->setEditableSelectionOffsets(start
, end
);
1561 void RenderFrameImpl::OnSetCompositionFromExistingText(
1563 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1564 if (!GetRenderWidget()->ShouldHandleImeEvent())
1566 ImeEventGuard
guard(GetRenderWidget());
1567 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1570 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1571 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1574 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1575 if (!GetRenderWidget()->ShouldHandleImeEvent())
1578 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1580 ImeEventGuard
guard(GetRenderWidget());
1581 blink::WebScopedUserGesture gesture_indicator
;
1582 frame_
->extendSelectionAndDelete(before
, after
);
1585 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1586 if (accessibility_mode_
== new_mode
)
1588 accessibility_mode_
= new_mode
;
1589 if (renderer_accessibility_
) {
1590 // Note: this isn't called automatically by the destructor because
1591 // there'd be no point in calling it in frame teardown, only if there's
1592 // an accessibility mode change but the frame is persisting.
1593 renderer_accessibility_
->DisableAccessibility();
1595 delete renderer_accessibility_
;
1596 renderer_accessibility_
= NULL
;
1598 if (accessibility_mode_
== AccessibilityModeOff
)
1601 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1602 renderer_accessibility_
= new RendererAccessibility(this);
1605 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1606 ui::AXTreeUpdate
<AXContentNodeData
> response
;
1607 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1608 Send(new AccessibilityHostMsg_SnapshotResponse(
1609 routing_id_
, callback_id
, response
));
1612 void RenderFrameImpl::OnDisownOpener() {
1613 // TODO(creis): We should only see this for main frames for now. To support
1614 // disowning the opener on subframes, we will need to move WebContentsImpl's
1615 // opener_ to FrameTreeNode.
1616 CHECK(!frame_
->parent());
1618 if (frame_
->opener())
1619 frame_
->setOpener(NULL
);
1622 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1623 frame_
->setFrameOwnerSandboxFlags(flags
);
1626 void RenderFrameImpl::OnTextTrackSettingsChanged(
1627 const FrameMsg_TextTrackSettings_Params
& params
) {
1628 DCHECK(!frame_
->parent());
1629 if (!render_view_
->webview())
1632 if (params
.text_tracks_enabled
) {
1633 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1634 WebSettings::TextTrackKindUserPreference::Captions
);
1636 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1637 WebSettings::TextTrackKindUserPreference::Default
);
1639 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1640 WebString::fromUTF8(params
.text_track_background_color
));
1641 render_view_
->webview()->settings()->setTextTrackFontFamily(
1642 WebString::fromUTF8(params
.text_track_font_family
));
1643 render_view_
->webview()->settings()->setTextTrackFontStyle(
1644 WebString::fromUTF8(params
.text_track_font_style
));
1645 render_view_
->webview()->settings()->setTextTrackFontVariant(
1646 WebString::fromUTF8(params
.text_track_font_variant
));
1647 render_view_
->webview()->settings()->setTextTrackTextColor(
1648 WebString::fromUTF8(params
.text_track_text_color
));
1649 render_view_
->webview()->settings()->setTextTrackTextShadow(
1650 WebString::fromUTF8(params
.text_track_text_shadow
));
1651 render_view_
->webview()->settings()->setTextTrackTextSize(
1652 WebString::fromUTF8(params
.text_track_text_size
));
1655 void RenderFrameImpl::OnPostMessageEvent(
1656 const FrameMsg_PostMessage_Params
& params
) {
1657 // Find the source frame if it exists.
1658 WebFrame
* source_frame
= NULL
;
1659 if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1660 RenderFrameProxy
* source_proxy
=
1661 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1663 // Currently, navigating a top-level frame cross-process does not swap
1664 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1665 // WebRemoteFrame will not have an associated blink::Frame. If this is
1666 // the case for |source_proxy|, use the corresponding (swapped-out)
1667 // WebLocalFrame instead, so that event.source for this message can be
1668 // set and used properly.
1669 if (source_proxy
->IsMainFrameDetachedFromTree())
1670 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1672 source_frame
= source_proxy
->web_frame();
1676 // If the message contained MessagePorts, create the corresponding endpoints.
1677 blink::WebMessagePortChannelArray channels
=
1678 WebMessagePortChannelImpl::CreatePorts(
1679 params
.message_ports
, params
.new_routing_ids
,
1680 base::ThreadTaskRunnerHandle::Get().get());
1682 WebSerializedScriptValue serialized_script_value
;
1683 if (params
.is_data_raw_string
) {
1684 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1685 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1686 v8::Context::Scope
context_scope(context
);
1687 V8ValueConverterImpl converter
;
1688 converter
.SetDateAllowed(true);
1689 converter
.SetRegExpAllowed(true);
1690 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1691 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1693 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1695 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1698 // Create an event with the message. The next-to-last parameter to
1699 // initMessageEvent is the last event ID, which is not used with postMessage.
1700 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1701 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1702 msg_event
.initMessageEvent("message",
1703 // |canBubble| and |cancellable| are always false
1705 serialized_script_value
,
1706 params
.source_origin
, source_frame
,
1707 frame_
->document(), "", channels
);
1709 // We must pass in the target_origin to do the security check on this side,
1710 // since it may have changed since the original postMessage call was made.
1711 WebSecurityOrigin target_origin
;
1712 if (!params
.target_origin
.empty()) {
1714 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1716 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1719 #if defined(OS_ANDROID)
1720 void RenderFrameImpl::OnSelectPopupMenuItems(
1722 const std::vector
<int>& selected_indices
) {
1723 // It is possible to receive more than one of these calls if the user presses
1724 // a select faster than it takes for the show-select-popup IPC message to make
1725 // it to the browser UI thread. Ignore the extra-messages.
1726 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1727 if (!external_popup_menu_
)
1730 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1731 external_popup_menu_
.reset();
1735 #if defined(OS_MACOSX)
1736 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1737 if (external_popup_menu_
== NULL
)
1739 external_popup_menu_
->DidSelectItem(selected_index
);
1740 external_popup_menu_
.reset();
1744 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1745 frame_
->reload(ignore_cache
);
1748 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1749 blink::WebSurroundingText surroundingText
;
1750 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1752 if (surroundingText
.isNull()) {
1753 // |surroundingText| might not be correctly initialized, for example if
1754 // |frame_->selectionRange().isNull()|, in other words, if there was no
1756 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1757 routing_id_
, base::string16(), 0, 0));
1761 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1763 surroundingText
.textContent(),
1764 surroundingText
.startOffsetInTextContent(),
1765 surroundingText
.endOffsetInTextContent()));
1768 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1769 const base::string16
& message
,
1770 const base::string16
& default_value
,
1771 const GURL
& frame_url
,
1772 base::string16
* result
) {
1773 // Don't allow further dialogs if we are waiting to swap out, since the
1774 // PageGroupLoadDeferrer in our stack prevents it.
1775 if (render_view()->suppress_dialogs_until_swap_out_
)
1778 bool success
= false;
1779 base::string16 result_temp
;
1781 result
= &result_temp
;
1783 render_view()->SendAndRunNestedMessageLoop(
1784 new FrameHostMsg_RunJavaScriptMessage(
1785 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1790 void RenderFrameImpl::LoadNavigationErrorPage(
1791 const WebURLRequest
& failed_request
,
1792 const WebURLError
& error
,
1794 std::string error_html
;
1795 GetContentClient()->renderer()->GetNavigationErrorStrings(
1796 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1798 frame_
->loadHTMLString(error_html
,
1799 GURL(kUnreachableWebDataURL
),
1800 error
.unreachableURL
,
1804 void RenderFrameImpl::DidCommitCompositorFrame() {
1805 if (BrowserPluginManager::Get())
1806 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1808 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1811 RenderView
* RenderFrameImpl::GetRenderView() {
1812 return render_view_
.get();
1815 int RenderFrameImpl::GetRoutingID() {
1819 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1824 WebElement
RenderFrameImpl::GetFocusedElement() const {
1825 WebDocument doc
= frame_
->document();
1827 return doc
.focusedElement();
1829 return WebElement();
1832 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1833 return render_view_
->GetWebkitPreferences();
1836 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1837 const ContextMenuParams
& params
) {
1838 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1839 ContextMenuParams
our_params(params
);
1840 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1841 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1842 return our_params
.custom_context
.request_id
;
1845 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1846 DCHECK(pending_context_menus_
.Lookup(request_id
));
1847 pending_context_menus_
.Remove(request_id
);
1850 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1851 return context_menu_node_
;
1854 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1855 blink::WebFrame
* frame
,
1856 const WebPluginInfo
& info
,
1857 const blink::WebPluginParams
& params
,
1858 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1859 DCHECK_EQ(frame_
, frame
);
1860 #if defined(ENABLE_PLUGINS)
1861 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1862 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1863 this, GetContentClient()
1865 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1870 bool pepper_plugin_was_registered
= false;
1871 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1872 this, info
, &pepper_plugin_was_registered
));
1873 if (pepper_plugin_was_registered
) {
1874 if (pepper_module
.get()) {
1875 return new PepperWebPluginImpl(
1876 pepper_module
.get(), params
, this,
1878 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1881 #if defined(OS_CHROMEOS)
1882 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1884 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1885 // TODO(jam): change to take RenderFrame.
1886 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1893 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1894 const blink::WebURLRequest
& request
,
1895 blink::WebNavigationPolicy policy
) {
1896 DCHECK(!frame_
|| frame_
== frame
);
1897 loadURLExternally(frame
, request
, policy
, WebString());
1900 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1901 OnJavaScriptExecuteRequest(javascript
, 0, false);
1904 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1905 return &service_registry_
;
1908 #if defined(ENABLE_PLUGINS)
1909 void RenderFrameImpl::RegisterPeripheralPlugin(
1910 const GURL
& content_origin
,
1911 const base::Closure
& unthrottle_callback
) {
1912 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1913 content_origin
, unthrottle_callback
);
1915 #endif // defined(ENABLE_PLUGINS)
1917 bool RenderFrameImpl::IsFTPDirectoryListing() {
1918 WebURLResponseExtraDataImpl
* extra_data
=
1919 GetExtraDataFromResponse(frame_
->dataSource()->response());
1920 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1923 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1924 BrowserPluginManager::Get()->Attach(element_instance_id
);
1927 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1928 BrowserPluginManager::Get()->Detach(element_instance_id
);
1931 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1933 const gfx::Range
& range
) {
1934 // Use the routing id of Render Widget Host.
1935 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1941 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1942 v8::Isolate
* isolate
,
1943 v8::Local
<v8::Context
> context
) {
1944 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1945 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1948 v8::HandleScope
handle_scope(isolate
);
1949 registry
->AddBuiltinModule(
1950 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1951 registry
->AddBuiltinModule(isolate
,
1952 mojo::js::Support::kModuleName
,
1953 mojo::js::Support::GetModule(isolate
));
1954 registry
->AddBuiltinModule(
1956 ServiceRegistryJsWrapper::kModuleName
,
1957 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1960 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
1961 const std::string
& message
) {
1962 if (devtools_agent_
)
1963 devtools_agent_
->AddMessageToConsole(level
, message
);
1966 // blink::WebFrameClient implementation ----------------------------------------
1968 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1969 blink::WebLocalFrame
* frame
,
1970 const blink::WebPluginParams
& params
) {
1971 DCHECK_EQ(frame_
, frame
);
1972 return GetContentClient()
1974 ->CreatePluginPlaceholder(this, frame
, params
)
1978 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1979 blink::WebLocalFrame
* frame
,
1980 const blink::WebPluginParams
& params
) {
1981 DCHECK_EQ(frame_
, frame
);
1982 blink::WebPlugin
* plugin
= NULL
;
1983 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1984 this, frame
, params
, &plugin
)) {
1988 if (base::UTF16ToUTF8(base::StringPiece16(params
.mimeType
)) ==
1989 kBrowserPluginMimeType
) {
1990 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1991 this, GetContentClient()
1993 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
1998 #if defined(ENABLE_PLUGINS)
2000 std::string mime_type
;
2002 Send(new FrameHostMsg_GetPluginInfo(
2003 routing_id_
, params
.url
, frame
->top()->document().url(),
2004 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
2008 WebPluginParams params_to_use
= params
;
2009 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2010 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2013 #endif // defined(ENABLE_PLUGINS)
2016 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2017 blink::WebLocalFrame
* frame
,
2018 const blink::WebURL
& url
,
2019 WebMediaPlayerClient
* client
,
2020 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
2021 WebContentDecryptionModule
* initial_cdm
) {
2022 #if defined(VIDEO_HOLE)
2023 if (!contains_media_player_
) {
2024 render_view_
->RegisterVideoHoleFrame(this);
2025 contains_media_player_
= true;
2027 #endif // defined(VIDEO_HOLE)
2029 blink::WebMediaStream
web_stream(
2030 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2031 if (!web_stream
.isNull())
2032 return CreateWebMediaPlayerForMediaStream(client
);
2034 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2035 return CreateAndroidWebMediaPlayer(client
, encrypted_client
,
2036 GetMediaPermission(), initial_cdm
);
2038 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2040 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2041 media::WebMediaPlayerParams
params(
2042 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2043 base::Unretained(GetContentClient()->renderer()),
2044 static_cast<RenderFrame
*>(this), has_played_media_
),
2045 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2046 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2047 render_thread
->GetWorkerTaskRunner(),
2048 render_thread
->compositor_task_runner(),
2049 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2052 #if defined(ENABLE_MOJO_MEDIA)
2053 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2054 new media::MojoRendererFactory(GetMediaServiceFactory()));
2056 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2057 GetContentClient()->renderer()->CreateMediaRendererFactory(
2058 this, render_thread
->GetGpuFactories(), media_log
);
2060 if (!media_renderer_factory
.get()) {
2061 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2062 media_log
, render_thread
->GetGpuFactories(),
2063 *render_thread
->GetAudioHardwareConfig()));
2065 #endif // defined(ENABLE_MOJO_MEDIA)
2067 return new media::WebMediaPlayerImpl(
2068 frame
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
2069 media_renderer_factory
.Pass(), GetCdmFactory(), params
);
2070 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2073 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2074 blink::WebLocalFrame
* frame
,
2075 blink::WebApplicationCacheHostClient
* client
) {
2076 if (!frame
|| !frame
->view())
2078 DCHECK(!frame_
|| frame_
== frame
);
2079 return new RendererWebApplicationCacheHostImpl(
2080 RenderViewImpl::FromWebView(frame
->view()), client
,
2081 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2084 blink::WebWorkerContentSettingsClientProxy
*
2085 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2086 blink::WebLocalFrame
* frame
) {
2087 if (!frame
|| !frame
->view())
2089 DCHECK(!frame_
|| frame_
== frame
);
2090 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2094 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2095 const WebPopupMenuInfo
& popup_menu_info
,
2096 WebExternalPopupMenuClient
* popup_menu_client
) {
2097 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2098 // An IPC message is sent to the browser to build and display the actual
2099 // popup. The user could have time to click a different select by the time
2100 // the popup is shown. In that case external_popup_menu_ is non NULL.
2101 // By returning NULL in that case, we instruct Blink to cancel that new
2102 // popup. So from the user perspective, only the first one will show, and
2103 // will have to close the first one before another one can be shown.
2104 if (external_popup_menu_
)
2106 external_popup_menu_
.reset(
2107 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2108 if (render_view_
->screen_metrics_emulator_
) {
2109 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2110 external_popup_menu_
.get(),
2111 render_view_
->screen_metrics_emulator_
.get());
2113 return external_popup_menu_
.get();
2119 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2120 DCHECK(!frame_
|| frame_
== frame
);
2121 return &cookie_jar_
;
2124 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2125 blink::WebLocalFrame
* frame
) {
2126 DCHECK(!frame_
|| frame_
== frame
);
2127 // At this point we should have non-null data source.
2128 DCHECK(frame
->dataSource());
2129 if (!ChildThreadImpl::current())
2130 return NULL
; // May be null in some tests.
2131 ServiceWorkerNetworkProvider
* provider
=
2132 ServiceWorkerNetworkProvider::FromDocumentState(
2133 DocumentState::FromDataSource(frame
->dataSource()));
2135 return new WebServiceWorkerProviderImpl(
2136 ChildThreadImpl::current()->thread_safe_sender(),
2137 provider
->context());
2140 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2141 DCHECK(!frame_
|| frame_
== frame
);
2142 // If the request hasn't yet committed, notify the browser process that it is
2143 // no longer safe to show the pending URL of the main frame, since a URL spoof
2144 // is now possible. (If the request has committed, the browser already knows.)
2145 if (!frame
->parent()) {
2146 DocumentState
* document_state
=
2147 DocumentState::FromDataSource(frame
->dataSource());
2148 NavigationStateImpl
* navigation_state
=
2149 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2151 if (!navigation_state
->request_committed()) {
2152 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2157 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2158 blink::WebLocalFrame
* parent
,
2159 blink::WebTreeScopeType scope
,
2160 const blink::WebString
& name
,
2161 blink::WebSandboxFlags sandbox_flags
) {
2162 // Synchronously notify the browser of a child frame creation to get the
2163 // routing_id for the RenderFrame.
2164 int child_routing_id
= MSG_ROUTING_NONE
;
2165 Send(new FrameHostMsg_CreateChildFrame(
2167 base::UTF16ToUTF8(base::StringPiece16(name
)), sandbox_flags
,
2168 &child_routing_id
));
2170 // Allocation of routing id failed, so we can't create a child frame. This can
2171 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2172 // out state or synchronous IPC message above has failed.
2173 if (child_routing_id
== MSG_ROUTING_NONE
) {
2174 NOTREACHED() << "Failed to allocate routing id for child frame.";
2178 // Create the RenderFrame and WebLocalFrame, linking the two.
2179 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2180 render_view_
.get(), child_routing_id
);
2181 blink::WebLocalFrame
* web_frame
=
2182 WebLocalFrame::create(scope
, child_render_frame
);
2183 child_render_frame
->SetWebFrame(web_frame
);
2185 // Add the frame to the frame tree and initialize it.
2186 parent
->appendChild(web_frame
);
2187 child_render_frame
->Initialize();
2192 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2193 DCHECK(!frame_
|| frame_
== frame
);
2194 // We only need to notify the browser if the active, top-level frame clears
2195 // its opener. We can ignore cases where a swapped out frame clears its
2196 // opener after hearing about it from the browser, and the browser does not
2197 // (yet) care about subframe openers.
2198 if (is_swapped_out_
|| frame
->parent())
2201 // Notify WebContents and all its swapped out RenderViews.
2202 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2205 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2206 // NOTE: This function is called on the frame that is being detached and not
2207 // the parent frame. This is different from createChildFrame() which is
2208 // called on the parent frame.
2209 CHECK(!is_detaching_
);
2210 DCHECK(!frame_
|| frame_
== frame
);
2212 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2213 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2214 FrameDetached(frame
));
2216 // We only notify the browser process when the frame is being detached for
2217 // removal. If the frame is being detached for swap, we don't need to do this
2218 // since we are not modifiying the frame tree.
2219 if (type
== DetachType::Remove
)
2220 Send(new FrameHostMsg_Detach(routing_id_
));
2222 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2223 // sent before setting |is_detaching_| to true.
2224 is_detaching_
= true;
2226 // Clean up the associated RenderWidget for the frame, if there is one.
2227 if (render_widget_
) {
2228 render_widget_
->UnregisterRenderFrame(this);
2229 render_widget_
->CloseForFrame();
2232 // We need to clean up subframes by removing them from the map and deleting
2233 // the RenderFrameImpl. In contrast, the main frame is owned by its
2234 // containing RenderViewHost (so that they have the same lifetime), so only
2235 // removal from the map is needed and no deletion.
2236 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2237 CHECK(it
!= g_frame_map
.Get().end());
2238 CHECK_EQ(it
->second
, this);
2239 g_frame_map
.Get().erase(it
);
2241 // Only remove the frame from the renderer's frame tree if the frame is
2242 // being detached for removal. In the case of a swap, the frame needs to
2243 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2244 if (is_subframe_
&& type
== DetachType::Remove
)
2245 frame
->parent()->removeChild(frame
);
2247 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2248 // object may not be deleted immediately and other methods may try to access
2254 // Object is invalid after this point.
2257 void RenderFrameImpl::frameFocused() {
2258 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2261 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2262 DCHECK(!frame_
|| frame_
== frame
);
2264 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2265 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2266 FrameWillClose(frame
));
2269 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2270 const blink::WebString
& name
) {
2271 DCHECK(!frame_
|| frame_
== frame
);
2273 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2274 // updates may have performance implications for benchmarks like SunSpider.
2275 // For now, send these updates only for --site-per-process, which needs to
2276 // replicate frame names to frame proxies, and when
2277 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2278 // can be optimized further by only sending the update if there are any
2279 // remote frames in the frame tree, or delaying and batching up IPCs if
2280 // updates are happening too frequently.
2281 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2282 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2283 Send(new FrameHostMsg_DidChangeName(
2284 routing_id_
, base::UTF16ToUTF8(base::StringPiece16(name
))));
2288 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2289 blink::WebSandboxFlags flags
) {
2290 int frame_routing_id
= MSG_ROUTING_NONE
;
2291 if (child_frame
->isWebRemoteFrame()) {
2293 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2296 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2299 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2303 void RenderFrameImpl::didMatchCSS(
2304 blink::WebLocalFrame
* frame
,
2305 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2306 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2307 DCHECK(!frame_
|| frame_
== frame
);
2309 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2310 DidMatchCSS(newly_matching_selectors
,
2311 stopped_matching_selectors
));
2314 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2315 const blink::WebString
& source
) {
2316 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2320 void RenderFrameImpl::didAddMessageToConsole(
2321 const blink::WebConsoleMessage
& message
,
2322 const blink::WebString
& source_name
,
2323 unsigned source_line
,
2324 const blink::WebString
& stack_trace
) {
2325 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2326 switch (message
.level
) {
2327 case blink::WebConsoleMessage::LevelDebug
:
2328 log_severity
= logging::LOG_VERBOSE
;
2330 case blink::WebConsoleMessage::LevelLog
:
2331 case blink::WebConsoleMessage::LevelInfo
:
2332 log_severity
= logging::LOG_INFO
;
2334 case blink::WebConsoleMessage::LevelWarning
:
2335 log_severity
= logging::LOG_WARNING
;
2337 case blink::WebConsoleMessage::LevelError
:
2338 log_severity
= logging::LOG_ERROR
;
2341 log_severity
= logging::LOG_VERBOSE
;
2344 if (shouldReportDetailedMessageForSource(source_name
)) {
2346 RenderFrameObserver
, observers_
,
2347 DetailedConsoleMessageAdded(message
.text
,
2351 static_cast<int32
>(log_severity
)));
2354 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2355 static_cast<int32
>(log_severity
),
2357 static_cast<int32
>(source_line
),
2361 void RenderFrameImpl::loadURLExternally(
2362 blink::WebLocalFrame
* frame
,
2363 const blink::WebURLRequest
& request
,
2364 blink::WebNavigationPolicy policy
,
2365 const blink::WebString
& suggested_name
) {
2366 DCHECK(!frame_
|| frame_
== frame
);
2367 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2368 if (policy
== blink::WebNavigationPolicyDownload
) {
2369 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2370 request
.url(), referrer
,
2373 OpenURL(frame
, request
.url(), referrer
, policy
);
2377 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2378 const NavigationPolicyInfo
& info
) {
2379 DCHECK(!frame_
|| frame_
== info
.frame
);
2380 return DecidePolicyForNavigation(this, info
);
2383 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2384 blink::WebFrame
* frame
) {
2385 DCHECK(!frame_
|| frame_
== frame
);
2386 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2389 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2390 const blink::WebFormElement
& form
) {
2391 DCHECK(!frame_
|| frame_
== frame
);
2393 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2396 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2397 const blink::WebFormElement
& form
) {
2398 DCHECK(!frame_
|| frame_
== frame
);
2399 DocumentState
* document_state
=
2400 DocumentState::FromDataSource(frame
->provisionalDataSource());
2401 NavigationStateImpl
* navigation_state
=
2402 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2403 InternalDocumentStateData
* internal_data
=
2404 InternalDocumentStateData::FromDocumentState(document_state
);
2406 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2407 ui::PAGE_TRANSITION_LINK
)) {
2408 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2411 // Save these to be processed when the ensuing navigation is committed.
2412 WebSearchableFormData
web_searchable_form_data(form
);
2413 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2414 internal_data
->set_searchable_form_encoding(
2415 web_searchable_form_data
.encoding().utf8());
2417 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2420 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2421 blink::WebDataSource
* datasource
) {
2422 DCHECK(!frame_
|| frame_
== frame
);
2424 bool content_initiated
= !pending_navigation_params_
.get();
2426 // Make sure any previous redirect URLs end up in our new data source.
2427 if (pending_navigation_params_
.get()) {
2428 for (const auto& i
:
2429 pending_navigation_params_
->request_params
.redirects
) {
2430 datasource
->appendRedirect(i
);
2434 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2435 if (!document_state
) {
2436 document_state
= new DocumentState
;
2437 datasource
->setExtraData(document_state
);
2438 if (!content_initiated
)
2439 PopulateDocumentStateFromPending(document_state
);
2442 // Carry over the user agent override flag, if it exists.
2443 blink::WebView
* webview
= render_view_
->webview();
2444 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2445 webview
->mainFrame()->isWebLocalFrame() &&
2446 webview
->mainFrame()->dataSource()) {
2447 DocumentState
* old_document_state
=
2448 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2449 if (old_document_state
) {
2450 InternalDocumentStateData
* internal_data
=
2451 InternalDocumentStateData::FromDocumentState(document_state
);
2452 InternalDocumentStateData
* old_internal_data
=
2453 InternalDocumentStateData::FromDocumentState(old_document_state
);
2454 internal_data
->set_is_overriding_user_agent(
2455 old_internal_data
->is_overriding_user_agent());
2459 // The rest of RenderView assumes that a WebDataSource will always have a
2460 // non-null NavigationState.
2461 if (content_initiated
) {
2462 document_state
->set_navigation_state(
2463 NavigationStateImpl::CreateContentInitiated());
2465 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2466 pending_navigation_params_
.reset();
2469 // DocumentState::referred_by_prefetcher_ is true if we are
2470 // navigating from a page that used prefetching using a link on that
2471 // page. We are early enough in the request process here that we
2472 // can still see the DocumentState of the previous page and set
2473 // this value appropriately.
2474 // TODO(gavinp): catch the important case of navigation in a new
2475 // renderer process.
2477 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2478 const WebURLRequest
& original_request
= datasource
->originalRequest();
2479 const GURL
referrer(
2480 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2481 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2482 DocumentState::FromDataSource(old_frame
->dataSource())
2483 ->was_prefetcher()) {
2484 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2485 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2486 if (old_frame_datasource
&&
2487 referrer
== GURL(old_frame_datasource
->request().url())) {
2488 document_state
->set_was_referred_by_prefetcher(true);
2496 if (content_initiated
) {
2497 const WebURLRequest
& request
= datasource
->request();
2498 switch (request
.cachePolicy()) {
2499 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2500 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2502 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2503 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2504 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2506 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2507 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2509 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2510 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2517 // Create the serviceworker's per-document network observing object if it
2518 // does not exist (When navigation happens within a page, the provider already
2520 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2521 DocumentState::FromDataSource(datasource
))) {
2522 ServiceWorkerProviderType provider_type
=
2523 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2524 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2525 blink::WebSandboxFlags::Origin
) {
2526 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2528 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2529 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2530 ServiceWorkerNetworkProvider::AttachToDocumentState(
2531 DocumentState::FromDataSource(datasource
),
2532 network_provider
.Pass());
2536 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2537 double triggering_event_time
) {
2538 DCHECK(!frame_
|| frame_
== frame
);
2539 WebDataSource
* ds
= frame
->provisionalDataSource();
2541 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2542 // callback is invoked.
2546 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2547 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2548 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2550 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2551 CHECK_IMPLIES(ds
->request().url() == GURL(kSwappedOutURL
), is_swapped_out_
)
2552 << "Heard swappedout:// when not swapped out.";
2554 // Update the request time if WebKit has better knowledge of it.
2555 if (document_state
->request_time().is_null() &&
2556 triggering_event_time
!= 0.0) {
2557 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2560 // Start time is only set after request time.
2561 document_state
->set_start_load_time(Time::Now());
2563 bool is_top_most
= !frame
->parent();
2565 render_view_
->set_navigation_gesture(
2566 WebUserGestureIndicator::isProcessingUserGesture() ?
2567 NavigationGestureUser
: NavigationGestureAuto
);
2568 } else if (ds
->replacesCurrentHistoryItem()) {
2569 // Subframe navigations that don't add session history items must be
2570 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2571 // handle loading of error pages.
2572 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2573 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2576 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2577 DidStartProvisionalLoad(frame
));
2578 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2580 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2581 routing_id_
, ds
->request().url()));
2584 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2585 blink::WebLocalFrame
* frame
) {
2586 DCHECK(!frame_
|| frame_
== frame
);
2587 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2590 void RenderFrameImpl::didFailProvisionalLoad(
2591 blink::WebLocalFrame
* frame
,
2592 const blink::WebURLError
& error
,
2593 blink::WebHistoryCommitType commit_type
) {
2594 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2596 DCHECK(!frame_
|| frame_
== frame
);
2597 WebDataSource
* ds
= frame
->provisionalDataSource();
2600 const WebURLRequest
& failed_request
= ds
->request();
2602 // Notify the browser that we failed a provisional load with an error.
2604 // Note: It is important this notification occur before DidStopLoading so the
2605 // SSL manager can react to the provisional load failure before being
2606 // notified the load stopped.
2608 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2609 DidFailProvisionalLoad(frame
, error
));
2610 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2611 DidFailProvisionalLoad(error
));
2613 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2615 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2618 // Make sure we never show errors in view source mode.
2619 frame
->enableViewSourceMode(false);
2621 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2622 NavigationStateImpl
* navigation_state
=
2623 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2625 // If this is a failed back/forward/reload navigation, then we need to do a
2626 // 'replace' load. This is necessary to avoid messing up session history.
2627 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2628 // as session history is concerned.
2629 bool replace
= commit_type
!= blink::WebStandardCommit
;
2631 // If we failed on a browser initiated request, then make sure that our error
2632 // page load is regarded as the same browser initiated request.
2633 if (!navigation_state
->IsContentInitiated()) {
2634 pending_navigation_params_
.reset(new NavigationParams(
2635 navigation_state
->common_params(), navigation_state
->start_params(),
2636 navigation_state
->request_params()));
2637 pending_navigation_params_
->request_params
.request_time
=
2638 document_state
->request_time();
2641 // Load an error page.
2642 LoadNavigationErrorPage(failed_request
, error
, replace
);
2645 void RenderFrameImpl::didCommitProvisionalLoad(
2646 blink::WebLocalFrame
* frame
,
2647 const blink::WebHistoryItem
& item
,
2648 blink::WebHistoryCommitType commit_type
) {
2649 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2651 "url", GetLoadingUrl().possibly_invalid_spec());
2652 DCHECK(!frame_
|| frame_
== frame
);
2653 DocumentState
* document_state
=
2654 DocumentState::FromDataSource(frame
->dataSource());
2655 NavigationStateImpl
* navigation_state
=
2656 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2658 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2659 RenderFrameProxy
* proxy
=
2660 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2662 proxy
->web_frame()->swap(frame_
);
2663 proxy_routing_id_
= MSG_ROUTING_NONE
;
2665 // If this is the main frame going from a remote frame to a local frame,
2666 // it needs to set RenderViewImpl's pointer for the main frame to itself
2667 // and ensure RenderWidget is no longer in swapped out mode.
2668 if (!is_subframe_
) {
2669 CHECK(!render_view_
->main_render_frame_
);
2670 render_view_
->main_render_frame_
= this;
2671 if (render_view_
->is_swapped_out())
2672 render_view_
->SetSwappedOut(false);
2676 // When we perform a new navigation, we need to update the last committed
2677 // session history entry with state for the page we are leaving. Do this
2678 // before updating the HistoryController state.
2679 render_view_
->SendUpdateState();
2681 render_view_
->history_controller()->UpdateForCommit(
2682 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2684 InternalDocumentStateData
* internal_data
=
2685 InternalDocumentStateData::FromDocumentState(document_state
);
2687 if (document_state
->commit_load_time().is_null())
2688 document_state
->set_commit_load_time(Time::Now());
2690 if (internal_data
->must_reset_scroll_and_scale_state()) {
2691 render_view_
->webview()->resetScrollAndScaleState();
2692 internal_data
->set_must_reset_scroll_and_scale_state(false);
2695 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2696 if (is_new_navigation
) {
2697 // We bump our Page ID to correspond with the new session history entry.
2698 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2700 // Don't update history list values for kSwappedOutURL, since
2701 // we don't want to forget the entry that was there, and since we will
2702 // never come back to kSwappedOutURL. Note that we have to call
2703 // SendUpdateState and update page_id_ even in this case, so that
2704 // the current entry gets a state update and so that we don't send a
2705 // state update to the wrong entry when we swap back in.
2707 navigation_state
->common_params().should_replace_current_entry
,
2708 render_view_
->history_list_length_
> 0);
2709 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2710 !navigation_state
->common_params().should_replace_current_entry
) {
2711 // Advance our offset in session history, applying the length limit.
2712 // There is now no forward history.
2713 render_view_
->history_list_offset_
++;
2714 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2715 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2716 render_view_
->history_list_length_
=
2717 render_view_
->history_list_offset_
+ 1;
2720 const RequestNavigationParams
& request_params
=
2721 navigation_state
->request_params();
2722 if (request_params
.nav_entry_id
!= 0 &&
2723 !request_params
.intended_as_new_entry
) {
2724 // This is a successful session history navigation!
2725 render_view_
->page_id_
= request_params
.page_id
;
2727 render_view_
->history_list_offset_
=
2728 request_params
.pending_history_list_offset
;
2733 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2734 CHECK(sent
); // http://crbug.com/407376
2736 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2737 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2739 RenderFrameObserver
, observers_
,
2740 DidCommitProvisionalLoad(is_new_navigation
,
2741 navigation_state
->WasWithinSamePage()));
2743 if (!frame
->parent()) { // Only for top frames.
2744 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2745 if (render_thread_impl
) { // Can be NULL in tests.
2746 render_thread_impl
->histogram_customizer()->
2747 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2748 RenderView::GetRenderViewCount());
2752 // Remember that we've already processed this request, so we don't update
2753 // the session history again. We do this regardless of whether this is
2754 // a session history navigation, because if we attempted a session history
2755 // navigation without valid HistoryItem state, WebCore will think it is a
2757 navigation_state
->set_request_committed(true);
2759 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2761 // Check whether we have new encoding name.
2762 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2765 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2766 DCHECK(!frame_
|| frame_
== frame
);
2768 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2769 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2770 DidCreateNewDocument(frame
));
2773 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2774 DCHECK(!frame_
|| frame_
== frame
);
2776 int enabled_bindings
= render_view_
->GetEnabledBindings();
2778 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2779 WebUIExtension::Install(frame
);
2781 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2782 DomAutomationController::Install(this, frame
);
2784 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2785 StatsCollectionController::Install(frame
);
2787 const base::CommandLine
& command_line
=
2788 *base::CommandLine::ForCurrentProcess();
2790 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2791 GpuBenchmarking::Install(frame
);
2793 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2794 MemoryBenchmarkingExtension::Install(frame
);
2796 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2797 SkiaBenchmarking::Install(frame
);
2799 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2800 DidClearWindowObject(frame
));
2801 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2804 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2805 DCHECK(!frame_
|| frame_
== frame
);
2807 // Notify the browser about non-blank documents loading in the top frame.
2808 GURL url
= frame
->document().url();
2809 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2810 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2811 // frame->tree()->top().
2812 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2813 if (frame
== main_frame
) {
2814 // For now, don't remember plugin zoom values. We don't want to mix them
2815 // with normal web content (i.e. a fixed layout plugin would usually want
2817 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2818 render_view_
->GetRoutingID(),
2819 main_frame
->document().isPluginDocument()));
2823 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2824 DidCreateDocumentElement());
2825 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2826 DidCreateDocumentElement(frame
));
2829 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2830 const blink::WebString
& title
,
2831 blink::WebTextDirection direction
) {
2832 DCHECK(!frame_
|| frame_
== frame
);
2833 // Ignore all but top level navigations.
2834 if (!frame
->parent()) {
2835 base::string16 title16
= title
;
2836 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2837 routing_id_
, base::UTF16ToUTF8(title16
));
2839 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2840 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2841 shortened_title
, direction
));
2844 // Also check whether we have new encoding name.
2845 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2848 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2849 blink::WebIconURL::Type icon_type
) {
2850 DCHECK(!frame_
|| frame_
== frame
);
2851 // TODO(nasko): Investigate wheather implementation should move here.
2852 render_view_
->didChangeIcon(frame
, icon_type
);
2855 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
,
2856 bool document_is_empty
) {
2857 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2859 DCHECK(!frame_
|| frame_
== frame
);
2860 WebDataSource
* ds
= frame
->dataSource();
2861 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2862 document_state
->set_finish_document_load_time(Time::Now());
2864 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2866 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2867 DidFinishDocumentLoad(frame
));
2868 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2870 // Check whether we have new encoding name.
2871 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2873 // If this is an empty document with an http status code indicating an error,
2874 // we may want to display our own error page, so the user doesn't end up
2875 // with an unexplained blank page.
2876 if (!document_is_empty
)
2879 // Do not show error page when DevTools is attached.
2880 RenderFrameImpl
* localRoot
= this;
2881 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
2882 localRoot
->frame_
->parent()->isWebLocalFrame()) {
2883 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
2886 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
2889 // Display error page instead of a blank page, if appropriate.
2890 std::string error_domain
= "http";
2891 InternalDocumentStateData
* internal_data
=
2892 InternalDocumentStateData::FromDataSource(frame
->dataSource());
2893 int http_status_code
= internal_data
->http_status_code();
2894 if (GetContentClient()->renderer()->HasErrorPage(http_status_code
,
2897 error
.unreachableURL
= frame
->document().url();
2898 error
.domain
= WebString::fromUTF8(error_domain
);
2899 error
.reason
= http_status_code
;
2900 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
2904 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2905 DCHECK(!frame_
|| frame_
== frame
);
2906 if (!frame
->parent()) {
2907 FrameMsg_UILoadMetricsReportType::Value report_type
=
2908 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2909 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2910 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2911 base::TimeDelta::FromSecondsD(
2912 frame
->dataSource()->request().uiStartTime());
2914 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2915 routing_id_
, report_type
, ui_timestamp
));
2919 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2920 const blink::WebURLError
& error
,
2921 blink::WebHistoryCommitType commit_type
) {
2922 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2924 DCHECK(!frame_
|| frame_
== frame
);
2925 // TODO(nasko): Move implementation here. No state needed.
2926 WebDataSource
* ds
= frame
->dataSource();
2929 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2930 DidFailLoad(frame
, error
));
2932 const WebURLRequest
& failed_request
= ds
->request();
2933 base::string16 error_description
;
2934 GetContentClient()->renderer()->GetNavigationErrorStrings(
2940 &error_description
);
2941 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2942 failed_request
.url(),
2945 error
.wasIgnoredByHandler
));
2948 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2949 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2951 DCHECK(!frame_
|| frame_
== frame
);
2952 WebDataSource
* ds
= frame
->dataSource();
2953 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2954 if (document_state
->finish_load_time().is_null()) {
2955 if (!frame
->parent()) {
2956 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2957 TRACE_EVENT_SCOPE_PROCESS
);
2959 document_state
->set_finish_load_time(Time::Now());
2962 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2963 DidFinishLoad(frame
));
2964 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2966 // Don't send this message while the frame is swapped out.
2967 if (is_swapped_out())
2970 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2971 ds
->request().url()));
2974 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2975 const blink::WebHistoryItem
& item
,
2976 blink::WebHistoryCommitType commit_type
) {
2977 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2979 DCHECK(!frame_
|| frame_
== frame
);
2980 // If this was a reference fragment navigation that we initiated, then we
2981 // could end up having a non-null pending navigation params. We just need to
2982 // update the ExtraData on the datasource so that others who read the
2983 // ExtraData will get the new NavigationState. Similarly, if we did not
2984 // initiate this navigation, then we need to take care to reset any pre-
2985 // existing navigation state to a content-initiated navigation state.
2986 // didCreateDataSource conveniently takes care of this for us.
2987 didCreateDataSource(frame
, frame
->dataSource());
2989 DocumentState
* document_state
=
2990 DocumentState::FromDataSource(frame
->dataSource());
2991 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2992 ->set_was_within_same_page(true);
2994 didCommitProvisionalLoad(frame
, item
, commit_type
);
2997 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2998 DCHECK(!frame_
|| frame_
== frame
);
2999 // TODO(nasko): Move implementation here. Needed methods:
3000 // * StartNavStateSyncTimerIfNecessary
3001 render_view_
->didUpdateCurrentHistoryItem(frame
);
3004 void RenderFrameImpl::didChangeThemeColor() {
3005 if (frame_
->parent())
3008 Send(new FrameHostMsg_DidChangeThemeColor(
3009 routing_id_
, frame_
->document().themeColor()));
3012 void RenderFrameImpl::dispatchLoad() {
3013 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
3016 void RenderFrameImpl::requestNotificationPermission(
3017 const blink::WebSecurityOrigin
& origin
,
3018 blink::WebNotificationPermissionCallback
* callback
) {
3019 if (!notification_permission_dispatcher_
) {
3020 notification_permission_dispatcher_
=
3021 new NotificationPermissionDispatcher(this);
3024 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3027 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3028 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3031 if (is_empty_selection
)
3032 selection_text_
.clear();
3034 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3035 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3036 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3037 // to notify the selection was changed. Focus change should be notified
3038 // before selection change.
3039 GetRenderWidget()->UpdateTextInputState(
3040 RenderWidget::NO_SHOW_IME
, RenderWidget::FROM_NON_IME
);
3041 SyncSelectionIfRequired();
3044 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3045 blink::WebColorChooserClient
* client
,
3046 const blink::WebColor
& initial_color
,
3047 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3048 RendererWebColorChooserImpl
* color_chooser
=
3049 new RendererWebColorChooserImpl(this, client
);
3050 std::vector
<ColorSuggestion
> color_suggestions
;
3051 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3052 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3054 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3055 return color_chooser
;
3058 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3059 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3062 frame_
->document().url(),
3066 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3067 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3070 frame_
->document().url(),
3074 bool RenderFrameImpl::runModalPromptDialog(
3075 const blink::WebString
& message
,
3076 const blink::WebString
& default_value
,
3077 blink::WebString
* actual_value
) {
3078 base::string16 result
;
3079 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3082 frame_
->document().url(),
3085 actual_value
->assign(result
);
3089 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3091 const blink::WebString
& message
) {
3092 // If we are swapping out, we have already run the beforeunload handler.
3093 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3094 // at all, to avoid running it twice.
3095 if (is_swapped_out_
)
3098 // Don't allow further dialogs if we are waiting to swap out, since the
3099 // PageGroupLoadDeferrer in our stack prevents it.
3100 if (render_view()->suppress_dialogs_until_swap_out_
)
3103 bool success
= false;
3104 // This is an ignored return value, but is included so we can accept the same
3105 // response as RunJavaScriptMessage.
3106 base::string16 ignored_result
;
3107 render_view()->SendAndRunNestedMessageLoop(
3108 new FrameHostMsg_RunBeforeUnloadConfirm(
3109 routing_id_
, frame_
->document().url(), message
, is_reload
,
3110 &success
, &ignored_result
));
3114 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3115 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3116 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3117 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3118 if (GetRenderWidget()->has_host_context_menu_location()) {
3119 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3120 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3123 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3124 // it. We replace it with an empty GURL so the appropriate items are disabled
3125 // in the context menu.
3126 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3127 // data encoded images. We should have a way to save them.
3128 if (params
.src_url
.spec().size() > GetMaxURLChars())
3129 params
.src_url
= GURL();
3130 context_menu_node_
= data
.node
;
3132 #if defined(OS_ANDROID)
3133 gfx::Rect start_rect
;
3135 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3136 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3137 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3140 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3143 void RenderFrameImpl::clearContextMenu() {
3144 context_menu_node_
.reset();
3147 void RenderFrameImpl::willSendRequest(
3148 blink::WebLocalFrame
* frame
,
3149 unsigned identifier
,
3150 blink::WebURLRequest
& request
,
3151 const blink::WebURLResponse
& redirect_response
) {
3152 DCHECK(!frame_
|| frame_
== frame
);
3153 // The request my be empty during tests.
3154 if (request
.url().isEmpty())
3157 // Set the first party for cookies url if it has not been set yet (new
3158 // requests). For redirects, it is updated by WebURLLoaderImpl.
3159 if (request
.firstPartyForCookies().isEmpty()) {
3160 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3161 request
.setFirstPartyForCookies(request
.url());
3163 // TODO(nasko): When the top-level frame is remote, there is no document.
3164 // This is broken and should be fixed to propagate the first party.
3165 WebFrame
* top
= frame
->top();
3166 if (top
->isWebLocalFrame()) {
3167 request
.setFirstPartyForCookies(
3168 frame
->top()->document().firstPartyForCookies());
3173 WebDataSource
* provisional_data_source
= frame
->provisionalDataSource();
3174 WebDataSource
* data_source
=
3175 provisional_data_source
? provisional_data_source
: frame
->dataSource();
3177 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3178 DCHECK(document_state
);
3179 InternalDocumentStateData
* internal_data
=
3180 InternalDocumentStateData::FromDocumentState(document_state
);
3181 NavigationStateImpl
* navigation_state
=
3182 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3183 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3184 if (provisional_data_source
&& provisional_data_source
->isClientRedirect()) {
3185 transition_type
= ui::PageTransitionFromInt(
3186 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3189 GURL
request_url(request
.url());
3191 if (GetContentClient()->renderer()->WillSendRequest(
3195 request
.firstPartyForCookies(),
3197 request
.setURL(WebURL(new_url
));
3200 if (internal_data
->is_cache_policy_override_set())
3201 request
.setCachePolicy(internal_data
->cache_policy_override());
3203 // The request's extra data may indicate that we should set a custom user
3204 // agent. This needs to be done here, after WebKit is through with setting the
3205 // user agent on its own. Similarly, it may indicate that we should set an
3206 // X-Requested-With header. This must be done here to avoid breaking CORS
3208 // PlzNavigate: there may also be a stream url associated with the request.
3209 WebString custom_user_agent
;
3210 WebString requested_with
;
3211 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3212 if (request
.extraData()) {
3213 RequestExtraData
* old_extra_data
=
3214 static_cast<RequestExtraData
*>(request
.extraData());
3216 custom_user_agent
= old_extra_data
->custom_user_agent();
3217 if (!custom_user_agent
.isNull()) {
3218 if (custom_user_agent
.isEmpty())
3219 request
.clearHTTPHeaderField("User-Agent");
3221 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3224 requested_with
= old_extra_data
->requested_with();
3225 if (!requested_with
.isNull()) {
3226 if (requested_with
.isEmpty())
3227 request
.clearHTTPHeaderField("X-Requested-With");
3229 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3231 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3234 // Add the default accept header for frame request if it has not been set
3236 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3237 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3238 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3239 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3240 WebString::fromUTF8(kDefaultAcceptHeader
));
3243 // Add an empty HTTP origin header for non GET methods if none is currently
3245 request
.addHTTPOriginIfNeeded(WebString());
3247 // Attach |should_replace_current_entry| state to requests so that, should
3248 // this navigation later require a request transfer, all state is preserved
3249 // when it is re-created in the new process.
3250 bool should_replace_current_entry
= false;
3251 if (navigation_state
->IsContentInitiated()) {
3252 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3254 // If the navigation is browser-initiated, the NavigationState contains the
3255 // correct value instead of the WebDataSource.
3257 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3258 // NavigationState::should_replace_current_entry().
3259 should_replace_current_entry
=
3260 navigation_state
->common_params().should_replace_current_entry
;
3263 int provider_id
= kInvalidServiceWorkerProviderId
;
3264 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3265 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3266 // |provisionalDataSource| may be null in some content::ResourceFetcher
3267 // use cases, we don't hook those requests.
3268 if (frame
->provisionalDataSource()) {
3269 ServiceWorkerNetworkProvider
* provider
=
3270 ServiceWorkerNetworkProvider::FromDocumentState(
3271 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3272 provider_id
= provider
->provider_id();
3274 } else if (frame
->dataSource()) {
3275 ServiceWorkerNetworkProvider
* provider
=
3276 ServiceWorkerNetworkProvider::FromDocumentState(
3277 DocumentState::FromDataSource(frame
->dataSource()));
3278 provider_id
= provider
->provider_id();
3281 WebFrame
* parent
= frame
->parent();
3282 int parent_routing_id
= MSG_ROUTING_NONE
;
3284 parent_routing_id
= -1;
3285 } else if (parent
->isWebLocalFrame()) {
3286 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3288 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3291 RequestExtraData
* extra_data
= new RequestExtraData();
3292 extra_data
->set_visibility_state(render_view_
->visibilityState());
3293 extra_data
->set_custom_user_agent(custom_user_agent
);
3294 extra_data
->set_requested_with(requested_with
);
3295 extra_data
->set_render_frame_id(routing_id_
);
3296 extra_data
->set_is_main_frame(!parent
);
3297 extra_data
->set_frame_origin(
3298 GURL(frame
->document().securityOrigin().toString()));
3299 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3300 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3301 extra_data
->set_allow_download(
3302 navigation_state
->common_params().allow_download
);
3303 extra_data
->set_transition_type(transition_type
);
3304 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3305 extra_data
->set_transferred_request_child_id(
3306 navigation_state
->start_params().transferred_request_child_id
);
3307 extra_data
->set_transferred_request_request_id(
3308 navigation_state
->start_params().transferred_request_request_id
);
3309 extra_data
->set_service_worker_provider_id(provider_id
);
3310 extra_data
->set_stream_override(stream_override
.Pass());
3311 request
.setExtraData(extra_data
);
3313 // TODO(creis): Update prefetching to work with out-of-process iframes.
3314 WebFrame
* top_frame
= frame
->top();
3315 if (top_frame
&& top_frame
->isWebLocalFrame()) {
3316 DocumentState
* top_document_state
=
3317 DocumentState::FromDataSource(top_frame
->dataSource());
3318 if (top_document_state
) {
3319 // TODO(gavinp): separate out prefetching and prerender field trials
3320 // if the rel=prerender rel type is sticking around.
3321 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3322 top_document_state
->set_was_prefetcher(true);
3326 // This is an instance where we embed a copy of the routing id
3327 // into the data portion of the message. This can cause problems if we
3328 // don't register this id on the browser side, since the download manager
3329 // expects to find a RenderViewHost based off the id.
3330 request
.setRequestorID(render_view_
->GetRoutingID());
3331 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3333 if (!navigation_state
->start_params().extra_headers
.empty()) {
3334 for (net::HttpUtil::HeadersIterator
i(
3335 navigation_state
->start_params().extra_headers
.begin(),
3336 navigation_state
->start_params().extra_headers
.end(), "\n");
3338 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3339 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3340 blink::WebReferrerPolicyDefault
,
3342 WebString::fromUTF8(i
.values()));
3343 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3345 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3346 WebString::fromUTF8(i
.values()));
3351 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3352 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3355 void RenderFrameImpl::didReceiveResponse(
3356 blink::WebLocalFrame
* frame
,
3357 unsigned identifier
,
3358 const blink::WebURLResponse
& response
) {
3359 DCHECK(!frame_
|| frame_
== frame
);
3360 // Only do this for responses that correspond to a provisional data source
3361 // of the top-most frame. If we have a provisional data source, then we
3362 // can't have any sub-resources yet, so we know that this response must
3363 // correspond to a frame load.
3364 if (!frame
->provisionalDataSource() || frame
->parent())
3367 // If we are in view source mode, then just let the user see the source of
3368 // the server's error page.
3369 if (frame
->isViewSourceModeEnabled())
3372 DocumentState
* document_state
=
3373 DocumentState::FromDataSource(frame
->provisionalDataSource());
3374 int http_status_code
= response
.httpStatusCode();
3376 // Record page load flags.
3377 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3379 document_state
->set_was_fetched_via_spdy(
3380 extra_data
->was_fetched_via_spdy());
3381 document_state
->set_was_npn_negotiated(
3382 extra_data
->was_npn_negotiated());
3383 document_state
->set_npn_negotiated_protocol(
3384 extra_data
->npn_negotiated_protocol());
3385 document_state
->set_was_alternate_protocol_available(
3386 extra_data
->was_alternate_protocol_available());
3387 document_state
->set_connection_info(
3388 extra_data
->connection_info());
3389 document_state
->set_was_fetched_via_proxy(
3390 extra_data
->was_fetched_via_proxy());
3391 document_state
->set_proxy_server(
3392 extra_data
->proxy_server());
3394 InternalDocumentStateData
* internal_data
=
3395 InternalDocumentStateData::FromDocumentState(document_state
);
3396 internal_data
->set_http_status_code(http_status_code
);
3399 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3400 blink::WebLocalFrame
* frame
,
3401 const blink::WebURLRequest
& request
,
3402 const blink::WebURLResponse
& response
) {
3403 DCHECK(!frame_
|| frame_
== frame
);
3404 // The recipients of this message have no use for data: URLs: they don't
3405 // affect the page's insecure content list and are not in the disk cache. To
3406 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3407 // filter them out here.
3408 GURL
url(request
.url());
3409 if (url
.SchemeIs(url::kDataScheme
))
3412 // Let the browser know we loaded a resource from the memory cache. This
3413 // message is needed to display the correct SSL indicators.
3414 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3415 render_view_
->GetRoutingID(),
3417 response
.securityInfo(),
3418 request
.httpMethod().utf8(),
3419 response
.mimeType().utf8(),
3420 WebURLRequestToResourceType(request
)));
3423 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3424 DCHECK(!frame_
|| frame_
== frame
);
3425 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3426 render_view_
->GetRoutingID()));
3429 void RenderFrameImpl::didRunInsecureContent(
3430 blink::WebLocalFrame
* frame
,
3431 const blink::WebSecurityOrigin
& origin
,
3432 const blink::WebURL
& target
) {
3433 DCHECK(!frame_
|| frame_
== frame
);
3434 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3435 render_view_
->GetRoutingID(),
3436 origin
.toString().utf8(),
3438 GetContentClient()->renderer()->RecordRapporURL(
3439 "ContentSettings.MixedScript.RanMixedScript",
3440 GURL(origin
.toString().utf8()));
3443 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3444 DCHECK(!frame_
|| frame_
== frame
);
3445 #if defined(ENABLE_PLUGINS)
3446 if (frame
!= render_view_
->webview()->mainFrame())
3448 PluginChannelHost::Broadcast(
3449 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3453 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3454 v8::Local
<v8::Context
> context
,
3455 int extension_group
,
3457 DCHECK(!frame_
|| frame_
== frame
);
3459 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3460 DidCreateScriptContext(context
, extension_group
, world_id
));
3463 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3464 v8::Local
<v8::Context
> context
,
3466 DCHECK(!frame_
|| frame_
== frame
);
3468 FOR_EACH_OBSERVER(RenderFrameObserver
,
3470 WillReleaseScriptContext(context
, world_id
));
3473 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3474 blink::WebLocalFrame
* frame
) {
3475 DCHECK(!frame_
|| frame_
== frame
);
3476 if (frame
->parent())
3479 #if defined(OS_ANDROID)
3480 GetRenderWidget()->DidChangeBodyBackgroundColor(
3481 render_view_
->webwidget_
->backgroundColor());
3484 GetRenderWidget()->QueueMessage(
3485 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3486 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3489 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3490 DCHECK(!frame_
|| frame_
== frame
);
3491 // TODO(nasko): Move implementation here. Needed methods:
3492 // * StartNavStateSyncTimerIfNecessary
3493 render_view_
->didChangeScrollOffset(frame
);
3495 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3498 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3499 DCHECK(!frame_
|| frame_
== frame
);
3500 if (!frame
->parent()) {
3501 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3502 render_view_
->GetRoutingID()));
3506 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3508 bool final_update
) {
3509 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3511 active_match_ordinal
= 0;
3513 render_view_
->Send(new ViewHostMsg_Find_Reply(
3514 render_view_
->GetRoutingID(), request_id
, count
,
3515 gfx::Rect(), active_match_ordinal
, final_update
));
3518 void RenderFrameImpl::reportFindInPageSelection(
3520 int active_match_ordinal
,
3521 const blink::WebRect
& selection_rect
) {
3522 render_view_
->Send(new ViewHostMsg_Find_Reply(
3523 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3524 active_match_ordinal
, false));
3527 void RenderFrameImpl::requestStorageQuota(
3528 blink::WebLocalFrame
* frame
,
3529 blink::WebStorageQuotaType type
,
3530 unsigned long long requested_size
,
3531 blink::WebStorageQuotaCallbacks callbacks
) {
3532 DCHECK(!frame_
|| frame_
== frame
);
3533 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3534 if (origin
.isUnique()) {
3535 // Unique origins cannot store persistent state.
3536 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3539 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3540 render_view_
->GetRoutingID(),
3541 GURL(origin
.toString()),
3542 static_cast<storage::StorageType
>(type
),
3544 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3547 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3548 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3549 impl
->set_render_frame_id(routing_id_
);
3552 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3553 if (!geolocation_dispatcher_
)
3554 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3555 return geolocation_dispatcher_
;
3558 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3559 if (!presentation_dispatcher_
)
3560 presentation_dispatcher_
= new PresentationDispatcher(this);
3561 return presentation_dispatcher_
;
3564 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3565 if (!push_messaging_dispatcher_
)
3566 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3567 return push_messaging_dispatcher_
;
3570 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3571 blink::WebLocalFrame
* frame
,
3572 blink::WebRTCPeerConnectionHandler
* handler
) {
3573 DCHECK(!frame_
|| frame_
== frame
);
3574 #if defined(ENABLE_WEBRTC)
3575 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3579 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3580 if (!web_user_media_client_
)
3581 InitializeUserMediaClient();
3582 return web_user_media_client_
;
3585 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3586 if (!web_encrypted_media_client_
) {
3587 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3588 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3589 // is destructed before |this|, and does not give away ownership of the
3591 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3592 base::Unretained(this)),
3593 GetCdmFactory(), GetMediaPermission()));
3595 return web_encrypted_media_client_
.get();
3598 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3599 if (!midi_dispatcher_
)
3600 midi_dispatcher_
= new MidiDispatcher(this);
3601 return midi_dispatcher_
;
3604 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3605 blink::WebLocalFrame
* source_frame
,
3606 blink::WebFrame
* target_frame
,
3607 blink::WebSecurityOrigin target_origin
,
3608 blink::WebDOMMessageEvent event
) {
3609 DCHECK(!frame_
|| frame_
== target_frame
);
3611 // Currently, a postMessage that targets a cross-process frame can be plumbed
3612 // either through this function or RenderFrameProxy::postMessageEvent. This
3613 // function is used when the target cross-process frame is a top-level frame
3614 // which has been swapped out. In that case, the corresponding WebLocalFrame
3615 // currently remains in the frame tree even in site-per-process mode (see
3616 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3617 // --site-per-process mode for all other cases.
3619 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3620 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3621 // cross-process postMessages.
3622 if (!is_swapped_out_
)
3625 // It is possible to get here on a swapped-out frame without a
3626 // |render_frame_proxy_|. This happens when:
3627 // - This process only has one active RenderView and is about to go away
3628 // (e.g., due to cross-process navigation).
3629 // - The top frame has a subframe with an unload handler.
3630 // - The subframe sends a postMessage to the top-level frame in its unload
3632 // See https://crbug.com/475651 for details. We return false here, since we
3633 // don't want to deliver the message to the new process in this case.
3634 if (!render_frame_proxy_
)
3637 render_frame_proxy_
->postMessageEvent(
3638 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3642 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3643 const blink::WebURL
& url
) {
3644 DCHECK(!frame_
|| frame_
== frame
);
3645 std::string user_agent_override_for_url
=
3646 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3647 if (!user_agent_override_for_url
.empty())
3648 return WebString::fromUTF8(user_agent_override_for_url
);
3650 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3651 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3652 return blink::WebString();
3655 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3656 // associated with it, so the checks below are not valid. Temporarily
3657 // return early and fix properly as part of https://crbug.com/426555.
3658 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3659 return blink::WebString();
3661 // If we're in the middle of committing a load, the data source we need
3662 // will still be provisional.
3663 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3664 WebDataSource
* data_source
= NULL
;
3665 if (main_frame
->provisionalDataSource())
3666 data_source
= main_frame
->provisionalDataSource();
3668 data_source
= main_frame
->dataSource();
3670 InternalDocumentStateData
* internal_data
= data_source
?
3671 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3672 if (internal_data
&& internal_data
->is_overriding_user_agent())
3673 return WebString::fromUTF8(
3674 render_view_
->renderer_preferences_
.user_agent_override
);
3675 return blink::WebString();
3678 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3679 DCHECK(!frame_
|| frame_
== frame
);
3680 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3681 return WebString::fromUTF8("1");
3685 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3686 bool default_value
) {
3687 DCHECK(!frame_
|| frame_
== frame
);
3691 bool blocked
= true;
3692 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3693 render_view_
->GetRoutingID(),
3694 GURL(frame
->top()->securityOrigin().toString()),
3695 THREE_D_API_TYPE_WEBGL
,
3700 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3701 int arb_robustness_status_code
) {
3702 DCHECK(!frame_
|| frame_
== frame
);
3703 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3704 GURL(frame
->top()->securityOrigin().toString()),
3705 THREE_D_API_TYPE_WEBGL
,
3706 arb_robustness_status_code
));
3709 blink::WebScreenOrientationClient
*
3710 RenderFrameImpl::webScreenOrientationClient() {
3711 if (!screen_orientation_dispatcher_
)
3712 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3713 return screen_orientation_dispatcher_
;
3716 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3717 ServiceWorkerNetworkProvider
* provider
=
3718 ServiceWorkerNetworkProvider::FromDocumentState(
3719 DocumentState::FromDataSource(&data_source
));
3720 if (!provider
->context())
3722 return provider
->context()->controller_handle_id() !=
3723 kInvalidServiceWorkerHandleId
;
3726 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3727 ServiceWorkerNetworkProvider
* provider
=
3728 ServiceWorkerNetworkProvider::FromDocumentState(
3729 DocumentState::FromDataSource(&data_source
));
3730 if (provider
->context() && provider
->context()->controller())
3731 return provider
->context()->controller()->version_id();
3732 return kInvalidServiceWorkerVersionId
;
3735 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3736 blink::WebAXEvent event
) {
3737 HandleWebAccessibilityEvent(obj
, event
);
3740 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3743 const blink::WebAXObject
& start_object
,
3745 const blink::WebAXObject
& end_object
,
3747 if (renderer_accessibility_
) {
3748 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3749 identifier
, match_index
, start_object
, start_offset
,
3750 end_object
, end_offset
);
3754 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3755 DCHECK(!frame_
|| frame_
== frame
);
3757 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3760 bool RenderFrameImpl::enterFullscreen() {
3761 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3765 bool RenderFrameImpl::exitFullscreen() {
3766 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3770 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3771 if (!permission_client_
)
3772 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3774 return permission_client_
.get();
3777 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3778 if (!app_banner_client_
) {
3779 app_banner_client_
=
3780 GetContentClient()->renderer()->CreateAppBannerClient(this);
3783 return app_banner_client_
.get();
3786 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3788 const WebString
& title
) {
3789 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3790 Send(new FrameHostMsg_RegisterProtocolHandler(
3792 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3798 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3799 const WebURL
& url
) {
3800 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3801 Send(new FrameHostMsg_UnregisterProtocolHandler(
3803 base::UTF16ToUTF8(base::StringPiece16(scheme
)),
3808 blink::WebBluetooth
* RenderFrameImpl::bluetooth() {
3810 bluetooth_
.reset(new WebBluetoothImpl(
3811 ChildThreadImpl::current()->thread_safe_sender(), routing_id_
));
3814 return bluetooth_
.get();
3817 blink::WebUSBClient
* RenderFrameImpl::usbClient() {
3818 #if !defined(OS_ANDROID)
3820 mojo::ServiceProviderPtr device_services
=
3821 ConnectToApplication(GURL(device::kDevicesMojoAppUrl
));
3822 usb_client_
.reset(new WebUSBClientImpl(device_services
.Pass()));
3825 return usb_client_
.get();
3828 #if defined(ENABLE_WEBVR)
3829 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3830 if (!vr_dispatcher_
)
3831 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3833 return vr_dispatcher_
.get();
3837 void RenderFrameImpl::DidPlay(WebMediaPlayer
* player
) {
3838 has_played_media_
= true;
3839 Send(new FrameHostMsg_MediaPlayingNotification(
3840 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3841 player
->hasAudio(), player
->isRemote()));
3844 void RenderFrameImpl::DidPause(WebMediaPlayer
* player
) {
3845 Send(new FrameHostMsg_MediaPausedNotification(
3846 routing_id_
, reinterpret_cast<int64
>(player
)));
3849 void RenderFrameImpl::PlayerGone(WebMediaPlayer
* player
) {
3853 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3854 observers_
.AddObserver(observer
);
3857 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3858 observer
->RenderFrameGone();
3859 observers_
.RemoveObserver(observer
);
3862 void RenderFrameImpl::OnStop() {
3864 frame_
->stopLoading();
3865 if (!frame_
->parent())
3866 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3868 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3871 void RenderFrameImpl::WasHidden() {
3872 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3875 void RenderFrameImpl::WasShown() {
3876 // TODO(kenrb): Need to figure out how to do this better. Should
3877 // VisibilityState remain a page-level concept or move to frames?
3878 // The semantics of 'Show' might have to change here.
3879 if (render_widget_
) {
3880 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3881 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3883 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3886 void RenderFrameImpl::WidgetWillClose() {
3887 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3890 bool RenderFrameImpl::IsHidden() {
3891 return GetRenderWidget()->is_hidden();
3894 // Tell the embedding application that the URL of the active page has changed.
3895 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3896 blink::WebFrame
* frame
,
3897 blink::WebHistoryCommitType commit_type
,
3898 const blink::WebHistoryItem
& item
) {
3899 DCHECK(!frame_
|| frame_
== frame
);
3900 WebDataSource
* ds
= frame
->dataSource();
3903 const WebURLRequest
& request
= ds
->request();
3904 const WebURLResponse
& response
= ds
->response();
3906 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3907 NavigationStateImpl
* navigation_state
=
3908 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3909 InternalDocumentStateData
* internal_data
=
3910 InternalDocumentStateData::FromDocumentState(document_state
);
3912 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3913 params
.http_status_code
= response
.httpStatusCode();
3914 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3915 params
.is_post
= false;
3916 params
.intended_as_new_entry
=
3917 navigation_state
->request_params().intended_as_new_entry
;
3918 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3919 params
.post_id
= -1;
3920 params
.page_id
= render_view_
->page_id_
;
3921 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3922 // We need to track the RenderViewHost routing_id because of downstream
3923 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3924 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3925 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3926 // based on the ID stored in the resource requests. Once those dependencies
3927 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3928 // client to be based on the routing_id of the RenderFrameHost.
3929 params
.render_view_routing_id
= render_view_
->routing_id();
3930 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3931 params
.socket_address
.set_port(response
.remotePort());
3932 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3934 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3935 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3936 params
.security_info
= response
.securityInfo();
3938 // Set the URL to be displayed in the browser UI to the user.
3939 params
.url
= GetLoadingUrl();
3940 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3942 // Set the origin of the frame. This will be replicated to the corresponding
3943 // RenderFrameProxies in other processes.
3944 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3945 // to https://crbug.com/439608 and will be replicated as unique origins.
3946 if (!is_swapped_out_
) {
3947 std::string scheme
= frame
->document().securityOrigin().protocol().utf8();
3948 if (url::IsStandard(scheme
.c_str(),
3949 url::Component(0, static_cast<int>(scheme
.length())))) {
3950 params
.origin
= frame
->document().securityOrigin();
3954 if (frame
->document().baseURL() != params
.url
)
3955 params
.base_url
= frame
->document().baseURL();
3957 GetRedirectChain(ds
, ¶ms
.redirects
);
3958 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3959 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3961 params
.searchable_form_url
= internal_data
->searchable_form_url();
3962 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3964 params
.gesture
= render_view_
->navigation_gesture_
;
3965 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3967 // Make navigation state a part of the DidCommitProvisionalLoad message so
3968 // that committed entry has it at all times.
3969 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3970 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3972 params
.page_state
= HistoryEntryToPageState(entry
);
3974 params
.page_state
= PageState::CreateFromURL(request
.url());
3976 // In --site-per-process, just send a single HistoryItem for this frame,
3977 // rather than the whole tree. It will be stored in the corresponding
3978 // FrameNavigationEntry.
3979 params
.page_state
= SingleHistoryItemToPageState(item
);
3981 params
.item_sequence_number
= item
.itemSequenceNumber();
3982 params
.document_sequence_number
= item
.documentSequenceNumber();
3984 if (!frame
->parent()) {
3985 // Top-level navigation.
3987 // Reset the zoom limits in case a plugin had changed them previously. This
3988 // will also call us back which will cause us to send a message to
3989 // update WebContentsImpl.
3990 render_view_
->webview()->zoomLimitsChanged(
3991 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3992 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3994 // Set zoom level, but don't do it for full-page plugin since they don't use
3995 // the same zoom settings.
3996 HostZoomLevels::iterator host_zoom
=
3997 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3998 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3999 // Reset the zoom levels for plugins.
4000 render_view_
->webview()->setZoomLevel(0);
4002 // If the zoom level is not found, then do nothing. In-page navigation
4003 // relies on not changing the zoom level in this case.
4004 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
4005 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
4008 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
4009 // This zoom level was merely recorded transiently for this load. We can
4010 // erase it now. If at some point we reload this page, the browser will
4011 // send us a new, up-to-date zoom level.
4012 render_view_
->host_zoom_levels_
.erase(host_zoom
);
4015 // Update contents MIME type for main frame.
4016 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4018 params
.transition
= navigation_state
->GetTransitionType();
4019 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4020 // If the main frame does a load, it should not be reported as a subframe
4021 // navigation. This can occur in the following case:
4022 // 1. You're on a site with frames.
4023 // 2. You do a subframe navigation. This is stored with transition type
4025 // 3. You navigate to some non-frame site, say, google.com.
4026 // 4. You navigate back to the page from step 2. Since it was initially
4027 // MANUAL_SUBFRAME, it will be that same transition type here.
4028 // We don't want that, because any navigation that changes the toplevel
4029 // frame should be tracked as a toplevel navigation (this allows us to
4030 // update the URL bar, etc).
4031 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4034 // If the page contained a client redirect (meta refresh, document.loc...),
4035 // set the referrer and transition appropriately.
4036 if (ds
->isClientRedirect()) {
4038 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4039 params
.transition
= ui::PageTransitionFromInt(
4040 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4042 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4043 frame
, ds
->request());
4046 base::string16 method
= request
.httpMethod();
4047 if (base::EqualsASCII(method
, "POST")) {
4048 params
.is_post
= true;
4049 params
.post_id
= ExtractPostId(entry
);
4052 // Send the user agent override back.
4053 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4055 // Track the URL of the original request. We use the first entry of the
4056 // redirect chain if it exists because the chain may have started in another
4058 params
.original_request_url
= GetOriginalRequestURL(ds
);
4060 params
.history_list_was_cleared
=
4061 navigation_state
->request_params().should_clear_history_list
;
4063 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4064 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4065 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4066 frame
->dataSource()->request().uiStartTime());
4068 // Save some histogram data so we can compute the average memory used per
4069 // page load of the glyphs.
4070 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4071 blink::WebGlyphCache::pageCount());
4073 // This message needs to be sent before any of allowScripts(),
4074 // allowImages(), allowPlugins() is called for the new page, so that when
4075 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4076 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4077 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4079 // Subframe navigation: the type depends on whether this navigation
4080 // generated a new session history entry. When they do generate a session
4081 // history entry, it means the user initiated the navigation and we should
4083 if (commit_type
== blink::WebStandardCommit
)
4084 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4086 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4088 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4089 params
.history_list_was_cleared
= false;
4090 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4092 // Don't send this message while the subframe is swapped out.
4093 if (!is_swapped_out())
4094 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4097 // If we end up reusing this WebRequest (for example, due to a #ref click),
4098 // we don't want the transition type to persist. Just clear it.
4099 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4102 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4103 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4105 render_view_
->FrameDidStartLoading(frame_
);
4106 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4109 void RenderFrameImpl::didStopLoading() {
4110 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4112 render_view_
->FrameDidStopLoading(frame_
);
4113 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4116 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4117 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4120 void RenderFrameImpl::HandleWebAccessibilityEvent(
4121 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4122 if (renderer_accessibility_
)
4123 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4126 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4127 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4130 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4131 if (renderer_accessibility())
4132 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4136 void RenderFrameImpl::OnCommitNavigation(
4137 const ResourceResponseHead
& response
,
4138 const GURL
& stream_url
,
4139 const CommonNavigationParams
& common_params
,
4140 const RequestNavigationParams
& request_params
) {
4141 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4142 switches::kEnableBrowserSideNavigation
));
4143 // This will override the url requested by the WebURLLoader, as well as
4144 // provide it with the response to the request.
4145 scoped_ptr
<StreamOverrideParameters
> stream_override(
4146 new StreamOverrideParameters());
4147 stream_override
->stream_url
= stream_url
;
4148 stream_override
->response
= response
;
4150 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4151 stream_override
.Pass());
4154 void RenderFrameImpl::OnFailedNavigation(
4155 const CommonNavigationParams
& common_params
,
4156 const RequestNavigationParams
& request_params
,
4157 bool has_stale_copy_in_cache
,
4159 bool is_reload
= IsReload(common_params
.navigation_type
);
4160 bool is_history_navigation
= request_params
.page_state
.IsValid();
4161 WebURLRequest::CachePolicy cache_policy
=
4162 WebURLRequest::UseProtocolCachePolicy
;
4163 RenderFrameImpl::PrepareRenderViewForNavigation(
4164 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4166 GetContentClient()->SetActiveURL(common_params
.url
);
4168 pending_navigation_params_
.reset(new NavigationParams(
4169 common_params
, StartNavigationParams(), request_params
));
4171 // Inform the browser of the start of the provisional load. This is needed so
4172 // that the load is properly tracked by the WebNavigation API.
4173 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4174 routing_id_
, common_params
.url
));
4176 // Send the provisional load failure.
4177 blink::WebURLError error
=
4178 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4179 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4180 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4181 frame_
->isViewSourceModeEnabled());
4182 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4184 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4185 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4186 // http://crbug.com/501960
4187 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4191 // Make sure errors are not shown in view source mode.
4192 frame_
->enableViewSourceMode(false);
4194 // Replace the current history entry in reloads, history navigations and loads
4195 // of the same url. This corresponds to Blink's notion of a standard
4197 // TODO(clamy): see if initial commits in subframes should be handled
4199 bool replace
= is_reload
|| is_history_navigation
||
4200 common_params
.url
== GetLoadingUrl();
4201 LoadNavigationErrorPage(failed_request
, error
, replace
);
4204 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4205 RenderFrame
* render_frame
,
4206 const NavigationPolicyInfo
& info
) {
4207 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4210 // TODO(nick): Is consulting |is_subframe_| here correct?
4211 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_
) {
4212 // There's no reason to ignore navigations on subframes, since the swap out
4213 // logic no longer applies.
4215 if (is_swapped_out_
) {
4216 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4217 // Targeted links may try to navigate a swapped out frame. Allow the
4218 // browser process to navigate the tab instead. Note that it is also
4219 // possible for non-targeted navigations (from this view) to arrive
4220 // here just after we are swapped out. It's ok to send them to the
4221 // browser, as long as they're for the top level frame.
4222 // TODO(creis): Ensure this supports targeted form submissions when
4223 // fixing http://crbug.com/101395.
4224 if (info
.frame
->parent() == NULL
) {
4225 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4226 info
.defaultPolicy
);
4227 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4230 // We should otherwise ignore in-process iframe navigations, if they
4231 // arrive just after we are swapped out.
4232 return blink::WebNavigationPolicyIgnore
;
4235 // Allow kSwappedOutURL to complete.
4236 return info
.defaultPolicy
;
4240 // Webkit is asking whether to navigate to a new URL.
4241 // This is fine normally, except if we're showing UI from one security
4242 // context and they're trying to navigate to a different context.
4243 const GURL
& url
= info
.urlRequest
.url();
4245 // A content initiated navigation may have originated from a link-click,
4246 // script, drag-n-drop operation, etc.
4247 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4248 bool is_content_initiated
=
4249 document_state
->navigation_state()->IsContentInitiated();
4251 // If the browser is interested, then give it a chance to look at the request.
4252 if (is_content_initiated
) {
4254 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4255 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4256 base::EqualsASCII(base::StringPiece16(info
.urlRequest
.httpMethod()),
4258 bool browser_handles_request
=
4259 render_view_
->renderer_preferences_
4260 .browser_handles_non_local_top_level_requests
4261 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4263 if (!browser_handles_request
) {
4264 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4265 render_view_
->renderer_preferences_
4266 .browser_handles_all_top_level_requests
;
4269 if (browser_handles_request
) {
4270 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4271 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4275 // Use the frame's original request's URL rather than the document's URL for
4276 // subsequent checks. For a popup, the document's URL may become the opener
4277 // window's URL if the opener has called document.write().
4278 // See http://crbug.com/93517.
4279 GURL
old_url(info
.frame
->dataSource()->request().url());
4281 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4282 // an extension or app origin, leaving a WebUI page, etc). We only care about
4283 // top-level navigations (not iframes). But we sometimes navigate to
4284 // about:blank to clear a tab, and we want to still allow that.
4286 // Note: this is known to break POST submissions when crossing process
4287 // boundaries until http://crbug.com/101395 is fixed. This is better for
4288 // security than loading a WebUI, extension or app page in the wrong process.
4289 // POST requests don't work because this mechanism does not preserve form
4290 // POST data. We will need to send the request's httpBody data up to the
4291 // browser process, and issue a special POST navigation in WebKit (via
4292 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4293 // for examples of how to send the httpBody data.
4294 if (!info
.frame
->parent() && is_content_initiated
&&
4295 !url
.SchemeIs(url::kAboutScheme
)) {
4296 bool send_referrer
= false;
4298 // All navigations to or from WebUI URLs or within WebUI-enabled
4299 // RenderProcesses must be handled by the browser process so that the
4300 // correct bindings and data sources can be registered.
4301 // Similarly, navigations to view-source URLs or within ViewSource mode
4302 // must be handled by the browser process (except for reloads - those are
4303 // safe to leave within the renderer).
4304 // Lastly, access to file:// URLs from non-file:// URL pages must be
4305 // handled by the browser so that ordinary renderer processes don't get
4306 // blessed with file permissions.
4307 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4308 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4309 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4310 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4311 url
.SchemeIs(kViewSourceScheme
) ||
4312 (info
.frame
->isViewSourceModeEnabled() &&
4313 info
.navigationType
!= blink::WebNavigationTypeReload
);
4315 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4316 // Fork non-file to file opens. Check the opener URL if this is the
4317 // initial navigation in a newly opened window.
4318 GURL
source_url(old_url
);
4319 if (is_initial_navigation
&& source_url
.is_empty() &&
4320 info
.frame
->opener())
4321 source_url
= info
.frame
->opener()->top()->document().url();
4322 DCHECK(!source_url
.is_empty());
4323 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4327 // Give the embedder a chance.
4328 should_fork
= GetContentClient()->renderer()->ShouldFork(
4329 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4330 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4334 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4335 info
.defaultPolicy
);
4336 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4340 // Detect when a page is "forking" a new tab that can be safely rendered in
4341 // its own process. This is done by sites like Gmail that try to open links
4342 // in new windows without script connections back to the original page. We
4343 // treat such cases as browser navigations (in which we will create a new
4344 // renderer for a cross-site navigation), rather than WebKit navigations.
4346 // We use the following heuristic to decide whether to fork a new page in its
4348 // The parent page must open a new tab to about:blank, set the new tab's
4349 // window.opener to null, and then redirect the tab to a cross-site URL using
4352 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4355 // Must start from a tab showing about:blank, which is later redirected.
4356 old_url
== GURL(url::kAboutBlankURL
) &&
4357 // Must be the first real navigation of the tab.
4358 render_view_
->historyBackListCount() < 1 &&
4359 render_view_
->historyForwardListCount() < 1 &&
4360 // The parent page must have set the child's window.opener to null before
4361 // redirecting to the desired URL.
4362 info
.frame
->opener() == NULL
&&
4363 // Must be a top-level frame.
4364 info
.frame
->parent() == NULL
&&
4365 // Must not have issued the request from this page.
4366 is_content_initiated
&&
4367 // Must be targeted at the current tab.
4368 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4369 // Must be a JavaScript navigation, which appears as "other".
4370 info
.navigationType
== blink::WebNavigationTypeOther
;
4373 // Open the URL via the browser, not via WebKit.
4374 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4375 return blink::WebNavigationPolicyIgnore
;
4378 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4379 // This includes navigations with no request being sent to the network stack.
4380 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4381 switches::kEnableBrowserSideNavigation
) &&
4382 info
.urlRequest
.checkForBrowserSideNavigation() &&
4383 ShouldMakeNetworkRequestForURL(url
)) {
4384 BeginNavigation(&info
.urlRequest
);
4385 return blink::WebNavigationPolicyIgnore
;
4388 return info
.defaultPolicy
;
4391 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4393 const Referrer
& referrer
,
4394 WebNavigationPolicy policy
) {
4395 DCHECK_EQ(frame_
, frame
);
4397 FrameHostMsg_OpenURL_Params params
;
4399 params
.referrer
= referrer
;
4400 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4401 WebDataSource
* ds
= frame
->provisionalDataSource();
4403 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4404 NavigationStateImpl
* navigation_state
=
4405 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4406 if (navigation_state
->IsContentInitiated()) {
4407 params
.should_replace_current_entry
=
4408 ds
->replacesCurrentHistoryItem() &&
4409 render_view_
->history_list_length_
;
4411 // This is necessary to preserve the should_replace_current_entry value on
4412 // cross-process redirects, in the event it was set by a previous process.
4414 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4415 // NavigationState::should_replace_current_entry().
4416 params
.should_replace_current_entry
=
4417 navigation_state
->common_params().should_replace_current_entry
;
4420 params
.should_replace_current_entry
= false;
4422 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4423 if (GetContentClient()->renderer()->AllowPopup())
4424 params
.user_gesture
= true;
4426 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4427 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4428 policy
== blink::WebNavigationPolicyNewWindow
||
4429 policy
== blink::WebNavigationPolicyNewPopup
) {
4430 WebUserGestureIndicator::consumeUserGesture();
4433 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4436 void RenderFrameImpl::NavigateInternal(
4437 const CommonNavigationParams
& common_params
,
4438 const StartNavigationParams
& start_params
,
4439 const RequestNavigationParams
& request_params
,
4440 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4441 bool browser_side_navigation
=
4442 base::CommandLine::ForCurrentProcess()->HasSwitch(
4443 switches::kEnableBrowserSideNavigation
);
4444 bool is_reload
= IsReload(common_params
.navigation_type
);
4445 bool is_history_navigation
= request_params
.page_state
.IsValid();
4446 WebURLRequest::CachePolicy cache_policy
=
4447 WebURLRequest::UseProtocolCachePolicy
;
4448 RenderFrameImpl::PrepareRenderViewForNavigation(
4449 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4451 GetContentClient()->SetActiveURL(common_params
.url
);
4453 // If this frame isn't in the same process as the main frame, it may naively
4454 // assume that this is the first navigation in the iframe, but this may not
4455 // actually be the case. Inform the frame's state machine if this frame has
4456 // already committed other loads.
4457 if (request_params
.has_committed_real_load
&& frame_
->parent())
4458 frame_
->setCommittedFirstRealLoad();
4460 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4461 // We cannot reload if we do not have any history state. This happens, for
4462 // example, when recovering from a crash.
4464 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4467 pending_navigation_params_
.reset(
4468 new NavigationParams(common_params
, start_params
, request_params
));
4470 // Create parameters for a standard navigation.
4471 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4472 bool should_load_request
= false;
4473 WebHistoryItem item_for_history_navigation
;
4474 WebURLRequest request
= CreateURLRequestForNavigation(
4475 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4476 #if defined(OS_ANDROID)
4477 request
.setHasUserGesture(start_params
.has_user_gesture
);
4480 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4481 // navigation for this request (since it already went to the browser).
4482 if (browser_side_navigation
)
4483 request
.setCheckForBrowserSideNavigation(false);
4485 // If we are reloading, then use the history state of the current frame.
4486 // Otherwise, if we have history state, then we need to navigate to it, which
4487 // corresponds to a back/forward navigation event. Update the parameters
4488 // depending on the navigation type.
4490 bool ignore_cache
= (common_params
.navigation_type
==
4491 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4492 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4493 : blink::WebFrameLoadType::Reload
;
4495 if (!browser_side_navigation
) {
4496 const GURL override_url
=
4497 (common_params
.navigation_type
==
4498 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4501 request
= frame_
->requestForReload(load_type
, override_url
);
4503 should_load_request
= true;
4504 } else if (is_history_navigation
) {
4505 // We must know the page ID of the page we are navigating back to.
4506 DCHECK_NE(request_params
.page_id
, -1);
4507 // We must know the nav entry ID of the page we are navigating back to,
4508 // which should be the case because history navigations are routed via the
4510 DCHECK_NE(0, request_params
.nav_entry_id
);
4511 scoped_ptr
<HistoryEntry
> entry
=
4512 PageStateToHistoryEntry(request_params
.page_state
);
4514 // Ensure we didn't save the swapped out URL in UpdateState, since the
4515 // browser should never be telling us to navigate to swappedout://.
4516 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4518 if (!browser_side_navigation
) {
4519 scoped_ptr
<NavigationParams
> navigation_params(
4520 new NavigationParams(*pending_navigation_params_
.get()));
4521 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4522 // By default, tell the HistoryController to go the deserialized
4523 // HistoryEntry. This only works if all frames are in the same
4525 DCHECK(!frame_
->parent());
4526 render_view_
->history_controller()->GoToEntry(
4527 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4529 // In --site-per-process, the browser process sends a single
4530 // WebHistoryItem destined for this frame.
4531 // TODO(creis): Change PageState to FrameState. In the meantime, we
4532 // store the relevant frame's WebHistoryItem in the root of the
4534 SetPendingNavigationParams(navigation_params
.Pass());
4535 blink::WebHistoryItem history_item
= entry
->root();
4536 blink::WebHistoryLoadType load_type
=
4537 request_params
.is_same_document_history_load
4538 ? blink::WebHistorySameDocumentLoad
4539 : blink::WebHistoryDifferentDocumentLoad
;
4541 // Let the history controller know the provisional entry, since it is
4542 // used at commit time. Otherwise skip GoToEntry and navigate the
4544 // TODO(creis): Consider cloning the current entry to handle subframe
4545 // cases. Changes to SendUpdateState might affect this.
4546 render_view_
->history_controller()->set_provisional_entry(
4548 WebURLRequest request
=
4549 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4550 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4551 history_item
, load_type
);
4554 // TODO(clamy): this should be set to the HistoryItem sent by the
4555 // browser once the HistoryController has moved to the browser.
4556 // TODO(clamy): distinguish between different document and same document
4558 // TODO(clamy): update this for subframes history loads.
4559 item_for_history_navigation
=
4560 entry
->GetHistoryNodeForFrame(this)->item();
4561 load_type
= blink::WebFrameLoadType::BackForward
;
4562 should_load_request
= true;
4566 // Navigate to the given URL.
4567 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4568 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4569 start_params
.extra_headers
.end(),
4572 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4573 WebString::fromUTF8(i
.values()));
4577 if (start_params
.is_post
&& !browser_side_navigation
) {
4578 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4581 WebHTTPBody http_body
;
4582 http_body
.initialize();
4583 const char* data
= nullptr;
4584 if (start_params
.browser_initiated_post_data
.size()) {
4585 data
= reinterpret_cast<const char*>(
4586 &start_params
.browser_initiated_post_data
.front());
4588 http_body
.appendData(
4589 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4590 request
.setHTTPBody(http_body
);
4593 // A session history navigation should have been accompanied by state.
4594 CHECK_EQ(request_params
.page_id
, -1);
4596 should_load_request
= true;
4599 if (should_load_request
) {
4600 // Record this before starting the load. We need a lower bound of this
4601 // time to sanitize the navigationStart override set below.
4602 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4604 // Perform a navigation to a data url if needed.
4605 if (!common_params
.base_url_for_data_url
.is_empty() ||
4606 (browser_side_navigation
&&
4607 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4608 LoadDataURL(common_params
, frame_
);
4610 // Load the request.
4611 frame_
->toWebLocalFrame()->load(request
, load_type
,
4612 item_for_history_navigation
);
4615 if (load_type
== blink::WebFrameLoadType::Standard
) {
4616 UpdateFrameNavigationTiming(frame_
,
4617 request_params
.browser_navigation_start
,
4618 renderer_navigation_start
);
4622 // In case LoadRequest failed before didCreateDataSource was called.
4623 pending_navigation_params_
.reset();
4626 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4627 const std::string
& encoding_name
) {
4628 // Only update main frame's encoding_name.
4629 if (!frame
->parent())
4630 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4633 void RenderFrameImpl::SyncSelectionIfRequired() {
4634 base::string16 text
;
4637 #if defined(ENABLE_PLUGINS)
4638 if (render_view_
->focused_pepper_plugin_
) {
4639 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4640 offset
= 0; // Pepper API does not support offset reporting.
4641 // TODO(kinaba): cut as needed.
4645 size_t location
, length
;
4646 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4647 &location
, &length
)) {
4651 range
= gfx::Range(location
, location
+ length
);
4653 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4654 blink::WebTextInputTypeNone
) {
4655 // If current focused element is editable, we will send 100 more chars
4656 // before and after selection. It is for input method surrounding text
4658 if (location
> kExtraCharsBeforeAndAfterSelection
)
4659 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4662 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4663 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4664 if (!webrange
.isNull())
4665 text
= webrange
.toPlainText();
4668 text
= frame_
->selectionAsText();
4669 // http://crbug.com/101435
4670 // In some case, frame->selectionAsText() returned text's length is not
4671 // equal to the length returned from webwidget()->caretOrSelectionRange().
4672 // So we have to set the range according to text.length().
4673 range
.set_end(range
.start() + text
.length());
4677 // Sometimes we get repeated didChangeSelection calls from webkit when
4678 // the selection hasn't actually changed. We don't want to report these
4679 // because it will cause us to continually claim the X clipboard.
4680 if (selection_text_offset_
!= offset
||
4681 selection_range_
!= range
||
4682 selection_text_
!= text
) {
4683 selection_text_
= text
;
4684 selection_text_offset_
= offset
;
4685 selection_range_
= range
;
4686 SetSelectedText(text
, offset
, range
);
4688 GetRenderWidget()->UpdateSelectionBounds();
4691 void RenderFrameImpl::InitializeUserMediaClient() {
4692 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4695 #if defined(ENABLE_WEBRTC)
4696 DCHECK(!web_user_media_client_
);
4697 web_user_media_client_
= new UserMediaClientImpl(
4699 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4700 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4704 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4705 WebMediaPlayerClient
* client
) {
4706 #if defined(ENABLE_WEBRTC)
4707 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4709 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4710 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4711 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4712 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4713 new RenderMediaLog(),
4714 CreateRendererFactory());
4717 #endif // defined(ENABLE_WEBRTC)
4720 scoped_ptr
<MediaStreamRendererFactory
>
4721 RenderFrameImpl::CreateRendererFactory() {
4722 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4723 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4725 return factory
.Pass();
4726 #if defined(ENABLE_WEBRTC)
4727 return scoped_ptr
<MediaStreamRendererFactory
>(
4728 new MediaStreamRendererFactoryImpl());
4730 return scoped_ptr
<MediaStreamRendererFactory
>(
4731 static_cast<MediaStreamRendererFactory
*>(NULL
));
4735 void RenderFrameImpl::PrepareRenderViewForNavigation(
4737 const RequestNavigationParams
& request_params
,
4739 WebURLRequest::CachePolicy
* cache_policy
) {
4740 DCHECK(render_view_
->webview());
4742 MaybeHandleDebugURL(url
);
4745 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4747 render_view_
->history_list_offset_
=
4748 request_params
.current_history_list_offset
;
4749 render_view_
->history_list_length_
=
4750 request_params
.current_history_list_length
;
4751 if (request_params
.should_clear_history_list
) {
4752 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4753 CHECK_EQ(0, render_view_
->history_list_length_
);
4756 if (!is_swapped_out_
|| frame_
->parent())
4759 // This is a swapped out main frame, so swap the renderer back in.
4760 // We marked the view as hidden when swapping the view out, so be sure to
4761 // reset the visibility state before navigating to the new URL.
4762 render_view_
->webview()->setVisibilityState(
4763 render_view_
->visibilityState(), false);
4765 // If this is an attempt to reload while we are swapped out, we should not
4766 // reload swappedout://, but the previous page, which is stored in
4767 // params.state. Setting is_reload to false will treat this like a back
4768 // navigation to accomplish that.
4770 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4772 // We refresh timezone when a view is swapped in since timezone
4773 // can get out of sync when the system timezone is updated while
4774 // the view is swapped out.
4775 RenderThreadImpl::NotifyTimezoneChange();
4777 render_view_
->SetSwappedOut(false);
4778 is_swapped_out_
= false;
4782 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4783 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4784 switches::kEnableBrowserSideNavigation
));
4786 // TODO(clamy): Execute the beforeunload event.
4788 // Note: At this stage, the goal is to apply all the modifications the
4789 // renderer wants to make to the request, and then send it to the browser, so
4790 // that the actual network request can be started. Ideally, all such
4791 // modifications should take place in willSendRequest, and in the
4792 // implementation of willSendRequest for the various InspectorAgents
4795 // TODO(clamy): Apply devtools override.
4796 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4798 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4800 // TODO(clamy): Same-document navigations should not be sent back to the
4802 // TODO(clamy): Data urls should not be sent back to the browser either.
4803 bool should_replace_current_entry
= false;
4804 WebDataSource
* provisional_data_source
= frame_
->provisionalDataSource();
4805 WebDataSource
* current_data_source
= frame_
->dataSource();
4806 WebDataSource
* data_source
=
4807 provisional_data_source
? provisional_data_source
: current_data_source
;
4809 // The current entry can only be replaced if there already is an entry in the
4811 if (data_source
&& render_view_
->history_list_length_
> 0) {
4812 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
4814 Send(new FrameHostMsg_BeginNavigation(
4816 MakeCommonNavigationParams(request
, should_replace_current_entry
),
4817 BeginNavigationParams(
4818 request
->httpMethod().latin1(), GetWebURLRequestHeaders(*request
),
4819 GetLoadFlagsForWebURLRequest(*request
), request
->hasUserGesture()),
4820 GetRequestBodyForWebURLRequest(*request
)));
4823 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4825 // A loadData request with a specified base URL.
4826 std::string mime_type
, charset
, data
;
4827 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4828 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4829 params
.url
: params
.base_url_for_data_url
;
4831 WebData(data
.c_str(), data
.length()),
4832 WebString::fromUTF8(mime_type
),
4833 WebString::fromUTF8(charset
),
4835 params
.history_url_for_data_url
,
4838 CHECK(false) << "Invalid URL passed: "
4839 << params
.url
.possibly_invalid_spec();
4843 void RenderFrameImpl::SendFailedProvisionalLoad(
4844 const blink::WebURLRequest
& request
,
4845 const blink::WebURLError
& error
,
4846 blink::WebLocalFrame
* frame
) {
4847 bool show_repost_interstitial
=
4848 (error
.reason
== net::ERR_CACHE_MISS
&&
4849 base::EqualsASCII(base::StringPiece16(request
.httpMethod()), "POST"));
4851 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4852 params
.error_code
= error
.reason
;
4853 GetContentClient()->renderer()->GetNavigationErrorStrings(
4854 render_view_
.get(), frame
, request
, error
, NULL
,
4855 ¶ms
.error_description
);
4856 params
.url
= error
.unreachableURL
;
4857 params
.showing_repost_interstitial
= show_repost_interstitial
;
4858 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4859 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4862 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4864 const GURL
& unreachable_url
) {
4865 // Don't display an error page if this is simply a cancelled load. Aside
4866 // from being dumb, Blink doesn't expect it and it will cause a crash.
4867 if (error_code
== net::ERR_ABORTED
)
4870 // Don't display "client blocked" error page if browser has asked us not to.
4871 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4872 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4876 // Allow the embedder to suppress an error page.
4877 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4878 this, unreachable_url
)) {
4882 if (RenderThreadImpl::current() &&
4883 RenderThreadImpl::current()->layout_test_mode()) {
4890 GURL
RenderFrameImpl::GetLoadingUrl() const {
4891 WebDataSource
* ds
= frame_
->dataSource();
4892 if (ds
->hasUnreachableURL())
4893 return ds
->unreachableURL();
4895 const WebURLRequest
& request
= ds
->request();
4896 return request
.url();
4899 void RenderFrameImpl::PopulateDocumentStateFromPending(
4900 DocumentState
* document_state
) {
4901 document_state
->set_request_time(
4902 pending_navigation_params_
->request_params
.request_time
);
4904 InternalDocumentStateData
* internal_data
=
4905 InternalDocumentStateData::FromDocumentState(document_state
);
4907 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4908 url::kJavaScriptScheme
) &&
4909 pending_navigation_params_
->common_params
.navigation_type
==
4910 FrameMsg_Navigate_Type::RESTORE
) {
4911 // We're doing a load of a page that was restored from the last session. By
4912 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4913 // can result in stale data for pages that are set to expire. We explicitly
4914 // override that by setting the policy here so that as necessary we load
4915 // from the network.
4917 // TODO(davidben): Remove this in favor of passing a cache policy to the
4918 // loadHistoryItem call in OnNavigate. That requires not overloading
4919 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4920 // policy based on load type, etc".
4921 internal_data
->set_cache_policy_override(
4922 WebURLRequest::UseProtocolCachePolicy
);
4925 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4926 document_state
->set_load_type(DocumentState::RELOAD
);
4927 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4928 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4930 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4932 internal_data
->set_is_overriding_user_agent(
4933 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4934 internal_data
->set_must_reset_scroll_and_scale_state(
4935 pending_navigation_params_
->common_params
.navigation_type
==
4936 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4937 document_state
->set_can_load_local_resources(
4938 pending_navigation_params_
->request_params
.can_load_local_resources
);
4941 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4942 // A navigation resulting from loading a javascript URL should not be treated
4943 // as a browser initiated event. Instead, we want it to look as if the page
4944 // initiated any load resulting from JS execution.
4945 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4946 url::kJavaScriptScheme
)) {
4947 return NavigationStateImpl::CreateBrowserInitiated(
4948 pending_navigation_params_
->common_params
,
4949 pending_navigation_params_
->start_params
,
4950 pending_navigation_params_
->request_params
);
4952 return NavigationStateImpl::CreateContentInitiated();
4955 #if defined(OS_ANDROID)
4957 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4958 WebMediaPlayerClient
* client
,
4959 WebMediaPlayerEncryptedMediaClient
* encrypted_client
,
4960 media::MediaPermission
* media_permission
,
4961 WebContentDecryptionModule
* initial_cdm
) {
4962 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4963 if (SynchronousCompositorFactory
* factory
=
4964 SynchronousCompositorFactory::GetInstance()) {
4965 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4967 GpuChannelHost
* gpu_channel_host
=
4968 RenderThreadImpl::current()->EstablishGpuChannelSync(
4969 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4971 if (!gpu_channel_host
) {
4972 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4976 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4977 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4979 if (!context_provider
.get()) {
4980 LOG(ERROR
) << "Failed to get context3d for media player";
4984 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4985 context_provider
, gpu_channel_host
, routing_id_
);
4988 return new WebMediaPlayerAndroid(
4989 frame_
, client
, encrypted_client
, weak_factory_
.GetWeakPtr(),
4990 GetMediaPlayerManager(), GetCdmFactory(), media_permission
, initial_cdm
,
4991 stream_texture_factory
,
4992 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4993 new RenderMediaLog());
4996 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4997 if (!media_player_manager_
)
4998 media_player_manager_
= new RendererMediaPlayerManager(this);
4999 return media_player_manager_
;
5002 #endif // defined(OS_ANDROID)
5004 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
5005 if (!media_permission_dispatcher_
)
5006 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
5007 return media_permission_dispatcher_
;
5010 #if defined(ENABLE_MOJO_MEDIA)
5011 media::interfaces::ServiceFactory
* RenderFrameImpl::GetMediaServiceFactory() {
5012 if (!media_service_factory_
) {
5013 mojo::ServiceProviderPtr service_provider
=
5014 ConnectToApplication(GURL("mojo:media"));
5015 mojo::ConnectToService(service_provider
.get(), &media_service_factory_
);
5016 media_service_factory_
.set_connection_error_handler(
5017 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError
,
5018 base::Unretained(this)));
5021 return media_service_factory_
.get();
5024 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5025 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5026 // violation on the old |media_service_factory_| by outstanding
5027 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5029 // media_service_factory_.reset();
5033 bool RenderFrameImpl::AreSecureCodecsSupported() {
5034 #if defined(OS_ANDROID)
5035 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5036 return render_view_
->renderer_preferences_
5037 .use_video_overlay_for_embedded_encrypted_video
;
5040 #endif // defined(OS_ANDROID)
5043 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5044 #if defined(ENABLE_BROWSER_CDMS)
5046 cdm_manager_
= new RendererCdmManager(this);
5047 #endif // defined(ENABLE_BROWSER_CDMS)
5049 if (!cdm_factory_
) {
5052 #if defined(ENABLE_MOJO_MEDIA)
5053 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5055 cdm_factory_
.reset(new RenderCdmFactory(
5056 #if defined(ENABLE_PEPPER_CDMS)
5057 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5058 #elif defined(ENABLE_BROWSER_CDMS)
5062 #endif // defined(ENABLE_MOJO_MEDIA)
5065 return cdm_factory_
.get();
5068 void RenderFrameImpl::RegisterMojoServices() {
5069 // Only main frame have ImageDownloader service.
5070 if (!frame_
->parent()) {
5071 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5072 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5073 base::Unretained(this)));
5077 mojo::ServiceProviderPtr
RenderFrameImpl::ConnectToApplication(
5079 DCHECK(mojo_shell_
);
5080 mojo::ServiceProviderPtr service_provider
;
5081 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5082 request
->url
= mojo::String::From(url
);
5083 mojo_shell_
->ConnectToApplication(request
.Pass(), GetProxy(&service_provider
),
5085 return service_provider
.Pass();
5088 } // namespace content