1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/time/time.h"
22 #include "cc/base/switches.h"
23 #include "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/permissions/permission_dispatcher.h"
25 #include "content/child/plugin_messages.h"
26 #include "content/child/quota_dispatcher.h"
27 #include "content/child/request_extra_data.h"
28 #include "content/child/service_worker/service_worker_handle_reference.h"
29 #include "content/child/service_worker/service_worker_network_provider.h"
30 #include "content/child/service_worker/service_worker_provider_context.h"
31 #include "content/child/service_worker/web_service_worker_provider_impl.h"
32 #include "content/child/v8_value_converter_impl.h"
33 #include "content/child/web_url_loader_impl.h"
34 #include "content/child/web_url_request_util.h"
35 #include "content/child/webmessageportchannel_impl.h"
36 #include "content/child/websocket_bridge.h"
37 #include "content/child/weburlresponse_extradata_impl.h"
38 #include "content/common/clipboard_messages.h"
39 #include "content/common/frame_messages.h"
40 #include "content/common/frame_replication_state.h"
41 #include "content/common/input_messages.h"
42 #include "content/common/navigation_params.h"
43 #include "content/common/service_worker/service_worker_types.h"
44 #include "content/common/swapped_out_messages.h"
45 #include "content/common/view_messages.h"
46 #include "content/public/common/bindings_policy.h"
47 #include "content/public/common/content_constants.h"
48 #include "content/public/common/content_switches.h"
49 #include "content/public/common/context_menu_params.h"
50 #include "content/public/common/isolated_world_ids.h"
51 #include "content/public/common/page_state.h"
52 #include "content/public/common/resource_response.h"
53 #include "content/public/common/url_constants.h"
54 #include "content/public/common/url_utils.h"
55 #include "content/public/renderer/browser_plugin_delegate.h"
56 #include "content/public/renderer/content_renderer_client.h"
57 #include "content/public/renderer/context_menu_client.h"
58 #include "content/public/renderer/document_state.h"
59 #include "content/public/renderer/navigation_state.h"
60 #include "content/public/renderer/render_frame_observer.h"
61 #include "content/public/renderer/renderer_ppapi_host.h"
62 #include "content/renderer/accessibility/renderer_accessibility.h"
63 #include "content/renderer/browser_plugin/browser_plugin.h"
64 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
65 #include "content/renderer/child_frame_compositing_helper.h"
66 #include "content/renderer/context_menu_params_builder.h"
67 #include "content/renderer/devtools/devtools_agent.h"
68 #include "content/renderer/dom_automation_controller.h"
69 #include "content/renderer/external_popup_menu.h"
70 #include "content/renderer/geolocation_dispatcher.h"
71 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
72 #include "content/renderer/history_controller.h"
73 #include "content/renderer/history_serialization.h"
74 #include "content/renderer/image_downloader/image_downloader_impl.h"
75 #include "content/renderer/ime_event_guard.h"
76 #include "content/renderer/internal_document_state_data.h"
77 #include "content/renderer/manifest/manifest_manager.h"
78 #include "content/renderer/media/audio_renderer_mixer_manager.h"
79 #include "content/renderer/media/crypto/render_cdm_factory.h"
80 #include "content/renderer/media/media_permission_dispatcher.h"
81 #include "content/renderer/media/media_stream_dispatcher.h"
82 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
83 #include "content/renderer/media/midi_dispatcher.h"
84 #include "content/renderer/media/render_media_log.h"
85 #include "content/renderer/media/user_media_client_impl.h"
86 #include "content/renderer/media/webmediaplayer_ms.h"
87 #include "content/renderer/memory_benchmarking_extension.h"
88 #include "content/renderer/mojo/service_registry_js_wrapper.h"
89 #include "content/renderer/navigation_state_impl.h"
90 #include "content/renderer/notification_permission_dispatcher.h"
91 #include "content/renderer/npapi/plugin_channel_host.h"
92 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
93 #include "content/renderer/presentation/presentation_dispatcher.h"
94 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
95 #include "content/renderer/render_frame_proxy.h"
96 #include "content/renderer/render_process.h"
97 #include "content/renderer/render_thread_impl.h"
98 #include "content/renderer/render_view_impl.h"
99 #include "content/renderer/render_widget_fullscreen_pepper.h"
100 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
101 #include "content/renderer/renderer_webcolorchooser_impl.h"
102 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
103 #include "content/renderer/shared_worker_repository.h"
104 #include "content/renderer/skia_benchmarking_extension.h"
105 #include "content/renderer/stats_collection_controller.h"
106 #include "content/renderer/web_ui_extension.h"
107 #include "content/renderer/websharedworker_proxy.h"
108 #include "gin/modules/module_registry.h"
109 #include "media/base/audio_renderer_mixer_input.h"
110 #include "media/base/media_log.h"
111 #include "media/blink/webencryptedmediaclient_impl.h"
112 #include "media/blink/webmediaplayer_impl.h"
113 #include "media/blink/webmediaplayer_params.h"
114 #include "media/renderers/gpu_video_accelerator_factories.h"
115 #include "net/base/data_url.h"
116 #include "net/base/net_errors.h"
117 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
118 #include "net/http/http_util.h"
119 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
120 #include "third_party/WebKit/public/platform/WebString.h"
121 #include "third_party/WebKit/public/platform/WebURL.h"
122 #include "third_party/WebKit/public/platform/WebURLError.h"
123 #include "third_party/WebKit/public/platform/WebURLResponse.h"
124 #include "third_party/WebKit/public/platform/WebVector.h"
125 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
126 #include "third_party/WebKit/public/web/WebDocument.h"
127 #include "third_party/WebKit/public/web/WebFrameWidget.h"
128 #include "third_party/WebKit/public/web/WebGlyphCache.h"
129 #include "third_party/WebKit/public/web/WebKit.h"
130 #include "third_party/WebKit/public/web/WebLocalFrame.h"
131 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
132 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
133 #include "third_party/WebKit/public/web/WebPlugin.h"
134 #include "third_party/WebKit/public/web/WebPluginParams.h"
135 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
136 #include "third_party/WebKit/public/web/WebRange.h"
137 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
138 #include "third_party/WebKit/public/web/WebScriptSource.h"
139 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
140 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
141 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
142 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
143 #include "third_party/WebKit/public/web/WebSettings.h"
144 #include "third_party/WebKit/public/web/WebSurroundingText.h"
145 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
146 #include "third_party/WebKit/public/web/WebView.h"
147 #include "third_party/mojo/src/mojo/edk/js/core.h"
148 #include "third_party/mojo/src/mojo/edk/js/support.h"
150 #if defined(ENABLE_PLUGINS)
151 #include "content/renderer/npapi/webplugin_impl.h"
152 #include "content/renderer/pepper/pepper_browser_connection.h"
153 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
154 #include "content/renderer/pepper/pepper_webplugin_impl.h"
155 #include "content/renderer/pepper/plugin_module.h"
158 #if defined(ENABLE_WEBRTC)
159 #include "content/renderer/media/rtc_peer_connection_handler.h"
162 #if defined(OS_ANDROID)
163 #include <cpu-features.h>
165 #include "content/common/gpu/client/context_provider_command_buffer.h"
166 #include "content/renderer/android/synchronous_compositor_factory.h"
167 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
168 #include "content/renderer/media/android/renderer_media_player_manager.h"
169 #include "content/renderer/media/android/stream_texture_factory_impl.h"
170 #include "content/renderer/media/android/webmediaplayer_android.h"
172 #include "cc/blink/context_provider_web_context.h"
175 #if defined(ENABLE_PEPPER_CDMS)
176 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
177 #elif defined(ENABLE_BROWSER_CDMS)
178 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
181 #if defined(ENABLE_MOJO_MEDIA)
182 #include "media/mojo/services/mojo_cdm_factory.h"
183 #include "media/mojo/services/mojo_renderer_factory.h"
184 #include "mojo/application/public/interfaces/shell.mojom.h"
185 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
187 #include "media/renderers/default_renderer_factory.h"
190 #if defined(ENABLE_WEBVR)
191 #include "content/renderer/vr/vr_dispatcher.h"
194 using blink::WebContextMenuData
;
195 using blink::WebData
;
196 using blink::WebDataSource
;
197 using blink::WebDocument
;
198 using blink::WebDOMEvent
;
199 using blink::WebDOMMessageEvent
;
200 using blink::WebElement
;
201 using blink::WebExternalPopupMenu
;
202 using blink::WebExternalPopupMenuClient
;
203 using blink::WebFrame
;
204 using blink::WebHistoryItem
;
205 using blink::WebHTTPBody
;
206 using blink::WebLocalFrame
;
207 using blink::WebMediaPlayer
;
208 using blink::WebMediaPlayerClient
;
209 using blink::WebNavigationPolicy
;
210 using blink::WebNavigationType
;
211 using blink::WebNode
;
212 using blink::WebPluginParams
;
213 using blink::WebPopupMenuInfo
;
214 using blink::WebRange
;
215 using blink::WebReferrerPolicy
;
216 using blink::WebScriptSource
;
217 using blink::WebSearchableFormData
;
218 using blink::WebSecurityOrigin
;
219 using blink::WebSecurityPolicy
;
220 using blink::WebSerializedScriptValue
;
221 using blink::WebServiceWorkerProvider
;
222 using blink::WebSettings
;
223 using blink::WebStorageQuotaCallbacks
;
224 using blink::WebString
;
226 using blink::WebURLError
;
227 using blink::WebURLRequest
;
228 using blink::WebURLResponse
;
229 using blink::WebUserGestureIndicator
;
230 using blink::WebVector
;
231 using blink::WebView
;
233 using base::TimeDelta
;
239 const char kDefaultAcceptHeader
[] =
240 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
242 const char kAcceptHeader
[] = "Accept";
244 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
246 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
247 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
248 LAZY_INSTANCE_INITIALIZER
;
250 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
251 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
253 int64
ExtractPostId(HistoryEntry
* entry
) {
257 const WebHistoryItem
& item
= entry
->root();
258 if (item
.isNull() || item
.httpBody().isNull())
261 return item
.httpBody().identifier();
264 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
265 const WebURLResponse
& response
) {
266 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
269 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
270 // Replace any occurrences of swappedout:// with about:blank.
271 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
272 WebVector
<WebURL
> urls
;
273 ds
->redirectChain(urls
);
274 result
->reserve(urls
.size());
275 for (size_t i
= 0; i
< urls
.size(); ++i
) {
276 if (urls
[i
] != GURL(kSwappedOutURL
))
277 result
->push_back(urls
[i
]);
279 result
->push_back(blank_url
);
283 // Returns the original request url. If there is no redirect, the original
284 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
285 // frame was loaded by loadData, the original url will be ds->unreachableURL()
286 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
287 // WebDataSource has unreachable URL means that the frame is loaded through
288 // blink::WebFrame::loadData(), and the base URL will be in the redirect
289 // chain. However, we never visited the baseURL. So in this case, we should
290 // use the unreachable URL as the original URL.
291 if (ds
->hasUnreachableURL())
292 return ds
->unreachableURL();
294 std::vector
<GURL
> redirects
;
295 GetRedirectChain(ds
, &redirects
);
296 if (!redirects
.empty())
297 return redirects
.at(0);
299 return ds
->originalRequest().url();
302 NOINLINE
void CrashIntentionally() {
303 // NOTE(shess): Crash directly rather than using NOTREACHED() so
304 // that the signature is easier to triage in crash reports.
305 volatile int* zero
= NULL
;
309 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
310 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
311 // NOTE(rogerm): We intentionally perform an invalid heap access here in
312 // order to trigger an Address Sanitizer (ASAN) error report.
313 const char kCrashDomain
[] = "crash";
314 const char kHeapOverflow
[] = "/heap-overflow";
315 const char kHeapUnderflow
[] = "/heap-underflow";
316 const char kUseAfterFree
[] = "/use-after-free";
317 #if defined(SYZYASAN)
318 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
319 const char kCorruptHeap
[] = "/corrupt-heap";
322 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
328 std::string
crash_type(url
.path());
329 if (crash_type
== kHeapOverflow
) {
330 base::debug::AsanHeapOverflow();
331 } else if (crash_type
== kHeapUnderflow
) {
332 base::debug::AsanHeapUnderflow();
333 } else if (crash_type
== kUseAfterFree
) {
334 base::debug::AsanHeapUseAfterFree();
335 #if defined(SYZYASAN)
336 } else if (crash_type
== kCorruptHeapBlock
) {
337 base::debug::AsanCorruptHeapBlock();
338 } else if (crash_type
== kCorruptHeap
) {
339 base::debug::AsanCorruptHeap();
343 #endif // ADDRESS_SANITIZER || SYZYASAN
345 void MaybeHandleDebugURL(const GURL
& url
) {
346 if (!url
.SchemeIs(kChromeUIScheme
))
348 if (url
== GURL(kChromeUICrashURL
)) {
349 CrashIntentionally();
350 } else if (url
== GURL(kChromeUIDumpURL
)) {
351 // This URL will only correctly create a crash dump file if content is
352 // hosted in a process that has correctly called
353 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
354 // of base::debug::DumpWithoutCrashing for more details.
355 base::debug::DumpWithoutCrashing();
356 } else if (url
== GURL(kChromeUIKillURL
)) {
357 base::Process::Current().Terminate(1, false);
358 } else if (url
== GURL(kChromeUIHangURL
)) {
360 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
362 } else if (url
== GURL(kChromeUIShorthangURL
)) {
363 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
366 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
367 MaybeTriggerAsanError(url
);
368 #endif // ADDRESS_SANITIZER || SYZYASAN
371 // Returns false unless this is a top-level navigation.
372 bool IsTopLevelNavigation(WebFrame
* frame
) {
373 return frame
->parent() == NULL
;
376 // Returns false unless this is a top-level navigation that crosses origins.
377 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
379 WebNavigationType type
,
381 if (!IsTopLevelNavigation(frame
))
384 // Navigations initiated within Webkit are not sent out to the external host
385 // in the following cases.
386 // 1. The url scheme is not http/https
387 // 2. The origin of the url and the opener is the same in which case the
388 // opener relationship is maintained.
389 // 3. Reloads/form submits/back forward navigations
390 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
393 if (type
!= blink::WebNavigationTypeReload
&&
394 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
395 // The opener relationship between the new window and the parent allows the
396 // new window to script the parent and vice versa. This is not allowed if
397 // the origins of the two domains are different. This can be treated as a
398 // top level navigation and routed back to the host.
399 blink::WebFrame
* opener
= frame
->opener();
403 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
409 WebURLRequest
CreateURLRequestForNavigation(
410 const CommonNavigationParams
& common_params
,
411 scoped_ptr
<StreamOverrideParameters
> stream_override
,
412 bool is_view_source_mode_enabled
) {
413 WebURLRequest
request(common_params
.url
);
414 if (is_view_source_mode_enabled
)
415 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
417 if (common_params
.referrer
.url
.is_valid()) {
418 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
419 common_params
.referrer
.policy
,
421 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
422 if (!web_referrer
.isEmpty())
423 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
426 RequestExtraData
* extra_data
= new RequestExtraData();
427 extra_data
->set_stream_override(stream_override
.Pass());
428 request
.setExtraData(extra_data
);
430 // Set the ui timestamp for this navigation. Currently the timestamp here is
431 // only non empty when the navigation was triggered by an Android intent. The
432 // timestamp is converted to a double version supported by blink. It will be
433 // passed back to the browser in the DidCommitProvisionalLoad and the
434 // DocumentLoadComplete IPCs.
435 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
436 request
.setUiStartTime(ui_timestamp
.InSecondsF());
437 request
.setInputPerfMetricReportPolicy(
438 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
439 common_params
.report_type
));
443 void UpdateFrameNavigationTiming(WebFrame
* frame
,
444 base::TimeTicks browser_navigation_start
,
445 base::TimeTicks renderer_navigation_start
) {
446 // The browser provides the navigation_start time to bootstrap the
447 // Navigation Timing information for the browser-initiated navigations. In
448 // case of cross-process navigations, this carries over the time of
449 // finishing the onbeforeunload handler of the previous page.
450 DCHECK(!browser_navigation_start
.is_null());
451 if (frame
->provisionalDataSource()) {
452 // |browser_navigation_start| is likely before this process existed, so we
453 // can't use InterProcessTimeTicksConverter. We need at least to ensure
454 // that the browser-side navigation start we set is not later than the one
455 // on the renderer side.
456 base::TimeTicks navigation_start
= std::min(
457 browser_navigation_start
, renderer_navigation_start
);
458 double navigation_start_seconds
=
459 (navigation_start
- base::TimeTicks()).InSecondsF();
460 frame
->provisionalDataSource()->setNavigationStartTime(
461 navigation_start_seconds
);
462 // TODO(clamy): We need to provide additional timing values for the
463 // Navigation Timing API to work with browser-side navigations.
468 CommonNavigationParams
MakeCommonNavigationParams(
469 blink::WebURLRequest
* request
) {
470 const RequestExtraData kEmptyData
;
471 const RequestExtraData
* extra_data
=
472 static_cast<RequestExtraData
*>(request
->extraData());
474 extra_data
= &kEmptyData
;
476 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
477 request
->referrerPolicy());
479 // Set the ui timestamp for this navigation. Currently the timestamp here is
480 // only non empty when the navigation was triggered by an Android intent, or
481 // by the user clicking on a link. The timestamp is converted from a double
482 // version supported by blink. It will be passed back to the renderer in the
483 // CommitNavigation IPC, and then back to the browser again in the
484 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
485 base::TimeTicks ui_timestamp
=
486 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
487 FrameMsg_UILoadMetricsReportType::Value report_type
=
488 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
489 request
->inputPerfMetricReportPolicy());
490 return CommonNavigationParams(request
->url(), referrer
,
491 extra_data
->transition_type(),
492 FrameMsg_Navigate_Type::NORMAL
, true,
493 ui_timestamp
, report_type
, GURL(), GURL());
496 #if !defined(OS_ANDROID)
497 media::Context3D
GetSharedMainThreadContext3D() {
498 cc::ContextProvider
* provider
=
499 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
501 return media::Context3D();
502 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
506 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
507 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
508 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
509 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
512 bool IsSwappedOutStateForbidden() {
513 return base::CommandLine::ForCurrentProcess()->HasSwitch(
514 switches::kSitePerProcess
);
517 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
523 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
525 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
526 CreateParams
params(render_view
, routing_id
);
528 if (g_create_render_frame_impl
)
529 return g_create_render_frame_impl(params
);
531 return new RenderFrameImpl(params
);
535 RenderFrame
* RenderFrame::FromRoutingID(int routing_id
) {
536 return RenderFrameImpl::FromRoutingID(routing_id
);
540 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int routing_id
) {
541 RoutingIDFrameMap::iterator iter
=
542 g_routing_id_frame_map
.Get().find(routing_id
);
543 if (iter
!= g_routing_id_frame_map
.Get().end())
549 void RenderFrameImpl::CreateFrame(
551 int parent_routing_id
,
552 int previous_sibling_routing_id
,
553 int proxy_routing_id
,
554 const FrameReplicationState
& replicated_state
,
555 CompositorDependencies
* compositor_deps
,
556 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
557 blink::WebLocalFrame
* web_frame
;
558 RenderFrameImpl
* render_frame
;
559 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
560 RenderFrameProxy
* parent_proxy
=
561 RenderFrameProxy::FromRoutingID(parent_routing_id
);
562 // If the browser is sending a valid parent routing id, it should already
563 // be created and registered.
565 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
567 blink::WebFrame
* previous_sibling_web_frame
= nullptr;
568 RenderFrameProxy
* previous_sibling_proxy
=
569 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id
);
570 if (previous_sibling_proxy
)
571 previous_sibling_web_frame
= previous_sibling_proxy
->web_frame();
573 // Create the RenderFrame and WebLocalFrame, linking the two.
575 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
576 web_frame
= parent_web_frame
->createLocalChild(
577 replicated_state
.scope
, WebString::fromUTF8(replicated_state
.name
),
578 replicated_state
.sandbox_flags
, render_frame
,
579 previous_sibling_web_frame
);
581 RenderFrameProxy
* proxy
=
582 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
584 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
586 blink::WebLocalFrame::create(replicated_state
.scope
, render_frame
);
587 render_frame
->proxy_routing_id_
= proxy_routing_id
;
588 web_frame
->initializeToReplaceRemoteFrame(
589 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
590 replicated_state
.sandbox_flags
);
592 render_frame
->SetWebFrame(web_frame
);
593 CHECK_IMPLIES(parent_routing_id
== MSG_ROUTING_NONE
, !web_frame
->parent());
595 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
596 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
597 switches::kSitePerProcess
));
598 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
599 widget_params
.routing_id
, widget_params
.surface_id
,
600 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
601 compositor_deps
, web_frame
);
602 // TODO(kenrb): Observing shouldn't be necessary when we sort out
603 // WasShown and WasHidden, separating page-level visibility from
604 // frame-level visibility.
605 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
608 render_frame
->Initialize();
612 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
613 return RenderFrameImpl::FromWebFrame(web_frame
);
617 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
618 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
619 if (iter
!= g_frame_map
.Get().end())
625 void RenderFrameImpl::InstallCreateHook(
626 CreateRenderFrameImplFunction create_render_frame_impl
) {
627 CHECK(!g_create_render_frame_impl
);
628 g_create_render_frame_impl
= create_render_frame_impl
;
631 // RenderFrameImpl ----------------------------------------------------------
632 RenderFrameImpl::RenderFrameImpl(const CreateParams
& params
)
635 is_local_root_(false),
636 render_view_(params
.render_view
->AsWeakPtr()),
637 routing_id_(params
.routing_id
),
638 is_swapped_out_(false),
639 render_frame_proxy_(NULL
),
640 is_detaching_(false),
641 proxy_routing_id_(MSG_ROUTING_NONE
),
642 #if defined(ENABLE_PLUGINS)
643 plugin_power_saver_helper_(NULL
),
646 selection_text_offset_(0),
647 selection_range_(gfx::Range::InvalidRange()),
648 handling_select_range_(false),
649 notification_permission_dispatcher_(NULL
),
650 web_user_media_client_(NULL
),
651 media_permission_dispatcher_(NULL
),
652 midi_dispatcher_(NULL
),
653 #if defined(OS_ANDROID)
654 media_player_manager_(NULL
),
656 #if defined(ENABLE_BROWSER_CDMS)
659 #if defined(VIDEO_HOLE)
660 contains_media_player_(false),
662 devtools_agent_(nullptr),
663 geolocation_dispatcher_(NULL
),
664 push_messaging_dispatcher_(NULL
),
665 presentation_dispatcher_(NULL
),
666 screen_orientation_dispatcher_(NULL
),
667 manifest_manager_(NULL
),
668 accessibility_mode_(AccessibilityModeOff
),
669 renderer_accessibility_(NULL
),
670 weak_factory_(this) {
671 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
672 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
673 CHECK(result
.second
) << "Inserting a duplicate item.";
675 RenderThread::Get()->AddRoute(routing_id_
, this);
677 render_view_
->RegisterRenderFrame(this);
679 // Everything below subclasses RenderFrameObserver and is automatically
680 // deleted when the RenderFrame gets deleted.
681 #if defined(OS_ANDROID)
682 new GinJavaBridgeDispatcher(this);
685 #if defined(ENABLE_PLUGINS)
686 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
689 manifest_manager_
= new ManifestManager(this);
692 RenderFrameImpl::~RenderFrameImpl() {
693 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
694 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
696 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_
);
698 #if defined(VIDEO_HOLE)
699 if (contains_media_player_
)
700 render_view_
->UnregisterVideoHoleFrame(this);
704 if (!IsSwappedOutStateForbidden()) {
705 // When using swapped out frames, RenderFrameProxy is "owned" by
706 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
707 // along with this object.
708 if (render_frame_proxy_
&&
709 !base::CommandLine::ForCurrentProcess()->HasSwitch(
710 switches::kSitePerProcess
)) {
711 // The following method calls back into this object and clears
712 // |render_frame_proxy_|.
713 render_frame_proxy_
->frameDetached(
714 blink::WebRemoteFrameClient::DetachType::Remove
);
718 // Ensure the RenderView doesn't point to this object, once it is destroyed.
719 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
720 // is |this|, once the object is no longer leaked.
721 // See https://crbug.com/464764.
722 render_view_
->main_render_frame_
= nullptr;
725 render_view_
->UnregisterRenderFrame(this);
726 g_routing_id_frame_map
.Get().erase(routing_id_
);
727 RenderThread::Get()->RemoveRoute(routing_id_
);
730 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
733 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
734 std::make_pair(web_frame
, this));
735 CHECK(result
.second
) << "Inserting a duplicate item.";
740 void RenderFrameImpl::Initialize() {
741 is_subframe_
= !!frame_
->parent();
742 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
744 #if defined(ENABLE_PLUGINS)
745 new PepperBrowserConnection(this);
747 new SharedWorkerRepository(this);
749 if (is_local_root_
&& !render_frame_proxy_
) {
750 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
751 // when |this| is deleted.
752 devtools_agent_
= new DevToolsAgent(this);
755 RegisterMojoServices();
757 // We delay calling this until we have the WebFrame so that any observer or
758 // embedder can call GetWebFrame on any RenderFrame.
759 GetContentClient()->renderer()->RenderFrameCreated(this);
762 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
763 return render_view_
.get();
766 #if defined(ENABLE_PLUGINS)
767 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
768 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
769 DidCreatePepperPlugin(host
));
770 if (host
->GetPluginName() == kFlashPluginName
) {
771 RenderThread::Get()->RecordAction(
772 base::UserMetricsAction("FrameLoadWithFlash"));
776 void RenderFrameImpl::PepperDidChangeCursor(
777 PepperPluginInstanceImpl
* instance
,
778 const blink::WebCursorInfo
& cursor
) {
779 // Update the cursor appearance immediately if the requesting plugin is the
780 // one which receives the last mouse event. Otherwise, the new cursor won't be
781 // picked up until the plugin gets the next input event. That is bad if, e.g.,
782 // the plugin would like to set an invisible cursor when there isn't any user
783 // input for a while.
784 if (instance
== render_view_
->pepper_last_mouse_event_target())
785 GetRenderWidget()->didChangeCursor(cursor
);
788 void RenderFrameImpl::PepperDidReceiveMouseEvent(
789 PepperPluginInstanceImpl
* instance
) {
790 render_view_
->set_pepper_last_mouse_event_target(instance
);
793 void RenderFrameImpl::PepperTextInputTypeChanged(
794 PepperPluginInstanceImpl
* instance
) {
795 if (instance
!= render_view_
->focused_pepper_plugin())
798 GetRenderWidget()->UpdateTextInputType();
800 FocusedNodeChangedForAccessibility(WebNode());
803 void RenderFrameImpl::PepperCaretPositionChanged(
804 PepperPluginInstanceImpl
* instance
) {
805 if (instance
!= render_view_
->focused_pepper_plugin())
807 GetRenderWidget()->UpdateSelectionBounds();
810 void RenderFrameImpl::PepperCancelComposition(
811 PepperPluginInstanceImpl
* instance
) {
812 if (instance
!= render_view_
->focused_pepper_plugin())
814 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
815 #if defined(OS_MACOSX) || defined(USE_AURA)
816 GetRenderWidget()->UpdateCompositionInfo(true);
820 void RenderFrameImpl::PepperSelectionChanged(
821 PepperPluginInstanceImpl
* instance
) {
822 if (instance
!= render_view_
->focused_pepper_plugin())
824 SyncSelectionIfRequired();
827 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
828 PepperPluginInstanceImpl
* plugin
) {
830 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
831 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
832 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
833 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
834 plugin
, active_url
, GetRenderWidget()->screenInfo());
835 widget
->show(blink::WebNavigationPolicyIgnore
);
839 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
840 if (!render_view_
->focused_pepper_plugin())
842 return render_view_
->focused_pepper_plugin()->
843 IsPluginAcceptingCompositionEvents();
846 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
847 base::ProcessId plugin_pid
) {
848 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
849 // routing_id_ as a result.
850 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
853 void RenderFrameImpl::SimulateImeSetComposition(
854 const base::string16
& text
,
855 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
858 render_view_
->OnImeSetComposition(
859 text
, underlines
, selection_start
, selection_end
);
862 void RenderFrameImpl::SimulateImeConfirmComposition(
863 const base::string16
& text
,
864 const gfx::Range
& replacement_range
) {
865 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
868 void RenderFrameImpl::OnImeSetComposition(
869 const base::string16
& text
,
870 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
873 // When a PPAPI plugin has focus, we bypass WebKit.
874 if (!IsPepperAcceptingCompositionEvents()) {
875 pepper_composition_text_
= text
;
877 // TODO(kinaba) currently all composition events are sent directly to
878 // plugins. Use DOM event mechanism after WebKit is made aware about
879 // plugins that support composition.
880 // The code below mimics the behavior of WebCore::Editor::setComposition.
882 // Empty -> nonempty: composition started.
883 if (pepper_composition_text_
.empty() && !text
.empty()) {
884 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
887 // Nonempty -> empty: composition canceled.
888 if (!pepper_composition_text_
.empty() && text
.empty()) {
889 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
892 pepper_composition_text_
= text
;
893 // Nonempty: composition is ongoing.
894 if (!pepper_composition_text_
.empty()) {
895 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
896 pepper_composition_text_
, underlines
, selection_start
,
902 void RenderFrameImpl::OnImeConfirmComposition(
903 const base::string16
& text
,
904 const gfx::Range
& replacement_range
,
905 bool keep_selection
) {
906 // When a PPAPI plugin has focus, we bypass WebKit.
907 // Here, text.empty() has a special meaning. It means to commit the last
908 // update of composition text (see
909 // RenderWidgetHost::ImeConfirmComposition()).
910 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
913 // last_text is empty only when both text and pepper_composition_text_ is.
915 if (last_text
.empty())
918 if (!IsPepperAcceptingCompositionEvents()) {
919 base::i18n::UTF16CharIterator
iterator(&last_text
);
921 while (iterator
.Advance()) {
922 blink::WebKeyboardEvent char_event
;
923 char_event
.type
= blink::WebInputEvent::Char
;
924 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
925 char_event
.modifiers
= 0;
926 char_event
.windowsKeyCode
= last_text
[i
];
927 char_event
.nativeKeyCode
= last_text
[i
];
929 const int32 char_start
= i
;
930 for (; i
< iterator
.array_pos(); ++i
) {
931 char_event
.text
[i
- char_start
] = last_text
[i
];
932 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
935 if (GetRenderWidget()->webwidget())
936 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
939 // Mimics the order of events sent by WebKit.
940 // See WebCore::Editor::setComposition() for the corresponding code.
941 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
942 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
944 pepper_composition_text_
.clear();
946 #endif // defined(ENABLE_PLUGINS)
948 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
949 if (!web_user_media_client_
)
950 InitializeUserMediaClient();
951 return web_user_media_client_
?
952 web_user_media_client_
->media_stream_dispatcher() : NULL
;
955 bool RenderFrameImpl::Send(IPC::Message
* message
) {
960 if (is_swapped_out_
) {
961 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
967 return RenderThread::Get()->Send(message
);
970 #if defined(OS_MACOSX) || defined(OS_ANDROID)
971 void RenderFrameImpl::DidHideExternalPopupMenu() {
972 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
973 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
974 external_popup_menu_
.reset();
978 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
979 // We may get here while detaching, when the WebFrame has been deleted. Do
980 // not process any messages in this state.
984 // TODO(kenrb): document() should not be null, but as a transitional step
985 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
986 // to this method. This happens for a top-level remote frame, where a
987 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
988 // around and is still able to receive messages.
989 if (!frame_
->document().isNull())
990 GetContentClient()->SetActiveURL(frame_
->document().url());
992 base::ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
993 RenderFrameObserver
* observer
;
994 while ((observer
= it
.GetNext()) != NULL
) {
995 if (observer
->OnMessageReceived(msg
))
1000 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1001 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1002 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1003 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1004 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1005 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1006 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1007 OnCustomContextMenuAction
)
1008 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1009 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1010 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1011 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1012 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1013 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1014 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1015 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1016 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1017 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset
,
1018 OnAdjustSelectionByCharacterOffset
)
1019 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1020 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1021 OnMoveRangeSelectionExtent
)
1022 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1023 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1024 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1025 OnExtendSelectionAndDelete
)
1026 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1027 OnSetCompositionFromExistingText
)
1028 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1029 OnExecuteNoValueEditCommand
)
1030 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1031 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole
, OnAddMessageToConsole
)
1032 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1033 OnJavaScriptExecuteRequest
)
1034 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1035 OnJavaScriptExecuteRequestForTests
)
1036 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld
,
1037 OnJavaScriptExecuteRequestInIsolatedWorld
)
1038 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1039 OnVisualStateRequest
)
1040 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1041 OnSetEditableSelectionOffsets
)
1042 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1043 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1044 OnTextSurroundingSelectionRequest
)
1045 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1046 OnSetAccessibilityMode
)
1047 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1048 OnSnapshotAccessibilityTree
)
1049 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1050 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1051 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1052 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1053 OnTextTrackSettingsChanged
)
1054 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1055 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1056 #if defined(OS_ANDROID)
1057 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1058 #elif defined(OS_MACOSX)
1059 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1060 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1062 IPC_END_MESSAGE_MAP()
1067 void RenderFrameImpl::OnNavigate(
1068 const CommonNavigationParams
& common_params
,
1069 const StartNavigationParams
& start_params
,
1070 const RequestNavigationParams
& request_params
) {
1071 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1072 switches::kEnableBrowserSideNavigation
));
1073 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1074 "url", common_params
.url
.possibly_invalid_spec());
1075 NavigateInternal(common_params
, start_params
, request_params
,
1076 scoped_ptr
<StreamOverrideParameters
>());
1079 void RenderFrameImpl::NavigateToSwappedOutURL() {
1080 // We use loadRequest instead of loadHTMLString because the former commits
1081 // synchronously. Otherwise a new navigation can interrupt the navigation
1082 // to kSwappedOutURL. If that happens to be to the page we had been
1083 // showing, then WebKit will never send a commit and we'll be left spinning.
1084 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1085 // the navigation to swappedout:// is not announced to the browser side.
1086 is_swapped_out_
= true;
1087 GURL
swappedOutURL(kSwappedOutURL
);
1088 WebURLRequest
request(swappedOutURL
);
1089 frame_
->loadRequest(request
);
1092 void RenderFrameImpl::BindServiceRegistry(
1093 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1094 mojo::ServiceProviderPtr exposed_services
) {
1095 service_registry_
.Bind(services
.Pass());
1096 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1099 ManifestManager
* RenderFrameImpl::manifest_manager() {
1100 return manifest_manager_
;
1103 void RenderFrameImpl::SetPendingNavigationParams(
1104 scoped_ptr
<NavigationParams
> navigation_params
) {
1105 pending_navigation_params_
= navigation_params
.Pass();
1108 void RenderFrameImpl::OnBeforeUnload() {
1109 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1111 // TODO(creis): Right now, this is only called on the main frame. Make the
1112 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1114 CHECK(!frame_
->parent());
1116 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1117 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1118 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1119 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1120 before_unload_start_time
,
1121 before_unload_end_time
));
1124 void RenderFrameImpl::OnSwapOut(
1125 int proxy_routing_id
,
1127 const FrameReplicationState
& replicated_frame_state
) {
1128 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1129 RenderFrameProxy
* proxy
= NULL
;
1130 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1131 switches::kSitePerProcess
);
1132 bool is_main_frame
= !frame_
->parent();
1134 // This codepath should only be hit for subframes when in --site-per-process.
1135 CHECK_IMPLIES(!is_main_frame
, is_site_per_process
);
1137 // Only run unload if we're not swapped out yet, but send the ack either way.
1138 if (!is_swapped_out_
) {
1139 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1140 // a different process. This involves running the unload handler and
1141 // clearing the page. We also allow this process to exit if there are no
1142 // other active RenderFrames in it.
1144 // Send an UpdateState message before we get swapped out.
1145 render_view_
->SyncNavigationState();
1147 // If we need a proxy to replace this, create it now so its routing id is
1148 // registered for receiving IPC messages.
1149 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1150 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(
1151 this, proxy_routing_id
, replicated_frame_state
.scope
);
1154 // Synchronously run the unload handler before sending the ACK.
1155 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1156 // unload on subframes as well.
1158 frame_
->dispatchUnloadEvent();
1160 // Swap out and stop sending any IPC messages that are not ACKs.
1162 render_view_
->SetSwappedOut(true);
1163 is_swapped_out_
= true;
1165 // Set the proxy here, since OnStop() below could cause an onload event
1166 // handler to execute, which could trigger code such as
1167 // willCheckAndDispatchMessageEvent() that needs the proxy.
1169 set_render_frame_proxy(proxy
);
1171 // Now that we're swapped out and filtering IPC messages, stop loading to
1172 // ensure that no other in-progress navigation continues. We do this here
1173 // to avoid sending a DidStopLoading message to the browser process.
1174 // TODO(creis): Should we be stopping all frames here and using
1175 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1177 if (!IsSwappedOutStateForbidden())
1180 // Transfer settings such as initial drawing parameters to the remote frame,
1181 // if one is created, that will replace this frame.
1182 if (!is_main_frame
&& proxy
)
1183 proxy
->web_frame()->initializeFromFrame(frame_
);
1185 // Replace the page with a blank dummy URL. The unload handler will not be
1186 // run a second time, thanks to a check in FrameLoader::stopLoading.
1187 // TODO(creis): Need to add a better way to do this that avoids running the
1188 // beforeunload handler. For now, we just run it a second time silently.
1189 if (!IsSwappedOutStateForbidden())
1190 NavigateToSwappedOutURL();
1192 // Let WebKit know that this view is hidden so it can drop resources and
1193 // stop compositing.
1194 // TODO(creis): Support this for subframes as well.
1195 if (is_main_frame
) {
1196 render_view_
->webview()->setVisibilityState(
1197 blink::WebPageVisibilityStateHidden
, false);
1201 // It is now safe to show modal dialogs again.
1202 // TODO(creis): Deal with modal dialogs from subframes.
1204 render_view_
->suppress_dialogs_until_swap_out_
= false;
1206 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1208 RenderViewImpl
* render_view
= render_view_
.get();
1210 // Now that all of the cleanup is complete and the browser side is notified,
1211 // start using the RenderFrameProxy, if one is created.
1212 if (proxy
&& IsSwappedOutStateForbidden()) {
1213 frame_
->swap(proxy
->web_frame());
1216 proxy
->OnDidStartLoading();
1219 // In --site-per-process, initialize the WebRemoteFrame with the replication
1220 // state passed by the process that is now rendering the frame.
1221 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1222 // in that case we leave the LocalFrame as the main frame visible to Blink
1223 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1224 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1225 // When we do an unconditional swap for all frames, we can remove
1226 // !is_main_frame below.
1227 if (proxy
&& IsSwappedOutStateForbidden())
1228 proxy
->SetReplicatedState(replicated_frame_state
);
1230 // Safe to exit if no one else is using the process.
1231 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1232 // the process based on the lifetime of this RenderFrameImpl object.
1233 if (is_main_frame
) {
1234 render_view
->WasSwappedOut();
1238 void RenderFrameImpl::OnContextMenuClosed(
1239 const CustomContextMenuContext
& custom_context
) {
1240 if (custom_context
.request_id
) {
1241 // External request, should be in our map.
1242 ContextMenuClient
* client
=
1243 pending_context_menus_
.Lookup(custom_context
.request_id
);
1245 client
->OnMenuClosed(custom_context
.request_id
);
1246 pending_context_menus_
.Remove(custom_context
.request_id
);
1249 if (custom_context
.link_followed
.is_valid())
1250 frame_
->sendPings(context_menu_node_
, custom_context
.link_followed
);
1251 // Internal request, forward to WebKit.
1252 context_menu_node_
.reset();
1256 void RenderFrameImpl::OnCustomContextMenuAction(
1257 const CustomContextMenuContext
& custom_context
,
1259 if (custom_context
.request_id
) {
1260 // External context menu request, look in our map.
1261 ContextMenuClient
* client
=
1262 pending_context_menus_
.Lookup(custom_context
.request_id
);
1264 client
->OnMenuAction(custom_context
.request_id
, action
);
1266 // Internal request, forward to WebKit.
1267 render_view_
->webview()->performCustomContextMenuAction(action
);
1271 void RenderFrameImpl::OnUndo() {
1272 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1275 void RenderFrameImpl::OnRedo() {
1276 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1279 void RenderFrameImpl::OnCut() {
1280 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1281 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1284 void RenderFrameImpl::OnCopy() {
1285 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1286 WebNode current_node
= context_menu_node_
.isNull() ?
1287 GetFocusedElement() : context_menu_node_
;
1288 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1291 void RenderFrameImpl::OnPaste() {
1292 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1293 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1296 void RenderFrameImpl::OnPasteAndMatchStyle() {
1297 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1298 frame_
->executeCommand(
1299 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1302 #if defined(OS_MACOSX)
1303 void RenderFrameImpl::OnCopyToFindPboard() {
1304 // Since the find pasteboard supports only plain text, this can be simpler
1305 // than the |OnCopy()| case.
1306 if (frame_
->hasSelection()) {
1307 base::string16 selection
= frame_
->selectionAsText();
1308 RenderThread::Get()->Send(
1309 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1314 void RenderFrameImpl::OnDelete() {
1315 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1318 void RenderFrameImpl::OnSelectAll() {
1319 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1320 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1323 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1324 const gfx::Point
& extent
) {
1325 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1326 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1328 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1329 frame_
->selectRange(base
, extent
);
1332 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust
,
1334 size_t start
, length
;
1335 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1340 // Sanity checks to disallow empty and out of range selections.
1341 if (start_adjust
- end_adjust
> static_cast<int>(length
)
1342 || static_cast<int>(start
) + start_adjust
< 0) {
1346 // A negative adjust amount moves the selection towards the beginning of
1347 // the document, a positive amount moves the selection towards the end of
1349 start
+= start_adjust
;
1350 length
+= end_adjust
- start_adjust
;
1352 frame_
->selectRange(WebRange::fromDocumentRange(frame_
, start
, length
));
1355 void RenderFrameImpl::OnUnselect() {
1356 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1357 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1360 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1361 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1362 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1363 GetRenderWidget()->routing_id()));
1365 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1366 frame_
->moveRangeSelectionExtent(point
);
1369 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1370 if (!frame_
->hasSelection())
1371 frame_
->selectWordAroundCaret();
1373 frame_
->replaceSelection(text
);
1376 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1377 if (!frame_
->hasSelection())
1380 frame_
->replaceMisspelledRange(text
);
1383 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1384 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1387 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level
,
1388 const std::string
& message
) {
1389 AddMessageToConsole(level
, message
);
1392 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1393 const base::string16
& jscript
,
1395 bool notify_result
) {
1396 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1397 TRACE_EVENT_SCOPE_THREAD
);
1399 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1400 v8::Local
<v8::Value
> result
=
1401 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1403 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1406 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1407 const base::string16
& jscript
,
1410 bool has_user_gesture
) {
1411 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1412 TRACE_EVENT_SCOPE_THREAD
);
1414 // A bunch of tests expect to run code in the context of a user gesture, which
1415 // can grant additional privileges (e.g. the ability to create popups).
1416 scoped_ptr
<blink::WebScopedUserGesture
> gesture(
1417 has_user_gesture
? new blink::WebScopedUserGesture
: nullptr);
1418 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1419 v8::Local
<v8::Value
> result
=
1420 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1422 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1425 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1426 const base::string16
& jscript
,
1430 TRACE_EVENT_INSTANT0("test_tracing",
1431 "OnJavaScriptExecuteRequestInIsolatedWorld",
1432 TRACE_EVENT_SCOPE_THREAD
);
1434 if (world_id
<= ISOLATED_WORLD_ID_GLOBAL
||
1435 world_id
> ISOLATED_WORLD_ID_MAX
) {
1436 // Return if the world_id is not valid. world_id is passed as a plain int
1437 // over IPC and needs to be verified here, in the IPC endpoint.
1442 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1443 WebScriptSource script
= WebScriptSource(jscript
);
1444 JavaScriptIsolatedWorldRequest
* request
= new JavaScriptIsolatedWorldRequest(
1445 id
, notify_result
, routing_id_
, weak_factory_
.GetWeakPtr());
1446 frame_
->requestExecuteScriptInIsolatedWorld(world_id
, &script
, 1, 0, false,
1450 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1454 base::WeakPtr
<RenderFrameImpl
> render_frame_impl
)
1456 notify_result_(notify_result
),
1457 routing_id_(routing_id
),
1458 render_frame_impl_(render_frame_impl
) {
1461 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1462 ~JavaScriptIsolatedWorldRequest() {
1465 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1466 const blink::WebVector
<v8::Local
<v8::Value
>>& result
) {
1467 if (!render_frame_impl_
.get()) {
1471 if (notify_result_
) {
1472 base::ListValue list
;
1473 if (!result
.isEmpty()) {
1474 // It's safe to always use the main world context when converting
1475 // here. V8ValueConverterImpl shouldn't actually care about the
1476 // context scope, and it switches to v8::Object's creation context
1477 // when encountered. (from extensions/renderer/script_injection.cc)
1478 v8::Local
<v8::Context
> context
=
1479 render_frame_impl_
.get()->frame_
->mainWorldScriptContext();
1480 v8::Context::Scope
context_scope(context
);
1481 V8ValueConverterImpl converter
;
1482 converter
.SetDateAllowed(true);
1483 converter
.SetRegExpAllowed(true);
1484 for (const auto& value
: result
) {
1485 scoped_ptr
<base::Value
> result_value(
1486 converter
.FromV8Value(value
, context
));
1487 list
.Append(result_value
? result_value
.Pass()
1488 : base::Value::CreateNullValue());
1491 list
.Set(0, base::Value::CreateNullValue());
1493 render_frame_impl_
.get()->Send(
1494 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id_
, list
));
1500 void RenderFrameImpl::HandleJavascriptExecutionResult(
1501 const base::string16
& jscript
,
1504 v8::Local
<v8::Value
> result
) {
1505 if (notify_result
) {
1506 base::ListValue list
;
1507 if (!result
.IsEmpty()) {
1508 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1509 v8::Context::Scope
context_scope(context
);
1510 V8ValueConverterImpl converter
;
1511 converter
.SetDateAllowed(true);
1512 converter
.SetRegExpAllowed(true);
1513 scoped_ptr
<base::Value
> result_value(
1514 converter
.FromV8Value(result
, context
));
1515 list
.Set(0, result_value
? result_value
.Pass()
1516 : base::Value::CreateNullValue());
1518 list
.Set(0, base::Value::CreateNullValue());
1520 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1524 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1525 GetRenderWidget()->QueueMessage(
1526 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1527 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1530 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1531 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1532 if (!GetRenderWidget()->ShouldHandleImeEvent())
1534 ImeEventGuard
guard(GetRenderWidget());
1535 frame_
->setEditableSelectionOffsets(start
, end
);
1538 void RenderFrameImpl::OnSetCompositionFromExistingText(
1540 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1541 if (!GetRenderWidget()->ShouldHandleImeEvent())
1543 ImeEventGuard
guard(GetRenderWidget());
1544 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1547 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1548 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1551 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1552 if (!GetRenderWidget()->ShouldHandleImeEvent())
1554 ImeEventGuard
guard(GetRenderWidget());
1555 frame_
->extendSelectionAndDelete(before
, after
);
1558 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1559 if (accessibility_mode_
== new_mode
)
1561 accessibility_mode_
= new_mode
;
1562 if (renderer_accessibility_
) {
1563 // Note: this isn't called automatically by the destructor because
1564 // there'd be no point in calling it in frame teardown, only if there's
1565 // an accessibility mode change but the frame is persisting.
1566 renderer_accessibility_
->DisableAccessibility();
1568 delete renderer_accessibility_
;
1569 renderer_accessibility_
= NULL
;
1571 if (accessibility_mode_
== AccessibilityModeOff
)
1574 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1575 renderer_accessibility_
= new RendererAccessibility(this);
1578 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1579 ui::AXTreeUpdate response
;
1580 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1581 Send(new AccessibilityHostMsg_SnapshotResponse(
1582 routing_id_
, callback_id
, response
));
1585 void RenderFrameImpl::OnDisownOpener() {
1586 // TODO(creis): We should only see this for main frames for now. To support
1587 // disowning the opener on subframes, we will need to move WebContentsImpl's
1588 // opener_ to FrameTreeNode.
1589 CHECK(!frame_
->parent());
1591 if (frame_
->opener())
1592 frame_
->setOpener(NULL
);
1595 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags
) {
1596 frame_
->setFrameOwnerSandboxFlags(flags
);
1599 void RenderFrameImpl::OnTextTrackSettingsChanged(
1600 const FrameMsg_TextTrackSettings_Params
& params
) {
1601 DCHECK(!frame_
->parent());
1602 if (!render_view_
->webview())
1605 if (params
.text_tracks_enabled
) {
1606 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1607 WebSettings::TextTrackKindUserPreference::Captions
);
1609 render_view_
->webview()->settings()->setTextTrackKindUserPreference(
1610 WebSettings::TextTrackKindUserPreference::Default
);
1612 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1613 WebString::fromUTF8(params
.text_track_background_color
));
1614 render_view_
->webview()->settings()->setTextTrackFontFamily(
1615 WebString::fromUTF8(params
.text_track_font_family
));
1616 render_view_
->webview()->settings()->setTextTrackFontStyle(
1617 WebString::fromUTF8(params
.text_track_font_style
));
1618 render_view_
->webview()->settings()->setTextTrackFontVariant(
1619 WebString::fromUTF8(params
.text_track_font_variant
));
1620 render_view_
->webview()->settings()->setTextTrackTextColor(
1621 WebString::fromUTF8(params
.text_track_text_color
));
1622 render_view_
->webview()->settings()->setTextTrackTextShadow(
1623 WebString::fromUTF8(params
.text_track_text_shadow
));
1624 render_view_
->webview()->settings()->setTextTrackTextSize(
1625 WebString::fromUTF8(params
.text_track_text_size
));
1628 void RenderFrameImpl::OnPostMessageEvent(
1629 const FrameMsg_PostMessage_Params
& params
) {
1630 // Find the source frame if it exists.
1631 WebFrame
* source_frame
= NULL
;
1632 if (params
.source_view_routing_id
!= MSG_ROUTING_NONE
) {
1633 // Support a legacy postMessage path for specifying a source RenderView;
1634 // this is currently used when sending messages to Android WebView.
1635 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1636 RenderViewImpl
* source_view
=
1637 RenderViewImpl::FromRoutingID(params
.source_view_routing_id
);
1639 source_frame
= source_view
->webview()->mainFrame();
1640 } else if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1641 RenderFrameProxy
* source_proxy
=
1642 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1644 // Currently, navigating a top-level frame cross-process does not swap
1645 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1646 // WebRemoteFrame will not have an associated blink::Frame. If this is
1647 // the case for |source_proxy|, use the corresponding (swapped-out)
1648 // WebLocalFrame instead, so that event.source for this message can be
1649 // set and used properly.
1650 if (source_proxy
->IsMainFrameDetachedFromTree())
1651 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1653 source_frame
= source_proxy
->web_frame();
1657 // If the message contained MessagePorts, create the corresponding endpoints.
1658 blink::WebMessagePortChannelArray channels
=
1659 WebMessagePortChannelImpl::CreatePorts(
1660 params
.message_ports
, params
.new_routing_ids
,
1661 base::ThreadTaskRunnerHandle::Get().get());
1663 WebSerializedScriptValue serialized_script_value
;
1664 if (params
.is_data_raw_string
) {
1665 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1666 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1667 v8::Context::Scope
context_scope(context
);
1668 V8ValueConverterImpl converter
;
1669 converter
.SetDateAllowed(true);
1670 converter
.SetRegExpAllowed(true);
1671 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1672 v8::Local
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1674 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1676 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1679 // Create an event with the message. The next-to-last parameter to
1680 // initMessageEvent is the last event ID, which is not used with postMessage.
1681 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1682 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1683 msg_event
.initMessageEvent("message",
1684 // |canBubble| and |cancellable| are always false
1686 serialized_script_value
,
1687 params
.source_origin
, source_frame
, "", channels
);
1689 // We must pass in the target_origin to do the security check on this side,
1690 // since it may have changed since the original postMessage call was made.
1691 WebSecurityOrigin target_origin
;
1692 if (!params
.target_origin
.empty()) {
1694 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1696 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1699 #if defined(OS_ANDROID)
1700 void RenderFrameImpl::OnSelectPopupMenuItems(
1702 const std::vector
<int>& selected_indices
) {
1703 // It is possible to receive more than one of these calls if the user presses
1704 // a select faster than it takes for the show-select-popup IPC message to make
1705 // it to the browser UI thread. Ignore the extra-messages.
1706 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1707 if (!external_popup_menu_
)
1710 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1711 external_popup_menu_
.reset();
1715 #if defined(OS_MACOSX)
1716 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1717 if (external_popup_menu_
== NULL
)
1719 external_popup_menu_
->DidSelectItem(selected_index
);
1720 external_popup_menu_
.reset();
1724 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1725 frame_
->reload(ignore_cache
);
1728 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1729 blink::WebSurroundingText surroundingText
;
1730 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1732 if (surroundingText
.isNull()) {
1733 // |surroundingText| might not be correctly initialized, for example if
1734 // |frame_->selectionRange().isNull()|, in other words, if there was no
1736 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1737 routing_id_
, base::string16(), 0, 0));
1741 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1743 surroundingText
.textContent(),
1744 surroundingText
.startOffsetInTextContent(),
1745 surroundingText
.endOffsetInTextContent()));
1748 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1749 const base::string16
& message
,
1750 const base::string16
& default_value
,
1751 const GURL
& frame_url
,
1752 base::string16
* result
) {
1753 // Don't allow further dialogs if we are waiting to swap out, since the
1754 // PageGroupLoadDeferrer in our stack prevents it.
1755 if (render_view()->suppress_dialogs_until_swap_out_
)
1758 bool success
= false;
1759 base::string16 result_temp
;
1761 result
= &result_temp
;
1763 render_view()->SendAndRunNestedMessageLoop(
1764 new FrameHostMsg_RunJavaScriptMessage(
1765 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1770 void RenderFrameImpl::LoadNavigationErrorPage(
1771 const WebURLRequest
& failed_request
,
1772 const WebURLError
& error
,
1774 std::string error_html
;
1775 GetContentClient()->renderer()->GetNavigationErrorStrings(
1776 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1778 frame_
->loadHTMLString(error_html
,
1779 GURL(kUnreachableWebDataURL
),
1780 error
.unreachableURL
,
1784 void RenderFrameImpl::DidCommitCompositorFrame() {
1785 if (BrowserPluginManager::Get())
1786 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1788 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1791 RenderView
* RenderFrameImpl::GetRenderView() {
1792 return render_view_
.get();
1795 int RenderFrameImpl::GetRoutingID() {
1799 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1804 WebElement
RenderFrameImpl::GetFocusedElement() const {
1805 WebDocument doc
= frame_
->document();
1807 return doc
.focusedElement();
1809 return WebElement();
1812 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1813 return render_view_
->GetWebkitPreferences();
1816 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1817 const ContextMenuParams
& params
) {
1818 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1819 ContextMenuParams
our_params(params
);
1820 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1821 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1822 return our_params
.custom_context
.request_id
;
1825 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1826 DCHECK(pending_context_menus_
.Lookup(request_id
));
1827 pending_context_menus_
.Remove(request_id
);
1830 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1831 return context_menu_node_
;
1834 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1835 blink::WebFrame
* frame
,
1836 const WebPluginInfo
& info
,
1837 const blink::WebPluginParams
& params
,
1838 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1839 DCHECK_EQ(frame_
, frame
);
1840 #if defined(ENABLE_PLUGINS)
1841 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1842 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1843 this, GetContentClient()
1845 ->CreateBrowserPluginDelegate(this, params
.mimeType
.utf8(),
1850 bool pepper_plugin_was_registered
= false;
1851 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1852 this, info
, &pepper_plugin_was_registered
));
1853 if (pepper_plugin_was_registered
) {
1854 if (pepper_module
.get()) {
1855 return new PepperWebPluginImpl(
1856 pepper_module
.get(), params
, this,
1858 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1861 #if defined(OS_CHROMEOS)
1862 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1864 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_NPAPI
) {
1865 // TODO(jam): change to take RenderFrame.
1866 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1873 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1874 const blink::WebURLRequest
& request
,
1875 blink::WebNavigationPolicy policy
) {
1876 DCHECK(!frame_
|| frame_
== frame
);
1877 loadURLExternally(frame
, request
, policy
, WebString());
1880 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1881 OnJavaScriptExecuteRequest(javascript
, 0, false);
1884 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1885 return &service_registry_
;
1888 #if defined(ENABLE_PLUGINS)
1889 void RenderFrameImpl::RegisterPeripheralPlugin(
1890 const GURL
& content_origin
,
1891 const base::Closure
& unthrottle_callback
) {
1892 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1893 content_origin
, unthrottle_callback
);
1895 #endif // defined(ENABLE_PLUGINS)
1897 bool RenderFrameImpl::IsFTPDirectoryListing() {
1898 WebURLResponseExtraDataImpl
* extra_data
=
1899 GetExtraDataFromResponse(frame_
->dataSource()->response());
1900 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1903 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1904 BrowserPluginManager::Get()->Attach(element_instance_id
);
1907 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1908 BrowserPluginManager::Get()->Detach(element_instance_id
);
1911 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1913 const gfx::Range
& range
) {
1914 // Use the routing id of Render Widget Host.
1915 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1921 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1922 v8::Isolate
* isolate
,
1923 v8::Local
<v8::Context
> context
) {
1924 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1925 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1928 v8::HandleScope
handle_scope(isolate
);
1929 registry
->AddBuiltinModule(
1930 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1931 registry
->AddBuiltinModule(isolate
,
1932 mojo::js::Support::kModuleName
,
1933 mojo::js::Support::GetModule(isolate
));
1934 registry
->AddBuiltinModule(
1936 ServiceRegistryJsWrapper::kModuleName
,
1937 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1940 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level
,
1941 const std::string
& message
) {
1942 if (devtools_agent_
)
1943 devtools_agent_
->AddMessageToConsole(level
, message
);
1946 // blink::WebFrameClient implementation ----------------------------------------
1948 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1949 blink::WebLocalFrame
* frame
,
1950 const blink::WebPluginParams
& params
) {
1951 DCHECK_EQ(frame_
, frame
);
1952 return GetContentClient()
1954 ->CreatePluginPlaceholder(this, frame
, params
)
1958 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1959 blink::WebLocalFrame
* frame
,
1960 const blink::WebPluginParams
& params
) {
1961 DCHECK_EQ(frame_
, frame
);
1962 blink::WebPlugin
* plugin
= NULL
;
1963 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1964 this, frame
, params
, &plugin
)) {
1968 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1969 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1970 this, GetContentClient()
1972 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType
,
1977 #if defined(ENABLE_PLUGINS)
1979 std::string mime_type
;
1981 Send(new FrameHostMsg_GetPluginInfo(
1982 routing_id_
, params
.url
, frame
->top()->document().url(),
1983 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
1987 WebPluginParams params_to_use
= params
;
1988 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
1989 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
1992 #endif // defined(ENABLE_PLUGINS)
1995 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1996 blink::WebLocalFrame
* frame
,
1997 const blink::WebURL
& url
,
1998 blink::WebMediaPlayerClient
* client
,
1999 blink::WebContentDecryptionModule
* initial_cdm
) {
2000 #if defined(VIDEO_HOLE)
2001 if (!contains_media_player_
) {
2002 render_view_
->RegisterVideoHoleFrame(this);
2003 contains_media_player_
= true;
2005 #endif // defined(VIDEO_HOLE)
2007 blink::WebMediaStream
web_stream(
2008 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2009 if (!web_stream
.isNull())
2010 return CreateWebMediaPlayerForMediaStream(client
);
2012 #if defined(OS_ANDROID)
2013 return CreateAndroidWebMediaPlayer(client
, GetMediaPermission(), initial_cdm
);
2015 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2017 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2018 media::WebMediaPlayerParams
params(
2019 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2020 base::Unretained(GetContentClient()->renderer()),
2021 static_cast<RenderFrame
*>(this)),
2022 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2023 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2024 render_thread
->compositor_task_runner(),
2025 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2028 #if defined(ENABLE_MOJO_MEDIA)
2029 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2030 new media::MojoRendererFactory(GetMediaServiceProvider()));
2032 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2033 GetContentClient()->renderer()->CreateMediaRendererFactory(
2034 this, render_thread
->GetGpuFactories(), media_log
);
2036 if (!media_renderer_factory
.get()) {
2037 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2038 media_log
, render_thread
->GetGpuFactories(),
2039 *render_thread
->GetAudioHardwareConfig()));
2041 #endif // defined(ENABLE_MOJO_MEDIA)
2043 return new media::WebMediaPlayerImpl(
2044 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer_factory
.Pass(),
2045 GetCdmFactory(), params
);
2046 #endif // defined(OS_ANDROID)
2049 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2050 blink::WebLocalFrame
* frame
,
2051 blink::WebApplicationCacheHostClient
* client
) {
2052 if (!frame
|| !frame
->view())
2054 DCHECK(!frame_
|| frame_
== frame
);
2055 return new RendererWebApplicationCacheHostImpl(
2056 RenderViewImpl::FromWebView(frame
->view()), client
,
2057 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2060 blink::WebWorkerContentSettingsClientProxy
*
2061 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2062 blink::WebLocalFrame
* frame
) {
2063 if (!frame
|| !frame
->view())
2065 DCHECK(!frame_
|| frame_
== frame
);
2066 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2070 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2071 const WebPopupMenuInfo
& popup_menu_info
,
2072 WebExternalPopupMenuClient
* popup_menu_client
) {
2073 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2074 // An IPC message is sent to the browser to build and display the actual
2075 // popup. The user could have time to click a different select by the time
2076 // the popup is shown. In that case external_popup_menu_ is non NULL.
2077 // By returning NULL in that case, we instruct Blink to cancel that new
2078 // popup. So from the user perspective, only the first one will show, and
2079 // will have to close the first one before another one can be shown.
2080 if (external_popup_menu_
)
2082 external_popup_menu_
.reset(
2083 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2084 if (render_view_
->screen_metrics_emulator_
) {
2085 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2086 external_popup_menu_
.get(),
2087 render_view_
->screen_metrics_emulator_
.get());
2089 return external_popup_menu_
.get();
2095 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2096 DCHECK(!frame_
|| frame_
== frame
);
2097 return &cookie_jar_
;
2100 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2101 blink::WebLocalFrame
* frame
) {
2102 DCHECK(!frame_
|| frame_
== frame
);
2103 // At this point we should have non-null data source.
2104 DCHECK(frame
->dataSource());
2105 if (!ChildThreadImpl::current())
2106 return NULL
; // May be null in some tests.
2107 ServiceWorkerNetworkProvider
* provider
=
2108 ServiceWorkerNetworkProvider::FromDocumentState(
2109 DocumentState::FromDataSource(frame
->dataSource()));
2111 return new WebServiceWorkerProviderImpl(
2112 ChildThreadImpl::current()->thread_safe_sender(),
2113 provider
->context());
2116 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2117 DCHECK(!frame_
|| frame_
== frame
);
2118 // If the request hasn't yet committed, notify the browser process that it is
2119 // no longer safe to show the pending URL of the main frame, since a URL spoof
2120 // is now possible. (If the request has committed, the browser already knows.)
2121 if (!frame
->parent()) {
2122 DocumentState
* document_state
=
2123 DocumentState::FromDataSource(frame
->dataSource());
2124 NavigationStateImpl
* navigation_state
=
2125 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2127 if (!navigation_state
->request_committed()) {
2128 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2133 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2134 blink::WebLocalFrame
* parent
,
2135 blink::WebTreeScopeType scope
,
2136 const blink::WebString
& name
,
2137 blink::WebSandboxFlags sandbox_flags
) {
2138 // Synchronously notify the browser of a child frame creation to get the
2139 // routing_id for the RenderFrame.
2140 int child_routing_id
= MSG_ROUTING_NONE
;
2141 Send(new FrameHostMsg_CreateChildFrame(routing_id_
, scope
,
2142 base::UTF16ToUTF8(name
), sandbox_flags
,
2143 &child_routing_id
));
2145 // Allocation of routing id failed, so we can't create a child frame. This can
2146 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2147 // out state or synchronous IPC message above has failed.
2148 if (child_routing_id
== MSG_ROUTING_NONE
) {
2149 NOTREACHED() << "Failed to allocate routing id for child frame.";
2153 // Create the RenderFrame and WebLocalFrame, linking the two.
2154 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2155 render_view_
.get(), child_routing_id
);
2156 blink::WebLocalFrame
* web_frame
=
2157 WebLocalFrame::create(scope
, child_render_frame
);
2158 child_render_frame
->SetWebFrame(web_frame
);
2160 // Add the frame to the frame tree and initialize it.
2161 parent
->appendChild(web_frame
);
2162 child_render_frame
->Initialize();
2167 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2168 blink::WebLocalFrame
* parent
,
2169 const blink::WebString
& name
,
2170 blink::WebSandboxFlags sandbox_flags
) {
2171 return createChildFrame(parent
, blink::WebTreeScopeType::Document
, name
,
2175 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2176 DCHECK(!frame_
|| frame_
== frame
);
2177 // We only need to notify the browser if the active, top-level frame clears
2178 // its opener. We can ignore cases where a swapped out frame clears its
2179 // opener after hearing about it from the browser, and the browser does not
2180 // (yet) care about subframe openers.
2181 if (is_swapped_out_
|| frame
->parent())
2184 // Notify WebContents and all its swapped out RenderViews.
2185 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2188 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
, DetachType type
) {
2189 // NOTE: This function is called on the frame that is being detached and not
2190 // the parent frame. This is different from createChildFrame() which is
2191 // called on the parent frame.
2192 CHECK(!is_detaching_
);
2193 DCHECK(!frame_
|| frame_
== frame
);
2195 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2196 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2197 FrameDetached(frame
));
2199 // We only notify the browser process when the frame is being detached for
2200 // removal. If the frame is being detached for swap, we don't need to do this
2201 // since we are not modifiying the frame tree.
2202 if (type
== DetachType::Remove
)
2203 Send(new FrameHostMsg_Detach(routing_id_
));
2205 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2206 // sent before setting |is_detaching_| to true.
2207 is_detaching_
= true;
2210 render_widget_
->UnregisterRenderFrame(this);
2212 // We need to clean up subframes by removing them from the map and deleting
2213 // the RenderFrameImpl. In contrast, the main frame is owned by its
2214 // containing RenderViewHost (so that they have the same lifetime), so only
2215 // removal from the map is needed and no deletion.
2216 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2217 CHECK(it
!= g_frame_map
.Get().end());
2218 CHECK_EQ(it
->second
, this);
2219 g_frame_map
.Get().erase(it
);
2221 // Only remove the frame from the renderer's frame tree if the frame is
2222 // being detached for removal. In the case of a swap, the frame needs to
2223 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2224 if (is_subframe_
&& type
== DetachType::Remove
)
2225 frame
->parent()->removeChild(frame
);
2227 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2228 // object may not be deleted immediately and other methods may try to access
2234 // Object is invalid after this point.
2237 void RenderFrameImpl::frameFocused() {
2238 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2241 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2242 DCHECK(!frame_
|| frame_
== frame
);
2244 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2245 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2246 FrameWillClose(frame
));
2249 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2250 const blink::WebString
& name
) {
2251 DCHECK(!frame_
|| frame_
== frame
);
2253 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2254 // updates may have performance implications for benchmarks like SunSpider.
2255 // For now, send these updates only for --site-per-process, which needs to
2256 // replicate frame names to frame proxies, and when
2257 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2258 // can be optimized further by only sending the update if there are any
2259 // remote frames in the frame tree, or delaying and batching up IPCs if
2260 // updates are happening too frequently.
2261 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
2262 switches::kSitePerProcess
);
2263 if (is_site_per_process
||
2264 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2265 Send(new FrameHostMsg_DidChangeName(routing_id_
, base::UTF16ToUTF8(name
)));
2269 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2270 blink::WebSandboxFlags flags
) {
2271 int frame_routing_id
= MSG_ROUTING_NONE
;
2272 if (child_frame
->isWebRemoteFrame()) {
2274 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2277 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2280 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2284 void RenderFrameImpl::didMatchCSS(
2285 blink::WebLocalFrame
* frame
,
2286 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2287 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2288 DCHECK(!frame_
|| frame_
== frame
);
2290 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2291 DidMatchCSS(newly_matching_selectors
,
2292 stopped_matching_selectors
));
2295 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2296 const blink::WebString
& source
) {
2297 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2301 void RenderFrameImpl::didAddMessageToConsole(
2302 const blink::WebConsoleMessage
& message
,
2303 const blink::WebString
& source_name
,
2304 unsigned source_line
,
2305 const blink::WebString
& stack_trace
) {
2306 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2307 switch (message
.level
) {
2308 case blink::WebConsoleMessage::LevelDebug
:
2309 log_severity
= logging::LOG_VERBOSE
;
2311 case blink::WebConsoleMessage::LevelLog
:
2312 case blink::WebConsoleMessage::LevelInfo
:
2313 log_severity
= logging::LOG_INFO
;
2315 case blink::WebConsoleMessage::LevelWarning
:
2316 log_severity
= logging::LOG_WARNING
;
2318 case blink::WebConsoleMessage::LevelError
:
2319 log_severity
= logging::LOG_ERROR
;
2322 log_severity
= logging::LOG_VERBOSE
;
2325 if (shouldReportDetailedMessageForSource(source_name
)) {
2327 RenderFrameObserver
, observers_
,
2328 DetailedConsoleMessageAdded(message
.text
,
2332 static_cast<int32
>(log_severity
)));
2335 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2336 static_cast<int32
>(log_severity
),
2338 static_cast<int32
>(source_line
),
2342 void RenderFrameImpl::loadURLExternally(
2343 blink::WebLocalFrame
* frame
,
2344 const blink::WebURLRequest
& request
,
2345 blink::WebNavigationPolicy policy
,
2346 const blink::WebString
& suggested_name
) {
2347 DCHECK(!frame_
|| frame_
== frame
);
2348 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2349 if (policy
== blink::WebNavigationPolicyDownload
) {
2350 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2351 request
.url(), referrer
,
2354 OpenURL(frame
, request
.url(), referrer
, policy
);
2358 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2359 const NavigationPolicyInfo
& info
) {
2360 DCHECK(!frame_
|| frame_
== info
.frame
);
2361 return DecidePolicyForNavigation(this, info
);
2364 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2365 blink::WebFrame
* frame
) {
2366 DCHECK(!frame_
|| frame_
== frame
);
2367 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2370 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2371 const blink::WebFormElement
& form
) {
2372 DCHECK(!frame_
|| frame_
== frame
);
2374 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2377 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2378 const blink::WebFormElement
& form
) {
2379 DCHECK(!frame_
|| frame_
== frame
);
2380 DocumentState
* document_state
=
2381 DocumentState::FromDataSource(frame
->provisionalDataSource());
2382 NavigationStateImpl
* navigation_state
=
2383 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2384 InternalDocumentStateData
* internal_data
=
2385 InternalDocumentStateData::FromDocumentState(document_state
);
2387 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2388 ui::PAGE_TRANSITION_LINK
)) {
2389 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2392 // Save these to be processed when the ensuing navigation is committed.
2393 WebSearchableFormData
web_searchable_form_data(form
);
2394 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2395 internal_data
->set_searchable_form_encoding(
2396 web_searchable_form_data
.encoding().utf8());
2398 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2401 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2402 blink::WebDataSource
* datasource
) {
2403 DCHECK(!frame_
|| frame_
== frame
);
2405 bool content_initiated
= !pending_navigation_params_
.get();
2407 // Make sure any previous redirect URLs end up in our new data source.
2408 if (pending_navigation_params_
.get()) {
2409 for (const auto& i
:
2410 pending_navigation_params_
->request_params
.redirects
) {
2411 datasource
->appendRedirect(i
);
2415 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2416 if (!document_state
) {
2417 document_state
= new DocumentState
;
2418 datasource
->setExtraData(document_state
);
2419 if (!content_initiated
)
2420 PopulateDocumentStateFromPending(document_state
);
2423 // Carry over the user agent override flag, if it exists.
2424 blink::WebView
* webview
= render_view_
->webview();
2425 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2426 webview
->mainFrame()->isWebLocalFrame() &&
2427 webview
->mainFrame()->dataSource()) {
2428 DocumentState
* old_document_state
=
2429 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2430 if (old_document_state
) {
2431 InternalDocumentStateData
* internal_data
=
2432 InternalDocumentStateData::FromDocumentState(document_state
);
2433 InternalDocumentStateData
* old_internal_data
=
2434 InternalDocumentStateData::FromDocumentState(old_document_state
);
2435 internal_data
->set_is_overriding_user_agent(
2436 old_internal_data
->is_overriding_user_agent());
2440 // The rest of RenderView assumes that a WebDataSource will always have a
2441 // non-null NavigationState.
2442 if (content_initiated
) {
2443 document_state
->set_navigation_state(
2444 NavigationStateImpl::CreateContentInitiated());
2446 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2447 pending_navigation_params_
.reset();
2450 // DocumentState::referred_by_prefetcher_ is true if we are
2451 // navigating from a page that used prefetching using a link on that
2452 // page. We are early enough in the request process here that we
2453 // can still see the DocumentState of the previous page and set
2454 // this value appropriately.
2455 // TODO(gavinp): catch the important case of navigation in a new
2456 // renderer process.
2458 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2459 const WebURLRequest
& original_request
= datasource
->originalRequest();
2460 const GURL
referrer(
2461 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2462 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2463 DocumentState::FromDataSource(old_frame
->dataSource())
2464 ->was_prefetcher()) {
2465 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2466 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2467 if (old_frame_datasource
&&
2468 referrer
== GURL(old_frame_datasource
->request().url())) {
2469 document_state
->set_was_referred_by_prefetcher(true);
2477 if (content_initiated
) {
2478 const WebURLRequest
& request
= datasource
->request();
2479 switch (request
.cachePolicy()) {
2480 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2481 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2483 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2484 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2485 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2487 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2488 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2490 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2491 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2498 // Create the serviceworker's per-document network observing object if it
2499 // does not exist (When navigation happens within a page, the provider already
2501 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2502 DocumentState::FromDataSource(datasource
))) {
2503 ServiceWorkerProviderType provider_type
=
2504 SERVICE_WORKER_PROVIDER_FOR_WINDOW
;
2505 if ((frame
->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin
) ==
2506 blink::WebSandboxFlags::Origin
) {
2507 provider_type
= SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME
;
2509 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2510 new ServiceWorkerNetworkProvider(routing_id_
, provider_type
));
2511 ServiceWorkerNetworkProvider::AttachToDocumentState(
2512 DocumentState::FromDataSource(datasource
),
2513 network_provider
.Pass());
2517 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2518 double triggering_event_time
) {
2519 DCHECK(!frame_
|| frame_
== frame
);
2520 WebDataSource
* ds
= frame
->provisionalDataSource();
2522 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2523 // callback is invoked.
2527 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2528 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2529 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2531 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2532 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2534 "Heard swappedout:// when not swapped out.";
2536 // Update the request time if WebKit has better knowledge of it.
2537 if (document_state
->request_time().is_null() &&
2538 triggering_event_time
!= 0.0) {
2539 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2542 // Start time is only set after request time.
2543 document_state
->set_start_load_time(Time::Now());
2545 bool is_top_most
= !frame
->parent();
2547 render_view_
->set_navigation_gesture(
2548 WebUserGestureIndicator::isProcessingUserGesture() ?
2549 NavigationGestureUser
: NavigationGestureAuto
);
2550 } else if (ds
->replacesCurrentHistoryItem()) {
2551 // Subframe navigations that don't add session history items must be
2552 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2553 // handle loading of error pages.
2554 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2555 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2558 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2559 DidStartProvisionalLoad(frame
));
2560 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2562 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2563 routing_id_
, ds
->request().url()));
2566 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2567 blink::WebLocalFrame
* frame
) {
2568 DCHECK(!frame_
|| frame_
== frame
);
2569 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2572 void RenderFrameImpl::didFailProvisionalLoad(
2573 blink::WebLocalFrame
* frame
,
2574 const blink::WebURLError
& error
,
2575 blink::WebHistoryCommitType commit_type
) {
2576 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2578 DCHECK(!frame_
|| frame_
== frame
);
2579 WebDataSource
* ds
= frame
->provisionalDataSource();
2582 const WebURLRequest
& failed_request
= ds
->request();
2584 // Notify the browser that we failed a provisional load with an error.
2586 // Note: It is important this notification occur before DidStopLoading so the
2587 // SSL manager can react to the provisional load failure before being
2588 // notified the load stopped.
2590 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2591 DidFailProvisionalLoad(frame
, error
));
2592 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2593 DidFailProvisionalLoad(error
));
2595 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2597 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2600 // Make sure we never show errors in view source mode.
2601 frame
->enableViewSourceMode(false);
2603 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2604 NavigationStateImpl
* navigation_state
=
2605 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2607 // If this is a failed back/forward/reload navigation, then we need to do a
2608 // 'replace' load. This is necessary to avoid messing up session history.
2609 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2610 // as session history is concerned.
2611 bool replace
= commit_type
!= blink::WebStandardCommit
;
2613 // If we failed on a browser initiated request, then make sure that our error
2614 // page load is regarded as the same browser initiated request.
2615 if (!navigation_state
->IsContentInitiated()) {
2616 pending_navigation_params_
.reset(new NavigationParams(
2617 navigation_state
->common_params(), navigation_state
->start_params(),
2618 navigation_state
->request_params()));
2619 pending_navigation_params_
->request_params
.request_time
=
2620 document_state
->request_time();
2623 // Load an error page.
2624 LoadNavigationErrorPage(failed_request
, error
, replace
);
2627 void RenderFrameImpl::didCommitProvisionalLoad(
2628 blink::WebLocalFrame
* frame
,
2629 const blink::WebHistoryItem
& item
,
2630 blink::WebHistoryCommitType commit_type
) {
2631 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2633 "url", GetLoadingUrl().possibly_invalid_spec());
2634 DCHECK(!frame_
|| frame_
== frame
);
2635 DocumentState
* document_state
=
2636 DocumentState::FromDataSource(frame
->dataSource());
2637 NavigationStateImpl
* navigation_state
=
2638 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2640 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2641 RenderFrameProxy
* proxy
=
2642 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2644 proxy
->web_frame()->swap(frame_
);
2645 proxy_routing_id_
= MSG_ROUTING_NONE
;
2647 // If this is the main frame going from a remote frame to a local frame,
2648 // it needs to set RenderViewImpl's pointer for the main frame to itself
2649 // and ensure RenderWidget is no longer in swapped out mode.
2650 if (!is_subframe_
) {
2651 CHECK(!render_view_
->main_render_frame_
);
2652 render_view_
->main_render_frame_
= this;
2653 if (render_view_
->is_swapped_out())
2654 render_view_
->SetSwappedOut(false);
2658 // When we perform a new navigation, we need to update the last committed
2659 // session history entry with state for the page we are leaving. Do this
2660 // before updating the HistoryController state.
2661 render_view_
->UpdateSessionHistory(frame
);
2663 render_view_
->history_controller()->UpdateForCommit(
2664 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2666 InternalDocumentStateData
* internal_data
=
2667 InternalDocumentStateData::FromDocumentState(document_state
);
2669 if (document_state
->commit_load_time().is_null())
2670 document_state
->set_commit_load_time(Time::Now());
2672 if (internal_data
->must_reset_scroll_and_scale_state()) {
2673 render_view_
->webview()->resetScrollAndScaleState();
2674 internal_data
->set_must_reset_scroll_and_scale_state(false);
2676 internal_data
->set_use_error_page(false);
2678 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2679 if (is_new_navigation
) {
2680 // We bump our Page ID to correspond with the new session history entry.
2681 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2683 // Don't update history list values for kSwappedOutURL, since
2684 // we don't want to forget the entry that was there, and since we will
2685 // never come back to kSwappedOutURL. Note that we have to call
2686 // UpdateSessionHistory and update page_id_ even in this case, so that
2687 // the current entry gets a state update and so that we don't send a
2688 // state update to the wrong entry when we swap back in.
2690 navigation_state
->start_params().should_replace_current_entry
,
2691 render_view_
->history_list_length_
> 0);
2692 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2693 !navigation_state
->start_params().should_replace_current_entry
) {
2694 // Advance our offset in session history, applying the length limit.
2695 // There is now no forward history.
2696 render_view_
->history_list_offset_
++;
2697 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2698 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2699 render_view_
->history_list_length_
=
2700 render_view_
->history_list_offset_
+ 1;
2703 const RequestNavigationParams
& request_params
=
2704 navigation_state
->request_params();
2705 if (request_params
.nav_entry_id
!= 0 &&
2706 !request_params
.intended_as_new_entry
) {
2707 // This is a successful session history navigation!
2708 render_view_
->page_id_
= request_params
.page_id
;
2710 render_view_
->history_list_offset_
=
2711 request_params
.pending_history_list_offset
;
2716 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2717 CHECK(sent
); // http://crbug.com/407376
2719 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2720 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2722 RenderFrameObserver
, observers_
,
2723 DidCommitProvisionalLoad(is_new_navigation
,
2724 navigation_state
->WasWithinSamePage()));
2726 if (!frame
->parent()) { // Only for top frames.
2727 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2728 if (render_thread_impl
) { // Can be NULL in tests.
2729 render_thread_impl
->histogram_customizer()->
2730 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2731 RenderView::GetRenderViewCount());
2735 // Remember that we've already processed this request, so we don't update
2736 // the session history again. We do this regardless of whether this is
2737 // a session history navigation, because if we attempted a session history
2738 // navigation without valid HistoryItem state, WebCore will think it is a
2740 navigation_state
->set_request_committed(true);
2742 SendDidCommitProvisionalLoad(frame
, commit_type
, item
);
2744 // Check whether we have new encoding name.
2745 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2748 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2749 DCHECK(!frame_
|| frame_
== frame
);
2751 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidCreateNewDocument());
2752 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2753 DidCreateNewDocument(frame
));
2756 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2757 DCHECK(!frame_
|| frame_
== frame
);
2759 int enabled_bindings
= render_view_
->GetEnabledBindings();
2761 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2762 WebUIExtension::Install(frame
);
2764 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2765 DomAutomationController::Install(this, frame
);
2767 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2768 StatsCollectionController::Install(frame
);
2770 const base::CommandLine
& command_line
=
2771 *base::CommandLine::ForCurrentProcess();
2773 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2774 GpuBenchmarking::Install(frame
);
2776 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2777 MemoryBenchmarkingExtension::Install(frame
);
2779 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2780 SkiaBenchmarking::Install(frame
);
2782 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2783 DidClearWindowObject(frame
));
2784 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2787 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2788 DCHECK(!frame_
|| frame_
== frame
);
2790 // Notify the browser about non-blank documents loading in the top frame.
2791 GURL url
= frame
->document().url();
2792 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2793 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2794 // frame->tree()->top().
2795 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2796 if (frame
== main_frame
) {
2797 // For now, don't remember plugin zoom values. We don't want to mix them
2798 // with normal web content (i.e. a fixed layout plugin would usually want
2800 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2801 render_view_
->GetRoutingID(),
2802 main_frame
->document().isPluginDocument()));
2806 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2807 DidCreateDocumentElement());
2808 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2809 DidCreateDocumentElement(frame
));
2812 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2813 const blink::WebString
& title
,
2814 blink::WebTextDirection direction
) {
2815 DCHECK(!frame_
|| frame_
== frame
);
2816 // Ignore all but top level navigations.
2817 if (!frame
->parent()) {
2818 base::string16 title16
= title
;
2819 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2820 routing_id_
, base::UTF16ToUTF8(title16
));
2822 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2823 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2824 shortened_title
, direction
));
2827 // Also check whether we have new encoding name.
2828 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2831 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2832 blink::WebIconURL::Type icon_type
) {
2833 DCHECK(!frame_
|| frame_
== frame
);
2834 // TODO(nasko): Investigate wheather implementation should move here.
2835 render_view_
->didChangeIcon(frame
, icon_type
);
2838 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2839 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2841 DCHECK(!frame_
|| frame_
== frame
);
2842 WebDataSource
* ds
= frame
->dataSource();
2843 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2844 document_state
->set_finish_document_load_time(Time::Now());
2846 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2848 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2849 DidFinishDocumentLoad(frame
));
2850 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2852 // Check whether we have new encoding name.
2853 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2856 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2857 DCHECK(!frame_
|| frame_
== frame
);
2858 if (!frame
->parent()) {
2859 FrameMsg_UILoadMetricsReportType::Value report_type
=
2860 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2861 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2862 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2863 base::TimeDelta::FromSecondsD(
2864 frame
->dataSource()->request().uiStartTime());
2866 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2867 routing_id_
, report_type
, ui_timestamp
));
2871 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2872 const blink::WebURLError
& error
,
2873 blink::WebHistoryCommitType commit_type
) {
2874 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2876 DCHECK(!frame_
|| frame_
== frame
);
2877 // TODO(nasko): Move implementation here. No state needed.
2878 WebDataSource
* ds
= frame
->dataSource();
2881 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2882 DidFailLoad(frame
, error
));
2884 const WebURLRequest
& failed_request
= ds
->request();
2885 base::string16 error_description
;
2886 GetContentClient()->renderer()->GetNavigationErrorStrings(
2892 &error_description
);
2893 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2894 failed_request
.url(),
2897 error
.wasIgnoredByHandler
));
2900 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2901 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2903 DCHECK(!frame_
|| frame_
== frame
);
2904 WebDataSource
* ds
= frame
->dataSource();
2905 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2906 if (document_state
->finish_load_time().is_null()) {
2907 if (!frame
->parent()) {
2908 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2909 TRACE_EVENT_SCOPE_PROCESS
);
2911 document_state
->set_finish_load_time(Time::Now());
2914 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2915 DidFinishLoad(frame
));
2916 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2918 // Don't send this message while the frame is swapped out.
2919 if (is_swapped_out())
2922 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2923 ds
->request().url()));
2926 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2927 const blink::WebHistoryItem
& item
,
2928 blink::WebHistoryCommitType commit_type
) {
2929 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2931 DCHECK(!frame_
|| frame_
== frame
);
2932 // If this was a reference fragment navigation that we initiated, then we
2933 // could end up having a non-null pending navigation params. We just need to
2934 // update the ExtraData on the datasource so that others who read the
2935 // ExtraData will get the new NavigationState. Similarly, if we did not
2936 // initiate this navigation, then we need to take care to reset any pre-
2937 // existing navigation state to a content-initiated navigation state.
2938 // didCreateDataSource conveniently takes care of this for us.
2939 didCreateDataSource(frame
, frame
->dataSource());
2941 DocumentState
* document_state
=
2942 DocumentState::FromDataSource(frame
->dataSource());
2943 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2944 ->set_was_within_same_page(true);
2946 didCommitProvisionalLoad(frame
, item
, commit_type
);
2949 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2950 DCHECK(!frame_
|| frame_
== frame
);
2951 // TODO(nasko): Move implementation here. Needed methods:
2952 // * StartNavStateSyncTimerIfNecessary
2953 render_view_
->didUpdateCurrentHistoryItem(frame
);
2956 void RenderFrameImpl::didChangeThemeColor() {
2957 if (frame_
->parent())
2960 Send(new FrameHostMsg_DidChangeThemeColor(
2961 routing_id_
, frame_
->document().themeColor()));
2964 void RenderFrameImpl::dispatchLoad() {
2965 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
2968 void RenderFrameImpl::requestNotificationPermission(
2969 const blink::WebSecurityOrigin
& origin
,
2970 blink::WebNotificationPermissionCallback
* callback
) {
2971 if (!notification_permission_dispatcher_
) {
2972 notification_permission_dispatcher_
=
2973 new NotificationPermissionDispatcher(this);
2976 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
2979 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
2980 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
2983 if (is_empty_selection
)
2984 selection_text_
.clear();
2986 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2987 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2988 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2989 // to notify the selection was changed. Focus change should be notified
2990 // before selection change.
2991 GetRenderWidget()->UpdateTextInputType();
2992 SyncSelectionIfRequired();
2993 #if defined(OS_ANDROID)
2994 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
2995 RenderWidget::FROM_NON_IME
);
2999 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3000 blink::WebColorChooserClient
* client
,
3001 const blink::WebColor
& initial_color
,
3002 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3003 RendererWebColorChooserImpl
* color_chooser
=
3004 new RendererWebColorChooserImpl(this, client
);
3005 std::vector
<ColorSuggestion
> color_suggestions
;
3006 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3007 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3009 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3010 return color_chooser
;
3013 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3014 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3017 frame_
->document().url(),
3021 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3022 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3025 frame_
->document().url(),
3029 bool RenderFrameImpl::runModalPromptDialog(
3030 const blink::WebString
& message
,
3031 const blink::WebString
& default_value
,
3032 blink::WebString
* actual_value
) {
3033 base::string16 result
;
3034 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3037 frame_
->document().url(),
3040 actual_value
->assign(result
);
3044 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3046 const blink::WebString
& message
) {
3047 // If we are swapping out, we have already run the beforeunload handler.
3048 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3049 // at all, to avoid running it twice.
3050 if (is_swapped_out_
)
3053 // Don't allow further dialogs if we are waiting to swap out, since the
3054 // PageGroupLoadDeferrer in our stack prevents it.
3055 if (render_view()->suppress_dialogs_until_swap_out_
)
3058 bool success
= false;
3059 // This is an ignored return value, but is included so we can accept the same
3060 // response as RunJavaScriptMessage.
3061 base::string16 ignored_result
;
3062 render_view()->SendAndRunNestedMessageLoop(
3063 new FrameHostMsg_RunBeforeUnloadConfirm(
3064 routing_id_
, frame_
->document().url(), message
, is_reload
,
3065 &success
, &ignored_result
));
3069 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3070 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3071 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3072 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3073 if (GetRenderWidget()->has_host_context_menu_location()) {
3074 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3075 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3078 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3079 // it. We replace it with an empty GURL so the appropriate items are disabled
3080 // in the context menu.
3081 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3082 // data encoded images. We should have a way to save them.
3083 if (params
.src_url
.spec().size() > GetMaxURLChars())
3084 params
.src_url
= GURL();
3085 context_menu_node_
= data
.node
;
3087 #if defined(OS_ANDROID)
3088 gfx::Rect start_rect
;
3090 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3091 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3092 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3095 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3098 void RenderFrameImpl::clearContextMenu() {
3099 context_menu_node_
.reset();
3102 void RenderFrameImpl::willSendRequest(
3103 blink::WebLocalFrame
* frame
,
3104 unsigned identifier
,
3105 blink::WebURLRequest
& request
,
3106 const blink::WebURLResponse
& redirect_response
) {
3107 DCHECK(!frame_
|| frame_
== frame
);
3108 // The request my be empty during tests.
3109 if (request
.url().isEmpty())
3112 // Set the first party for cookies url if it has not been set yet (new
3113 // requests). For redirects, it is updated by WebURLLoaderImpl.
3114 if (request
.firstPartyForCookies().isEmpty()) {
3115 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3116 request
.setFirstPartyForCookies(request
.url());
3118 // TODO(nasko): When the top-level frame is remote, there is no document.
3119 // This is broken and should be fixed to propagate the first party.
3120 WebFrame
* top
= frame
->top();
3121 if (top
->isWebLocalFrame()) {
3122 request
.setFirstPartyForCookies(
3123 frame
->top()->document().firstPartyForCookies());
3128 WebFrame
* top_frame
= frame
->top();
3129 // TODO(nasko): Hack around asking about top-frame data source. This means
3130 // for out-of-process iframes we are treating the current frame as the
3131 // top-level frame, which is wrong.
3132 if (!top_frame
|| top_frame
->isWebRemoteFrame())
3134 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
3135 WebDataSource
* top_data_source
= top_frame
->dataSource();
3136 WebDataSource
* data_source
=
3137 provisional_data_source
? provisional_data_source
: top_data_source
;
3139 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3140 DCHECK(document_state
);
3141 InternalDocumentStateData
* internal_data
=
3142 InternalDocumentStateData::FromDocumentState(document_state
);
3143 NavigationStateImpl
* navigation_state
=
3144 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3145 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3146 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
3147 if (frame_ds
&& frame_ds
->isClientRedirect()) {
3148 transition_type
= ui::PageTransitionFromInt(
3149 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3152 GURL
request_url(request
.url());
3154 if (GetContentClient()->renderer()->WillSendRequest(
3158 request
.firstPartyForCookies(),
3160 request
.setURL(WebURL(new_url
));
3163 if (internal_data
->is_cache_policy_override_set())
3164 request
.setCachePolicy(internal_data
->cache_policy_override());
3166 // The request's extra data may indicate that we should set a custom user
3167 // agent. This needs to be done here, after WebKit is through with setting the
3168 // user agent on its own. Similarly, it may indicate that we should set an
3169 // X-Requested-With header. This must be done here to avoid breaking CORS
3171 // PlzNavigate: there may also be a stream url associated with the request.
3172 WebString custom_user_agent
;
3173 WebString requested_with
;
3174 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3175 if (request
.extraData()) {
3176 RequestExtraData
* old_extra_data
=
3177 static_cast<RequestExtraData
*>(request
.extraData());
3179 custom_user_agent
= old_extra_data
->custom_user_agent();
3180 if (!custom_user_agent
.isNull()) {
3181 if (custom_user_agent
.isEmpty())
3182 request
.clearHTTPHeaderField("User-Agent");
3184 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3187 requested_with
= old_extra_data
->requested_with();
3188 if (!requested_with
.isNull()) {
3189 if (requested_with
.isEmpty())
3190 request
.clearHTTPHeaderField("X-Requested-With");
3192 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3194 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3197 // Add the default accept header for frame request if it has not been set
3199 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3200 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3201 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3202 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3203 WebString::fromUTF8(kDefaultAcceptHeader
));
3206 // Add an empty HTTP origin header for non GET methods if none is currently
3208 request
.addHTTPOriginIfNeeded(WebString());
3210 // Attach |should_replace_current_entry| state to requests so that, should
3211 // this navigation later require a request transfer, all state is preserved
3212 // when it is re-created in the new process.
3213 bool should_replace_current_entry
= false;
3214 if (navigation_state
->IsContentInitiated()) {
3215 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3217 // If the navigation is browser-initiated, the NavigationState contains the
3218 // correct value instead of the WebDataSource.
3220 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3221 // NavigationState::should_replace_current_entry().
3222 should_replace_current_entry
=
3223 navigation_state
->start_params().should_replace_current_entry
;
3226 int provider_id
= kInvalidServiceWorkerProviderId
;
3227 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3228 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3229 // |provisionalDataSource| may be null in some content::ResourceFetcher
3230 // use cases, we don't hook those requests.
3231 if (frame
->provisionalDataSource()) {
3232 ServiceWorkerNetworkProvider
* provider
=
3233 ServiceWorkerNetworkProvider::FromDocumentState(
3234 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3235 provider_id
= provider
->provider_id();
3237 } else if (frame
->dataSource()) {
3238 ServiceWorkerNetworkProvider
* provider
=
3239 ServiceWorkerNetworkProvider::FromDocumentState(
3240 DocumentState::FromDataSource(frame
->dataSource()));
3241 provider_id
= provider
->provider_id();
3244 WebFrame
* parent
= frame
->parent();
3245 int parent_routing_id
= MSG_ROUTING_NONE
;
3247 parent_routing_id
= -1;
3248 } else if (parent
->isWebLocalFrame()) {
3249 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3251 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3254 RequestExtraData
* extra_data
= new RequestExtraData();
3255 extra_data
->set_visibility_state(render_view_
->visibilityState());
3256 extra_data
->set_custom_user_agent(custom_user_agent
);
3257 extra_data
->set_requested_with(requested_with
);
3258 extra_data
->set_render_frame_id(routing_id_
);
3259 extra_data
->set_is_main_frame(!parent
);
3260 extra_data
->set_frame_origin(
3261 GURL(frame
->document().securityOrigin().toString()));
3262 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3263 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3264 extra_data
->set_allow_download(
3265 navigation_state
->common_params().allow_download
);
3266 extra_data
->set_transition_type(transition_type
);
3267 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3268 extra_data
->set_transferred_request_child_id(
3269 navigation_state
->start_params().transferred_request_child_id
);
3270 extra_data
->set_transferred_request_request_id(
3271 navigation_state
->start_params().transferred_request_request_id
);
3272 extra_data
->set_service_worker_provider_id(provider_id
);
3273 extra_data
->set_stream_override(stream_override
.Pass());
3274 request
.setExtraData(extra_data
);
3276 DocumentState
* top_document_state
=
3277 DocumentState::FromDataSource(top_data_source
);
3278 if (top_document_state
) {
3279 // TODO(gavinp): separate out prefetching and prerender field trials
3280 // if the rel=prerender rel type is sticking around.
3281 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3282 top_document_state
->set_was_prefetcher(true);
3285 // This is an instance where we embed a copy of the routing id
3286 // into the data portion of the message. This can cause problems if we
3287 // don't register this id on the browser side, since the download manager
3288 // expects to find a RenderViewHost based off the id.
3289 request
.setRequestorID(render_view_
->GetRoutingID());
3290 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3292 if (!navigation_state
->start_params().extra_headers
.empty()) {
3293 for (net::HttpUtil::HeadersIterator
i(
3294 navigation_state
->start_params().extra_headers
.begin(),
3295 navigation_state
->start_params().extra_headers
.end(), "\n");
3297 if (base::LowerCaseEqualsASCII(i
.name(), "referer")) {
3298 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3299 blink::WebReferrerPolicyDefault
,
3301 WebString::fromUTF8(i
.values()));
3302 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3304 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3305 WebString::fromUTF8(i
.values()));
3310 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3311 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3314 void RenderFrameImpl::didReceiveResponse(
3315 blink::WebLocalFrame
* frame
,
3316 unsigned identifier
,
3317 const blink::WebURLResponse
& response
) {
3318 DCHECK(!frame_
|| frame_
== frame
);
3319 // Only do this for responses that correspond to a provisional data source
3320 // of the top-most frame. If we have a provisional data source, then we
3321 // can't have any sub-resources yet, so we know that this response must
3322 // correspond to a frame load.
3323 if (!frame
->provisionalDataSource() || frame
->parent())
3326 // If we are in view source mode, then just let the user see the source of
3327 // the server's error page.
3328 if (frame
->isViewSourceModeEnabled())
3331 DocumentState
* document_state
=
3332 DocumentState::FromDataSource(frame
->provisionalDataSource());
3333 int http_status_code
= response
.httpStatusCode();
3335 // Record page load flags.
3336 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3338 document_state
->set_was_fetched_via_spdy(
3339 extra_data
->was_fetched_via_spdy());
3340 document_state
->set_was_npn_negotiated(
3341 extra_data
->was_npn_negotiated());
3342 document_state
->set_npn_negotiated_protocol(
3343 extra_data
->npn_negotiated_protocol());
3344 document_state
->set_was_alternate_protocol_available(
3345 extra_data
->was_alternate_protocol_available());
3346 document_state
->set_connection_info(
3347 extra_data
->connection_info());
3348 document_state
->set_was_fetched_via_proxy(
3349 extra_data
->was_fetched_via_proxy());
3350 document_state
->set_proxy_server(
3351 extra_data
->proxy_server());
3353 InternalDocumentStateData
* internal_data
=
3354 InternalDocumentStateData::FromDocumentState(document_state
);
3355 internal_data
->set_http_status_code(http_status_code
);
3356 // Whether or not the http status code actually corresponds to an error is
3357 // only checked when the page is done loading, if |use_error_page| is
3359 internal_data
->set_use_error_page(true);
3362 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3363 unsigned identifier
) {
3364 DCHECK(!frame_
|| frame_
== frame
);
3365 InternalDocumentStateData
* internal_data
=
3366 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3367 if (!internal_data
->use_error_page())
3370 // Do not show error page when DevTools is attached.
3371 RenderFrameImpl
* localRoot
= this;
3372 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
3373 localRoot
->frame_
->parent()->isWebLocalFrame()) {
3374 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
3377 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
3380 // Display error page, if appropriate.
3381 std::string error_domain
= "http";
3382 int http_status_code
= internal_data
->http_status_code();
3383 if (GetContentClient()->renderer()->HasErrorPage(
3384 http_status_code
, &error_domain
)) {
3386 error
.unreachableURL
= frame
->document().url();
3387 error
.domain
= WebString::fromUTF8(error_domain
);
3388 error
.reason
= http_status_code
;
3389 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3393 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3394 blink::WebLocalFrame
* frame
,
3395 const blink::WebURLRequest
& request
,
3396 const blink::WebURLResponse
& response
) {
3397 DCHECK(!frame_
|| frame_
== frame
);
3398 // The recipients of this message have no use for data: URLs: they don't
3399 // affect the page's insecure content list and are not in the disk cache. To
3400 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3401 // filter them out here.
3402 GURL
url(request
.url());
3403 if (url
.SchemeIs(url::kDataScheme
))
3406 // Let the browser know we loaded a resource from the memory cache. This
3407 // message is needed to display the correct SSL indicators.
3408 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3409 render_view_
->GetRoutingID(),
3411 response
.securityInfo(),
3412 request
.httpMethod().utf8(),
3413 response
.mimeType().utf8(),
3414 WebURLRequestToResourceType(request
)));
3417 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3418 DCHECK(!frame_
|| frame_
== frame
);
3419 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3420 render_view_
->GetRoutingID()));
3423 void RenderFrameImpl::didRunInsecureContent(
3424 blink::WebLocalFrame
* frame
,
3425 const blink::WebSecurityOrigin
& origin
,
3426 const blink::WebURL
& target
) {
3427 DCHECK(!frame_
|| frame_
== frame
);
3428 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3429 render_view_
->GetRoutingID(),
3430 origin
.toString().utf8(),
3432 GetContentClient()->renderer()->RecordRapporURL(
3433 "ContentSettings.MixedScript.RanMixedScript",
3434 GURL(origin
.toString().utf8()));
3437 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3438 DCHECK(!frame_
|| frame_
== frame
);
3439 #if defined(ENABLE_PLUGINS)
3440 if (frame
!= render_view_
->webview()->mainFrame())
3442 PluginChannelHost::Broadcast(
3443 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3447 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3448 v8::Local
<v8::Context
> context
,
3449 int extension_group
,
3451 DCHECK(!frame_
|| frame_
== frame
);
3453 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3454 DidCreateScriptContext(context
, extension_group
, world_id
));
3457 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3458 v8::Local
<v8::Context
> context
,
3460 DCHECK(!frame_
|| frame_
== frame
);
3462 FOR_EACH_OBSERVER(RenderFrameObserver
,
3464 WillReleaseScriptContext(context
, world_id
));
3467 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3468 blink::WebLocalFrame
* frame
) {
3469 DCHECK(!frame_
|| frame_
== frame
);
3470 if (frame
->parent())
3473 InternalDocumentStateData
* data
=
3474 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3475 data
->set_did_first_visually_non_empty_layout(true);
3477 #if defined(OS_ANDROID)
3478 GetRenderWidget()->DidChangeBodyBackgroundColor(
3479 render_view_
->webwidget_
->backgroundColor());
3482 GetRenderWidget()->QueueMessage(
3483 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3484 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3487 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3488 DCHECK(!frame_
|| frame_
== frame
);
3489 // TODO(nasko): Move implementation here. Needed methods:
3490 // * StartNavStateSyncTimerIfNecessary
3491 render_view_
->didChangeScrollOffset(frame
);
3493 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3496 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3497 DCHECK(!frame_
|| frame_
== frame
);
3498 if (!frame
->parent()) {
3499 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3500 render_view_
->GetRoutingID()));
3504 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3506 bool final_update
) {
3507 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3509 active_match_ordinal
= 0;
3511 render_view_
->Send(new ViewHostMsg_Find_Reply(
3512 render_view_
->GetRoutingID(), request_id
, count
,
3513 gfx::Rect(), active_match_ordinal
, final_update
));
3516 void RenderFrameImpl::reportFindInPageSelection(
3518 int active_match_ordinal
,
3519 const blink::WebRect
& selection_rect
) {
3520 render_view_
->Send(new ViewHostMsg_Find_Reply(
3521 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3522 active_match_ordinal
, false));
3525 void RenderFrameImpl::requestStorageQuota(
3526 blink::WebLocalFrame
* frame
,
3527 blink::WebStorageQuotaType type
,
3528 unsigned long long requested_size
,
3529 blink::WebStorageQuotaCallbacks callbacks
) {
3530 DCHECK(!frame_
|| frame_
== frame
);
3531 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3532 if (origin
.isUnique()) {
3533 // Unique origins cannot store persistent state.
3534 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3537 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3538 render_view_
->GetRoutingID(),
3539 GURL(origin
.toString()),
3540 static_cast<storage::StorageType
>(type
),
3542 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3545 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3546 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3547 impl
->set_render_frame_id(routing_id_
);
3550 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3551 if (!geolocation_dispatcher_
)
3552 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3553 return geolocation_dispatcher_
;
3556 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3557 if (!presentation_dispatcher_
)
3558 presentation_dispatcher_
= new PresentationDispatcher(this);
3559 return presentation_dispatcher_
;
3562 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3563 if (!push_messaging_dispatcher_
)
3564 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3565 return push_messaging_dispatcher_
;
3568 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3569 blink::WebLocalFrame
* frame
,
3570 blink::WebRTCPeerConnectionHandler
* handler
) {
3571 DCHECK(!frame_
|| frame_
== frame
);
3572 #if defined(ENABLE_WEBRTC)
3573 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3577 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3578 if (!web_user_media_client_
)
3579 InitializeUserMediaClient();
3580 return web_user_media_client_
;
3583 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3584 if (!web_encrypted_media_client_
) {
3585 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3586 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3587 // is destructed before |this|, and does not give away ownership of the
3589 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported
,
3590 base::Unretained(this)),
3591 GetCdmFactory(), GetMediaPermission()));
3593 return web_encrypted_media_client_
.get();
3596 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3597 if (!midi_dispatcher_
)
3598 midi_dispatcher_
= new MidiDispatcher(this);
3599 return midi_dispatcher_
;
3602 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3603 blink::WebLocalFrame
* source_frame
,
3604 blink::WebFrame
* target_frame
,
3605 blink::WebSecurityOrigin target_origin
,
3606 blink::WebDOMMessageEvent event
) {
3607 DCHECK(!frame_
|| frame_
== target_frame
);
3609 // Currently, a postMessage that targets a cross-process frame can be plumbed
3610 // either through this function or RenderFrameProxy::postMessageEvent. This
3611 // function is used when the target cross-process frame is a top-level frame
3612 // which has been swapped out. In that case, the corresponding WebLocalFrame
3613 // currently remains in the frame tree even in site-per-process mode (see
3614 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3615 // --site-per-process mode for all other cases.
3617 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3618 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3619 // cross-process postMessages.
3620 if (!is_swapped_out_
)
3623 // It is possible to get here on a swapped-out frame without a
3624 // |render_frame_proxy_|. This happens when:
3625 // - This process only has one active RenderView and is about to go away
3626 // (e.g., due to cross-process navigation).
3627 // - The top frame has a subframe with an unload handler.
3628 // - The subframe sends a postMessage to the top-level frame in its unload
3630 // See https://crbug.com/475651 for details. We return false here, since we
3631 // don't want to deliver the message to the new process in this case.
3632 if (!render_frame_proxy_
)
3635 render_frame_proxy_
->postMessageEvent(
3636 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3640 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3641 const blink::WebURL
& url
) {
3642 DCHECK(!frame_
|| frame_
== frame
);
3643 std::string user_agent_override_for_url
=
3644 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3645 if (!user_agent_override_for_url
.empty())
3646 return WebString::fromUTF8(user_agent_override_for_url
);
3648 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3649 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3650 return blink::WebString();
3653 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3654 // associated with it, so the checks below are not valid. Temporarily
3655 // return early and fix properly as part of https://crbug.com/426555.
3656 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3657 return blink::WebString();
3659 // If we're in the middle of committing a load, the data source we need
3660 // will still be provisional.
3661 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3662 WebDataSource
* data_source
= NULL
;
3663 if (main_frame
->provisionalDataSource())
3664 data_source
= main_frame
->provisionalDataSource();
3666 data_source
= main_frame
->dataSource();
3668 InternalDocumentStateData
* internal_data
= data_source
?
3669 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3670 if (internal_data
&& internal_data
->is_overriding_user_agent())
3671 return WebString::fromUTF8(
3672 render_view_
->renderer_preferences_
.user_agent_override
);
3673 return blink::WebString();
3676 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3677 DCHECK(!frame_
|| frame_
== frame
);
3678 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3679 return WebString::fromUTF8("1");
3683 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3684 bool default_value
) {
3685 DCHECK(!frame_
|| frame_
== frame
);
3689 bool blocked
= true;
3690 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3691 render_view_
->GetRoutingID(),
3692 GURL(frame
->top()->securityOrigin().toString()),
3693 THREE_D_API_TYPE_WEBGL
,
3698 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3699 int arb_robustness_status_code
) {
3700 DCHECK(!frame_
|| frame_
== frame
);
3701 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3702 GURL(frame
->top()->securityOrigin().toString()),
3703 THREE_D_API_TYPE_WEBGL
,
3704 arb_robustness_status_code
));
3707 blink::WebScreenOrientationClient
*
3708 RenderFrameImpl::webScreenOrientationClient() {
3709 if (!screen_orientation_dispatcher_
)
3710 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3711 return screen_orientation_dispatcher_
;
3714 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3715 ServiceWorkerNetworkProvider
* provider
=
3716 ServiceWorkerNetworkProvider::FromDocumentState(
3717 DocumentState::FromDataSource(&data_source
));
3718 if (!provider
->context())
3720 return provider
->context()->controller_handle_id() !=
3721 kInvalidServiceWorkerHandleId
;
3724 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3725 ServiceWorkerNetworkProvider
* provider
=
3726 ServiceWorkerNetworkProvider::FromDocumentState(
3727 DocumentState::FromDataSource(&data_source
));
3728 if (provider
->context() && provider
->context()->controller())
3729 return provider
->context()->controller()->version_id();
3730 return kInvalidServiceWorkerVersionId
;
3733 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3734 blink::WebAXEvent event
) {
3735 HandleWebAccessibilityEvent(obj
, event
);
3738 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3741 const blink::WebAXObject
& start_object
,
3743 const blink::WebAXObject
& end_object
,
3745 if (renderer_accessibility_
) {
3746 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3747 identifier
, match_index
, start_object
, start_offset
,
3748 end_object
, end_offset
);
3752 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3753 DCHECK(!frame_
|| frame_
== frame
);
3755 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3758 void RenderFrameImpl::didChangeDefaultPresentation(
3759 blink::WebLocalFrame
* frame
) {
3760 DCHECK(!frame_
|| frame_
== frame
);
3763 RenderFrameObserver
, observers_
, DidChangeDefaultPresentation());
3766 bool RenderFrameImpl::enterFullscreen() {
3767 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3771 bool RenderFrameImpl::exitFullscreen() {
3772 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3776 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3777 if (!permission_client_
)
3778 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3780 return permission_client_
.get();
3783 blink::WebAppBannerClient
* RenderFrameImpl::appBannerClient() {
3784 if (!app_banner_client_
) {
3785 app_banner_client_
=
3786 GetContentClient()->renderer()->CreateAppBannerClient(this);
3789 return app_banner_client_
.get();
3792 void RenderFrameImpl::registerProtocolHandler(const WebString
& scheme
,
3794 const WebString
& title
) {
3795 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3796 Send(new FrameHostMsg_RegisterProtocolHandler(routing_id_
,
3797 base::UTF16ToUTF8(scheme
),
3803 void RenderFrameImpl::unregisterProtocolHandler(const WebString
& scheme
,
3804 const WebURL
& url
) {
3805 bool user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3806 Send(new FrameHostMsg_UnregisterProtocolHandler(routing_id_
,
3807 base::UTF16ToUTF8(scheme
),
3812 #if defined(ENABLE_WEBVR)
3813 blink::WebVRClient
* RenderFrameImpl::webVRClient() {
3814 if (!vr_dispatcher_
)
3815 vr_dispatcher_
.reset(new VRDispatcher(GetServiceRegistry()));
3817 return vr_dispatcher_
.get();
3821 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3822 Send(new FrameHostMsg_MediaPlayingNotification(
3823 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3824 player
->hasAudio(), player
->isRemote()));
3827 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3828 Send(new FrameHostMsg_MediaPausedNotification(
3829 routing_id_
, reinterpret_cast<int64
>(player
)));
3832 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3836 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3837 observers_
.AddObserver(observer
);
3840 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3841 observer
->RenderFrameGone();
3842 observers_
.RemoveObserver(observer
);
3845 void RenderFrameImpl::OnStop() {
3847 frame_
->stopLoading();
3848 if (!frame_
->parent())
3849 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3851 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3854 void RenderFrameImpl::WasHidden() {
3855 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3858 void RenderFrameImpl::WasShown() {
3859 // TODO(kenrb): Need to figure out how to do this better. Should
3860 // VisibilityState remain a page-level concept or move to frames?
3861 // The semantics of 'Show' might have to change here.
3862 if (render_widget_
) {
3863 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3864 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3866 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3869 void RenderFrameImpl::WidgetWillClose() {
3870 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3873 bool RenderFrameImpl::IsHidden() {
3874 return GetRenderWidget()->is_hidden();
3877 // Tell the embedding application that the URL of the active page has changed.
3878 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3879 blink::WebFrame
* frame
,
3880 blink::WebHistoryCommitType commit_type
,
3881 const blink::WebHistoryItem
& item
) {
3882 DCHECK(!frame_
|| frame_
== frame
);
3883 WebDataSource
* ds
= frame
->dataSource();
3886 const WebURLRequest
& request
= ds
->request();
3887 const WebURLResponse
& response
= ds
->response();
3889 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3890 NavigationStateImpl
* navigation_state
=
3891 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3892 InternalDocumentStateData
* internal_data
=
3893 InternalDocumentStateData::FromDocumentState(document_state
);
3895 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3896 params
.http_status_code
= response
.httpStatusCode();
3897 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3898 params
.is_post
= false;
3899 params
.intended_as_new_entry
=
3900 navigation_state
->request_params().intended_as_new_entry
;
3901 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3902 params
.post_id
= -1;
3903 params
.page_id
= render_view_
->page_id_
;
3904 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3905 // We need to track the RenderViewHost routing_id because of downstream
3906 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3907 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3908 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3909 // based on the ID stored in the resource requests. Once those dependencies
3910 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3911 // client to be based on the routing_id of the RenderFrameHost.
3912 params
.render_view_routing_id
= render_view_
->routing_id();
3913 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3914 params
.socket_address
.set_port(response
.remotePort());
3915 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3917 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3918 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3919 params
.security_info
= response
.securityInfo();
3921 // Set the URL to be displayed in the browser UI to the user.
3922 params
.url
= GetLoadingUrl();
3923 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3925 // Set the origin of the frame. This will be replicated to the corresponding
3926 // RenderFrameProxies in other processes.
3927 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3928 // to https://crbug.com/439608 and will be replicated as unique origins.
3929 if (!is_swapped_out_
) {
3930 WebString
serialized_origin(frame
->document().securityOrigin().toString());
3931 if (GURL(serialized_origin
).IsStandard())
3932 params
.origin
= url::DeprecatedSerializedOrigin(serialized_origin
.utf8());
3935 if (frame
->document().baseURL() != params
.url
)
3936 params
.base_url
= frame
->document().baseURL();
3938 GetRedirectChain(ds
, ¶ms
.redirects
);
3939 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3940 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3942 params
.searchable_form_url
= internal_data
->searchable_form_url();
3943 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3945 params
.gesture
= render_view_
->navigation_gesture_
;
3946 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3948 // Make navigation state a part of the DidCommitProvisionalLoad message so
3949 // that committed entry has it at all times.
3950 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3951 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
3952 switches::kSitePerProcess
)) {
3954 params
.page_state
= HistoryEntryToPageState(entry
);
3956 params
.page_state
= PageState::CreateFromURL(request
.url());
3958 // In --site-per-process, just send a single HistoryItem for this frame,
3959 // rather than the whole tree. It will be stored in the corresponding
3960 // FrameNavigationEntry.
3961 params
.page_state
= SingleHistoryItemToPageState(item
);
3963 params
.item_sequence_number
= item
.itemSequenceNumber();
3964 params
.document_sequence_number
= item
.documentSequenceNumber();
3966 if (!frame
->parent()) {
3967 // Top-level navigation.
3969 // Reset the zoom limits in case a plugin had changed them previously. This
3970 // will also call us back which will cause us to send a message to
3971 // update WebContentsImpl.
3972 render_view_
->webview()->zoomLimitsChanged(
3973 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3974 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3976 // Set zoom level, but don't do it for full-page plugin since they don't use
3977 // the same zoom settings.
3978 HostZoomLevels::iterator host_zoom
=
3979 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3980 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3981 // Reset the zoom levels for plugins.
3982 render_view_
->webview()->setZoomLevel(0);
3984 // If the zoom level is not found, then do nothing. In-page navigation
3985 // relies on not changing the zoom level in this case.
3986 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3987 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3990 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3991 // This zoom level was merely recorded transiently for this load. We can
3992 // erase it now. If at some point we reload this page, the browser will
3993 // send us a new, up-to-date zoom level.
3994 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3997 // Update contents MIME type for main frame.
3998 params
.contents_mime_type
= ds
->response().mimeType().utf8();
4000 params
.transition
= navigation_state
->GetTransitionType();
4001 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
4002 // If the main frame does a load, it should not be reported as a subframe
4003 // navigation. This can occur in the following case:
4004 // 1. You're on a site with frames.
4005 // 2. You do a subframe navigation. This is stored with transition type
4007 // 3. You navigate to some non-frame site, say, google.com.
4008 // 4. You navigate back to the page from step 2. Since it was initially
4009 // MANUAL_SUBFRAME, it will be that same transition type here.
4010 // We don't want that, because any navigation that changes the toplevel
4011 // frame should be tracked as a toplevel navigation (this allows us to
4012 // update the URL bar, etc).
4013 params
.transition
= ui::PAGE_TRANSITION_LINK
;
4016 // If the page contained a client redirect (meta refresh, document.loc...),
4017 // set the referrer and transition appropriately.
4018 if (ds
->isClientRedirect()) {
4020 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
4021 params
.transition
= ui::PageTransitionFromInt(
4022 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
4024 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
4025 frame
, ds
->request());
4028 base::string16 method
= request
.httpMethod();
4029 if (base::EqualsASCII(method
, "POST")) {
4030 params
.is_post
= true;
4031 params
.post_id
= ExtractPostId(entry
);
4034 // Send the user agent override back.
4035 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
4037 // Track the URL of the original request. We use the first entry of the
4038 // redirect chain if it exists because the chain may have started in another
4040 params
.original_request_url
= GetOriginalRequestURL(ds
);
4042 params
.history_list_was_cleared
=
4043 navigation_state
->request_params().should_clear_history_list
;
4045 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4046 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4047 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4048 frame
->dataSource()->request().uiStartTime());
4050 // Save some histogram data so we can compute the average memory used per
4051 // page load of the glyphs.
4052 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4053 blink::WebGlyphCache::pageCount());
4055 // This message needs to be sent before any of allowScripts(),
4056 // allowImages(), allowPlugins() is called for the new page, so that when
4057 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4058 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4059 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4061 // Subframe navigation: the type depends on whether this navigation
4062 // generated a new session history entry. When they do generate a session
4063 // history entry, it means the user initiated the navigation and we should
4065 if (commit_type
== blink::WebStandardCommit
)
4066 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4068 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4070 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4071 params
.history_list_was_cleared
= false;
4072 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4074 // Don't send this message while the subframe is swapped out.
4075 if (!is_swapped_out())
4076 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4079 // If we end up reusing this WebRequest (for example, due to a #ref click),
4080 // we don't want the transition type to persist. Just clear it.
4081 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4084 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4085 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4087 render_view_
->FrameDidStartLoading(frame_
);
4088 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4091 void RenderFrameImpl::didStopLoading() {
4092 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4094 render_view_
->FrameDidStopLoading(frame_
);
4095 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4098 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4099 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4102 void RenderFrameImpl::HandleWebAccessibilityEvent(
4103 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4104 if (renderer_accessibility_
)
4105 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4108 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4109 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4112 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4113 if (renderer_accessibility())
4114 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4118 void RenderFrameImpl::OnCommitNavigation(
4119 const ResourceResponseHead
& response
,
4120 const GURL
& stream_url
,
4121 const CommonNavigationParams
& common_params
,
4122 const RequestNavigationParams
& request_params
) {
4123 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4124 switches::kEnableBrowserSideNavigation
));
4125 // This will override the url requested by the WebURLLoader, as well as
4126 // provide it with the response to the request.
4127 scoped_ptr
<StreamOverrideParameters
> stream_override(
4128 new StreamOverrideParameters());
4129 stream_override
->stream_url
= stream_url
;
4130 stream_override
->response
= response
;
4132 NavigateInternal(common_params
, StartNavigationParams(), request_params
,
4133 stream_override
.Pass());
4136 void RenderFrameImpl::OnFailedNavigation(
4137 const CommonNavigationParams
& common_params
,
4138 const RequestNavigationParams
& request_params
,
4139 bool has_stale_copy_in_cache
,
4141 bool is_reload
= IsReload(common_params
.navigation_type
);
4142 bool is_history_navigation
= request_params
.page_state
.IsValid();
4143 WebURLRequest::CachePolicy cache_policy
=
4144 WebURLRequest::UseProtocolCachePolicy
;
4145 RenderFrameImpl::PrepareRenderViewForNavigation(
4146 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4148 GetContentClient()->SetActiveURL(common_params
.url
);
4150 pending_navigation_params_
.reset(new NavigationParams(
4151 common_params
, StartNavigationParams(), request_params
));
4153 // Inform the browser of the start of the provisional load. This is needed so
4154 // that the load is properly tracked by the WebNavigation API.
4155 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4156 routing_id_
, common_params
.url
));
4158 // Send the provisional load failure.
4159 blink::WebURLError error
=
4160 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4161 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4162 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4163 frame_
->isViewSourceModeEnabled());
4164 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4166 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4167 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4168 // http://crbug.com/501960
4169 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4173 // Make sure errors are not shown in view source mode.
4174 frame_
->enableViewSourceMode(false);
4176 // Replace the current history entry in reloads, history navigations and loads
4177 // of the same url. This corresponds to Blink's notion of a standard
4179 // TODO(clamy): see if initial commits in subframes should be handled
4181 bool replace
= is_reload
|| is_history_navigation
||
4182 common_params
.url
== GetLoadingUrl();
4183 LoadNavigationErrorPage(failed_request
, error
, replace
);
4186 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4187 RenderFrame
* render_frame
,
4188 const NavigationPolicyInfo
& info
) {
4190 // The handlenavigation API is deprecated and will be removed once
4191 // crbug.com/325351 is resolved.
4192 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
4193 GetContentClient()->renderer()->HandleNavigation(
4195 static_cast<DocumentState
*>(info
.extraData
),
4196 render_view_
->opener_id_
,
4199 info
.navigationType
,
4202 return blink::WebNavigationPolicyIgnore
;
4206 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4208 const base::CommandLine
& command_line
=
4209 *base::CommandLine::ForCurrentProcess();
4211 if (command_line
.HasSwitch(switches::kSitePerProcess
) && 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(info
.urlRequest
.httpMethod(), "POST");
4257 bool browser_handles_request
=
4258 render_view_
->renderer_preferences_
4259 .browser_handles_non_local_top_level_requests
4260 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4262 if (!browser_handles_request
) {
4263 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4264 render_view_
->renderer_preferences_
4265 .browser_handles_all_top_level_requests
;
4268 if (browser_handles_request
) {
4269 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4270 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4274 // Use the frame's original request's URL rather than the document's URL for
4275 // subsequent checks. For a popup, the document's URL may become the opener
4276 // window's URL if the opener has called document.write().
4277 // See http://crbug.com/93517.
4278 GURL
old_url(info
.frame
->dataSource()->request().url());
4280 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4281 // an extension or app origin, leaving a WebUI page, etc). We only care about
4282 // top-level navigations (not iframes). But we sometimes navigate to
4283 // about:blank to clear a tab, and we want to still allow that.
4285 // Note: this is known to break POST submissions when crossing process
4286 // boundaries until http://crbug.com/101395 is fixed. This is better for
4287 // security than loading a WebUI, extension or app page in the wrong process.
4288 // POST requests don't work because this mechanism does not preserve form
4289 // POST data. We will need to send the request's httpBody data up to the
4290 // browser process, and issue a special POST navigation in WebKit (via
4291 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4292 // for examples of how to send the httpBody data.
4293 if (!info
.frame
->parent() && is_content_initiated
&&
4294 !url
.SchemeIs(url::kAboutScheme
)) {
4295 bool send_referrer
= false;
4297 // All navigations to or from WebUI URLs or within WebUI-enabled
4298 // RenderProcesses must be handled by the browser process so that the
4299 // correct bindings and data sources can be registered.
4300 // Similarly, navigations to view-source URLs or within ViewSource mode
4301 // must be handled by the browser process (except for reloads - those are
4302 // safe to leave within the renderer).
4303 // Lastly, access to file:// URLs from non-file:// URL pages must be
4304 // handled by the browser so that ordinary renderer processes don't get
4305 // blessed with file permissions.
4306 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4307 bool is_initial_navigation
= render_view_
->history_list_length_
== 0;
4308 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4309 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4310 url
.SchemeIs(kViewSourceScheme
) ||
4311 (info
.frame
->isViewSourceModeEnabled() &&
4312 info
.navigationType
!= blink::WebNavigationTypeReload
);
4314 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4315 // Fork non-file to file opens. Check the opener URL if this is the
4316 // initial navigation in a newly opened window.
4317 GURL
source_url(old_url
);
4318 if (is_initial_navigation
&& source_url
.is_empty() &&
4319 info
.frame
->opener())
4320 source_url
= info
.frame
->opener()->top()->document().url();
4321 DCHECK(!source_url
.is_empty());
4322 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4326 // Give the embedder a chance.
4327 should_fork
= GetContentClient()->renderer()->ShouldFork(
4328 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4329 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4333 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4334 info
.defaultPolicy
);
4335 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4339 // Detect when a page is "forking" a new tab that can be safely rendered in
4340 // its own process. This is done by sites like Gmail that try to open links
4341 // in new windows without script connections back to the original page. We
4342 // treat such cases as browser navigations (in which we will create a new
4343 // renderer for a cross-site navigation), rather than WebKit navigations.
4345 // We use the following heuristic to decide whether to fork a new page in its
4347 // The parent page must open a new tab to about:blank, set the new tab's
4348 // window.opener to null, and then redirect the tab to a cross-site URL using
4351 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4354 // Must start from a tab showing about:blank, which is later redirected.
4355 old_url
== GURL(url::kAboutBlankURL
) &&
4356 // Must be the first real navigation of the tab.
4357 render_view_
->historyBackListCount() < 1 &&
4358 render_view_
->historyForwardListCount() < 1 &&
4359 // The parent page must have set the child's window.opener to null before
4360 // redirecting to the desired URL.
4361 info
.frame
->opener() == NULL
&&
4362 // Must be a top-level frame.
4363 info
.frame
->parent() == NULL
&&
4364 // Must not have issued the request from this page.
4365 is_content_initiated
&&
4366 // Must be targeted at the current tab.
4367 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4368 // Must be a JavaScript navigation, which appears as "other".
4369 info
.navigationType
== blink::WebNavigationTypeOther
;
4372 // Open the URL via the browser, not via WebKit.
4373 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4374 return blink::WebNavigationPolicyIgnore
;
4377 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4378 // This includes navigations with no request being sent to the network stack.
4379 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4380 switches::kEnableBrowserSideNavigation
) &&
4381 info
.urlRequest
.checkForBrowserSideNavigation() &&
4382 ShouldMakeNetworkRequestForURL(url
)) {
4383 BeginNavigation(&info
.urlRequest
);
4384 return blink::WebNavigationPolicyIgnore
;
4387 return info
.defaultPolicy
;
4390 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4392 const Referrer
& referrer
,
4393 WebNavigationPolicy policy
) {
4394 DCHECK_EQ(frame_
, frame
);
4396 FrameHostMsg_OpenURL_Params params
;
4398 params
.referrer
= referrer
;
4399 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4400 WebDataSource
* ds
= frame
->provisionalDataSource();
4402 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4403 NavigationStateImpl
* navigation_state
=
4404 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4405 if (navigation_state
->IsContentInitiated()) {
4406 params
.should_replace_current_entry
=
4407 ds
->replacesCurrentHistoryItem() &&
4408 render_view_
->history_list_length_
;
4410 // This is necessary to preserve the should_replace_current_entry value on
4411 // cross-process redirects, in the event it was set by a previous process.
4413 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4414 // NavigationState::should_replace_current_entry().
4415 params
.should_replace_current_entry
=
4416 navigation_state
->start_params().should_replace_current_entry
;
4419 params
.should_replace_current_entry
= false;
4421 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4422 if (GetContentClient()->renderer()->AllowPopup())
4423 params
.user_gesture
= true;
4425 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4426 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4427 policy
== blink::WebNavigationPolicyNewWindow
||
4428 policy
== blink::WebNavigationPolicyNewPopup
) {
4429 WebUserGestureIndicator::consumeUserGesture();
4432 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4435 void RenderFrameImpl::NavigateInternal(
4436 const CommonNavigationParams
& common_params
,
4437 const StartNavigationParams
& start_params
,
4438 const RequestNavigationParams
& request_params
,
4439 scoped_ptr
<StreamOverrideParameters
> stream_params
) {
4440 bool browser_side_navigation
=
4441 base::CommandLine::ForCurrentProcess()->HasSwitch(
4442 switches::kEnableBrowserSideNavigation
);
4443 bool is_reload
= IsReload(common_params
.navigation_type
);
4444 bool is_history_navigation
= request_params
.page_state
.IsValid();
4445 WebURLRequest::CachePolicy cache_policy
=
4446 WebURLRequest::UseProtocolCachePolicy
;
4447 RenderFrameImpl::PrepareRenderViewForNavigation(
4448 common_params
.url
, request_params
, &is_reload
, &cache_policy
);
4450 GetContentClient()->SetActiveURL(common_params
.url
);
4452 // If this frame isn't in the same process as the main frame, it may naively
4453 // assume that this is the first navigation in the iframe, but this may not
4454 // actually be the case. Inform the frame's state machine if this frame has
4455 // already committed other loads.
4456 if (request_params
.has_committed_real_load
&& frame_
->parent())
4457 frame_
->setCommittedFirstRealLoad();
4459 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
4460 // We cannot reload if we do not have any history state. This happens, for
4461 // example, when recovering from a crash.
4463 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4466 pending_navigation_params_
.reset(
4467 new NavigationParams(common_params
, start_params
, request_params
));
4469 // Create parameters for a standard navigation.
4470 blink::WebFrameLoadType load_type
= blink::WebFrameLoadType::Standard
;
4471 bool should_load_request
= false;
4472 WebHistoryItem item_for_history_navigation
;
4473 WebURLRequest request
= CreateURLRequestForNavigation(
4474 common_params
, stream_params
.Pass(), frame_
->isViewSourceModeEnabled());
4476 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4477 // navigation for this request (since it already went to the browser).
4478 if (browser_side_navigation
)
4479 request
.setCheckForBrowserSideNavigation(false);
4481 // If we are reloading, then use the history state of the current frame.
4482 // Otherwise, if we have history state, then we need to navigate to it, which
4483 // corresponds to a back/forward navigation event. Update the parameters
4484 // depending on the navigation type.
4486 bool ignore_cache
= (common_params
.navigation_type
==
4487 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
4488 load_type
= ignore_cache
? blink::WebFrameLoadType::ReloadFromOrigin
4489 : blink::WebFrameLoadType::Reload
;
4491 if (!browser_side_navigation
) {
4492 const GURL override_url
=
4493 (common_params
.navigation_type
==
4494 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
)
4497 request
= frame_
->requestForReload(load_type
, override_url
);
4499 should_load_request
= true;
4500 } else if (is_history_navigation
) {
4501 // We must know the page ID of the page we are navigating back to.
4502 DCHECK_NE(request_params
.page_id
, -1);
4503 // We must know the nav entry ID of the page we are navigating back to,
4504 // which should be the case because history navigations are routed via the
4506 DCHECK_NE(0, request_params
.nav_entry_id
);
4507 scoped_ptr
<HistoryEntry
> entry
=
4508 PageStateToHistoryEntry(request_params
.page_state
);
4510 // Ensure we didn't save the swapped out URL in UpdateState, since the
4511 // browser should never be telling us to navigate to swappedout://.
4512 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
4514 if (!browser_side_navigation
) {
4515 scoped_ptr
<NavigationParams
> navigation_params(
4516 new NavigationParams(*pending_navigation_params_
.get()));
4517 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
4518 switches::kSitePerProcess
)) {
4519 // By default, tell the HistoryController to go the deserialized
4520 // HistoryEntry. This only works if all frames are in the same
4522 DCHECK(!frame_
->parent());
4523 render_view_
->history_controller()->GoToEntry(
4524 frame_
, entry
.Pass(), navigation_params
.Pass(), cache_policy
);
4526 // In --site-per-process, the browser process sends a single
4527 // WebHistoryItem destined for this frame.
4528 // TODO(creis): Change PageState to FrameState. In the meantime, we
4529 // store the relevant frame's WebHistoryItem in the root of the
4531 SetPendingNavigationParams(navigation_params
.Pass());
4532 blink::WebHistoryItem history_item
= entry
->root();
4533 blink::WebHistoryLoadType load_type
=
4534 request_params
.is_same_document_history_load
4535 ? blink::WebHistorySameDocumentLoad
4536 : blink::WebHistoryDifferentDocumentLoad
;
4538 // Let the history controller know the provisional entry, since it is
4539 // used at commit time. Otherwise skip GoToEntry and navigate the
4541 // TODO(creis): Consider cloning the current entry to handle subframe
4542 // cases. Changes to SendUpdateState might affect this.
4543 render_view_
->history_controller()->set_provisional_entry(
4545 WebURLRequest request
=
4546 frame_
->requestFromHistoryItem(history_item
, cache_policy
);
4547 frame_
->load(request
, blink::WebFrameLoadType::BackForward
,
4548 history_item
, load_type
);
4551 // TODO(clamy): this should be set to the HistoryItem sent by the
4552 // browser once the HistoryController has moved to the browser.
4553 // TODO(clamy): distinguish between different document and same document
4555 // TODO(clamy): update this for subframes history loads.
4556 item_for_history_navigation
=
4557 entry
->GetHistoryNodeForFrame(this)->item();
4558 load_type
= blink::WebFrameLoadType::BackForward
;
4559 should_load_request
= true;
4563 // Navigate to the given URL.
4564 if (!start_params
.extra_headers
.empty() && !browser_side_navigation
) {
4565 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
4566 start_params
.extra_headers
.end(),
4569 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
4570 WebString::fromUTF8(i
.values()));
4574 if (start_params
.is_post
&& !browser_side_navigation
) {
4575 request
.setHTTPMethod(WebString::fromUTF8("POST"));
4578 WebHTTPBody http_body
;
4579 http_body
.initialize();
4580 const char* data
= nullptr;
4581 if (start_params
.browser_initiated_post_data
.size()) {
4582 data
= reinterpret_cast<const char*>(
4583 &start_params
.browser_initiated_post_data
.front());
4585 http_body
.appendData(
4586 WebData(data
, start_params
.browser_initiated_post_data
.size()));
4587 request
.setHTTPBody(http_body
);
4590 // A session history navigation should have been accompanied by state.
4591 CHECK_EQ(request_params
.page_id
, -1);
4593 should_load_request
= true;
4596 if (should_load_request
) {
4597 // Record this before starting the load. We need a lower bound of this
4598 // time to sanitize the navigationStart override set below.
4599 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4601 // Perform a navigation to a data url if needed.
4602 if (!common_params
.base_url_for_data_url
.is_empty() ||
4603 (browser_side_navigation
&&
4604 common_params
.url
.SchemeIs(url::kDataScheme
))) {
4605 LoadDataURL(common_params
, frame_
);
4607 // Load the request.
4608 frame_
->toWebLocalFrame()->load(request
, load_type
,
4609 item_for_history_navigation
);
4612 if (load_type
== blink::WebFrameLoadType::Standard
) {
4613 UpdateFrameNavigationTiming(frame_
,
4614 request_params
.browser_navigation_start
,
4615 renderer_navigation_start
);
4619 // In case LoadRequest failed before didCreateDataSource was called.
4620 pending_navigation_params_
.reset();
4623 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4624 const std::string
& encoding_name
) {
4625 // Only update main frame's encoding_name.
4626 if (!frame
->parent())
4627 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4630 void RenderFrameImpl::SyncSelectionIfRequired() {
4631 base::string16 text
;
4634 #if defined(ENABLE_PLUGINS)
4635 if (render_view_
->focused_pepper_plugin_
) {
4636 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4637 offset
= 0; // Pepper API does not support offset reporting.
4638 // TODO(kinaba): cut as needed.
4642 size_t location
, length
;
4643 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4644 &location
, &length
)) {
4648 range
= gfx::Range(location
, location
+ length
);
4650 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4651 blink::WebTextInputTypeNone
) {
4652 // If current focused element is editable, we will send 100 more chars
4653 // before and after selection. It is for input method surrounding text
4655 if (location
> kExtraCharsBeforeAndAfterSelection
)
4656 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4659 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4660 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4661 if (!webrange
.isNull())
4662 text
= webrange
.toPlainText();
4665 text
= frame_
->selectionAsText();
4666 // http://crbug.com/101435
4667 // In some case, frame->selectionAsText() returned text's length is not
4668 // equal to the length returned from webwidget()->caretOrSelectionRange().
4669 // So we have to set the range according to text.length().
4670 range
.set_end(range
.start() + text
.length());
4674 // Sometimes we get repeated didChangeSelection calls from webkit when
4675 // the selection hasn't actually changed. We don't want to report these
4676 // because it will cause us to continually claim the X clipboard.
4677 if (selection_text_offset_
!= offset
||
4678 selection_range_
!= range
||
4679 selection_text_
!= text
) {
4680 selection_text_
= text
;
4681 selection_text_offset_
= offset
;
4682 selection_range_
= range
;
4683 SetSelectedText(text
, offset
, range
);
4685 GetRenderWidget()->UpdateSelectionBounds();
4688 void RenderFrameImpl::InitializeUserMediaClient() {
4689 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4692 #if defined(OS_ANDROID)
4693 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4694 switches::kDisableWebRTC
))
4698 #if defined(ENABLE_WEBRTC)
4699 DCHECK(!web_user_media_client_
);
4700 web_user_media_client_
= new UserMediaClientImpl(
4702 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4703 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4707 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4708 WebMediaPlayerClient
* client
) {
4709 #if defined(ENABLE_WEBRTC)
4710 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4712 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4713 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4714 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4715 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4716 new RenderMediaLog(),
4717 CreateRendererFactory());
4720 #endif // defined(ENABLE_WEBRTC)
4723 scoped_ptr
<MediaStreamRendererFactory
>
4724 RenderFrameImpl::CreateRendererFactory() {
4725 scoped_ptr
<MediaStreamRendererFactory
> factory
=
4726 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4728 return factory
.Pass();
4729 #if defined(ENABLE_WEBRTC)
4730 return scoped_ptr
<MediaStreamRendererFactory
>(
4731 new MediaStreamRendererFactoryImpl());
4733 return scoped_ptr
<MediaStreamRendererFactory
>(
4734 static_cast<MediaStreamRendererFactory
*>(NULL
));
4738 void RenderFrameImpl::PrepareRenderViewForNavigation(
4740 const RequestNavigationParams
& request_params
,
4742 WebURLRequest::CachePolicy
* cache_policy
) {
4743 DCHECK(render_view_
->webview());
4745 MaybeHandleDebugURL(url
);
4748 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4750 render_view_
->history_list_offset_
=
4751 request_params
.current_history_list_offset
;
4752 render_view_
->history_list_length_
=
4753 request_params
.current_history_list_length
;
4754 if (request_params
.should_clear_history_list
) {
4755 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4756 CHECK_EQ(0, render_view_
->history_list_length_
);
4759 if (!is_swapped_out_
|| frame_
->parent())
4762 // This is a swapped out main frame, so swap the renderer back in.
4763 // We marked the view as hidden when swapping the view out, so be sure to
4764 // reset the visibility state before navigating to the new URL.
4765 render_view_
->webview()->setVisibilityState(
4766 render_view_
->visibilityState(), false);
4768 // If this is an attempt to reload while we are swapped out, we should not
4769 // reload swappedout://, but the previous page, which is stored in
4770 // params.state. Setting is_reload to false will treat this like a back
4771 // navigation to accomplish that.
4773 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4775 // We refresh timezone when a view is swapped in since timezone
4776 // can get out of sync when the system timezone is updated while
4777 // the view is swapped out.
4778 RenderThreadImpl::NotifyTimezoneChange();
4780 render_view_
->SetSwappedOut(false);
4781 is_swapped_out_
= false;
4785 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4786 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4787 switches::kEnableBrowserSideNavigation
));
4789 // TODO(clamy): Execute the beforeunload event.
4791 // Note: At this stage, the goal is to apply all the modifications the
4792 // renderer wants to make to the request, and then send it to the browser, so
4793 // that the actual network request can be started. Ideally, all such
4794 // modifications should take place in willSendRequest, and in the
4795 // implementation of willSendRequest for the various InspectorAgents
4798 // TODO(clamy): Apply devtools override.
4799 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4801 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4803 // TODO(clamy): Same-document navigations should not be sent back to the
4805 Send(new FrameHostMsg_BeginNavigation(
4806 routing_id_
, MakeCommonNavigationParams(request
),
4807 BeginNavigationParams(request
->httpMethod().latin1(),
4808 GetWebURLRequestHeaders(*request
),
4809 GetLoadFlagsForWebURLRequest(*request
),
4810 request
->hasUserGesture()),
4811 GetRequestBodyForWebURLRequest(*request
)));
4814 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4816 // A loadData request with a specified base URL.
4817 std::string mime_type
, charset
, data
;
4818 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4819 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4820 params
.url
: params
.base_url_for_data_url
;
4822 WebData(data
.c_str(), data
.length()),
4823 WebString::fromUTF8(mime_type
),
4824 WebString::fromUTF8(charset
),
4826 params
.history_url_for_data_url
,
4829 CHECK(false) << "Invalid URL passed: "
4830 << params
.url
.possibly_invalid_spec();
4834 void RenderFrameImpl::SendFailedProvisionalLoad(
4835 const blink::WebURLRequest
& request
,
4836 const blink::WebURLError
& error
,
4837 blink::WebLocalFrame
* frame
) {
4838 bool show_repost_interstitial
=
4839 (error
.reason
== net::ERR_CACHE_MISS
&&
4840 base::EqualsASCII(request
.httpMethod(), "POST"));
4842 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4843 params
.error_code
= error
.reason
;
4844 GetContentClient()->renderer()->GetNavigationErrorStrings(
4845 render_view_
.get(), frame
, request
, error
, NULL
,
4846 ¶ms
.error_description
);
4847 params
.url
= error
.unreachableURL
;
4848 params
.showing_repost_interstitial
= show_repost_interstitial
;
4849 params
.was_ignored_by_handler
= error
.wasIgnoredByHandler
;
4850 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4853 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4855 const GURL
& unreachable_url
) {
4856 // Don't display an error page if this is simply a cancelled load. Aside
4857 // from being dumb, Blink doesn't expect it and it will cause a crash.
4858 if (error_code
== net::ERR_ABORTED
)
4861 // Don't display "client blocked" error page if browser has asked us not to.
4862 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4863 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4867 // Allow the embedder to suppress an error page.
4868 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4869 this, unreachable_url
)) {
4873 if (RenderThreadImpl::current() &&
4874 RenderThreadImpl::current()->layout_test_mode()) {
4881 GURL
RenderFrameImpl::GetLoadingUrl() const {
4882 WebDataSource
* ds
= frame_
->dataSource();
4883 if (ds
->hasUnreachableURL())
4884 return ds
->unreachableURL();
4886 const WebURLRequest
& request
= ds
->request();
4887 return request
.url();
4890 void RenderFrameImpl::PopulateDocumentStateFromPending(
4891 DocumentState
* document_state
) {
4892 document_state
->set_request_time(
4893 pending_navigation_params_
->request_params
.request_time
);
4895 InternalDocumentStateData
* internal_data
=
4896 InternalDocumentStateData::FromDocumentState(document_state
);
4898 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4899 url::kJavaScriptScheme
) &&
4900 pending_navigation_params_
->common_params
.navigation_type
==
4901 FrameMsg_Navigate_Type::RESTORE
) {
4902 // We're doing a load of a page that was restored from the last session. By
4903 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4904 // can result in stale data for pages that are set to expire. We explicitly
4905 // override that by setting the policy here so that as necessary we load
4906 // from the network.
4908 // TODO(davidben): Remove this in favor of passing a cache policy to the
4909 // loadHistoryItem call in OnNavigate. That requires not overloading
4910 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4911 // policy based on load type, etc".
4912 internal_data
->set_cache_policy_override(
4913 WebURLRequest::UseProtocolCachePolicy
);
4916 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4917 document_state
->set_load_type(DocumentState::RELOAD
);
4918 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4919 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4921 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4923 internal_data
->set_is_overriding_user_agent(
4924 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4925 internal_data
->set_must_reset_scroll_and_scale_state(
4926 pending_navigation_params_
->common_params
.navigation_type
==
4927 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4928 document_state
->set_can_load_local_resources(
4929 pending_navigation_params_
->request_params
.can_load_local_resources
);
4932 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4933 // A navigation resulting from loading a javascript URL should not be treated
4934 // as a browser initiated event. Instead, we want it to look as if the page
4935 // initiated any load resulting from JS execution.
4936 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4937 url::kJavaScriptScheme
)) {
4938 return NavigationStateImpl::CreateBrowserInitiated(
4939 pending_navigation_params_
->common_params
,
4940 pending_navigation_params_
->start_params
,
4941 pending_navigation_params_
->request_params
);
4943 return NavigationStateImpl::CreateContentInitiated();
4946 #if defined(OS_ANDROID)
4948 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4949 WebMediaPlayerClient
* client
,
4950 media::MediaPermission
* media_permission
,
4951 blink::WebContentDecryptionModule
* initial_cdm
) {
4953 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4954 if (SynchronousCompositorFactory
* factory
=
4955 SynchronousCompositorFactory::GetInstance()) {
4956 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4958 GpuChannelHost
* gpu_channel_host
=
4959 RenderThreadImpl::current()->EstablishGpuChannelSync(
4960 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4962 if (!gpu_channel_host
) {
4963 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4967 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4968 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4970 if (!context_provider
.get()) {
4971 LOG(ERROR
) << "Failed to get context3d for media player";
4975 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4976 context_provider
, gpu_channel_host
, routing_id_
);
4979 return new WebMediaPlayerAndroid(
4980 frame_
, client
, weak_factory_
.GetWeakPtr(), GetMediaPlayerManager(),
4981 GetCdmFactory(), media_permission
, initial_cdm
, stream_texture_factory
,
4982 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4983 new RenderMediaLog());
4986 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4987 if (!media_player_manager_
)
4988 media_player_manager_
= new RendererMediaPlayerManager(this);
4989 return media_player_manager_
;
4992 #endif // defined(OS_ANDROID)
4994 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4995 if (!media_permission_dispatcher_
)
4996 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
4997 return media_permission_dispatcher_
;
5000 #if defined(ENABLE_MOJO_MEDIA)
5001 mojo::ServiceProvider
* RenderFrameImpl::GetMediaServiceProvider() {
5002 if (!media_service_provider_
) {
5003 mojo::InterfacePtr
<mojo::Shell
> shell_ptr
;
5004 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr
));
5005 mojo::URLRequestPtr
request(mojo::URLRequest::New());
5006 request
->url
= mojo::String::From("mojo:media");
5007 shell_ptr
->ConnectToApplication(
5008 request
.Pass(), GetProxy(&media_service_provider_
), nullptr);
5009 media_service_provider_
.set_connection_error_handler(
5010 base::Bind(&RenderFrameImpl::OnMediaServiceProviderConnectionError
,
5011 base::Unretained(this)));
5013 return media_service_provider_
.get();
5016 void RenderFrameImpl::OnMediaServiceProviderConnectionError() {
5017 media_service_provider_
.reset();
5021 bool RenderFrameImpl::AreSecureCodecsSupported() {
5022 #if defined(OS_ANDROID)
5023 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5024 return render_view_
->renderer_preferences_
5025 .use_video_overlay_for_embedded_encrypted_video
;
5028 #endif // defined(OS_ANDROID)
5031 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
5032 #if defined(ENABLE_BROWSER_CDMS)
5034 cdm_manager_
= new RendererCdmManager(this);
5035 #endif // defined(ENABLE_BROWSER_CDMS)
5037 if (!cdm_factory_
) {
5040 #if defined(ENABLE_MOJO_MEDIA)
5041 cdm_factory_
.reset(new media::MojoCdmFactory(GetMediaServiceProvider()));
5043 cdm_factory_
.reset(new RenderCdmFactory(
5044 #if defined(ENABLE_PEPPER_CDMS)
5045 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
)
5046 #elif defined(ENABLE_BROWSER_CDMS)
5050 #endif // defined(ENABLE_MOJO_MEDIA)
5053 return cdm_factory_
.get();
5056 void RenderFrameImpl::RegisterMojoServices() {
5057 // Only main frame have ImageDownloader service.
5058 if (!frame_
->parent()) {
5059 GetServiceRegistry()->AddService
<image_downloader::ImageDownloader
>(
5060 base::Bind(&ImageDownloaderImpl::CreateMojoService
,
5061 base::Unretained(this)));
5065 } // namespace content