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/time/time.h"
21 #include "cc/base/switches.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/permissions/permission_dispatcher.h"
24 #include "content/child/plugin_messages.h"
25 #include "content/child/quota_dispatcher.h"
26 #include "content/child/request_extra_data.h"
27 #include "content/child/service_worker/service_worker_handle_reference.h"
28 #include "content/child/service_worker/service_worker_network_provider.h"
29 #include "content/child/service_worker/service_worker_provider_context.h"
30 #include "content/child/service_worker/web_service_worker_provider_impl.h"
31 #include "content/child/v8_value_converter_impl.h"
32 #include "content/child/web_url_loader_impl.h"
33 #include "content/child/web_url_request_util.h"
34 #include "content/child/webmessageportchannel_impl.h"
35 #include "content/child/websocket_bridge.h"
36 #include "content/child/weburlresponse_extradata_impl.h"
37 #include "content/common/clipboard_messages.h"
38 #include "content/common/frame_messages.h"
39 #include "content/common/frame_replication_state.h"
40 #include "content/common/input_messages.h"
41 #include "content/common/navigation_params.h"
42 #include "content/common/service_worker/service_worker_types.h"
43 #include "content/common/swapped_out_messages.h"
44 #include "content/common/view_messages.h"
45 #include "content/public/common/bindings_policy.h"
46 #include "content/public/common/content_constants.h"
47 #include "content/public/common/content_switches.h"
48 #include "content/public/common/context_menu_params.h"
49 #include "content/public/common/page_state.h"
50 #include "content/public/common/resource_response.h"
51 #include "content/public/common/url_constants.h"
52 #include "content/public/common/url_utils.h"
53 #include "content/public/renderer/browser_plugin_delegate.h"
54 #include "content/public/renderer/content_renderer_client.h"
55 #include "content/public/renderer/context_menu_client.h"
56 #include "content/public/renderer/document_state.h"
57 #include "content/public/renderer/navigation_state.h"
58 #include "content/public/renderer/render_frame_observer.h"
59 #include "content/public/renderer/renderer_ppapi_host.h"
60 #include "content/renderer/accessibility/renderer_accessibility.h"
61 #include "content/renderer/browser_plugin/browser_plugin.h"
62 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
63 #include "content/renderer/child_frame_compositing_helper.h"
64 #include "content/renderer/context_menu_params_builder.h"
65 #include "content/renderer/devtools/devtools_agent.h"
66 #include "content/renderer/dom_automation_controller.h"
67 #include "content/renderer/dom_utils.h"
68 #include "content/renderer/external_popup_menu.h"
69 #include "content/renderer/geolocation_dispatcher.h"
70 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
71 #include "content/renderer/history_controller.h"
72 #include "content/renderer/history_serialization.h"
73 #include "content/renderer/image_loading_helper.h"
74 #include "content/renderer/ime_event_guard.h"
75 #include "content/renderer/internal_document_state_data.h"
76 #include "content/renderer/manifest/manifest_manager.h"
77 #include "content/renderer/media/audio_renderer_mixer_manager.h"
78 #include "content/renderer/media/crypto/render_cdm_factory.h"
79 #include "content/renderer/media/media_permission_dispatcher.h"
80 #include "content/renderer/media/media_stream_dispatcher.h"
81 #include "content/renderer/media/media_stream_renderer_factory.h"
82 #include "content/renderer/media/midi_dispatcher.h"
83 #include "content/renderer/media/render_media_log.h"
84 #include "content/renderer/media/user_media_client_impl.h"
85 #include "content/renderer/media/webmediaplayer_ms.h"
86 #include "content/renderer/memory_benchmarking_extension.h"
87 #include "content/renderer/mojo/service_registry_js_wrapper.h"
88 #include "content/renderer/navigation_state_impl.h"
89 #include "content/renderer/notification_permission_dispatcher.h"
90 #include "content/renderer/npapi/plugin_channel_host.h"
91 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
92 #include "content/renderer/presentation/presentation_dispatcher.h"
93 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
94 #include "content/renderer/render_frame_proxy.h"
95 #include "content/renderer/render_process.h"
96 #include "content/renderer/render_thread_impl.h"
97 #include "content/renderer/render_view_impl.h"
98 #include "content/renderer/render_widget_fullscreen_pepper.h"
99 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
100 #include "content/renderer/renderer_webcolorchooser_impl.h"
101 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
102 #include "content/renderer/shared_worker_repository.h"
103 #include "content/renderer/skia_benchmarking_extension.h"
104 #include "content/renderer/stats_collection_controller.h"
105 #include "content/renderer/web_ui_extension.h"
106 #include "content/renderer/websharedworker_proxy.h"
107 #include "gin/modules/module_registry.h"
108 #include "media/base/audio_renderer_mixer_input.h"
109 #include "media/base/media_log.h"
110 #include "media/blink/webencryptedmediaclient_impl.h"
111 #include "media/blink/webmediaplayer_impl.h"
112 #include "media/blink/webmediaplayer_params.h"
113 #include "media/renderers/gpu_video_accelerator_factories.h"
114 #include "net/base/data_url.h"
115 #include "net/base/net_errors.h"
116 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
117 #include "net/http/http_util.h"
118 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
119 #include "third_party/WebKit/public/platform/WebString.h"
120 #include "third_party/WebKit/public/platform/WebURL.h"
121 #include "third_party/WebKit/public/platform/WebURLError.h"
122 #include "third_party/WebKit/public/platform/WebURLResponse.h"
123 #include "third_party/WebKit/public/platform/WebVector.h"
124 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
125 #include "third_party/WebKit/public/web/WebDocument.h"
126 #include "third_party/WebKit/public/web/WebFrameWidget.h"
127 #include "third_party/WebKit/public/web/WebGlyphCache.h"
128 #include "third_party/WebKit/public/web/WebKit.h"
129 #include "third_party/WebKit/public/web/WebLocalFrame.h"
130 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
131 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
132 #include "third_party/WebKit/public/web/WebPlugin.h"
133 #include "third_party/WebKit/public/web/WebPluginParams.h"
134 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
135 #include "third_party/WebKit/public/web/WebRange.h"
136 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
137 #include "third_party/WebKit/public/web/WebScriptSource.h"
138 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
139 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
140 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
141 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
142 #include "third_party/WebKit/public/web/WebSettings.h"
143 #include "third_party/WebKit/public/web/WebSurroundingText.h"
144 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
145 #include "third_party/WebKit/public/web/WebView.h"
146 #include "third_party/mojo/src/mojo/edk/js/core.h"
147 #include "third_party/mojo/src/mojo/edk/js/support.h"
149 #if defined(ENABLE_PLUGINS)
150 #include "content/renderer/npapi/webplugin_impl.h"
151 #include "content/renderer/pepper/pepper_browser_connection.h"
152 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
153 #include "content/renderer/pepper/pepper_webplugin_impl.h"
154 #include "content/renderer/pepper/plugin_module.h"
157 #if defined(ENABLE_WEBRTC)
158 #include "content/renderer/media/rtc_peer_connection_handler.h"
161 #if defined(OS_ANDROID)
162 #include <cpu-features.h>
164 #include "content/common/gpu/client/context_provider_command_buffer.h"
165 #include "content/renderer/android/synchronous_compositor_factory.h"
166 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
167 #include "content/renderer/media/android/renderer_media_player_manager.h"
168 #include "content/renderer/media/android/stream_texture_factory_impl.h"
169 #include "content/renderer/media/android/webmediaplayer_android.h"
171 #include "cc/blink/context_provider_web_context.h"
174 #if defined(ENABLE_PEPPER_CDMS)
175 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
176 #elif defined(ENABLE_BROWSER_CDMS)
177 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
180 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
181 #include "content/renderer/media/media_renderer_service_provider.h"
182 #include "media/mojo/services/mojo_renderer_factory.h"
184 #include "media/renderers/default_renderer_factory.h"
187 using blink::WebContextMenuData
;
188 using blink::WebData
;
189 using blink::WebDataSource
;
190 using blink::WebDocument
;
191 using blink::WebDOMEvent
;
192 using blink::WebDOMMessageEvent
;
193 using blink::WebElement
;
194 using blink::WebExternalPopupMenu
;
195 using blink::WebExternalPopupMenuClient
;
196 using blink::WebFrame
;
197 using blink::WebHistoryItem
;
198 using blink::WebHTTPBody
;
199 using blink::WebLocalFrame
;
200 using blink::WebMediaPlayer
;
201 using blink::WebMediaPlayerClient
;
202 using blink::WebNavigationPolicy
;
203 using blink::WebNavigationType
;
204 using blink::WebNode
;
205 using blink::WebPluginParams
;
206 using blink::WebPopupMenuInfo
;
207 using blink::WebRange
;
208 using blink::WebReferrerPolicy
;
209 using blink::WebScriptSource
;
210 using blink::WebSearchableFormData
;
211 using blink::WebSecurityOrigin
;
212 using blink::WebSecurityPolicy
;
213 using blink::WebSerializedScriptValue
;
214 using blink::WebServiceWorkerProvider
;
215 using blink::WebStorageQuotaCallbacks
;
216 using blink::WebString
;
218 using blink::WebURLError
;
219 using blink::WebURLRequest
;
220 using blink::WebURLResponse
;
221 using blink::WebUserGestureIndicator
;
222 using blink::WebVector
;
223 using blink::WebView
;
225 using base::TimeDelta
;
231 const char kDefaultAcceptHeader
[] =
232 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
234 const char kAcceptHeader
[] = "Accept";
236 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
238 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
239 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
240 LAZY_INSTANCE_INITIALIZER
;
242 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
243 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
245 int64
ExtractPostId(HistoryEntry
* entry
) {
249 const WebHistoryItem
& item
= entry
->root();
250 if (item
.isNull() || item
.httpBody().isNull())
253 return item
.httpBody().identifier();
256 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
257 const WebURLResponse
& response
) {
258 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
261 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
262 // Replace any occurrences of swappedout:// with about:blank.
263 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
264 WebVector
<WebURL
> urls
;
265 ds
->redirectChain(urls
);
266 result
->reserve(urls
.size());
267 for (size_t i
= 0; i
< urls
.size(); ++i
) {
268 if (urls
[i
] != GURL(kSwappedOutURL
))
269 result
->push_back(urls
[i
]);
271 result
->push_back(blank_url
);
275 // Returns the original request url. If there is no redirect, the original
276 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
277 // frame was loaded by loadData, the original url will be ds->unreachableURL()
278 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
279 // WebDataSource has unreachable URL means that the frame is loaded through
280 // blink::WebFrame::loadData(), and the base URL will be in the redirect
281 // chain. However, we never visited the baseURL. So in this case, we should
282 // use the unreachable URL as the original URL.
283 if (ds
->hasUnreachableURL())
284 return ds
->unreachableURL();
286 std::vector
<GURL
> redirects
;
287 GetRedirectChain(ds
, &redirects
);
288 if (!redirects
.empty())
289 return redirects
.at(0);
291 return ds
->originalRequest().url();
294 NOINLINE
void CrashIntentionally() {
295 // NOTE(shess): Crash directly rather than using NOTREACHED() so
296 // that the signature is easier to triage in crash reports.
297 volatile int* zero
= NULL
;
301 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
302 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
303 // NOTE(rogerm): We intentionally perform an invalid heap access here in
304 // order to trigger an Address Sanitizer (ASAN) error report.
305 const char kCrashDomain
[] = "crash";
306 const char kHeapOverflow
[] = "/heap-overflow";
307 const char kHeapUnderflow
[] = "/heap-underflow";
308 const char kUseAfterFree
[] = "/use-after-free";
309 #if defined(SYZYASAN)
310 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
311 const char kCorruptHeap
[] = "/corrupt-heap";
314 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
320 std::string
crash_type(url
.path());
321 if (crash_type
== kHeapOverflow
) {
322 base::debug::AsanHeapOverflow();
323 } else if (crash_type
== kHeapUnderflow
) {
324 base::debug::AsanHeapUnderflow();
325 } else if (crash_type
== kUseAfterFree
) {
326 base::debug::AsanHeapUseAfterFree();
327 #if defined(SYZYASAN)
328 } else if (crash_type
== kCorruptHeapBlock
) {
329 base::debug::AsanCorruptHeapBlock();
330 } else if (crash_type
== kCorruptHeap
) {
331 base::debug::AsanCorruptHeap();
335 #endif // ADDRESS_SANITIZER || SYZYASAN
337 void MaybeHandleDebugURL(const GURL
& url
) {
338 if (!url
.SchemeIs(kChromeUIScheme
))
340 if (url
== GURL(kChromeUICrashURL
)) {
341 CrashIntentionally();
342 } else if (url
== GURL(kChromeUIDumpURL
)) {
343 // This URL will only correctly create a crash dump file if content is
344 // hosted in a process that has correctly called
345 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
346 // of base::debug::DumpWithoutCrashing for more details.
347 base::debug::DumpWithoutCrashing();
348 } else if (url
== GURL(kChromeUIKillURL
)) {
349 base::Process::Current().Terminate(1, false);
350 } else if (url
== GURL(kChromeUIHangURL
)) {
352 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
354 } else if (url
== GURL(kChromeUIShorthangURL
)) {
355 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
358 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
359 MaybeTriggerAsanError(url
);
360 #endif // ADDRESS_SANITIZER || SYZYASAN
363 // Returns false unless this is a top-level navigation.
364 bool IsTopLevelNavigation(WebFrame
* frame
) {
365 return frame
->parent() == NULL
;
368 // Returns false unless this is a top-level navigation that crosses origins.
369 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
371 WebNavigationType type
,
373 if (!IsTopLevelNavigation(frame
))
376 // Navigations initiated within Webkit are not sent out to the external host
377 // in the following cases.
378 // 1. The url scheme is not http/https
379 // 2. The origin of the url and the opener is the same in which case the
380 // opener relationship is maintained.
381 // 3. Reloads/form submits/back forward navigations
382 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
385 if (type
!= blink::WebNavigationTypeReload
&&
386 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
387 // The opener relationship between the new window and the parent allows the
388 // new window to script the parent and vice versa. This is not allowed if
389 // the origins of the two domains are different. This can be treated as a
390 // top level navigation and routed back to the host.
391 blink::WebFrame
* opener
= frame
->opener();
395 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
401 WebURLRequest
CreateURLRequestForNavigation(
402 const CommonNavigationParams
& common_params
,
403 scoped_ptr
<StreamOverrideParameters
> stream_override
,
404 bool is_view_source_mode_enabled
) {
405 WebURLRequest
request(common_params
.url
);
406 if (is_view_source_mode_enabled
)
407 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
409 if (common_params
.referrer
.url
.is_valid()) {
410 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
411 common_params
.referrer
.policy
,
413 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
414 if (!web_referrer
.isEmpty())
415 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
418 RequestExtraData
* extra_data
= new RequestExtraData();
419 extra_data
->set_stream_override(stream_override
.Pass());
420 request
.setExtraData(extra_data
);
422 // Set the ui timestamp for this navigation. Currently the timestamp here is
423 // only non empty when the navigation was triggered by an Android intent. The
424 // timestamp is converted to a double version supported by blink. It will be
425 // passed back to the browser in the DidCommitProvisionalLoad and the
426 // DocumentLoadComplete IPCs.
427 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
428 request
.setUiStartTime(ui_timestamp
.InSecondsF());
429 request
.setInputPerfMetricReportPolicy(
430 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
431 common_params
.report_type
));
435 void UpdateFrameNavigationTiming(WebFrame
* frame
,
436 base::TimeTicks browser_navigation_start
,
437 base::TimeTicks renderer_navigation_start
) {
438 // The browser provides the navigation_start time to bootstrap the
439 // Navigation Timing information for the browser-initiated navigations. In
440 // case of cross-process navigations, this carries over the time of
441 // finishing the onbeforeunload handler of the previous page.
442 DCHECK(!browser_navigation_start
.is_null());
443 if (frame
->provisionalDataSource()) {
444 // |browser_navigation_start| is likely before this process existed, so we
445 // can't use InterProcessTimeTicksConverter. We need at least to ensure
446 // that the browser-side navigation start we set is not later than the one
447 // on the renderer side.
448 base::TimeTicks navigation_start
= std::min(
449 browser_navigation_start
, renderer_navigation_start
);
450 double navigation_start_seconds
=
451 (navigation_start
- base::TimeTicks()).InSecondsF();
452 frame
->provisionalDataSource()->setNavigationStartTime(
453 navigation_start_seconds
);
454 // TODO(clamy): We need to provide additional timing values for the
455 // Navigation Timing API to work with browser-side navigations.
460 CommonNavigationParams
MakeCommonNavigationParams(
461 blink::WebURLRequest
* request
) {
462 const RequestExtraData kEmptyData
;
463 const RequestExtraData
* extra_data
=
464 static_cast<RequestExtraData
*>(request
->extraData());
466 extra_data
= &kEmptyData
;
468 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
469 request
->referrerPolicy());
471 // Set the ui timestamp for this navigation. Currently the timestamp here is
472 // only non empty when the navigation was triggered by an Android intent, or
473 // by the user clicking on a link. The timestamp is converted from a double
474 // version supported by blink. It will be passed back to the renderer in the
475 // CommitNavigation IPC, and then back to the browser again in the
476 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
477 base::TimeTicks ui_timestamp
=
478 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
479 FrameMsg_UILoadMetricsReportType::Value report_type
=
480 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
481 request
->inputPerfMetricReportPolicy());
482 return CommonNavigationParams(request
->url(), referrer
,
483 extra_data
->transition_type(),
484 FrameMsg_Navigate_Type::NORMAL
, true,
485 ui_timestamp
, report_type
, GURL(), GURL());
488 #if !defined(OS_ANDROID)
489 media::Context3D
GetSharedMainThreadContext3D() {
490 cc::ContextProvider
* provider
=
491 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
493 return media::Context3D();
494 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
498 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
499 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
500 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
501 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
504 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
507 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
509 static_cast<int>(content_name) == static_cast<int>(blink_name), \
510 "enum values must match")
512 // Check that blink::WebSandboxFlags is kept in sync with
513 // content::SandboxFlags.
514 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE
,
515 blink::WebSandboxFlags::None
);
516 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION
,
517 blink::WebSandboxFlags::Navigation
);
518 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS
,
519 blink::WebSandboxFlags::Plugins
);
520 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN
,
521 blink::WebSandboxFlags::Origin
);
522 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS
,
523 blink::WebSandboxFlags::Forms
);
524 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS
,
525 blink::WebSandboxFlags::Scripts
);
526 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION
,
527 blink::WebSandboxFlags::TopNavigation
);
528 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS
,
529 blink::WebSandboxFlags::Popups
);
530 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES
,
531 blink::WebSandboxFlags::AutomaticFeatures
);
532 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK
,
533 blink::WebSandboxFlags::PointerLock
);
534 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN
,
535 blink::WebSandboxFlags::DocumentDomain
);
536 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK
,
537 blink::WebSandboxFlags::OrientationLock
);
538 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL
,
539 blink::WebSandboxFlags::All
);
544 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
546 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
548 if (g_create_render_frame_impl
)
549 return g_create_render_frame_impl(render_view
, routing_id
);
551 return new RenderFrameImpl(render_view
, routing_id
);
555 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int32 routing_id
) {
556 RoutingIDFrameMap::iterator iter
=
557 g_routing_id_frame_map
.Get().find(routing_id
);
558 if (iter
!= g_routing_id_frame_map
.Get().end())
564 void RenderFrameImpl::CreateFrame(
566 int parent_routing_id
,
567 int proxy_routing_id
,
568 const FrameReplicationState
& replicated_state
,
569 CompositorDependencies
* compositor_deps
,
570 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
571 // TODO(nasko): For now, this message is only sent for subframes, as the
572 // top level frame is created when the RenderView is created through the
574 CHECK_NE(MSG_ROUTING_NONE
, parent_routing_id
);
576 blink::WebLocalFrame
* web_frame
;
577 RenderFrameImpl
* render_frame
;
578 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
579 RenderFrameProxy
* parent_proxy
=
580 RenderFrameProxy::FromRoutingID(parent_routing_id
);
581 // If the browser is sending a valid parent routing id, it should already
582 // be created and registered.
584 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
586 // Create the RenderFrame and WebLocalFrame, linking the two.
588 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
589 web_frame
= parent_web_frame
->createLocalChild(
590 WebString::fromUTF8(replicated_state
.name
),
591 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
), render_frame
);
593 RenderFrameProxy
* proxy
=
594 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
596 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
597 web_frame
= blink::WebLocalFrame::create(render_frame
);
598 render_frame
->proxy_routing_id_
= proxy_routing_id
;
599 web_frame
->initializeToReplaceRemoteFrame(
600 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
601 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
));
603 render_frame
->SetWebFrame(web_frame
);
605 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
606 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
607 switches::kSitePerProcess
));
608 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
609 widget_params
.routing_id
, widget_params
.surface_id
,
610 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
611 compositor_deps
, web_frame
);
612 // TODO(kenrb): Observing shouldn't be necessary when we sort out
613 // WasShown and WasHidden, separating page-level visibility from
614 // frame-level visibility.
615 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
618 render_frame
->Initialize();
622 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
623 return RenderFrameImpl::FromWebFrame(web_frame
);
627 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
628 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
629 if (iter
!= g_frame_map
.Get().end())
635 void RenderFrameImpl::InstallCreateHook(
636 CreateRenderFrameImplFunction create_render_frame_impl
) {
637 CHECK(!g_create_render_frame_impl
);
638 g_create_render_frame_impl
= create_render_frame_impl
;
642 content::SandboxFlags
RenderFrameImpl::WebToContentSandboxFlags(
643 blink::WebSandboxFlags flags
) {
644 return static_cast<content::SandboxFlags
>(flags
);
648 blink::WebSandboxFlags
RenderFrameImpl::ContentToWebSandboxFlags(
649 content::SandboxFlags flags
) {
650 return static_cast<blink::WebSandboxFlags
>(flags
);
653 // RenderFrameImpl ----------------------------------------------------------
654 RenderFrameImpl::RenderFrameImpl(RenderViewImpl
* render_view
, int routing_id
)
656 is_local_root_(false),
657 render_view_(render_view
->AsWeakPtr()),
658 routing_id_(routing_id
),
659 is_swapped_out_(false),
660 render_frame_proxy_(NULL
),
661 is_detaching_(false),
662 proxy_routing_id_(MSG_ROUTING_NONE
),
663 #if defined(ENABLE_PLUGINS)
664 plugin_power_saver_helper_(NULL
),
667 selection_text_offset_(0),
668 selection_range_(gfx::Range::InvalidRange()),
669 handling_select_range_(false),
670 notification_permission_dispatcher_(NULL
),
671 web_user_media_client_(NULL
),
672 media_permission_dispatcher_(NULL
),
673 midi_dispatcher_(NULL
),
674 #if defined(OS_ANDROID)
675 media_player_manager_(NULL
),
677 #if defined(ENABLE_BROWSER_CDMS)
681 #if defined(VIDEO_HOLE)
682 contains_media_player_(false),
684 devtools_agent_(nullptr),
685 geolocation_dispatcher_(NULL
),
686 push_messaging_dispatcher_(NULL
),
687 presentation_dispatcher_(NULL
),
688 screen_orientation_dispatcher_(NULL
),
689 manifest_manager_(NULL
),
690 accessibility_mode_(AccessibilityModeOff
),
691 renderer_accessibility_(NULL
),
692 weak_factory_(this) {
693 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
694 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
695 CHECK(result
.second
) << "Inserting a duplicate item.";
697 RenderThread::Get()->AddRoute(routing_id_
, this);
699 render_view_
->RegisterRenderFrame(this);
701 // Everything below subclasses RenderFrameObserver and is automatically
702 // deleted when the RenderFrame gets deleted.
703 #if defined(OS_ANDROID)
704 new GinJavaBridgeDispatcher(this);
707 #if defined(ENABLE_PLUGINS)
708 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
711 manifest_manager_
= new ManifestManager(this);
714 RenderFrameImpl::~RenderFrameImpl() {
715 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
716 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
718 #if defined(VIDEO_HOLE)
719 if (contains_media_player_
)
720 render_view_
->UnregisterVideoHoleFrame(this);
723 if (render_frame_proxy_
)
724 delete render_frame_proxy_
;
726 render_view_
->UnregisterRenderFrame(this);
727 g_routing_id_frame_map
.Get().erase(routing_id_
);
728 RenderThread::Get()->RemoveRoute(routing_id_
);
731 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
734 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
735 std::make_pair(web_frame
, this));
736 CHECK(result
.second
) << "Inserting a duplicate item.";
741 void RenderFrameImpl::Initialize() {
742 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
744 #if defined(ENABLE_PLUGINS)
745 new PepperBrowserConnection(this);
747 new SharedWorkerRepository(this);
749 if (!frame_
->parent())
750 new ImageLoadingHelper(this);
752 if (is_local_root_
&& !render_frame_proxy_
) {
753 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
754 // when |this| is deleted.
755 devtools_agent_
= new DevToolsAgent(this);
758 // We delay calling this until we have the WebFrame so that any observer or
759 // embedder can call GetWebFrame on any RenderFrame.
760 GetContentClient()->renderer()->RenderFrameCreated(this);
763 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
764 return render_view_
.get();
767 #if defined(ENABLE_PLUGINS)
768 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
769 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
770 DidCreatePepperPlugin(host
));
771 if (host
->GetPluginName() == kFlashPluginName
) {
772 RenderThread::Get()->RecordAction(
773 base::UserMetricsAction("FrameLoadWithFlash"));
777 void RenderFrameImpl::PepperDidChangeCursor(
778 PepperPluginInstanceImpl
* instance
,
779 const blink::WebCursorInfo
& cursor
) {
780 // Update the cursor appearance immediately if the requesting plugin is the
781 // one which receives the last mouse event. Otherwise, the new cursor won't be
782 // picked up until the plugin gets the next input event. That is bad if, e.g.,
783 // the plugin would like to set an invisible cursor when there isn't any user
784 // input for a while.
785 if (instance
== render_view_
->pepper_last_mouse_event_target())
786 GetRenderWidget()->didChangeCursor(cursor
);
789 void RenderFrameImpl::PepperDidReceiveMouseEvent(
790 PepperPluginInstanceImpl
* instance
) {
791 render_view_
->set_pepper_last_mouse_event_target(instance
);
794 void RenderFrameImpl::PepperTextInputTypeChanged(
795 PepperPluginInstanceImpl
* instance
) {
796 if (instance
!= render_view_
->focused_pepper_plugin())
799 GetRenderWidget()->UpdateTextInputType();
801 FocusedNodeChangedForAccessibility(WebNode());
804 void RenderFrameImpl::PepperCaretPositionChanged(
805 PepperPluginInstanceImpl
* instance
) {
806 if (instance
!= render_view_
->focused_pepper_plugin())
808 GetRenderWidget()->UpdateSelectionBounds();
811 void RenderFrameImpl::PepperCancelComposition(
812 PepperPluginInstanceImpl
* instance
) {
813 if (instance
!= render_view_
->focused_pepper_plugin())
815 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
816 #if defined(OS_MACOSX) || defined(USE_AURA)
817 GetRenderWidget()->UpdateCompositionInfo(true);
821 void RenderFrameImpl::PepperSelectionChanged(
822 PepperPluginInstanceImpl
* instance
) {
823 if (instance
!= render_view_
->focused_pepper_plugin())
825 SyncSelectionIfRequired();
828 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
829 PepperPluginInstanceImpl
* plugin
) {
831 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
832 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
833 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
834 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
835 plugin
, active_url
, GetRenderWidget()->screenInfo());
836 widget
->show(blink::WebNavigationPolicyIgnore
);
840 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
841 if (!render_view_
->focused_pepper_plugin())
843 return render_view_
->focused_pepper_plugin()->
844 IsPluginAcceptingCompositionEvents();
847 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
848 base::ProcessId plugin_pid
) {
849 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
850 // routing_id_ as a result.
851 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
854 void RenderFrameImpl::SimulateImeSetComposition(
855 const base::string16
& text
,
856 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
859 render_view_
->OnImeSetComposition(
860 text
, underlines
, selection_start
, selection_end
);
863 void RenderFrameImpl::SimulateImeConfirmComposition(
864 const base::string16
& text
,
865 const gfx::Range
& replacement_range
) {
866 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
869 void RenderFrameImpl::OnImeSetComposition(
870 const base::string16
& text
,
871 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
874 // When a PPAPI plugin has focus, we bypass WebKit.
875 if (!IsPepperAcceptingCompositionEvents()) {
876 pepper_composition_text_
= text
;
878 // TODO(kinaba) currently all composition events are sent directly to
879 // plugins. Use DOM event mechanism after WebKit is made aware about
880 // plugins that support composition.
881 // The code below mimics the behavior of WebCore::Editor::setComposition.
883 // Empty -> nonempty: composition started.
884 if (pepper_composition_text_
.empty() && !text
.empty()) {
885 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
888 // Nonempty -> empty: composition canceled.
889 if (!pepper_composition_text_
.empty() && text
.empty()) {
890 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
893 pepper_composition_text_
= text
;
894 // Nonempty: composition is ongoing.
895 if (!pepper_composition_text_
.empty()) {
896 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
897 pepper_composition_text_
, underlines
, selection_start
,
903 void RenderFrameImpl::OnImeConfirmComposition(
904 const base::string16
& text
,
905 const gfx::Range
& replacement_range
,
906 bool keep_selection
) {
907 // When a PPAPI plugin has focus, we bypass WebKit.
908 // Here, text.empty() has a special meaning. It means to commit the last
909 // update of composition text (see
910 // RenderWidgetHost::ImeConfirmComposition()).
911 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
914 // last_text is empty only when both text and pepper_composition_text_ is.
916 if (last_text
.empty())
919 if (!IsPepperAcceptingCompositionEvents()) {
920 base::i18n::UTF16CharIterator
iterator(&last_text
);
922 while (iterator
.Advance()) {
923 blink::WebKeyboardEvent char_event
;
924 char_event
.type
= blink::WebInputEvent::Char
;
925 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
926 char_event
.modifiers
= 0;
927 char_event
.windowsKeyCode
= last_text
[i
];
928 char_event
.nativeKeyCode
= last_text
[i
];
930 const int32 char_start
= i
;
931 for (; i
< iterator
.array_pos(); ++i
) {
932 char_event
.text
[i
- char_start
] = last_text
[i
];
933 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
936 if (GetRenderWidget()->webwidget())
937 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
940 // Mimics the order of events sent by WebKit.
941 // See WebCore::Editor::setComposition() for the corresponding code.
942 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
943 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
945 pepper_composition_text_
.clear();
947 #endif // defined(ENABLE_PLUGINS)
949 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
950 if (!web_user_media_client_
)
951 InitializeUserMediaClient();
952 return web_user_media_client_
?
953 web_user_media_client_
->media_stream_dispatcher() : NULL
;
956 bool RenderFrameImpl::Send(IPC::Message
* message
) {
961 if (is_swapped_out_
) {
962 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
968 return RenderThread::Get()->Send(message
);
971 #if defined(OS_MACOSX) || defined(OS_ANDROID)
972 void RenderFrameImpl::DidHideExternalPopupMenu() {
973 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
974 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
975 external_popup_menu_
.reset();
979 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
980 // We may get here while detaching, when the WebFrame has been deleted. Do
981 // not process any messages in this state.
985 // TODO(kenrb): document() should not be null, but as a transitional step
986 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
987 // to this method. This happens for a top-level remote frame, where a
988 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
989 // around and is still able to receive messages.
990 if (!frame_
->document().isNull())
991 GetContentClient()->SetActiveURL(frame_
->document().url());
993 ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
994 RenderFrameObserver
* observer
;
995 while ((observer
= it
.GetNext()) != NULL
) {
996 if (observer
->OnMessageReceived(msg
))
1000 bool handled
= true;
1001 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1002 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1003 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1004 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1005 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1006 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1007 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1008 OnCustomContextMenuAction
)
1009 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1010 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1011 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1012 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1013 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1014 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1015 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1016 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1017 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1018 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1019 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1020 OnMoveRangeSelectionExtent
)
1021 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1022 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1023 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1024 OnExtendSelectionAndDelete
)
1025 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1026 OnSetCompositionFromExistingText
)
1027 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1028 OnExecuteNoValueEditCommand
)
1029 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1030 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1031 OnJavaScriptExecuteRequest
)
1032 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1033 OnJavaScriptExecuteRequestForTests
)
1034 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1035 OnVisualStateRequest
)
1036 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1037 OnSetEditableSelectionOffsets
)
1038 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView
, OnSetupTransitionView
)
1039 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition
, OnBeginExitTransition
)
1040 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition
, OnRevertExitTransition
)
1041 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements
,
1042 OnHideTransitionElements
)
1043 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements
,
1044 OnShowTransitionElements
)
1045 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1046 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1047 OnTextSurroundingSelectionRequest
)
1048 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL
,
1049 OnAddStyleSheetByURL
)
1050 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1051 OnSetAccessibilityMode
)
1052 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1053 OnSnapshotAccessibilityTree
)
1054 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1055 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1056 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1057 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1058 OnTextTrackSettingsChanged
)
1059 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1060 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1061 #if defined(OS_ANDROID)
1062 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1063 #elif defined(OS_MACOSX)
1064 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1065 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1067 IPC_END_MESSAGE_MAP()
1072 void RenderFrameImpl::OnNavigate(
1073 const CommonNavigationParams
& common_params
,
1074 const StartNavigationParams
& start_params
,
1075 const RequestNavigationParams
& request_params
) {
1076 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1077 switches::kEnableBrowserSideNavigation
));
1078 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1079 "url", common_params
.url
.possibly_invalid_spec());
1081 bool is_reload
= IsReload(common_params
.navigation_type
);
1082 bool is_history_navigation
= request_params
.page_state
.IsValid();
1083 WebURLRequest::CachePolicy cache_policy
=
1084 WebURLRequest::UseProtocolCachePolicy
;
1085 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1086 common_params
.url
, is_history_navigation
, request_params
, &is_reload
,
1088 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
1092 GetContentClient()->SetActiveURL(common_params
.url
);
1094 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
1095 // We cannot reload if we do not have any history state. This happens, for
1096 // example, when recovering from a crash.
1098 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1101 pending_navigation_params_
.reset(
1102 new NavigationParams(common_params
, start_params
, request_params
));
1104 // If we are reloading, then WebKit will use the history state of the current
1105 // page, so we should just ignore any given history state. Otherwise, if we
1106 // have history state, then we need to navigate to it, which corresponds to a
1107 // back/forward navigation event.
1109 bool reload_original_url
=
1110 (common_params
.navigation_type
==
1111 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1112 bool ignore_cache
= (common_params
.navigation_type
==
1113 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1115 if (reload_original_url
)
1116 frame_
->reloadWithOverrideURL(common_params
.url
, true);
1118 frame_
->reload(ignore_cache
);
1119 } else if (is_history_navigation
) {
1120 // We must know the page ID of the page we are navigating back to.
1121 DCHECK_NE(request_params
.page_id
, -1);
1122 // We must know the nav entry ID of the page we are navigating back to,
1123 // which should be the case because history navigations are routed via the
1125 DCHECK_NE(0, request_params
.nav_entry_id
);
1126 scoped_ptr
<HistoryEntry
> entry
=
1127 PageStateToHistoryEntry(request_params
.page_state
);
1129 // Ensure we didn't save the swapped out URL in UpdateState, since the
1130 // browser should never be telling us to navigate to swappedout://.
1131 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
1132 scoped_ptr
<NavigationParams
> navigation_params(
1133 new NavigationParams(*pending_navigation_params_
.get()));
1134 render_view_
->history_controller()->GoToEntry(
1135 entry
.Pass(), navigation_params
.Pass(), cache_policy
);
1137 } else if (!common_params
.base_url_for_data_url
.is_empty()) {
1138 LoadDataURL(common_params
, frame_
);
1140 // Navigate to the given URL.
1141 WebURLRequest request
= CreateURLRequestForNavigation(
1142 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
1143 frame_
->isViewSourceModeEnabled());
1145 if (!start_params
.extra_headers
.empty()) {
1146 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
1147 start_params
.extra_headers
.end(),
1150 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
1151 WebString::fromUTF8(i
.values()));
1155 if (start_params
.is_post
) {
1156 request
.setHTTPMethod(WebString::fromUTF8("POST"));
1159 WebHTTPBody http_body
;
1160 http_body
.initialize();
1161 const char* data
= NULL
;
1162 if (start_params
.browser_initiated_post_data
.size()) {
1163 data
= reinterpret_cast<const char*>(
1164 &start_params
.browser_initiated_post_data
.front());
1166 http_body
.appendData(
1167 WebData(data
, start_params
.browser_initiated_post_data
.size()));
1168 request
.setHTTPBody(http_body
);
1171 // A session history navigation should have been accompanied by state.
1172 CHECK_EQ(request_params
.page_id
, -1);
1174 // Record this before starting the load, we need a lower bound of this time
1175 // to sanitize the navigationStart override set below.
1176 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
1177 frame_
->loadRequest(request
);
1179 UpdateFrameNavigationTiming(frame_
, request_params
.browser_navigation_start
,
1180 renderer_navigation_start
);
1183 // In case LoadRequest failed before didCreateDataSource was called.
1184 pending_navigation_params_
.reset();
1187 void RenderFrameImpl::NavigateToSwappedOutURL() {
1188 // We use loadRequest instead of loadHTMLString because the former commits
1189 // synchronously. Otherwise a new navigation can interrupt the navigation
1190 // to kSwappedOutURL. If that happens to be to the page we had been
1191 // showing, then WebKit will never send a commit and we'll be left spinning.
1192 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1193 // the navigation to swappedout:// is not announced to the browser side.
1194 is_swapped_out_
= true;
1195 GURL
swappedOutURL(kSwappedOutURL
);
1196 WebURLRequest
request(swappedOutURL
);
1197 frame_
->loadRequest(request
);
1200 void RenderFrameImpl::BindServiceRegistry(
1201 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1202 mojo::ServiceProviderPtr exposed_services
) {
1203 service_registry_
.Bind(services
.Pass());
1204 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1207 ManifestManager
* RenderFrameImpl::manifest_manager() {
1208 return manifest_manager_
;
1211 void RenderFrameImpl::SetPendingNavigationParams(
1212 scoped_ptr
<NavigationParams
> navigation_params
) {
1213 pending_navigation_params_
= navigation_params
.Pass();
1216 void RenderFrameImpl::OnBeforeUnload() {
1217 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1219 // TODO(creis): Right now, this is only called on the main frame. Make the
1220 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1222 CHECK(!frame_
->parent());
1224 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1225 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1226 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1227 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1228 before_unload_start_time
,
1229 before_unload_end_time
));
1232 void RenderFrameImpl::OnSwapOut(
1233 int proxy_routing_id
,
1235 const FrameReplicationState
& replicated_frame_state
) {
1236 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1237 RenderFrameProxy
* proxy
= NULL
;
1238 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1239 switches::kSitePerProcess
);
1240 bool is_main_frame
= !frame_
->parent();
1242 // Only run unload if we're not swapped out yet, but send the ack either way.
1243 if (!is_swapped_out_
) {
1244 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1245 // a different process. This involves running the unload handler and
1246 // clearing the page. We also allow this process to exit if there are no
1247 // other active RenderFrames in it.
1249 // Send an UpdateState message before we get swapped out.
1250 render_view_
->SyncNavigationState();
1252 // If we need a proxy to replace this, create it now so its routing id is
1253 // registered for receiving IPC messages.
1254 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1255 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(this,
1259 // Synchronously run the unload handler before sending the ACK.
1260 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1261 // unload on subframes as well.
1263 frame_
->dispatchUnloadEvent();
1265 // Swap out and stop sending any IPC messages that are not ACKs.
1267 render_view_
->SetSwappedOut(true);
1268 is_swapped_out_
= true;
1270 // Set the proxy here, since OnStop() below could cause an onload event
1271 // handler to execute, which could trigger code such as
1272 // willCheckAndDispatchMessageEvent() that needs the proxy.
1274 set_render_frame_proxy(proxy
);
1276 // Now that we're swapped out and filtering IPC messages, stop loading to
1277 // ensure that no other in-progress navigation continues. We do this here
1278 // to avoid sending a DidStopLoading message to the browser process.
1279 // TODO(creis): Should we be stopping all frames here and using
1280 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1284 // Transfer settings such as initial drawing parameters to the remote frame,
1285 // if one is created, that will replace this frame.
1286 if (!is_main_frame
&& proxy
)
1287 proxy
->web_frame()->initializeFromFrame(frame_
);
1289 // Replace the page with a blank dummy URL. The unload handler will not be
1290 // run a second time, thanks to a check in FrameLoader::stopLoading.
1291 // TODO(creis): Need to add a better way to do this that avoids running the
1292 // beforeunload handler. For now, we just run it a second time silently.
1293 if (!is_site_per_process
|| is_main_frame
)
1294 NavigateToSwappedOutURL();
1296 // Let WebKit know that this view is hidden so it can drop resources and
1297 // stop compositing.
1298 // TODO(creis): Support this for subframes as well.
1299 if (is_main_frame
) {
1300 render_view_
->webview()->setVisibilityState(
1301 blink::WebPageVisibilityStateHidden
, false);
1305 // It is now safe to show modal dialogs again.
1306 // TODO(creis): Deal with modal dialogs from subframes.
1308 render_view_
->suppress_dialogs_until_swap_out_
= false;
1310 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1312 // Now that all of the cleanup is complete and the browser side is notified,
1313 // start using the RenderFrameProxy, if one is created.
1315 if (!is_main_frame
) {
1316 frame_
->swap(proxy
->web_frame());
1319 proxy
->OnDidStartLoading();
1321 if (is_site_per_process
) {
1322 // TODO(nasko): delete the frame here, since we've replaced it with a
1328 // In --site-per-process, initialize the WebRemoteFrame with the replication
1329 // state passed by the process that is now rendering the frame.
1330 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1331 // in that case we leave the LocalFrame as the main frame visible to Blink
1332 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1333 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1334 // When we do an unconditional swap for all frames, we can remove
1335 // !is_main_frame below.
1336 if (is_site_per_process
&& proxy
&& !is_main_frame
)
1337 proxy
->SetReplicatedState(replicated_frame_state
);
1339 // Safe to exit if no one else is using the process.
1341 render_view_
->WasSwappedOut();
1344 void RenderFrameImpl::OnContextMenuClosed(
1345 const CustomContextMenuContext
& custom_context
) {
1346 if (custom_context
.request_id
) {
1347 // External request, should be in our map.
1348 ContextMenuClient
* client
=
1349 pending_context_menus_
.Lookup(custom_context
.request_id
);
1351 client
->OnMenuClosed(custom_context
.request_id
);
1352 pending_context_menus_
.Remove(custom_context
.request_id
);
1355 if (custom_context
.link_followed
.is_valid()) {
1357 DomUtils::ExtractParentAnchorNode(context_menu_node_
),
1358 custom_context
.link_followed
);
1360 // Internal request, forward to WebKit.
1361 context_menu_node_
.reset();
1365 void RenderFrameImpl::OnCustomContextMenuAction(
1366 const CustomContextMenuContext
& custom_context
,
1368 if (custom_context
.request_id
) {
1369 // External context menu request, look in our map.
1370 ContextMenuClient
* client
=
1371 pending_context_menus_
.Lookup(custom_context
.request_id
);
1373 client
->OnMenuAction(custom_context
.request_id
, action
);
1375 // Internal request, forward to WebKit.
1376 render_view_
->webview()->performCustomContextMenuAction(action
);
1380 void RenderFrameImpl::OnUndo() {
1381 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1384 void RenderFrameImpl::OnRedo() {
1385 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1388 void RenderFrameImpl::OnCut() {
1389 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1390 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1393 void RenderFrameImpl::OnCopy() {
1394 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1395 WebNode current_node
= context_menu_node_
.isNull() ?
1396 GetFocusedElement() : context_menu_node_
;
1397 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1400 void RenderFrameImpl::OnPaste() {
1401 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1402 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1405 void RenderFrameImpl::OnPasteAndMatchStyle() {
1406 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1407 frame_
->executeCommand(
1408 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1411 #if defined(OS_MACOSX)
1412 void RenderFrameImpl::OnCopyToFindPboard() {
1413 // Since the find pasteboard supports only plain text, this can be simpler
1414 // than the |OnCopy()| case.
1415 if (frame_
->hasSelection()) {
1416 base::string16 selection
= frame_
->selectionAsText();
1417 RenderThread::Get()->Send(
1418 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1423 void RenderFrameImpl::OnDelete() {
1424 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1427 void RenderFrameImpl::OnSelectAll() {
1428 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1429 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1432 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1433 const gfx::Point
& extent
) {
1434 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1435 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1437 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1438 frame_
->selectRange(base
, extent
);
1441 void RenderFrameImpl::OnUnselect() {
1442 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1443 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1446 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1447 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1448 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1449 GetRenderWidget()->routing_id()));
1451 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1452 frame_
->moveRangeSelectionExtent(point
);
1455 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1456 if (!frame_
->hasSelection())
1457 frame_
->selectWordAroundCaret();
1459 frame_
->replaceSelection(text
);
1462 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1463 if (!frame_
->hasSelection())
1466 frame_
->replaceMisspelledRange(text
);
1469 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1470 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1473 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1474 const base::string16
& jscript
,
1476 bool notify_result
) {
1477 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1478 TRACE_EVENT_SCOPE_THREAD
);
1480 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1481 v8::Handle
<v8::Value
> result
=
1482 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1484 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1487 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1488 const base::string16
& jscript
,
1490 bool notify_result
) {
1491 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1492 TRACE_EVENT_SCOPE_THREAD
);
1494 // A bunch of tests expect to run code in the context of a user gesture, which
1495 // can grant additional privileges (e.g. the ability to create popups).
1496 blink::WebScopedUserGesture gesture
;
1497 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1498 v8::Handle
<v8::Value
> result
=
1499 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1501 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1504 void RenderFrameImpl::HandleJavascriptExecutionResult(
1505 const base::string16
& jscript
,
1508 v8::Handle
<v8::Value
> result
) {
1509 if (notify_result
) {
1510 base::ListValue list
;
1511 if (!result
.IsEmpty()) {
1512 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1513 v8::Context::Scope
context_scope(context
);
1514 V8ValueConverterImpl converter
;
1515 converter
.SetDateAllowed(true);
1516 converter
.SetRegExpAllowed(true);
1517 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
1518 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
1520 list
.Set(0, base::Value::CreateNullValue());
1522 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1526 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1527 GetRenderWidget()->QueueMessage(
1528 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1529 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1532 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1533 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1534 if (!GetRenderWidget()->ShouldHandleImeEvent())
1536 ImeEventGuard
guard(GetRenderWidget());
1537 frame_
->setEditableSelectionOffsets(start
, end
);
1540 void RenderFrameImpl::OnSetCompositionFromExistingText(
1542 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1543 if (!GetRenderWidget()->ShouldHandleImeEvent())
1545 ImeEventGuard
guard(GetRenderWidget());
1546 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1549 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1550 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1553 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1554 if (!GetRenderWidget()->ShouldHandleImeEvent())
1556 ImeEventGuard
guard(GetRenderWidget());
1557 frame_
->extendSelectionAndDelete(before
, after
);
1560 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1561 if (accessibility_mode_
== new_mode
)
1563 accessibility_mode_
= new_mode
;
1564 if (renderer_accessibility_
) {
1565 // Note: this isn't called automatically by the destructor because
1566 // there'd be no point in calling it in frame teardown, only if there's
1567 // an accessibility mode change but the frame is persisting.
1568 renderer_accessibility_
->DisableAccessibility();
1570 delete renderer_accessibility_
;
1571 renderer_accessibility_
= NULL
;
1573 if (accessibility_mode_
== AccessibilityModeOff
)
1576 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1577 renderer_accessibility_
= new RendererAccessibility(this);
1580 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1581 ui::AXTreeUpdate response
;
1582 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1583 Send(new AccessibilityHostMsg_SnapshotResponse(
1584 routing_id_
, callback_id
, response
));
1587 void RenderFrameImpl::OnDisownOpener() {
1588 // TODO(creis): We should only see this for main frames for now. To support
1589 // disowning the opener on subframes, we will need to move WebContentsImpl's
1590 // opener_ to FrameTreeNode.
1591 CHECK(!frame_
->parent());
1593 if (frame_
->opener())
1594 frame_
->setOpener(NULL
);
1597 void RenderFrameImpl::OnDidUpdateSandboxFlags(SandboxFlags flags
) {
1598 frame_
->setFrameOwnerSandboxFlags(ContentToWebSandboxFlags(flags
));
1601 void RenderFrameImpl::OnTextTrackSettingsChanged(
1602 const FrameMsg_TextTrackSettings_Params
& params
) {
1603 DCHECK(!frame_
->parent());
1604 if (!render_view_
->webview())
1606 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1607 WebString::fromUTF8(params
.text_track_background_color
));
1608 render_view_
->webview()->settings()->setTextTrackFontFamily(
1609 WebString::fromUTF8(params
.text_track_font_family
));
1610 render_view_
->webview()->settings()->setTextTrackFontStyle(
1611 WebString::fromUTF8(params
.text_track_font_style
));
1612 render_view_
->webview()->settings()->setTextTrackFontVariant(
1613 WebString::fromUTF8(params
.text_track_font_variant
));
1614 render_view_
->webview()->settings()->setTextTrackTextColor(
1615 WebString::fromUTF8(params
.text_track_text_color
));
1616 render_view_
->webview()->settings()->setTextTrackTextShadow(
1617 WebString::fromUTF8(params
.text_track_text_shadow
));
1618 render_view_
->webview()->settings()->setTextTrackTextSize(
1619 WebString::fromUTF8(params
.text_track_text_size
));
1622 void RenderFrameImpl::OnPostMessageEvent(
1623 const FrameMsg_PostMessage_Params
& params
) {
1624 // Find the source frame if it exists.
1625 WebFrame
* source_frame
= NULL
;
1626 if (params
.source_view_routing_id
!= MSG_ROUTING_NONE
) {
1627 // Support a legacy postMessage path for specifying a source RenderView;
1628 // this is currently used when sending messages to Android WebView.
1629 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1630 RenderViewImpl
* source_view
=
1631 RenderViewImpl::FromRoutingID(params
.source_view_routing_id
);
1633 source_frame
= source_view
->webview()->mainFrame();
1634 } else if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1635 RenderFrameProxy
* source_proxy
=
1636 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1638 // Currently, navigating a top-level frame cross-process does not swap
1639 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1640 // WebRemoteFrame will not have an associated blink::Frame. If this is
1641 // the case for |source_proxy|, use the corresponding (swapped-out)
1642 // WebLocalFrame instead, so that event.source for this message can be
1643 // set and used properly.
1644 if (source_proxy
->IsMainFrameDetachedFromTree())
1645 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1647 source_frame
= source_proxy
->web_frame();
1651 // If the message contained MessagePorts, create the corresponding endpoints.
1652 blink::WebMessagePortChannelArray channels
=
1653 WebMessagePortChannelImpl::CreatePorts(
1654 params
.message_ports
, params
.new_routing_ids
,
1655 base::MessageLoopProxy::current().get());
1657 WebSerializedScriptValue serialized_script_value
;
1658 if (params
.is_data_raw_string
) {
1659 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1660 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1661 v8::Context::Scope
context_scope(context
);
1662 V8ValueConverterImpl converter
;
1663 converter
.SetDateAllowed(true);
1664 converter
.SetRegExpAllowed(true);
1665 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1666 v8::Handle
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1668 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1670 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1673 // Create an event with the message. The next-to-last parameter to
1674 // initMessageEvent is the last event ID, which is not used with postMessage.
1675 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1676 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1677 msg_event
.initMessageEvent("message",
1678 // |canBubble| and |cancellable| are always false
1680 serialized_script_value
,
1681 params
.source_origin
, source_frame
, "", channels
);
1683 // We must pass in the target_origin to do the security check on this side,
1684 // since it may have changed since the original postMessage call was made.
1685 WebSecurityOrigin target_origin
;
1686 if (!params
.target_origin
.empty()) {
1688 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1690 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1693 #if defined(OS_ANDROID)
1694 void RenderFrameImpl::OnSelectPopupMenuItems(
1696 const std::vector
<int>& selected_indices
) {
1697 // It is possible to receive more than one of these calls if the user presses
1698 // a select faster than it takes for the show-select-popup IPC message to make
1699 // it to the browser UI thread. Ignore the extra-messages.
1700 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1701 if (!external_popup_menu_
)
1704 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1705 external_popup_menu_
.reset();
1709 #if defined(OS_MACOSX)
1710 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1711 if (external_popup_menu_
== NULL
)
1713 external_popup_menu_
->DidSelectItem(selected_index
);
1714 external_popup_menu_
.reset();
1718 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1719 frame_
->reload(ignore_cache
);
1722 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1723 blink::WebSurroundingText surroundingText
;
1724 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1726 if (surroundingText
.isNull()) {
1727 // |surroundingText| might not be correctly initialized, for example if
1728 // |frame_->selectionRange().isNull()|, in other words, if there was no
1730 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1731 routing_id_
, base::string16(), 0, 0));
1735 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1737 surroundingText
.textContent(),
1738 surroundingText
.startOffsetInTextContent(),
1739 surroundingText
.endOffsetInTextContent()));
1742 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string
& url
) {
1743 frame_
->addStyleSheetByURL(WebString::fromUTF8(url
));
1746 void RenderFrameImpl::OnSetupTransitionView(const std::string
& markup
) {
1747 frame_
->document().setIsTransitionDocument(true);
1748 frame_
->navigateToSandboxedMarkup(WebData(markup
.data(), markup
.length()));
1751 void RenderFrameImpl::OnBeginExitTransition(const std::string
& css_selector
,
1752 bool exit_to_native_app
) {
1753 frame_
->document().setIsTransitionDocument(true);
1754 frame_
->document().beginExitTransition(WebString::fromUTF8(css_selector
),
1755 exit_to_native_app
);
1758 void RenderFrameImpl::OnRevertExitTransition() {
1759 frame_
->document().setIsTransitionDocument(false);
1760 frame_
->document().revertExitTransition();
1763 void RenderFrameImpl::OnHideTransitionElements(
1764 const std::string
& css_selector
) {
1765 frame_
->document().hideTransitionElements(WebString::fromUTF8(css_selector
));
1768 void RenderFrameImpl::OnShowTransitionElements(
1769 const std::string
& css_selector
) {
1770 frame_
->document().showTransitionElements(WebString::fromUTF8(css_selector
));
1773 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1774 const base::string16
& message
,
1775 const base::string16
& default_value
,
1776 const GURL
& frame_url
,
1777 base::string16
* result
) {
1778 // Don't allow further dialogs if we are waiting to swap out, since the
1779 // PageGroupLoadDeferrer in our stack prevents it.
1780 if (render_view()->suppress_dialogs_until_swap_out_
)
1783 bool success
= false;
1784 base::string16 result_temp
;
1786 result
= &result_temp
;
1788 render_view()->SendAndRunNestedMessageLoop(
1789 new FrameHostMsg_RunJavaScriptMessage(
1790 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1795 void RenderFrameImpl::LoadNavigationErrorPage(
1796 const WebURLRequest
& failed_request
,
1797 const WebURLError
& error
,
1799 std::string error_html
;
1800 GetContentClient()->renderer()->GetNavigationErrorStrings(
1801 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1803 frame_
->loadHTMLString(error_html
,
1804 GURL(kUnreachableWebDataURL
),
1805 error
.unreachableURL
,
1809 void RenderFrameImpl::DidCommitCompositorFrame() {
1810 if (BrowserPluginManager::Get())
1811 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1813 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1816 RenderView
* RenderFrameImpl::GetRenderView() {
1817 return render_view_
.get();
1820 int RenderFrameImpl::GetRoutingID() {
1824 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1829 WebElement
RenderFrameImpl::GetFocusedElement() const {
1830 WebDocument doc
= frame_
->document();
1832 return doc
.focusedElement();
1834 return WebElement();
1837 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1838 return render_view_
->GetWebkitPreferences();
1841 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1842 const ContextMenuParams
& params
) {
1843 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1844 ContextMenuParams
our_params(params
);
1845 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1846 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1847 return our_params
.custom_context
.request_id
;
1850 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1851 DCHECK(pending_context_menus_
.Lookup(request_id
));
1852 pending_context_menus_
.Remove(request_id
);
1855 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1856 return context_menu_node_
;
1859 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1860 blink::WebFrame
* frame
,
1861 const WebPluginInfo
& info
,
1862 const blink::WebPluginParams
& params
,
1863 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1864 DCHECK_EQ(frame_
, frame
);
1865 #if defined(ENABLE_PLUGINS)
1866 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1867 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1868 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1869 this, params
.mimeType
.utf8(), GURL(params
.url
)));
1870 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1871 this, browser_plugin_delegate
.Pass());
1874 bool pepper_plugin_was_registered
= false;
1875 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1876 this, info
, &pepper_plugin_was_registered
));
1877 if (pepper_plugin_was_registered
) {
1878 if (pepper_module
.get()) {
1879 return new PepperWebPluginImpl(
1880 pepper_module
.get(), params
, this,
1882 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1885 #if defined(OS_CHROMEOS)
1886 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1889 // TODO(jam): change to take RenderFrame.
1890 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1897 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1898 const blink::WebURLRequest
& request
,
1899 blink::WebNavigationPolicy policy
) {
1900 DCHECK(!frame_
|| frame_
== frame
);
1901 loadURLExternally(frame
, request
, policy
, WebString());
1904 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1905 OnJavaScriptExecuteRequest(javascript
, 0, false);
1908 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1909 return &service_registry_
;
1912 #if defined(ENABLE_PLUGINS)
1913 void RenderFrameImpl::RegisterPeripheralPlugin(
1914 const GURL
& content_origin
,
1915 const base::Closure
& unthrottle_callback
) {
1916 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1917 content_origin
, unthrottle_callback
);
1919 #endif // defined(ENABLE_PLUGINS)
1921 bool RenderFrameImpl::IsFTPDirectoryListing() {
1922 WebURLResponseExtraDataImpl
* extra_data
=
1923 GetExtraDataFromResponse(frame_
->dataSource()->response());
1924 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1927 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1928 BrowserPluginManager::Get()->Attach(element_instance_id
);
1931 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1932 BrowserPluginManager::Get()->Detach(element_instance_id
);
1935 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1937 const gfx::Range
& range
) {
1938 // Use the routing id of Render Widget Host.
1939 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1945 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1946 v8::Isolate
* isolate
,
1947 v8::Local
<v8::Context
> context
) {
1948 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1949 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1952 v8::HandleScope
handle_scope(isolate
);
1953 registry
->AddBuiltinModule(
1954 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1955 registry
->AddBuiltinModule(isolate
,
1956 mojo::js::Support::kModuleName
,
1957 mojo::js::Support::GetModule(isolate
));
1958 registry
->AddBuiltinModule(
1960 ServiceRegistryJsWrapper::kModuleName
,
1961 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1964 // blink::WebFrameClient implementation ----------------------------------------
1966 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1967 blink::WebLocalFrame
* frame
,
1968 const blink::WebPluginParams
& params
) {
1969 DCHECK_EQ(frame_
, frame
);
1970 return GetContentClient()
1972 ->CreatePluginPlaceholder(this, frame
, params
)
1976 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1977 blink::WebLocalFrame
* frame
,
1978 const blink::WebPluginParams
& params
) {
1979 DCHECK_EQ(frame_
, frame
);
1980 blink::WebPlugin
* plugin
= NULL
;
1981 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1982 this, frame
, params
, &plugin
)) {
1986 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1987 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1988 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1989 kBrowserPluginMimeType
, GURL(params
.url
)));
1990 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1991 this, browser_plugin_delegate
.Pass());
1994 #if defined(ENABLE_PLUGINS)
1996 std::string mime_type
;
1998 Send(new FrameHostMsg_GetPluginInfo(
1999 routing_id_
, params
.url
, frame
->top()->document().url(),
2000 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
2004 WebPluginParams params_to_use
= params
;
2005 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2006 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2009 #endif // defined(ENABLE_PLUGINS)
2012 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2013 blink::WebLocalFrame
* frame
,
2014 const blink::WebURL
& url
,
2015 blink::WebMediaPlayerClient
* client
) {
2016 return createMediaPlayer(frame
, url
, client
, nullptr);
2019 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2020 blink::WebLocalFrame
* frame
,
2021 const blink::WebURL
& url
,
2022 blink::WebMediaPlayerClient
* client
,
2023 blink::WebContentDecryptionModule
* initial_cdm
) {
2024 #if defined(VIDEO_HOLE)
2025 if (!contains_media_player_
) {
2026 render_view_
->RegisterVideoHoleFrame(this);
2027 contains_media_player_
= true;
2029 #endif // defined(VIDEO_HOLE)
2031 blink::WebMediaStream
web_stream(
2032 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2033 if (!web_stream
.isNull())
2034 return CreateWebMediaPlayerForMediaStream(url
, client
);
2036 #if defined(OS_ANDROID)
2037 return CreateAndroidWebMediaPlayer(url
, client
, GetMediaPermission(),
2040 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2042 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2043 media::WebMediaPlayerParams
params(
2044 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2045 base::Unretained(GetContentClient()->renderer()),
2046 static_cast<RenderFrame
*>(this)),
2047 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2048 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2049 render_thread
->compositor_message_loop_proxy(),
2050 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2053 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
2054 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2055 new media::MojoRendererFactory(make_scoped_ptr(
2056 new MediaRendererServiceProvider(GetServiceRegistry()))));
2058 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2059 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
2062 if (!media_renderer_factory
.get()) {
2063 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2064 media_log
, render_thread
->GetGpuFactories(),
2065 *render_thread
->GetAudioHardwareConfig()));
2067 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
2069 return new media::WebMediaPlayerImpl(
2070 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer_factory
.Pass(),
2071 GetCdmFactory(), params
);
2072 #endif // defined(OS_ANDROID)
2075 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2076 blink::WebLocalFrame
* frame
,
2077 blink::WebApplicationCacheHostClient
* client
) {
2078 if (!frame
|| !frame
->view())
2080 DCHECK(!frame_
|| frame_
== frame
);
2081 return new RendererWebApplicationCacheHostImpl(
2082 RenderViewImpl::FromWebView(frame
->view()), client
,
2083 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2086 blink::WebWorkerContentSettingsClientProxy
*
2087 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2088 blink::WebLocalFrame
* frame
) {
2089 if (!frame
|| !frame
->view())
2091 DCHECK(!frame_
|| frame_
== frame
);
2092 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2096 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2097 const WebPopupMenuInfo
& popup_menu_info
,
2098 WebExternalPopupMenuClient
* popup_menu_client
) {
2099 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2100 // An IPC message is sent to the browser to build and display the actual
2101 // popup. The user could have time to click a different select by the time
2102 // the popup is shown. In that case external_popup_menu_ is non NULL.
2103 // By returning NULL in that case, we instruct Blink to cancel that new
2104 // popup. So from the user perspective, only the first one will show, and
2105 // will have to close the first one before another one can be shown.
2106 if (external_popup_menu_
)
2108 external_popup_menu_
.reset(
2109 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2110 if (render_view_
->screen_metrics_emulator_
) {
2111 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2112 external_popup_menu_
.get(),
2113 render_view_
->screen_metrics_emulator_
.get());
2115 return external_popup_menu_
.get();
2121 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2122 DCHECK(!frame_
|| frame_
== frame
);
2123 return &cookie_jar_
;
2126 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2127 blink::WebLocalFrame
* frame
) {
2128 DCHECK(!frame_
|| frame_
== frame
);
2129 // At this point we should have non-null data source.
2130 DCHECK(frame
->dataSource());
2131 if (!ChildThreadImpl::current())
2132 return NULL
; // May be null in some tests.
2133 ServiceWorkerNetworkProvider
* provider
=
2134 ServiceWorkerNetworkProvider::FromDocumentState(
2135 DocumentState::FromDataSource(frame
->dataSource()));
2136 return new WebServiceWorkerProviderImpl(
2137 ChildThreadImpl::current()->thread_safe_sender(),
2138 provider
? provider
->context() : NULL
);
2141 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2142 DCHECK(!frame_
|| frame_
== frame
);
2143 // If the request hasn't yet committed, notify the browser process that it is
2144 // no longer safe to show the pending URL of the main frame, since a URL spoof
2145 // is now possible. (If the request has committed, the browser already knows.)
2146 if (!frame
->parent()) {
2147 DocumentState
* document_state
=
2148 DocumentState::FromDataSource(frame
->dataSource());
2149 NavigationStateImpl
* navigation_state
=
2150 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2152 if (!navigation_state
->request_committed()) {
2153 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2158 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2159 blink::WebLocalFrame
* parent
,
2160 const blink::WebString
& name
,
2161 blink::WebSandboxFlags sandbox_flags
) {
2162 // Synchronously notify the browser of a child frame creation to get the
2163 // routing_id for the RenderFrame.
2164 int child_routing_id
= MSG_ROUTING_NONE
;
2165 Send(new FrameHostMsg_CreateChildFrame(
2166 routing_id_
, base::UTF16ToUTF8(name
),
2167 WebToContentSandboxFlags(sandbox_flags
), &child_routing_id
));
2169 // Allocation of routing id failed, so we can't create a child frame. This can
2170 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2171 // out state or synchronous IPC message above has failed.
2172 if (child_routing_id
== MSG_ROUTING_NONE
) {
2173 NOTREACHED() << "Failed to allocate routing id for child frame.";
2177 // Create the RenderFrame and WebLocalFrame, linking the two.
2178 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2179 render_view_
.get(), child_routing_id
);
2180 blink::WebLocalFrame
* web_frame
= WebLocalFrame::create(child_render_frame
);
2181 child_render_frame
->SetWebFrame(web_frame
);
2183 // Add the frame to the frame tree and initialize it.
2184 parent
->appendChild(web_frame
);
2185 child_render_frame
->Initialize();
2190 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2191 DCHECK(!frame_
|| frame_
== frame
);
2192 // We only need to notify the browser if the active, top-level frame clears
2193 // its opener. We can ignore cases where a swapped out frame clears its
2194 // opener after hearing about it from the browser, and the browser does not
2195 // (yet) care about subframe openers.
2196 if (is_swapped_out_
|| frame
->parent())
2199 // Notify WebContents and all its swapped out RenderViews.
2200 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2203 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
) {
2204 // NOTE: This function is called on the frame that is being detached and not
2205 // the parent frame. This is different from createChildFrame() which is
2206 // called on the parent frame.
2207 CHECK(!is_detaching_
);
2208 DCHECK(!frame_
|| frame_
== frame
);
2210 bool is_subframe
= !!frame
->parent();
2212 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2213 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2214 FrameDetached(frame
));
2216 Send(new FrameHostMsg_Detach(routing_id_
));
2218 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2219 // sent before setting |is_detaching_| to true.
2220 is_detaching_
= true;
2222 // We need to clean up subframes by removing them from the map and deleting
2223 // the RenderFrameImpl. In contrast, the main frame is owned by its
2224 // containing RenderViewHost (so that they have the same lifetime), so only
2225 // removal from the map is needed and no deletion.
2226 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2227 CHECK(it
!= g_frame_map
.Get().end());
2228 CHECK_EQ(it
->second
, this);
2229 g_frame_map
.Get().erase(it
);
2232 frame
->parent()->removeChild(frame
);
2234 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2235 // object may not be deleted immediately and other methods may try to access
2242 // Object is invalid after this point.
2246 void RenderFrameImpl::frameFocused() {
2247 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2250 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2251 DCHECK(!frame_
|| frame_
== frame
);
2253 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2254 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2255 FrameWillClose(frame
));
2258 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2259 const blink::WebString
& name
) {
2260 DCHECK(!frame_
|| frame_
== frame
);
2262 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2263 // updates may have performance implications for benchmarks like SunSpider.
2264 // For now, send these updates only for --site-per-process, which needs to
2265 // replicate frame names to frame proxies, and when
2266 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2267 // can be optimized further by only sending the update if there are any
2268 // remote frames in the frame tree, or delaying and batching up IPCs if
2269 // updates are happening too frequently.
2270 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
2271 switches::kSitePerProcess
);
2272 if (is_site_per_process
||
2273 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2274 Send(new FrameHostMsg_DidChangeName(routing_id_
, base::UTF16ToUTF8(name
)));
2278 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2279 blink::WebSandboxFlags flags
) {
2280 int frame_routing_id
= MSG_ROUTING_NONE
;
2281 if (child_frame
->isWebRemoteFrame()) {
2283 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2286 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2289 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2290 WebToContentSandboxFlags(flags
)));
2293 void RenderFrameImpl::didMatchCSS(
2294 blink::WebLocalFrame
* frame
,
2295 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2296 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2297 DCHECK(!frame_
|| frame_
== frame
);
2299 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2301 newly_matching_selectors
,
2302 stopped_matching_selectors
));
2305 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2306 const blink::WebString
& source
) {
2307 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2311 void RenderFrameImpl::didAddMessageToConsole(
2312 const blink::WebConsoleMessage
& message
,
2313 const blink::WebString
& source_name
,
2314 unsigned source_line
,
2315 const blink::WebString
& stack_trace
) {
2316 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2317 switch (message
.level
) {
2318 case blink::WebConsoleMessage::LevelDebug
:
2319 log_severity
= logging::LOG_VERBOSE
;
2321 case blink::WebConsoleMessage::LevelLog
:
2322 case blink::WebConsoleMessage::LevelInfo
:
2323 log_severity
= logging::LOG_INFO
;
2325 case blink::WebConsoleMessage::LevelWarning
:
2326 log_severity
= logging::LOG_WARNING
;
2328 case blink::WebConsoleMessage::LevelError
:
2329 log_severity
= logging::LOG_ERROR
;
2332 log_severity
= logging::LOG_VERBOSE
;
2335 if (shouldReportDetailedMessageForSource(source_name
)) {
2337 RenderFrameObserver
, observers_
,
2338 DetailedConsoleMessageAdded(message
.text
,
2342 static_cast<int32
>(log_severity
)));
2345 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2346 static_cast<int32
>(log_severity
),
2348 static_cast<int32
>(source_line
),
2352 void RenderFrameImpl::loadURLExternally(
2353 blink::WebLocalFrame
* frame
,
2354 const blink::WebURLRequest
& request
,
2355 blink::WebNavigationPolicy policy
,
2356 const blink::WebString
& suggested_name
) {
2357 DCHECK(!frame_
|| frame_
== frame
);
2358 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2359 if (policy
== blink::WebNavigationPolicyDownload
) {
2360 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2361 request
.url(), referrer
,
2364 OpenURL(frame
, request
.url(), referrer
, policy
);
2368 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2369 const NavigationPolicyInfo
& info
) {
2370 DCHECK(!frame_
|| frame_
== info
.frame
);
2371 return DecidePolicyForNavigation(this, info
);
2374 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2375 blink::WebFrame
* frame
) {
2376 DCHECK(!frame_
|| frame_
== frame
);
2377 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2380 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2381 const blink::WebFormElement
& form
) {
2382 DCHECK(!frame_
|| frame_
== frame
);
2384 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2387 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2388 const blink::WebFormElement
& form
) {
2389 DCHECK(!frame_
|| frame_
== frame
);
2390 DocumentState
* document_state
=
2391 DocumentState::FromDataSource(frame
->provisionalDataSource());
2392 NavigationStateImpl
* navigation_state
=
2393 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2394 InternalDocumentStateData
* internal_data
=
2395 InternalDocumentStateData::FromDocumentState(document_state
);
2397 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2398 ui::PAGE_TRANSITION_LINK
)) {
2399 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2402 // Save these to be processed when the ensuing navigation is committed.
2403 WebSearchableFormData
web_searchable_form_data(form
);
2404 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2405 internal_data
->set_searchable_form_encoding(
2406 web_searchable_form_data
.encoding().utf8());
2408 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2411 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2412 blink::WebDataSource
* datasource
) {
2413 DCHECK(!frame_
|| frame_
== frame
);
2415 bool content_initiated
= !pending_navigation_params_
.get();
2417 // Make sure any previous redirect URLs end up in our new data source.
2418 if (pending_navigation_params_
.get()) {
2419 for (const auto& i
:
2420 pending_navigation_params_
->request_params
.redirects
) {
2421 datasource
->appendRedirect(i
);
2425 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2426 if (!document_state
) {
2427 document_state
= new DocumentState
;
2428 datasource
->setExtraData(document_state
);
2429 if (!content_initiated
)
2430 PopulateDocumentStateFromPending(document_state
);
2433 // Carry over the user agent override flag, if it exists.
2434 blink::WebView
* webview
= render_view_
->webview();
2435 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2436 webview
->mainFrame()->isWebLocalFrame() &&
2437 webview
->mainFrame()->dataSource()) {
2438 DocumentState
* old_document_state
=
2439 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2440 if (old_document_state
) {
2441 InternalDocumentStateData
* internal_data
=
2442 InternalDocumentStateData::FromDocumentState(document_state
);
2443 InternalDocumentStateData
* old_internal_data
=
2444 InternalDocumentStateData::FromDocumentState(old_document_state
);
2445 internal_data
->set_is_overriding_user_agent(
2446 old_internal_data
->is_overriding_user_agent());
2450 // The rest of RenderView assumes that a WebDataSource will always have a
2451 // non-null NavigationState.
2452 if (content_initiated
) {
2453 document_state
->set_navigation_state(
2454 NavigationStateImpl::CreateContentInitiated());
2456 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2457 pending_navigation_params_
.reset();
2460 // DocumentState::referred_by_prefetcher_ is true if we are
2461 // navigating from a page that used prefetching using a link on that
2462 // page. We are early enough in the request process here that we
2463 // can still see the DocumentState of the previous page and set
2464 // this value appropriately.
2465 // TODO(gavinp): catch the important case of navigation in a new
2466 // renderer process.
2468 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2469 const WebURLRequest
& original_request
= datasource
->originalRequest();
2470 const GURL
referrer(
2471 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2472 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2473 DocumentState::FromDataSource(old_frame
->dataSource())
2474 ->was_prefetcher()) {
2475 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2476 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2477 if (old_frame_datasource
&&
2478 referrer
== GURL(old_frame_datasource
->request().url())) {
2479 document_state
->set_was_referred_by_prefetcher(true);
2487 if (content_initiated
) {
2488 const WebURLRequest
& request
= datasource
->request();
2489 switch (request
.cachePolicy()) {
2490 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2491 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2493 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2494 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2495 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2497 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2498 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2500 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2501 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2508 // Create the serviceworker's per-document network observing object if it
2509 // does not exist (When navigation happens within a page, the provider already
2511 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2512 DocumentState::FromDataSource(datasource
))) {
2513 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2514 new ServiceWorkerNetworkProvider(routing_id_
,
2515 SERVICE_WORKER_PROVIDER_FOR_WINDOW
));
2516 ServiceWorkerNetworkProvider::AttachToDocumentState(
2517 DocumentState::FromDataSource(datasource
),
2518 network_provider
.Pass());
2522 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2523 bool is_transition_navigation
,
2524 double triggering_event_time
) {
2525 DCHECK(!frame_
|| frame_
== frame
);
2526 WebDataSource
* ds
= frame
->provisionalDataSource();
2528 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2529 // callback is invoked.
2533 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2534 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2535 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2537 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2538 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2540 "Heard swappedout:// when not swapped out.";
2542 // Update the request time if WebKit has better knowledge of it.
2543 if (document_state
->request_time().is_null() &&
2544 triggering_event_time
!= 0.0) {
2545 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2548 // Start time is only set after request time.
2549 document_state
->set_start_load_time(Time::Now());
2551 bool is_top_most
= !frame
->parent();
2553 render_view_
->set_navigation_gesture(
2554 WebUserGestureIndicator::isProcessingUserGesture() ?
2555 NavigationGestureUser
: NavigationGestureAuto
);
2556 } else if (ds
->replacesCurrentHistoryItem()) {
2557 // Subframe navigations that don't add session history items must be
2558 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2559 // handle loading of error pages.
2560 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2561 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2564 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2565 DidStartProvisionalLoad(frame
));
2566 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2568 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2569 routing_id_
, ds
->request().url(), is_transition_navigation
));
2572 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2573 blink::WebLocalFrame
* frame
) {
2574 DCHECK(!frame_
|| frame_
== frame
);
2575 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2578 void RenderFrameImpl::didFailProvisionalLoad(
2579 blink::WebLocalFrame
* frame
,
2580 const blink::WebURLError
& error
,
2581 blink::WebHistoryCommitType commit_type
) {
2582 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2584 DCHECK(!frame_
|| frame_
== frame
);
2585 WebDataSource
* ds
= frame
->provisionalDataSource();
2588 const WebURLRequest
& failed_request
= ds
->request();
2590 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2591 NavigationStateImpl
* navigation_state
=
2592 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2594 // Notify the browser that we failed a provisional load with an error.
2596 // Note: It is important this notification occur before DidStopLoading so the
2597 // SSL manager can react to the provisional load failure before being
2598 // notified the load stopped.
2600 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2601 DidFailProvisionalLoad(frame
, error
));
2602 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2603 DidFailProvisionalLoad(error
));
2605 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2607 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2610 // Make sure we never show errors in view source mode.
2611 frame
->enableViewSourceMode(false);
2613 // If this is a failed back/forward/reload navigation, then we need to do a
2614 // 'replace' load. This is necessary to avoid messing up session history.
2615 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2616 // as session history is concerned.
2617 bool replace
= commit_type
!= blink::WebStandardCommit
;
2619 // If we failed on a browser initiated request, then make sure that our error
2620 // page load is regarded as the same browser initiated request.
2621 if (!navigation_state
->IsContentInitiated()) {
2622 pending_navigation_params_
.reset(new NavigationParams(
2623 navigation_state
->common_params(), navigation_state
->start_params(),
2624 navigation_state
->request_params()));
2625 pending_navigation_params_
->request_params
.request_time
=
2626 document_state
->request_time();
2629 // Load an error page.
2630 LoadNavigationErrorPage(failed_request
, error
, replace
);
2633 void RenderFrameImpl::didCommitProvisionalLoad(
2634 blink::WebLocalFrame
* frame
,
2635 const blink::WebHistoryItem
& item
,
2636 blink::WebHistoryCommitType commit_type
) {
2637 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2639 "url", GetLoadingUrl().possibly_invalid_spec());
2640 DCHECK(!frame_
|| frame_
== frame
);
2641 DocumentState
* document_state
=
2642 DocumentState::FromDataSource(frame
->dataSource());
2643 NavigationStateImpl
* navigation_state
=
2644 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2646 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2647 RenderFrameProxy
* proxy
=
2648 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2650 proxy
->web_frame()->swap(frame_
);
2651 proxy_routing_id_
= MSG_ROUTING_NONE
;
2654 // When we perform a new navigation, we need to update the last committed
2655 // session history entry with state for the page we are leaving. Do this
2656 // before updating the HistoryController state.
2657 render_view_
->UpdateSessionHistory(frame
);
2659 render_view_
->history_controller()->UpdateForCommit(
2660 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2662 InternalDocumentStateData
* internal_data
=
2663 InternalDocumentStateData::FromDocumentState(document_state
);
2665 if (document_state
->commit_load_time().is_null())
2666 document_state
->set_commit_load_time(Time::Now());
2668 if (internal_data
->must_reset_scroll_and_scale_state()) {
2669 render_view_
->webview()->resetScrollAndScaleState();
2670 internal_data
->set_must_reset_scroll_and_scale_state(false);
2672 internal_data
->set_use_error_page(false);
2674 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2675 if (is_new_navigation
) {
2676 // We bump our Page ID to correspond with the new session history entry.
2677 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2679 // Don't update history list values for kSwappedOutURL, since
2680 // we don't want to forget the entry that was there, and since we will
2681 // never come back to kSwappedOutURL. Note that we have to call
2682 // UpdateSessionHistory and update page_id_ even in this case, so that
2683 // the current entry gets a state update and so that we don't send a
2684 // state update to the wrong entry when we swap back in.
2686 navigation_state
->start_params().should_replace_current_entry
,
2687 render_view_
->history_list_length_
> 0);
2688 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2689 !navigation_state
->start_params().should_replace_current_entry
) {
2690 // Advance our offset in session history, applying the length limit.
2691 // There is now no forward history.
2692 render_view_
->history_list_offset_
++;
2693 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2694 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2695 render_view_
->history_list_length_
=
2696 render_view_
->history_list_offset_
+ 1;
2699 if (navigation_state
->request_params().page_id
!= -1) {
2700 // This is a successful session history navigation!
2701 render_view_
->page_id_
= navigation_state
->request_params().page_id
;
2703 render_view_
->history_list_offset_
=
2704 navigation_state
->request_params().pending_history_list_offset
;
2709 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2710 CHECK(sent
); // http://crbug.com/407376
2712 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2713 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2715 RenderFrameObserver
, observers_
,
2716 DidCommitProvisionalLoad(is_new_navigation
,
2717 navigation_state
->WasWithinSamePage()));
2719 if (!frame
->parent()) { // Only for top frames.
2720 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2721 if (render_thread_impl
) { // Can be NULL in tests.
2722 render_thread_impl
->histogram_customizer()->
2723 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2724 RenderViewImpl::GetRenderViewCount());
2728 // Remember that we've already processed this request, so we don't update
2729 // the session history again. We do this regardless of whether this is
2730 // a session history navigation, because if we attempted a session history
2731 // navigation without valid HistoryItem state, WebCore will think it is a
2733 navigation_state
->set_request_committed(true);
2735 SendDidCommitProvisionalLoad(frame
, commit_type
);
2737 // Check whether we have new encoding name.
2738 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2741 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2742 DCHECK(!frame_
|| frame_
== frame
);
2744 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2745 DidCreateNewDocument(frame
));
2748 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2749 DCHECK(!frame_
|| frame_
== frame
);
2751 int enabled_bindings
= render_view_
->GetEnabledBindings();
2753 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2754 WebUIExtension::Install(frame
);
2756 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2757 DomAutomationController::Install(this, frame
);
2759 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2760 StatsCollectionController::Install(frame
);
2762 const base::CommandLine
& command_line
=
2763 *base::CommandLine::ForCurrentProcess();
2765 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2766 GpuBenchmarking::Install(frame
);
2768 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2769 MemoryBenchmarkingExtension::Install(frame
);
2771 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2772 SkiaBenchmarking::Install(frame
);
2774 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2775 DidClearWindowObject(frame
));
2776 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2779 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2780 DCHECK(!frame_
|| frame_
== frame
);
2782 // Notify the browser about non-blank documents loading in the top frame.
2783 GURL url
= frame
->document().url();
2784 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2785 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2786 // frame->tree()->top().
2787 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2788 if (frame
== main_frame
) {
2789 // For now, don't remember plugin zoom values. We don't want to mix them
2790 // with normal web content (i.e. a fixed layout plugin would usually want
2792 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2793 render_view_
->GetRoutingID(),
2794 main_frame
->document().isPluginDocument()));
2798 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2799 DidCreateDocumentElement(frame
));
2802 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2803 const blink::WebString
& title
,
2804 blink::WebTextDirection direction
) {
2805 DCHECK(!frame_
|| frame_
== frame
);
2806 // Ignore all but top level navigations.
2807 if (!frame
->parent()) {
2808 base::string16 title16
= title
;
2809 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2810 routing_id_
, base::UTF16ToUTF8(title16
));
2812 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2813 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2814 shortened_title
, direction
));
2817 // Also check whether we have new encoding name.
2818 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2821 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2822 blink::WebIconURL::Type icon_type
) {
2823 DCHECK(!frame_
|| frame_
== frame
);
2824 // TODO(nasko): Investigate wheather implementation should move here.
2825 render_view_
->didChangeIcon(frame
, icon_type
);
2828 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2829 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2831 DCHECK(!frame_
|| frame_
== frame
);
2832 WebDataSource
* ds
= frame
->dataSource();
2833 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2834 document_state
->set_finish_document_load_time(Time::Now());
2836 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2838 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2839 DidFinishDocumentLoad(frame
));
2840 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2842 // Check whether we have new encoding name.
2843 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2846 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2847 DCHECK(!frame_
|| frame_
== frame
);
2848 if (!frame
->parent()) {
2849 FrameMsg_UILoadMetricsReportType::Value report_type
=
2850 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2851 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2852 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2853 base::TimeDelta::FromSecondsD(
2854 frame
->dataSource()->request().uiStartTime());
2856 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2857 routing_id_
, report_type
, ui_timestamp
));
2861 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2862 const blink::WebURLError
& error
,
2863 blink::WebHistoryCommitType commit_type
) {
2864 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2866 DCHECK(!frame_
|| frame_
== frame
);
2867 // TODO(nasko): Move implementation here. No state needed.
2868 WebDataSource
* ds
= frame
->dataSource();
2871 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2872 DidFailLoad(frame
, error
));
2874 const WebURLRequest
& failed_request
= ds
->request();
2875 base::string16 error_description
;
2876 GetContentClient()->renderer()->GetNavigationErrorStrings(
2882 &error_description
);
2883 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2884 failed_request
.url(),
2886 error_description
));
2889 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2890 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2892 DCHECK(!frame_
|| frame_
== frame
);
2893 WebDataSource
* ds
= frame
->dataSource();
2894 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2895 if (document_state
->finish_load_time().is_null()) {
2896 if (!frame
->parent()) {
2897 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2898 TRACE_EVENT_SCOPE_PROCESS
);
2900 document_state
->set_finish_load_time(Time::Now());
2903 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2904 DidFinishLoad(frame
));
2905 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2907 // Don't send this message while the frame is swapped out.
2908 if (is_swapped_out())
2911 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2912 ds
->request().url()));
2915 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2916 const blink::WebHistoryItem
& item
,
2917 blink::WebHistoryCommitType commit_type
) {
2918 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2920 DCHECK(!frame_
|| frame_
== frame
);
2921 // If this was a reference fragment navigation that we initiated, then we
2922 // could end up having a non-null pending navigation params. We just need to
2923 // update the ExtraData on the datasource so that others who read the
2924 // ExtraData will get the new NavigationState. Similarly, if we did not
2925 // initiate this navigation, then we need to take care to reset any pre-
2926 // existing navigation state to a content-initiated navigation state.
2927 // didCreateDataSource conveniently takes care of this for us.
2928 didCreateDataSource(frame
, frame
->dataSource());
2930 DocumentState
* document_state
=
2931 DocumentState::FromDataSource(frame
->dataSource());
2932 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2933 ->set_was_within_same_page(true);
2935 didCommitProvisionalLoad(frame
, item
, commit_type
);
2938 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2939 DCHECK(!frame_
|| frame_
== frame
);
2940 // TODO(nasko): Move implementation here. Needed methods:
2941 // * StartNavStateSyncTimerIfNecessary
2942 render_view_
->didUpdateCurrentHistoryItem(frame
);
2945 void RenderFrameImpl::addNavigationTransitionData(
2946 const blink::WebTransitionElementData
& data
) {
2947 FrameHostMsg_AddNavigationTransitionData_Params params
;
2948 params
.render_frame_id
= routing_id_
;
2949 params
.allowed_destination_host_pattern
=
2951 params
.selector
= data
.selector
.utf8();
2952 params
.markup
= data
.markup
.utf8();
2953 params
.elements
.resize(data
.elements
.size());
2954 for (size_t i
= 0; i
< data
.elements
.size(); i
++) {
2955 params
.elements
[i
].id
= data
.elements
[i
].id
.utf8();
2956 params
.elements
[i
].rect
= gfx::Rect(data
.elements
[i
].rect
);
2959 Send(new FrameHostMsg_AddNavigationTransitionData(params
));
2962 void RenderFrameImpl::didChangeThemeColor() {
2963 if (frame_
->parent())
2966 Send(new FrameHostMsg_DidChangeThemeColor(
2967 routing_id_
, frame_
->document().themeColor()));
2970 void RenderFrameImpl::dispatchLoad() {
2971 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
2974 void RenderFrameImpl::requestNotificationPermission(
2975 const blink::WebSecurityOrigin
& origin
,
2976 blink::WebNotificationPermissionCallback
* callback
) {
2977 if (!notification_permission_dispatcher_
) {
2978 notification_permission_dispatcher_
=
2979 new NotificationPermissionDispatcher(this);
2982 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
2985 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
2986 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
2989 if (is_empty_selection
)
2990 selection_text_
.clear();
2992 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2993 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2994 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2995 // to notify the selection was changed. Focus change should be notified
2996 // before selection change.
2997 GetRenderWidget()->UpdateTextInputType();
2998 SyncSelectionIfRequired();
2999 #if defined(OS_ANDROID)
3000 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
3001 RenderWidget::FROM_NON_IME
);
3005 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3006 blink::WebColorChooserClient
* client
,
3007 const blink::WebColor
& initial_color
,
3008 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3009 RendererWebColorChooserImpl
* color_chooser
=
3010 new RendererWebColorChooserImpl(this, client
);
3011 std::vector
<ColorSuggestion
> color_suggestions
;
3012 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3013 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3015 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3016 return color_chooser
;
3019 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3020 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3023 frame_
->document().url(),
3027 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3028 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3031 frame_
->document().url(),
3035 bool RenderFrameImpl::runModalPromptDialog(
3036 const blink::WebString
& message
,
3037 const blink::WebString
& default_value
,
3038 blink::WebString
* actual_value
) {
3039 base::string16 result
;
3040 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3043 frame_
->document().url(),
3046 actual_value
->assign(result
);
3050 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3052 const blink::WebString
& message
) {
3053 // If we are swapping out, we have already run the beforeunload handler.
3054 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3055 // at all, to avoid running it twice.
3056 if (is_swapped_out_
)
3059 // Don't allow further dialogs if we are waiting to swap out, since the
3060 // PageGroupLoadDeferrer in our stack prevents it.
3061 if (render_view()->suppress_dialogs_until_swap_out_
)
3064 bool success
= false;
3065 // This is an ignored return value, but is included so we can accept the same
3066 // response as RunJavaScriptMessage.
3067 base::string16 ignored_result
;
3068 render_view()->SendAndRunNestedMessageLoop(
3069 new FrameHostMsg_RunBeforeUnloadConfirm(
3070 routing_id_
, frame_
->document().url(), message
, is_reload
,
3071 &success
, &ignored_result
));
3075 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3076 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3077 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3078 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3079 if (GetRenderWidget()->has_host_context_menu_location()) {
3080 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3081 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3084 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3085 // it. We replace it with an empty GURL so the appropriate items are disabled
3086 // in the context menu.
3087 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3088 // data encoded images. We should have a way to save them.
3089 if (params
.src_url
.spec().size() > GetMaxURLChars())
3090 params
.src_url
= GURL();
3091 context_menu_node_
= data
.node
;
3093 #if defined(OS_ANDROID)
3094 gfx::Rect start_rect
;
3096 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3097 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3098 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3101 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3104 void RenderFrameImpl::clearContextMenu() {
3105 context_menu_node_
.reset();
3108 void RenderFrameImpl::willSendRequest(
3109 blink::WebLocalFrame
* frame
,
3110 unsigned identifier
,
3111 blink::WebURLRequest
& request
,
3112 const blink::WebURLResponse
& redirect_response
) {
3113 DCHECK(!frame_
|| frame_
== frame
);
3114 // The request my be empty during tests.
3115 if (request
.url().isEmpty())
3118 // Set the first party for cookies url if it has not been set yet (new
3119 // requests). For redirects, it is updated by WebURLLoaderImpl.
3120 if (request
.firstPartyForCookies().isEmpty()) {
3121 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3122 request
.setFirstPartyForCookies(request
.url());
3124 // TODO(nasko): When the top-level frame is remote, there is no document.
3125 // This is broken and should be fixed to propagate the first party.
3126 WebFrame
* top
= frame
->top();
3127 if (top
->isWebLocalFrame()) {
3128 request
.setFirstPartyForCookies(
3129 frame
->top()->document().firstPartyForCookies());
3134 WebFrame
* top_frame
= frame
->top();
3135 // TODO(nasko): Hack around asking about top-frame data source. This means
3136 // for out-of-process iframes we are treating the current frame as the
3137 // top-level frame, which is wrong.
3138 if (!top_frame
|| top_frame
->isWebRemoteFrame())
3140 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
3141 WebDataSource
* top_data_source
= top_frame
->dataSource();
3142 WebDataSource
* data_source
=
3143 provisional_data_source
? provisional_data_source
: top_data_source
;
3145 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3146 DCHECK(document_state
);
3147 InternalDocumentStateData
* internal_data
=
3148 InternalDocumentStateData::FromDocumentState(document_state
);
3149 NavigationStateImpl
* navigation_state
=
3150 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3151 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3152 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
3153 if (frame_ds
&& frame_ds
->isClientRedirect()) {
3154 transition_type
= ui::PageTransitionFromInt(
3155 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3158 GURL
request_url(request
.url());
3160 if (GetContentClient()->renderer()->WillSendRequest(
3164 request
.firstPartyForCookies(),
3166 request
.setURL(WebURL(new_url
));
3169 if (internal_data
->is_cache_policy_override_set())
3170 request
.setCachePolicy(internal_data
->cache_policy_override());
3172 // The request's extra data may indicate that we should set a custom user
3173 // agent. This needs to be done here, after WebKit is through with setting the
3174 // user agent on its own. Similarly, it may indicate that we should set an
3175 // X-Requested-With header. This must be done here to avoid breaking CORS
3177 // PlzNavigate: there may also be a stream url associated with the request.
3178 WebString custom_user_agent
;
3179 WebString requested_with
;
3180 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3181 if (request
.extraData()) {
3182 RequestExtraData
* old_extra_data
=
3183 static_cast<RequestExtraData
*>(request
.extraData());
3185 custom_user_agent
= old_extra_data
->custom_user_agent();
3186 if (!custom_user_agent
.isNull()) {
3187 if (custom_user_agent
.isEmpty())
3188 request
.clearHTTPHeaderField("User-Agent");
3190 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3193 requested_with
= old_extra_data
->requested_with();
3194 if (!requested_with
.isNull()) {
3195 if (requested_with
.isEmpty())
3196 request
.clearHTTPHeaderField("X-Requested-With");
3198 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3200 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3203 // Add the default accept header for frame request if it has not been set
3205 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3206 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3207 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3208 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3209 WebString::fromUTF8(kDefaultAcceptHeader
));
3212 // Add an empty HTTP origin header for non GET methods if none is currently
3214 request
.addHTTPOriginIfNeeded(WebString());
3216 // Attach |should_replace_current_entry| state to requests so that, should
3217 // this navigation later require a request transfer, all state is preserved
3218 // when it is re-created in the new process.
3219 bool should_replace_current_entry
= false;
3220 if (navigation_state
->IsContentInitiated()) {
3221 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3223 // If the navigation is browser-initiated, the NavigationState contains the
3224 // correct value instead of the WebDataSource.
3226 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3227 // NavigationState::should_replace_current_entry().
3228 should_replace_current_entry
=
3229 navigation_state
->start_params().should_replace_current_entry
;
3232 int provider_id
= kInvalidServiceWorkerProviderId
;
3233 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3234 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3235 // |provisionalDataSource| may be null in some content::ResourceFetcher
3236 // use cases, we don't hook those requests.
3237 if (frame
->provisionalDataSource()) {
3238 ServiceWorkerNetworkProvider
* provider
=
3239 ServiceWorkerNetworkProvider::FromDocumentState(
3240 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3241 provider_id
= provider
->provider_id();
3243 } else if (frame
->dataSource()) {
3244 ServiceWorkerNetworkProvider
* provider
=
3245 ServiceWorkerNetworkProvider::FromDocumentState(
3246 DocumentState::FromDataSource(frame
->dataSource()));
3247 provider_id
= provider
->provider_id();
3250 WebFrame
* parent
= frame
->parent();
3251 int parent_routing_id
= MSG_ROUTING_NONE
;
3253 parent_routing_id
= -1;
3254 } else if (parent
->isWebLocalFrame()) {
3255 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3257 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3260 RequestExtraData
* extra_data
= new RequestExtraData();
3261 extra_data
->set_visibility_state(render_view_
->visibilityState());
3262 extra_data
->set_custom_user_agent(custom_user_agent
);
3263 extra_data
->set_requested_with(requested_with
);
3264 extra_data
->set_render_frame_id(routing_id_
);
3265 extra_data
->set_is_main_frame(!parent
);
3266 extra_data
->set_frame_origin(
3267 GURL(frame
->document().securityOrigin().toString()));
3268 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3269 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3270 extra_data
->set_allow_download(
3271 navigation_state
->common_params().allow_download
);
3272 extra_data
->set_transition_type(transition_type
);
3273 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3274 extra_data
->set_transferred_request_child_id(
3275 navigation_state
->start_params().transferred_request_child_id
);
3276 extra_data
->set_transferred_request_request_id(
3277 navigation_state
->start_params().transferred_request_request_id
);
3278 extra_data
->set_service_worker_provider_id(provider_id
);
3279 extra_data
->set_stream_override(stream_override
.Pass());
3280 request
.setExtraData(extra_data
);
3282 DocumentState
* top_document_state
=
3283 DocumentState::FromDataSource(top_data_source
);
3284 if (top_document_state
) {
3285 // TODO(gavinp): separate out prefetching and prerender field trials
3286 // if the rel=prerender rel type is sticking around.
3287 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3288 top_document_state
->set_was_prefetcher(true);
3291 // This is an instance where we embed a copy of the routing id
3292 // into the data portion of the message. This can cause problems if we
3293 // don't register this id on the browser side, since the download manager
3294 // expects to find a RenderViewHost based off the id.
3295 request
.setRequestorID(render_view_
->GetRoutingID());
3296 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3298 if (!navigation_state
->start_params().extra_headers
.empty()) {
3299 for (net::HttpUtil::HeadersIterator
i(
3300 navigation_state
->start_params().extra_headers
.begin(),
3301 navigation_state
->start_params().extra_headers
.end(), "\n");
3303 if (LowerCaseEqualsASCII(i
.name(), "referer")) {
3304 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3305 blink::WebReferrerPolicyDefault
,
3307 WebString::fromUTF8(i
.values()));
3308 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3310 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3311 WebString::fromUTF8(i
.values()));
3316 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3317 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3320 void RenderFrameImpl::didReceiveResponse(
3321 blink::WebLocalFrame
* frame
,
3322 unsigned identifier
,
3323 const blink::WebURLResponse
& response
) {
3324 DCHECK(!frame_
|| frame_
== frame
);
3325 // Only do this for responses that correspond to a provisional data source
3326 // of the top-most frame. If we have a provisional data source, then we
3327 // can't have any sub-resources yet, so we know that this response must
3328 // correspond to a frame load.
3329 if (!frame
->provisionalDataSource() || frame
->parent())
3332 // If we are in view source mode, then just let the user see the source of
3333 // the server's error page.
3334 if (frame
->isViewSourceModeEnabled())
3337 DocumentState
* document_state
=
3338 DocumentState::FromDataSource(frame
->provisionalDataSource());
3339 int http_status_code
= response
.httpStatusCode();
3341 // Record page load flags.
3342 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3344 document_state
->set_was_fetched_via_spdy(
3345 extra_data
->was_fetched_via_spdy());
3346 document_state
->set_was_npn_negotiated(
3347 extra_data
->was_npn_negotiated());
3348 document_state
->set_npn_negotiated_protocol(
3349 extra_data
->npn_negotiated_protocol());
3350 document_state
->set_was_alternate_protocol_available(
3351 extra_data
->was_alternate_protocol_available());
3352 document_state
->set_connection_info(
3353 extra_data
->connection_info());
3354 document_state
->set_was_fetched_via_proxy(
3355 extra_data
->was_fetched_via_proxy());
3356 document_state
->set_proxy_server(
3357 extra_data
->proxy_server());
3359 InternalDocumentStateData
* internal_data
=
3360 InternalDocumentStateData::FromDocumentState(document_state
);
3361 internal_data
->set_http_status_code(http_status_code
);
3362 // Whether or not the http status code actually corresponds to an error is
3363 // only checked when the page is done loading, if |use_error_page| is
3365 internal_data
->set_use_error_page(true);
3368 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3369 unsigned identifier
) {
3370 DCHECK(!frame_
|| frame_
== frame
);
3371 InternalDocumentStateData
* internal_data
=
3372 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3373 if (!internal_data
->use_error_page())
3376 // Do not show error page when DevTools is attached.
3377 RenderFrameImpl
* localRoot
= this;
3378 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
3379 localRoot
->frame_
->parent()->isWebLocalFrame()) {
3380 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
3383 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
3386 // Display error page, if appropriate.
3387 std::string error_domain
= "http";
3388 int http_status_code
= internal_data
->http_status_code();
3389 if (GetContentClient()->renderer()->HasErrorPage(
3390 http_status_code
, &error_domain
)) {
3392 error
.unreachableURL
= frame
->document().url();
3393 error
.domain
= WebString::fromUTF8(error_domain
);
3394 error
.reason
= http_status_code
;
3395 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3399 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3400 blink::WebLocalFrame
* frame
,
3401 const blink::WebURLRequest
& request
,
3402 const blink::WebURLResponse
& response
) {
3403 DCHECK(!frame_
|| frame_
== frame
);
3404 // The recipients of this message have no use for data: URLs: they don't
3405 // affect the page's insecure content list and are not in the disk cache. To
3406 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3407 // filter them out here.
3408 GURL
url(request
.url());
3409 if (url
.SchemeIs(url::kDataScheme
))
3412 // Let the browser know we loaded a resource from the memory cache. This
3413 // message is needed to display the correct SSL indicators.
3414 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3415 render_view_
->GetRoutingID(),
3417 response
.securityInfo(),
3418 request
.httpMethod().utf8(),
3419 response
.mimeType().utf8(),
3420 WebURLRequestToResourceType(request
)));
3423 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3424 DCHECK(!frame_
|| frame_
== frame
);
3425 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3426 render_view_
->GetRoutingID()));
3429 void RenderFrameImpl::didRunInsecureContent(
3430 blink::WebLocalFrame
* frame
,
3431 const blink::WebSecurityOrigin
& origin
,
3432 const blink::WebURL
& target
) {
3433 DCHECK(!frame_
|| frame_
== frame
);
3434 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3435 render_view_
->GetRoutingID(),
3436 origin
.toString().utf8(),
3440 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3441 DCHECK(!frame_
|| frame_
== frame
);
3442 #if defined(ENABLE_PLUGINS)
3443 if (frame
!= render_view_
->webview()->mainFrame())
3445 PluginChannelHost::Broadcast(
3446 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3450 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3451 v8::Handle
<v8::Context
> context
,
3452 int extension_group
,
3454 DCHECK(!frame_
|| frame_
== frame
);
3456 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3457 DidCreateScriptContext(context
, extension_group
, world_id
));
3460 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3461 v8::Handle
<v8::Context
> context
,
3463 DCHECK(!frame_
|| frame_
== frame
);
3465 FOR_EACH_OBSERVER(RenderFrameObserver
,
3467 WillReleaseScriptContext(context
, world_id
));
3470 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3471 blink::WebLocalFrame
* frame
) {
3472 DCHECK(!frame_
|| frame_
== frame
);
3473 if (frame
->parent())
3476 InternalDocumentStateData
* data
=
3477 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3478 data
->set_did_first_visually_non_empty_layout(true);
3480 #if defined(OS_ANDROID)
3481 GetRenderWidget()->DidChangeBodyBackgroundColor(
3482 render_view_
->webwidget_
->backgroundColor());
3485 GetRenderWidget()->QueueMessage(
3486 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3487 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3490 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3491 DCHECK(!frame_
|| frame_
== frame
);
3492 // TODO(nasko): Move implementation here. Needed methods:
3493 // * StartNavStateSyncTimerIfNecessary
3494 render_view_
->didChangeScrollOffset(frame
);
3496 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3499 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3500 DCHECK(!frame_
|| frame_
== frame
);
3501 if (!frame
->parent()) {
3502 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3503 render_view_
->GetRoutingID()));
3507 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3509 bool final_update
) {
3510 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3512 active_match_ordinal
= 0;
3514 render_view_
->Send(new ViewHostMsg_Find_Reply(
3515 render_view_
->GetRoutingID(), request_id
, count
,
3516 gfx::Rect(), active_match_ordinal
, final_update
));
3519 void RenderFrameImpl::reportFindInPageSelection(
3521 int active_match_ordinal
,
3522 const blink::WebRect
& selection_rect
) {
3523 render_view_
->Send(new ViewHostMsg_Find_Reply(
3524 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3525 active_match_ordinal
, false));
3528 void RenderFrameImpl::requestStorageQuota(
3529 blink::WebLocalFrame
* frame
,
3530 blink::WebStorageQuotaType type
,
3531 unsigned long long requested_size
,
3532 blink::WebStorageQuotaCallbacks callbacks
) {
3533 DCHECK(!frame_
|| frame_
== frame
);
3534 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3535 if (origin
.isUnique()) {
3536 // Unique origins cannot store persistent state.
3537 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3540 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3541 render_view_
->GetRoutingID(),
3542 GURL(origin
.toString()),
3543 static_cast<storage::StorageType
>(type
),
3545 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3548 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3549 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3550 impl
->set_render_frame_id(routing_id_
);
3553 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3554 if (!geolocation_dispatcher_
)
3555 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3556 return geolocation_dispatcher_
;
3559 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3560 if (!presentation_dispatcher_
)
3561 presentation_dispatcher_
= new PresentationDispatcher(this);
3562 return presentation_dispatcher_
;
3565 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3566 if (!push_messaging_dispatcher_
)
3567 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3568 return push_messaging_dispatcher_
;
3571 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3572 blink::WebLocalFrame
* frame
,
3573 blink::WebRTCPeerConnectionHandler
* handler
) {
3574 DCHECK(!frame_
|| frame_
== frame
);
3575 #if defined(ENABLE_WEBRTC)
3576 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3580 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3581 if (!web_user_media_client_
)
3582 InitializeUserMediaClient();
3583 return web_user_media_client_
;
3586 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3587 if (!web_encrypted_media_client_
) {
3588 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3589 GetCdmFactory(), GetMediaPermission()));
3591 return web_encrypted_media_client_
.get();
3594 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3595 if (!midi_dispatcher_
)
3596 midi_dispatcher_
= new MidiDispatcher(this);
3597 return midi_dispatcher_
;
3600 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3601 blink::WebLocalFrame
* source_frame
,
3602 blink::WebFrame
* target_frame
,
3603 blink::WebSecurityOrigin target_origin
,
3604 blink::WebDOMMessageEvent event
) {
3605 DCHECK(!frame_
|| frame_
== target_frame
);
3607 // Currently, a postMessage that targets a cross-process frame can be plumbed
3608 // either through this function or RenderFrameProxy::postMessageEvent. This
3609 // function is used when the target cross-process frame is a top-level frame
3610 // which has been swapped out. In that case, the corresponding WebLocalFrame
3611 // currently remains in the frame tree even in site-per-process mode (see
3612 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3613 // --site-per-process mode for all other cases.
3615 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3616 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3617 // cross-process postMessages.
3618 if (!is_swapped_out_
)
3621 // It is possible to get here on a swapped-out frame without a
3622 // |render_frame_proxy_|. This happens when:
3623 // - This process only has one active RenderView and is about to go away
3624 // (e.g., due to cross-process navigation).
3625 // - The top frame has a subframe with an unload handler.
3626 // - The subframe sends a postMessage to the top-level frame in its unload
3628 // See https://crbug.com/475651 for details. We return false here, since we
3629 // don't want to deliver the message to the new process in this case.
3630 if (!render_frame_proxy_
)
3633 render_frame_proxy_
->postMessageEvent(
3634 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3638 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3639 const blink::WebURL
& url
) {
3640 DCHECK(!frame_
|| frame_
== frame
);
3641 std::string user_agent_override_for_url
=
3642 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3643 if (!user_agent_override_for_url
.empty())
3644 return WebString::fromUTF8(user_agent_override_for_url
);
3646 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3647 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3648 return blink::WebString();
3651 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3652 // associated with it, so the checks below are not valid. Temporarily
3653 // return early and fix properly as part of https://crbug.com/426555.
3654 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3655 return blink::WebString();
3657 // If we're in the middle of committing a load, the data source we need
3658 // will still be provisional.
3659 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3660 WebDataSource
* data_source
= NULL
;
3661 if (main_frame
->provisionalDataSource())
3662 data_source
= main_frame
->provisionalDataSource();
3664 data_source
= main_frame
->dataSource();
3666 InternalDocumentStateData
* internal_data
= data_source
?
3667 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3668 if (internal_data
&& internal_data
->is_overriding_user_agent())
3669 return WebString::fromUTF8(
3670 render_view_
->renderer_preferences_
.user_agent_override
);
3671 return blink::WebString();
3674 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3675 DCHECK(!frame_
|| frame_
== frame
);
3676 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3677 return WebString::fromUTF8("1");
3681 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3682 bool default_value
) {
3683 DCHECK(!frame_
|| frame_
== frame
);
3687 bool blocked
= true;
3688 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3689 render_view_
->GetRoutingID(),
3690 GURL(frame
->top()->document().securityOrigin().toString()),
3691 THREE_D_API_TYPE_WEBGL
,
3696 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3697 int arb_robustness_status_code
) {
3698 DCHECK(!frame_
|| frame_
== frame
);
3699 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3700 GURL(frame
->top()->document().securityOrigin().toString()),
3701 THREE_D_API_TYPE_WEBGL
,
3702 arb_robustness_status_code
));
3705 blink::WebScreenOrientationClient
*
3706 RenderFrameImpl::webScreenOrientationClient() {
3707 if (!screen_orientation_dispatcher_
)
3708 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3709 return screen_orientation_dispatcher_
;
3712 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3713 ServiceWorkerNetworkProvider
* provider
=
3714 ServiceWorkerNetworkProvider::FromDocumentState(
3715 DocumentState::FromDataSource(&data_source
));
3716 return provider
->context()->controller_handle_id() !=
3717 kInvalidServiceWorkerHandleId
;
3720 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3721 ServiceWorkerNetworkProvider
* provider
=
3722 ServiceWorkerNetworkProvider::FromDocumentState(
3723 DocumentState::FromDataSource(&data_source
));
3725 if (provider
->context()->controller())
3726 return provider
->context()->controller()->version_id();
3727 return kInvalidServiceWorkerVersionId
;
3730 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3731 blink::WebAXEvent event
) {
3732 HandleWebAccessibilityEvent(obj
, event
);
3735 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3738 const blink::WebAXObject
& start_object
,
3740 const blink::WebAXObject
& end_object
,
3742 if (renderer_accessibility_
) {
3743 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3744 identifier
, match_index
, start_object
, start_offset
,
3745 end_object
, end_offset
);
3749 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3750 DCHECK(!frame_
|| frame_
== frame
);
3752 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3755 void RenderFrameImpl::didChangeDefaultPresentation(
3756 blink::WebLocalFrame
* frame
) {
3757 DCHECK(!frame_
|| frame_
== frame
);
3760 RenderFrameObserver
, observers_
, DidChangeDefaultPresentation());
3763 bool RenderFrameImpl::enterFullscreen() {
3764 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3768 bool RenderFrameImpl::exitFullscreen() {
3769 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3773 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3774 if (!permission_client_
)
3775 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3777 return permission_client_
.get();
3780 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3781 Send(new FrameHostMsg_MediaPlayingNotification(
3782 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3783 player
->hasAudio(), player
->isRemote()));
3786 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3787 Send(new FrameHostMsg_MediaPausedNotification(
3788 routing_id_
, reinterpret_cast<int64
>(player
)));
3791 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3795 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3796 observers_
.AddObserver(observer
);
3799 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3800 observer
->RenderFrameGone();
3801 observers_
.RemoveObserver(observer
);
3804 void RenderFrameImpl::OnStop() {
3806 frame_
->stopLoading();
3807 if (!frame_
->parent())
3808 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3810 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3813 void RenderFrameImpl::WasHidden() {
3814 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3817 void RenderFrameImpl::WasShown() {
3818 // TODO(kenrb): Need to figure out how to do this better. Should
3819 // VisibilityState remain a page-level concept or move to frames?
3820 // The semantics of 'Show' might have to change here.
3821 if (render_widget_
) {
3822 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3823 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3825 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3828 void RenderFrameImpl::WidgetWillClose() {
3829 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3832 bool RenderFrameImpl::IsHidden() {
3833 return GetRenderWidget()->is_hidden();
3836 // Tell the embedding application that the URL of the active page has changed.
3837 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3838 blink::WebFrame
* frame
,
3839 blink::WebHistoryCommitType commit_type
) {
3840 DCHECK(!frame_
|| frame_
== frame
);
3841 WebDataSource
* ds
= frame
->dataSource();
3844 const WebURLRequest
& request
= ds
->request();
3845 const WebURLResponse
& response
= ds
->response();
3847 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3848 NavigationStateImpl
* navigation_state
=
3849 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3850 InternalDocumentStateData
* internal_data
=
3851 InternalDocumentStateData::FromDocumentState(document_state
);
3853 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3854 params
.http_status_code
= response
.httpStatusCode();
3855 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3856 params
.is_post
= false;
3857 params
.intended_as_new_entry
=
3858 navigation_state
->request_params().intended_as_new_entry
;
3859 params
.did_create_new_entry
= commit_type
== blink::WebStandardCommit
;
3860 params
.post_id
= -1;
3861 params
.page_id
= render_view_
->page_id_
;
3862 params
.nav_entry_id
= navigation_state
->request_params().nav_entry_id
;
3863 // We need to track the RenderViewHost routing_id because of downstream
3864 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3865 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3866 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3867 // based on the ID stored in the resource requests. Once those dependencies
3868 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3869 // client to be based on the routing_id of the RenderFrameHost.
3870 params
.render_view_routing_id
= render_view_
->routing_id();
3871 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3872 params
.socket_address
.set_port(response
.remotePort());
3873 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3875 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3876 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3877 params
.security_info
= response
.securityInfo();
3879 // Set the URL to be displayed in the browser UI to the user.
3880 params
.url
= GetLoadingUrl();
3881 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3883 // Set the origin of the frame. This will be replicated to the corresponding
3884 // RenderFrameProxies in other processes.
3885 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3886 // to https://crbug.com/439608 and will be replicated as unique origins.
3887 if (!is_swapped_out_
) {
3888 WebString
serialized_origin(frame
->document().securityOrigin().toString());
3889 if (GURL(serialized_origin
).IsStandard())
3890 params
.origin
= url::Origin(serialized_origin
.utf8());
3893 if (frame
->document().baseURL() != params
.url
)
3894 params
.base_url
= frame
->document().baseURL();
3896 GetRedirectChain(ds
, ¶ms
.redirects
);
3897 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3898 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3900 params
.searchable_form_url
= internal_data
->searchable_form_url();
3901 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3903 params
.gesture
= render_view_
->navigation_gesture_
;
3904 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3906 // Make navigation state a part of the DidCommitProvisionalLoad message so
3907 // that committed entry has it at all times.
3908 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3910 params
.page_state
= HistoryEntryToPageState(entry
);
3912 params
.page_state
= PageState::CreateFromURL(request
.url());
3914 if (!frame
->parent()) {
3915 // Top-level navigation.
3917 // Reset the zoom limits in case a plugin had changed them previously. This
3918 // will also call us back which will cause us to send a message to
3919 // update WebContentsImpl.
3920 render_view_
->webview()->zoomLimitsChanged(
3921 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3922 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3924 // Set zoom level, but don't do it for full-page plugin since they don't use
3925 // the same zoom settings.
3926 HostZoomLevels::iterator host_zoom
=
3927 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3928 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3929 // Reset the zoom levels for plugins.
3930 render_view_
->webview()->setZoomLevel(0);
3932 // If the zoom level is not found, then do nothing. In-page navigation
3933 // relies on not changing the zoom level in this case.
3934 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3935 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3938 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3939 // This zoom level was merely recorded transiently for this load. We can
3940 // erase it now. If at some point we reload this page, the browser will
3941 // send us a new, up-to-date zoom level.
3942 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3945 // Update contents MIME type for main frame.
3946 params
.contents_mime_type
= ds
->response().mimeType().utf8();
3948 params
.transition
= navigation_state
->GetTransitionType();
3949 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
3950 // If the main frame does a load, it should not be reported as a subframe
3951 // navigation. This can occur in the following case:
3952 // 1. You're on a site with frames.
3953 // 2. You do a subframe navigation. This is stored with transition type
3955 // 3. You navigate to some non-frame site, say, google.com.
3956 // 4. You navigate back to the page from step 2. Since it was initially
3957 // MANUAL_SUBFRAME, it will be that same transition type here.
3958 // We don't want that, because any navigation that changes the toplevel
3959 // frame should be tracked as a toplevel navigation (this allows us to
3960 // update the URL bar, etc).
3961 params
.transition
= ui::PAGE_TRANSITION_LINK
;
3964 // If the page contained a client redirect (meta refresh, document.loc...),
3965 // set the referrer and transition appropriately.
3966 if (ds
->isClientRedirect()) {
3968 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
3969 params
.transition
= ui::PageTransitionFromInt(
3970 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3972 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
3973 frame
, ds
->request());
3976 base::string16 method
= request
.httpMethod();
3977 if (EqualsASCII(method
, "POST")) {
3978 params
.is_post
= true;
3979 params
.post_id
= ExtractPostId(entry
);
3982 // Send the user agent override back.
3983 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
3985 // Track the URL of the original request. We use the first entry of the
3986 // redirect chain if it exists because the chain may have started in another
3988 params
.original_request_url
= GetOriginalRequestURL(ds
);
3990 params
.history_list_was_cleared
=
3991 navigation_state
->request_params().should_clear_history_list
;
3993 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
3994 frame
->dataSource()->request().inputPerfMetricReportPolicy());
3995 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
3996 frame
->dataSource()->request().uiStartTime());
3998 // Save some histogram data so we can compute the average memory used per
3999 // page load of the glyphs.
4000 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4001 blink::WebGlyphCache::pageCount());
4003 // This message needs to be sent before any of allowScripts(),
4004 // allowImages(), allowPlugins() is called for the new page, so that when
4005 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4006 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4007 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4009 // Subframe navigation: the type depends on whether this navigation
4010 // generated a new session history entry. When they do generate a session
4011 // history entry, it means the user initiated the navigation and we should
4013 if (commit_type
== blink::WebStandardCommit
)
4014 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4016 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4018 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4019 params
.history_list_was_cleared
= false;
4020 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4022 // Don't send this message while the subframe is swapped out.
4023 if (!is_swapped_out())
4024 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4027 // If we end up reusing this WebRequest (for example, due to a #ref click),
4028 // we don't want the transition type to persist. Just clear it.
4029 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4032 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4033 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4035 render_view_
->FrameDidStartLoading(frame_
);
4036 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4039 void RenderFrameImpl::didStopLoading() {
4040 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4042 render_view_
->FrameDidStopLoading(frame_
);
4043 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4046 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4047 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4050 void RenderFrameImpl::HandleWebAccessibilityEvent(
4051 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4052 if (renderer_accessibility_
)
4053 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4056 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4057 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4060 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4061 if (renderer_accessibility())
4062 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4066 void RenderFrameImpl::OnCommitNavigation(
4067 const ResourceResponseHead
& response
,
4068 const GURL
& stream_url
,
4069 const CommonNavigationParams
& common_params
,
4070 const RequestNavigationParams
& request_params
) {
4071 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4072 switches::kEnableBrowserSideNavigation
));
4073 bool is_reload
= false;
4074 bool is_history_navigation
= request_params
.page_state
.IsValid();
4075 WebURLRequest::CachePolicy cache_policy
=
4076 WebURLRequest::UseProtocolCachePolicy
;
4077 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4078 common_params
.url
, is_history_navigation
, request_params
, &is_reload
,
4080 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4084 GetContentClient()->SetActiveURL(common_params
.url
);
4086 pending_navigation_params_
.reset(new NavigationParams(
4087 common_params
, StartNavigationParams(), request_params
));
4089 if (!common_params
.base_url_for_data_url
.is_empty() ||
4090 common_params
.url
.SchemeIs(url::kDataScheme
)) {
4091 LoadDataURL(common_params
, frame_
);
4095 // Create a WebURLRequest that blink can use to get access to the body of the
4096 // response through a stream in the browser. Blink will then commit the
4098 // TODO(clamy): Have the navigation commit directly, without going through
4099 // loading a WebURLRequest.
4100 scoped_ptr
<StreamOverrideParameters
> stream_override(
4101 new StreamOverrideParameters());
4102 stream_override
->stream_url
= stream_url
;
4103 stream_override
->response
= response
;
4104 WebURLRequest request
=
4105 CreateURLRequestForNavigation(common_params
,
4106 stream_override
.Pass(),
4107 frame_
->isViewSourceModeEnabled());
4109 // Make sure that blink loader will not try to use browser side navigation for
4110 // this request (since it already went to the browser).
4111 request
.setCheckForBrowserSideNavigation(false);
4113 // Record this before starting the load. A lower bound of this time is needed
4114 // to sanitize the navigationStart override set below.
4115 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4116 frame_
->loadRequest(request
);
4117 UpdateFrameNavigationTiming(frame_
, request_params
.browser_navigation_start
,
4118 renderer_navigation_start
);
4121 void RenderFrameImpl::OnFailedNavigation(
4122 const CommonNavigationParams
& common_params
,
4123 const RequestNavigationParams
& request_params
,
4124 bool has_stale_copy_in_cache
,
4126 bool is_reload
= IsReload(common_params
.navigation_type
);
4127 bool is_history_navigation
= request_params
.page_state
.IsValid();
4128 WebURLRequest::CachePolicy cache_policy
=
4129 WebURLRequest::UseProtocolCachePolicy
;
4130 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4131 common_params
.url
, is_history_navigation
, request_params
, &is_reload
,
4133 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4137 GetContentClient()->SetActiveURL(common_params
.url
);
4139 pending_navigation_params_
.reset(new NavigationParams(
4140 common_params
, StartNavigationParams(), request_params
));
4142 // Inform the browser of the start of the provisional load. This is needed so
4143 // that the load is properly tracked by the WebNavigation API.
4144 // TODO(clamy): Properly set is_transition_navigation.
4145 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4146 routing_id_
, common_params
.url
, false));
4148 // Send the provisional load failure.
4149 blink::WebURLError error
=
4150 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4151 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4152 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4153 frame_
->isViewSourceModeEnabled());
4154 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4156 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4157 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4161 // Make sure errors are not shown in view source mode.
4162 frame_
->enableViewSourceMode(false);
4164 // Replace the current history entry in reloads, history navigations and loads
4165 // of the same url. This corresponds to Blink's notion of a standard
4167 // TODO(clamy): see if initial commits in subframes should be handled
4169 bool replace
= is_reload
|| is_history_navigation
||
4170 common_params
.url
== GetLoadingUrl();
4171 LoadNavigationErrorPage(failed_request
, error
, replace
);
4174 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4175 RenderFrame
* render_frame
,
4176 const NavigationPolicyInfo
& info
) {
4178 // The handlenavigation API is deprecated and will be removed once
4179 // crbug.com/325351 is resolved.
4180 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
4181 GetContentClient()->renderer()->HandleNavigation(
4183 static_cast<DocumentState
*>(info
.extraData
),
4184 render_view_
->opener_id_
,
4187 info
.navigationType
,
4190 return blink::WebNavigationPolicyIgnore
;
4194 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4196 const base::CommandLine
& command_line
=
4197 *base::CommandLine::ForCurrentProcess();
4199 bool is_subframe
= !!info
.frame
->parent();
4201 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe
) {
4202 // There's no reason to ignore navigations on subframes, since the swap out
4203 // logic no longer applies.
4205 if (is_swapped_out_
) {
4206 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4207 // Targeted links may try to navigate a swapped out frame. Allow the
4208 // browser process to navigate the tab instead. Note that it is also
4209 // possible for non-targeted navigations (from this view) to arrive
4210 // here just after we are swapped out. It's ok to send them to the
4211 // browser, as long as they're for the top level frame.
4212 // TODO(creis): Ensure this supports targeted form submissions when
4213 // fixing http://crbug.com/101395.
4214 if (info
.frame
->parent() == NULL
) {
4215 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4216 info
.defaultPolicy
);
4217 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4220 // We should otherwise ignore in-process iframe navigations, if they
4221 // arrive just after we are swapped out.
4222 return blink::WebNavigationPolicyIgnore
;
4225 // Allow kSwappedOutURL to complete.
4226 return info
.defaultPolicy
;
4230 // Webkit is asking whether to navigate to a new URL.
4231 // This is fine normally, except if we're showing UI from one security
4232 // context and they're trying to navigate to a different context.
4233 const GURL
& url
= info
.urlRequest
.url();
4235 // A content initiated navigation may have originated from a link-click,
4236 // script, drag-n-drop operation, etc.
4237 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4238 bool is_content_initiated
=
4239 document_state
->navigation_state()->IsContentInitiated();
4242 // If --enable-strict-site-isolation is enabled, send all top-level
4243 // navigations to the browser to let it swap processes when crossing site
4244 // boundaries. This is currently expected to break some script calls and
4245 // navigations, such as form submissions.
4246 bool force_swap_due_to_flag
=
4247 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
);
4248 if (force_swap_due_to_flag
&&
4249 !info
.frame
->parent() && (is_content_initiated
|| info
.isRedirect
)) {
4250 WebString origin_str
= info
.frame
->document().securityOrigin().toString();
4251 GURL
frame_url(origin_str
.utf8().data());
4252 // TODO(cevans): revisit whether this site check is still necessary once
4253 // crbug.com/101395 is fixed.
4254 bool same_domain_or_host
=
4255 net::registry_controlled_domains::SameDomainOrHost(
4258 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
4259 // Only keep same-site (domain + scheme) and data URLs in the same process.
4261 (same_domain_or_host
&& frame_url
.scheme() == url
.scheme()) ||
4262 url
.SchemeIs(url::kDataScheme
);
4263 if (!is_same_site
) {
4264 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4265 return blink::WebNavigationPolicyIgnore
;
4269 // If the browser is interested, then give it a chance to look at the request.
4270 if (is_content_initiated
) {
4272 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4273 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4274 EqualsASCII(info
.urlRequest
.httpMethod(), "POST");
4275 bool browser_handles_request
=
4276 render_view_
->renderer_preferences_
4277 .browser_handles_non_local_top_level_requests
4278 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4280 if (!browser_handles_request
) {
4281 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4282 render_view_
->renderer_preferences_
4283 .browser_handles_all_top_level_requests
;
4286 if (browser_handles_request
) {
4287 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4288 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4292 // Use the frame's original request's URL rather than the document's URL for
4293 // subsequent checks. For a popup, the document's URL may become the opener
4294 // window's URL if the opener has called document.write().
4295 // See http://crbug.com/93517.
4296 GURL
old_url(info
.frame
->dataSource()->request().url());
4298 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4299 // an extension or app origin, leaving a WebUI page, etc). We only care about
4300 // top-level navigations (not iframes). But we sometimes navigate to
4301 // about:blank to clear a tab, and we want to still allow that.
4303 // Note: this is known to break POST submissions when crossing process
4304 // boundaries until http://crbug.com/101395 is fixed. This is better for
4305 // security than loading a WebUI, extension or app page in the wrong process.
4306 // POST requests don't work because this mechanism does not preserve form
4307 // POST data. We will need to send the request's httpBody data up to the
4308 // browser process, and issue a special POST navigation in WebKit (via
4309 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4310 // for examples of how to send the httpBody data.
4311 if (!info
.frame
->parent() && is_content_initiated
&&
4312 !url
.SchemeIs(url::kAboutScheme
)) {
4313 bool send_referrer
= false;
4315 // All navigations to or from WebUI URLs or within WebUI-enabled
4316 // RenderProcesses must be handled by the browser process so that the
4317 // correct bindings and data sources can be registered.
4318 // Similarly, navigations to view-source URLs or within ViewSource mode
4319 // must be handled by the browser process (except for reloads - those are
4320 // safe to leave within the renderer).
4321 // Lastly, access to file:// URLs from non-file:// URL pages must be
4322 // handled by the browser so that ordinary renderer processes don't get
4323 // blessed with file permissions.
4324 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4325 bool is_initial_navigation
= render_view_
->page_id_
== -1;
4326 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4327 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4328 url
.SchemeIs(kViewSourceScheme
) ||
4329 (info
.frame
->isViewSourceModeEnabled() &&
4330 info
.navigationType
!= blink::WebNavigationTypeReload
);
4332 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4333 // Fork non-file to file opens. Check the opener URL if this is the
4334 // initial navigation in a newly opened window.
4335 GURL
source_url(old_url
);
4336 if (is_initial_navigation
&& source_url
.is_empty() &&
4337 info
.frame
->opener())
4338 source_url
= info
.frame
->opener()->top()->document().url();
4339 DCHECK(!source_url
.is_empty());
4340 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4344 // Give the embedder a chance.
4345 should_fork
= GetContentClient()->renderer()->ShouldFork(
4346 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4347 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4351 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4352 info
.defaultPolicy
);
4353 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4357 // Detect when a page is "forking" a new tab that can be safely rendered in
4358 // its own process. This is done by sites like Gmail that try to open links
4359 // in new windows without script connections back to the original page. We
4360 // treat such cases as browser navigations (in which we will create a new
4361 // renderer for a cross-site navigation), rather than WebKit navigations.
4363 // We use the following heuristic to decide whether to fork a new page in its
4365 // The parent page must open a new tab to about:blank, set the new tab's
4366 // window.opener to null, and then redirect the tab to a cross-site URL using
4369 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4372 // Must start from a tab showing about:blank, which is later redirected.
4373 old_url
== GURL(url::kAboutBlankURL
) &&
4374 // Must be the first real navigation of the tab.
4375 render_view_
->historyBackListCount() < 1 &&
4376 render_view_
->historyForwardListCount() < 1 &&
4377 // The parent page must have set the child's window.opener to null before
4378 // redirecting to the desired URL.
4379 info
.frame
->opener() == NULL
&&
4380 // Must be a top-level frame.
4381 info
.frame
->parent() == NULL
&&
4382 // Must not have issued the request from this page.
4383 is_content_initiated
&&
4384 // Must be targeted at the current tab.
4385 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4386 // Must be a JavaScript navigation, which appears as "other".
4387 info
.navigationType
== blink::WebNavigationTypeOther
;
4390 // Open the URL via the browser, not via WebKit.
4391 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4392 return blink::WebNavigationPolicyIgnore
;
4395 // PlzNavigate: send the request to the browser if needed.
4396 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4397 switches::kEnableBrowserSideNavigation
) &&
4398 info
.urlRequest
.checkForBrowserSideNavigation()) {
4399 BeginNavigation(&info
.urlRequest
);
4400 return blink::WebNavigationPolicyIgnore
;
4403 return info
.defaultPolicy
;
4406 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4408 const Referrer
& referrer
,
4409 WebNavigationPolicy policy
) {
4410 DCHECK_EQ(frame_
, frame
);
4412 FrameHostMsg_OpenURL_Params params
;
4414 params
.referrer
= referrer
;
4415 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4416 WebDataSource
* ds
= frame
->provisionalDataSource();
4418 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4419 NavigationStateImpl
* navigation_state
=
4420 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4421 if (navigation_state
->IsContentInitiated()) {
4422 params
.should_replace_current_entry
=
4423 ds
->replacesCurrentHistoryItem() &&
4424 render_view_
->history_list_length_
;
4426 // This is necessary to preserve the should_replace_current_entry value on
4427 // cross-process redirects, in the event it was set by a previous process.
4429 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4430 // NavigationState::should_replace_current_entry().
4431 params
.should_replace_current_entry
=
4432 navigation_state
->start_params().should_replace_current_entry
;
4435 params
.should_replace_current_entry
= false;
4437 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4438 if (GetContentClient()->renderer()->AllowPopup())
4439 params
.user_gesture
= true;
4441 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4442 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4443 policy
== blink::WebNavigationPolicyNewWindow
||
4444 policy
== blink::WebNavigationPolicyNewPopup
) {
4445 WebUserGestureIndicator::consumeUserGesture();
4448 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4451 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4452 const std::string
& encoding_name
) {
4453 // Only update main frame's encoding_name.
4454 if (!frame
->parent())
4455 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4458 void RenderFrameImpl::SyncSelectionIfRequired() {
4459 base::string16 text
;
4462 #if defined(ENABLE_PLUGINS)
4463 if (render_view_
->focused_pepper_plugin_
) {
4464 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4465 offset
= 0; // Pepper API does not support offset reporting.
4466 // TODO(kinaba): cut as needed.
4470 size_t location
, length
;
4471 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4472 &location
, &length
)) {
4476 range
= gfx::Range(location
, location
+ length
);
4478 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4479 blink::WebTextInputTypeNone
) {
4480 // If current focused element is editable, we will send 100 more chars
4481 // before and after selection. It is for input method surrounding text
4483 if (location
> kExtraCharsBeforeAndAfterSelection
)
4484 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4487 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4488 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4489 if (!webrange
.isNull())
4490 text
= webrange
.toPlainText();
4493 text
= frame_
->selectionAsText();
4494 // http://crbug.com/101435
4495 // In some case, frame->selectionAsText() returned text's length is not
4496 // equal to the length returned from webwidget()->caretOrSelectionRange().
4497 // So we have to set the range according to text.length().
4498 range
.set_end(range
.start() + text
.length());
4502 // Sometimes we get repeated didChangeSelection calls from webkit when
4503 // the selection hasn't actually changed. We don't want to report these
4504 // because it will cause us to continually claim the X clipboard.
4505 if (selection_text_offset_
!= offset
||
4506 selection_range_
!= range
||
4507 selection_text_
!= text
) {
4508 selection_text_
= text
;
4509 selection_text_offset_
= offset
;
4510 selection_range_
= range
;
4511 SetSelectedText(text
, offset
, range
);
4513 GetRenderWidget()->UpdateSelectionBounds();
4516 void RenderFrameImpl::InitializeUserMediaClient() {
4517 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4520 #if defined(OS_ANDROID)
4521 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4522 switches::kDisableWebRTC
))
4526 #if defined(ENABLE_WEBRTC)
4527 DCHECK(!web_user_media_client_
);
4528 web_user_media_client_
= new UserMediaClientImpl(
4530 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4531 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4535 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4536 const blink::WebURL
& url
,
4537 WebMediaPlayerClient
* client
) {
4538 #if defined(ENABLE_WEBRTC)
4539 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4541 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4542 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4543 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4544 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4545 new RenderMediaLog(),
4546 CreateRendererFactory());
4549 #endif // defined(ENABLE_WEBRTC)
4552 scoped_ptr
<MediaStreamRendererFactory
>
4553 RenderFrameImpl::CreateRendererFactory() {
4554 #if defined(ENABLE_WEBRTC)
4555 return scoped_ptr
<MediaStreamRendererFactory
>(
4556 new MediaStreamRendererFactory());
4558 return scoped_ptr
<MediaStreamRendererFactory
>(
4559 static_cast<MediaStreamRendererFactory
*>(NULL
));
4563 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4565 bool is_history_navigation
,
4566 const RequestNavigationParams
& request_params
,
4568 WebURLRequest::CachePolicy
* cache_policy
) {
4569 MaybeHandleDebugURL(url
);
4570 if (!render_view_
->webview())
4574 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4576 // If this is a stale back/forward (due to a recent navigation the browser
4577 // didn't know about), ignore it. Only check if swapped in because if the
4578 // frame is swapped out, it won't commit before asking the browser.
4579 if (!render_view_
->is_swapped_out() && is_history_navigation
&&
4580 render_view_
->history_list_offset_
!=
4581 request_params
.current_history_list_offset
) {
4585 render_view_
->history_list_offset_
=
4586 request_params
.current_history_list_offset
;
4587 render_view_
->history_list_length_
=
4588 request_params
.current_history_list_length
;
4589 if (request_params
.should_clear_history_list
) {
4590 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4591 CHECK_EQ(0, render_view_
->history_list_length_
);
4594 if (!is_swapped_out_
|| frame_
->parent())
4597 // This is a swapped out main frame, so swap the renderer back in.
4598 // We marked the view as hidden when swapping the view out, so be sure to
4599 // reset the visibility state before navigating to the new URL.
4600 render_view_
->webview()->setVisibilityState(
4601 render_view_
->visibilityState(), false);
4603 // If this is an attempt to reload while we are swapped out, we should not
4604 // reload swappedout://, but the previous page, which is stored in
4605 // params.state. Setting is_reload to false will treat this like a back
4606 // navigation to accomplish that.
4608 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4610 // We refresh timezone when a view is swapped in since timezone
4611 // can get out of sync when the system timezone is updated while
4612 // the view is swapped out.
4613 RenderThreadImpl::NotifyTimezoneChange();
4615 render_view_
->SetSwappedOut(false);
4616 is_swapped_out_
= false;
4620 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4621 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4622 switches::kEnableBrowserSideNavigation
));
4624 // TODO(clamy): Execute the beforeunload event.
4626 // Note: At this stage, the goal is to apply all the modifications the
4627 // renderer wants to make to the request, and then send it to the browser, so
4628 // that the actual network request can be started. Ideally, all such
4629 // modifications should take place in willSendRequest, and in the
4630 // implementation of willSendRequest for the various InspectorAgents
4633 // TODO(clamy): Apply devtools override.
4634 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4636 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4638 // TODO(clamy): Same-document navigations should not be sent back to the
4640 // TODO(clamy): Data urls should not be sent back to the browser either.
4641 Send(new FrameHostMsg_DidStartLoading(routing_id_
, true));
4642 Send(new FrameHostMsg_BeginNavigation(
4643 routing_id_
, MakeCommonNavigationParams(request
),
4644 BeginNavigationParams(request
->httpMethod().latin1(),
4645 GetWebURLRequestHeaders(*request
),
4646 GetLoadFlagsForWebURLRequest(*request
),
4647 request
->hasUserGesture()),
4648 GetRequestBodyForWebURLRequest(*request
)));
4651 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4653 // A loadData request with a specified base URL.
4654 std::string mime_type
, charset
, data
;
4655 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4656 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4657 params
.url
: params
.base_url_for_data_url
;
4659 WebData(data
.c_str(), data
.length()),
4660 WebString::fromUTF8(mime_type
),
4661 WebString::fromUTF8(charset
),
4663 params
.history_url_for_data_url
,
4666 CHECK(false) << "Invalid URL passed: "
4667 << params
.url
.possibly_invalid_spec();
4671 void RenderFrameImpl::SendFailedProvisionalLoad(
4672 const blink::WebURLRequest
& request
,
4673 const blink::WebURLError
& error
,
4674 blink::WebLocalFrame
* frame
) {
4675 bool show_repost_interstitial
= (error
.reason
== net::ERR_CACHE_MISS
&&
4676 EqualsASCII(request
.httpMethod(), "POST"));
4678 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4679 params
.error_code
= error
.reason
;
4680 GetContentClient()->renderer()->GetNavigationErrorStrings(
4681 render_view_
.get(), frame
, request
, error
, NULL
,
4682 ¶ms
.error_description
);
4683 params
.url
= error
.unreachableURL
;
4684 params
.showing_repost_interstitial
= show_repost_interstitial
;
4685 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4688 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4690 const GURL
& unreachable_url
) {
4691 // Don't display an error page if this is simply a cancelled load. Aside
4692 // from being dumb, Blink doesn't expect it and it will cause a crash.
4693 if (error_code
== net::ERR_ABORTED
)
4696 // Don't display "client blocked" error page if browser has asked us not to.
4697 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4698 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4702 // Allow the embedder to suppress an error page.
4703 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4704 this, unreachable_url
)) {
4708 if (RenderThreadImpl::current() &&
4709 RenderThreadImpl::current()->layout_test_mode()) {
4716 GURL
RenderFrameImpl::GetLoadingUrl() const {
4717 WebDataSource
* ds
= frame_
->dataSource();
4718 if (ds
->hasUnreachableURL())
4719 return ds
->unreachableURL();
4721 const WebURLRequest
& request
= ds
->request();
4722 return request
.url();
4725 void RenderFrameImpl::PopulateDocumentStateFromPending(
4726 DocumentState
* document_state
) {
4727 document_state
->set_request_time(
4728 pending_navigation_params_
->request_params
.request_time
);
4730 InternalDocumentStateData
* internal_data
=
4731 InternalDocumentStateData::FromDocumentState(document_state
);
4733 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4734 url::kJavaScriptScheme
) &&
4735 pending_navigation_params_
->common_params
.navigation_type
==
4736 FrameMsg_Navigate_Type::RESTORE
) {
4737 // We're doing a load of a page that was restored from the last session. By
4738 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4739 // can result in stale data for pages that are set to expire. We explicitly
4740 // override that by setting the policy here so that as necessary we load
4741 // from the network.
4743 // TODO(davidben): Remove this in favor of passing a cache policy to the
4744 // loadHistoryItem call in OnNavigate. That requires not overloading
4745 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4746 // policy based on load type, etc".
4747 internal_data
->set_cache_policy_override(
4748 WebURLRequest::UseProtocolCachePolicy
);
4751 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4752 document_state
->set_load_type(DocumentState::RELOAD
);
4753 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4754 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4756 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4758 internal_data
->set_is_overriding_user_agent(
4759 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4760 internal_data
->set_must_reset_scroll_and_scale_state(
4761 pending_navigation_params_
->common_params
.navigation_type
==
4762 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4763 document_state
->set_can_load_local_resources(
4764 pending_navigation_params_
->request_params
.can_load_local_resources
);
4767 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4768 // A navigation resulting from loading a javascript URL should not be treated
4769 // as a browser initiated event. Instead, we want it to look as if the page
4770 // initiated any load resulting from JS execution.
4771 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4772 url::kJavaScriptScheme
)) {
4773 return NavigationStateImpl::CreateBrowserInitiated(
4774 pending_navigation_params_
->common_params
,
4775 pending_navigation_params_
->start_params
,
4776 pending_navigation_params_
->request_params
);
4778 return NavigationStateImpl::CreateContentInitiated();
4781 #if defined(OS_ANDROID)
4783 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4784 const blink::WebURL
& url
,
4785 WebMediaPlayerClient
* client
,
4786 media::MediaPermission
* media_permission
,
4787 blink::WebContentDecryptionModule
* initial_cdm
) {
4788 GpuChannelHost
* gpu_channel_host
=
4789 RenderThreadImpl::current()->EstablishGpuChannelSync(
4790 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4791 if (!gpu_channel_host
) {
4792 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4796 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4797 if (SynchronousCompositorFactory
* factory
=
4798 SynchronousCompositorFactory::GetInstance()) {
4799 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4801 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4802 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4804 if (!context_provider
.get()) {
4805 LOG(ERROR
) << "Failed to get context3d for media player";
4809 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4810 context_provider
, gpu_channel_host
, routing_id_
);
4813 return new WebMediaPlayerAndroid(
4814 frame_
, client
, weak_factory_
.GetWeakPtr(), GetMediaPlayerManager(),
4815 GetCdmFactory(), media_permission
, initial_cdm
, stream_texture_factory
,
4816 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4817 new RenderMediaLog());
4820 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4821 if (!media_player_manager_
)
4822 media_player_manager_
= new RendererMediaPlayerManager(this);
4823 return media_player_manager_
;
4826 #endif // defined(OS_ANDROID)
4828 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4829 if (!media_permission_dispatcher_
)
4830 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
4831 return media_permission_dispatcher_
;
4834 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
4835 #if defined(ENABLE_BROWSER_CDMS)
4837 cdm_manager_
= new RendererCdmManager(this);
4838 #endif // defined(ENABLE_BROWSER_CDMS)
4840 if (!cdm_factory_
) {
4842 cdm_factory_
= new RenderCdmFactory(
4843 #if defined(ENABLE_PEPPER_CDMS)
4844 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
),
4845 #elif defined(ENABLE_BROWSER_CDMS)
4851 return cdm_factory_
;
4854 } // namespace content