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/kill.h"
18 #include "base/process/process.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/plugin_messages.h"
24 #include "content/child/quota_dispatcher.h"
25 #include "content/child/request_extra_data.h"
26 #include "content/child/service_worker/service_worker_handle_reference.h"
27 #include "content/child/service_worker/service_worker_network_provider.h"
28 #include "content/child/service_worker/service_worker_provider_context.h"
29 #include "content/child/service_worker/web_service_worker_provider_impl.h"
30 #include "content/child/web_url_loader_impl.h"
31 #include "content/child/web_url_request_util.h"
32 #include "content/child/webmessageportchannel_impl.h"
33 #include "content/child/websocket_bridge.h"
34 #include "content/child/weburlresponse_extradata_impl.h"
35 #include "content/common/clipboard_messages.h"
36 #include "content/common/frame_messages.h"
37 #include "content/common/frame_replication_state.h"
38 #include "content/common/input_messages.h"
39 #include "content/common/service_worker/service_worker_types.h"
40 #include "content/common/swapped_out_messages.h"
41 #include "content/common/view_messages.h"
42 #include "content/public/common/bindings_policy.h"
43 #include "content/public/common/content_constants.h"
44 #include "content/public/common/content_switches.h"
45 #include "content/public/common/context_menu_params.h"
46 #include "content/public/common/page_state.h"
47 #include "content/public/common/resource_response.h"
48 #include "content/public/common/url_constants.h"
49 #include "content/public/common/url_utils.h"
50 #include "content/public/renderer/browser_plugin_delegate.h"
51 #include "content/public/renderer/content_renderer_client.h"
52 #include "content/public/renderer/context_menu_client.h"
53 #include "content/public/renderer/document_state.h"
54 #include "content/public/renderer/navigation_state.h"
55 #include "content/public/renderer/render_frame_observer.h"
56 #include "content/public/renderer/renderer_ppapi_host.h"
57 #include "content/renderer/accessibility/renderer_accessibility.h"
58 #include "content/renderer/browser_plugin/browser_plugin.h"
59 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
60 #include "content/renderer/child_frame_compositing_helper.h"
61 #include "content/renderer/context_menu_params_builder.h"
62 #include "content/renderer/devtools/devtools_agent.h"
63 #include "content/renderer/dom_automation_controller.h"
64 #include "content/renderer/dom_utils.h"
65 #include "content/renderer/external_popup_menu.h"
66 #include "content/renderer/geolocation_dispatcher.h"
67 #include "content/renderer/history_controller.h"
68 #include "content/renderer/history_serialization.h"
69 #include "content/renderer/image_loading_helper.h"
70 #include "content/renderer/ime_event_guard.h"
71 #include "content/renderer/internal_document_state_data.h"
72 #include "content/renderer/manifest/manifest_manager.h"
73 #include "content/renderer/media/audio_renderer_mixer_manager.h"
74 #include "content/renderer/media/crypto/render_cdm_factory.h"
75 #include "content/renderer/media/media_permission_dispatcher.h"
76 #include "content/renderer/media/media_stream_dispatcher.h"
77 #include "content/renderer/media/media_stream_renderer_factory.h"
78 #include "content/renderer/media/midi_dispatcher.h"
79 #include "content/renderer/media/render_media_log.h"
80 #include "content/renderer/media/user_media_client_impl.h"
81 #include "content/renderer/media/webmediaplayer_ms.h"
82 #include "content/renderer/mojo/service_registry_js_wrapper.h"
83 #include "content/renderer/notification_permission_dispatcher.h"
84 #include "content/renderer/npapi/plugin_channel_host.h"
85 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
86 #include "content/renderer/presentation/presentation_dispatcher.h"
87 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
88 #include "content/renderer/render_frame_proxy.h"
89 #include "content/renderer/render_process.h"
90 #include "content/renderer/render_thread_impl.h"
91 #include "content/renderer/render_view_impl.h"
92 #include "content/renderer/render_widget_fullscreen_pepper.h"
93 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
94 #include "content/renderer/renderer_webcolorchooser_impl.h"
95 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
96 #include "content/renderer/shared_worker_repository.h"
97 #include "content/renderer/v8_value_converter_impl.h"
98 #include "content/renderer/websharedworker_proxy.h"
99 #include "gin/modules/module_registry.h"
100 #include "media/base/audio_renderer_mixer_input.h"
101 #include "media/base/media_log.h"
102 #include "media/blink/webcontentdecryptionmodule_impl.h"
103 #include "media/blink/webencryptedmediaclient_impl.h"
104 #include "media/blink/webmediaplayer_impl.h"
105 #include "media/blink/webmediaplayer_params.h"
106 #include "media/filters/gpu_video_accelerator_factories.h"
107 #include "net/base/data_url.h"
108 #include "net/base/net_errors.h"
109 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
110 #include "net/http/http_util.h"
111 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
112 #include "third_party/WebKit/public/platform/WebString.h"
113 #include "third_party/WebKit/public/platform/WebURL.h"
114 #include "third_party/WebKit/public/platform/WebURLError.h"
115 #include "third_party/WebKit/public/platform/WebURLResponse.h"
116 #include "third_party/WebKit/public/platform/WebVector.h"
117 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
118 #include "third_party/WebKit/public/web/WebDocument.h"
119 #include "third_party/WebKit/public/web/WebFrameWidget.h"
120 #include "third_party/WebKit/public/web/WebGlyphCache.h"
121 #include "third_party/WebKit/public/web/WebLocalFrame.h"
122 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
123 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
124 #include "third_party/WebKit/public/web/WebPlugin.h"
125 #include "third_party/WebKit/public/web/WebPluginParams.h"
126 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
127 #include "third_party/WebKit/public/web/WebRange.h"
128 #include "third_party/WebKit/public/web/WebScriptSource.h"
129 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
130 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
131 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
132 #include "third_party/WebKit/public/web/WebSurroundingText.h"
133 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
134 #include "third_party/WebKit/public/web/WebView.h"
135 #include "third_party/mojo/src/mojo/edk/js/core.h"
136 #include "third_party/mojo/src/mojo/edk/js/support.h"
138 #if defined(ENABLE_PLUGINS)
139 #include "content/renderer/npapi/webplugin_impl.h"
140 #include "content/renderer/pepper/pepper_browser_connection.h"
141 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
142 #include "content/renderer/pepper/pepper_webplugin_impl.h"
143 #include "content/renderer/pepper/plugin_module.h"
146 #if defined(ENABLE_WEBRTC)
147 #include "content/renderer/media/rtc_peer_connection_handler.h"
150 #if defined(OS_ANDROID)
151 #include <cpu-features.h>
153 #include "content/common/gpu/client/context_provider_command_buffer.h"
154 #include "content/renderer/android/synchronous_compositor_factory.h"
155 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
156 #include "content/renderer/media/android/renderer_media_player_manager.h"
157 #include "content/renderer/media/android/stream_texture_factory_impl.h"
158 #include "content/renderer/media/android/webmediaplayer_android.h"
160 #include "cc/blink/context_provider_web_context.h"
163 #if defined(ENABLE_PEPPER_CDMS)
164 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
165 #elif defined(ENABLE_BROWSER_CDMS)
166 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
169 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
170 #include "content/renderer/media/media_renderer_service_provider.h"
171 #include "media/mojo/services/mojo_renderer_factory.h"
173 #include "media/filters/default_renderer_factory.h"
176 using blink::WebContextMenuData
;
177 using blink::WebData
;
178 using blink::WebDataSource
;
179 using blink::WebDocument
;
180 using blink::WebElement
;
181 using blink::WebExternalPopupMenu
;
182 using blink::WebExternalPopupMenuClient
;
183 using blink::WebFrame
;
184 using blink::WebHistoryItem
;
185 using blink::WebHTTPBody
;
186 using blink::WebLocalFrame
;
187 using blink::WebMediaPlayer
;
188 using blink::WebMediaPlayerClient
;
189 using blink::WebNavigationPolicy
;
190 using blink::WebNavigationType
;
191 using blink::WebNode
;
192 using blink::WebPluginParams
;
193 using blink::WebPopupMenuInfo
;
194 using blink::WebRange
;
195 using blink::WebReferrerPolicy
;
196 using blink::WebScriptSource
;
197 using blink::WebSearchableFormData
;
198 using blink::WebSecurityOrigin
;
199 using blink::WebSecurityPolicy
;
200 using blink::WebServiceWorkerProvider
;
201 using blink::WebStorageQuotaCallbacks
;
202 using blink::WebString
;
204 using blink::WebURLError
;
205 using blink::WebURLRequest
;
206 using blink::WebURLResponse
;
207 using blink::WebUserGestureIndicator
;
208 using blink::WebVector
;
209 using blink::WebView
;
211 using base::TimeDelta
;
217 const char kDefaultAcceptHeader
[] =
218 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
220 const char kAcceptHeader
[] = "Accept";
222 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
224 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
225 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
226 LAZY_INSTANCE_INITIALIZER
;
228 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
229 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
231 int64
ExtractPostId(const WebHistoryItem
& item
) {
235 if (item
.httpBody().isNull())
238 return item
.httpBody().identifier();
241 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
242 const WebURLResponse
& response
) {
243 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
246 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
247 // Replace any occurrences of swappedout:// with about:blank.
248 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
249 WebVector
<WebURL
> urls
;
250 ds
->redirectChain(urls
);
251 result
->reserve(urls
.size());
252 for (size_t i
= 0; i
< urls
.size(); ++i
) {
253 if (urls
[i
] != GURL(kSwappedOutURL
))
254 result
->push_back(urls
[i
]);
256 result
->push_back(blank_url
);
260 // Returns the original request url. If there is no redirect, the original
261 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
262 // frame was loaded by loadData, the original url will be ds->unreachableURL()
263 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
264 // WebDataSource has unreachable URL means that the frame is loaded through
265 // blink::WebFrame::loadData(), and the base URL will be in the redirect
266 // chain. However, we never visited the baseURL. So in this case, we should
267 // use the unreachable URL as the original URL.
268 if (ds
->hasUnreachableURL())
269 return ds
->unreachableURL();
271 std::vector
<GURL
> redirects
;
272 GetRedirectChain(ds
, &redirects
);
273 if (!redirects
.empty())
274 return redirects
.at(0);
276 return ds
->originalRequest().url();
279 NOINLINE
void CrashIntentionally() {
280 // NOTE(shess): Crash directly rather than using NOTREACHED() so
281 // that the signature is easier to triage in crash reports.
282 volatile int* zero
= NULL
;
286 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
287 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
288 // NOTE(rogerm): We intentionally perform an invalid heap access here in
289 // order to trigger an Address Sanitizer (ASAN) error report.
290 const char kCrashDomain
[] = "crash";
291 const char kHeapOverflow
[] = "/heap-overflow";
292 const char kHeapUnderflow
[] = "/heap-underflow";
293 const char kUseAfterFree
[] = "/use-after-free";
294 #if defined(SYZYASAN)
295 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
296 const char kCorruptHeap
[] = "/corrupt-heap";
299 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
305 std::string
crash_type(url
.path());
306 if (crash_type
== kHeapOverflow
) {
307 base::debug::AsanHeapOverflow();
308 } else if (crash_type
== kHeapUnderflow
) {
309 base::debug::AsanHeapUnderflow();
310 } else if (crash_type
== kUseAfterFree
) {
311 base::debug::AsanHeapUseAfterFree();
312 #if defined(SYZYASAN)
313 } else if (crash_type
== kCorruptHeapBlock
) {
314 base::debug::AsanCorruptHeapBlock();
315 } else if (crash_type
== kCorruptHeap
) {
316 base::debug::AsanCorruptHeap();
320 #endif // ADDRESS_SANITIZER || SYZYASAN
322 void MaybeHandleDebugURL(const GURL
& url
) {
323 if (!url
.SchemeIs(kChromeUIScheme
))
325 if (url
== GURL(kChromeUICrashURL
)) {
326 CrashIntentionally();
327 } else if (url
== GURL(kChromeUIDumpURL
)) {
328 // This URL will only correctly create a crash dump file if content is
329 // hosted in a process that has correctly called
330 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
331 // of base::debug::DumpWithoutCrashing for more details.
332 base::debug::DumpWithoutCrashing();
333 } else if (url
== GURL(kChromeUIKillURL
)) {
334 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
335 } else if (url
== GURL(kChromeUIHangURL
)) {
337 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
339 } else if (url
== GURL(kChromeUIShorthangURL
)) {
340 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
343 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
344 MaybeTriggerAsanError(url
);
345 #endif // ADDRESS_SANITIZER || SYZYASAN
348 // Returns false unless this is a top-level navigation.
349 bool IsTopLevelNavigation(WebFrame
* frame
) {
350 return frame
->parent() == NULL
;
353 // Returns false unless this is a top-level navigation that crosses origins.
354 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
356 WebNavigationType type
,
358 if (!IsTopLevelNavigation(frame
))
361 // Navigations initiated within Webkit are not sent out to the external host
362 // in the following cases.
363 // 1. The url scheme is not http/https
364 // 2. The origin of the url and the opener is the same in which case the
365 // opener relationship is maintained.
366 // 3. Reloads/form submits/back forward navigations
367 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
370 if (type
!= blink::WebNavigationTypeReload
&&
371 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
372 // The opener relationship between the new window and the parent allows the
373 // new window to script the parent and vice versa. This is not allowed if
374 // the origins of the two domains are different. This can be treated as a
375 // top level navigation and routed back to the host.
376 blink::WebFrame
* opener
= frame
->opener();
380 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
386 WebURLRequest
CreateURLRequestForNavigation(
387 const CommonNavigationParams
& common_params
,
388 const RequestNavigationParams
& request_params
,
389 scoped_ptr
<StreamOverrideParameters
> stream_override
,
390 bool is_view_source_mode_enabled
) {
391 WebURLRequest
request(common_params
.url
);
392 if (is_view_source_mode_enabled
)
393 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
395 if (common_params
.referrer
.url
.is_valid()) {
396 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
397 common_params
.referrer
.policy
,
399 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
400 if (!web_referrer
.isEmpty())
401 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
404 if (!request_params
.extra_headers
.empty()) {
405 for (net::HttpUtil::HeadersIterator
i(request_params
.extra_headers
.begin(),
406 request_params
.extra_headers
.end(),
409 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
410 WebString::fromUTF8(i
.values()));
414 if (request_params
.is_post
) {
415 request
.setHTTPMethod(WebString::fromUTF8("POST"));
418 WebHTTPBody http_body
;
419 http_body
.initialize();
420 const char* data
= NULL
;
421 if (request_params
.browser_initiated_post_data
.size()) {
422 data
= reinterpret_cast<const char*>(
423 &request_params
.browser_initiated_post_data
.front());
425 http_body
.appendData(
426 WebData(data
, request_params
.browser_initiated_post_data
.size()));
427 request
.setHTTPBody(http_body
);
430 RequestExtraData
* extra_data
= new RequestExtraData();
431 extra_data
->set_stream_override(stream_override
.Pass());
432 request
.setExtraData(extra_data
);
434 // Set the ui timestamp for this navigation. Currently the timestamp here is
435 // only non empty when the navigation was triggered by an Android intent. The
436 // timestamp is converted to a double version supported by blink. It will be
437 // passed back to the browser in the DidCommitProvisionalLoad and the
438 // DocumentLoadComplete IPCs.
439 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
440 request
.setUiStartTime(ui_timestamp
.InSecondsF());
441 request
.setInputPerfMetricReportPolicy(
442 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
443 common_params
.report_type
));
447 void UpdateFrameNavigationTiming(WebFrame
* frame
,
448 base::TimeTicks browser_navigation_start
,
449 base::TimeTicks renderer_navigation_start
) {
450 // The browser provides the navigation_start time to bootstrap the
451 // Navigation Timing information for the browser-initiated navigations. In
452 // case of cross-process navigations, this carries over the time of
453 // finishing the onbeforeunload handler of the previous page.
454 DCHECK(!browser_navigation_start
.is_null());
455 if (frame
->provisionalDataSource()) {
456 // |browser_navigation_start| is likely before this process existed, so we
457 // can't use InterProcessTimeTicksConverter. We need at least to ensure
458 // that the browser-side navigation start we set is not later than the one
459 // on the renderer side.
460 base::TimeTicks navigation_start
= std::min(
461 browser_navigation_start
, renderer_navigation_start
);
462 double navigation_start_seconds
=
463 (navigation_start
- base::TimeTicks()).InSecondsF();
464 frame
->provisionalDataSource()->setNavigationStartTime(
465 navigation_start_seconds
);
466 // TODO(clamy): We need to provide additional timing values for the
467 // Navigation Timing API to work with browser-side navigations.
472 FrameHostMsg_BeginNavigation_Params
MakeBeginNavigationParams(
473 blink::WebURLRequest
* request
) {
474 FrameHostMsg_BeginNavigation_Params params
;
475 params
.method
= request
->httpMethod().latin1();
476 params
.headers
= GetWebURLRequestHeaders(*request
);
477 params
.load_flags
= GetLoadFlagsForWebURLRequest(*request
);
478 params
.request_body
= GetRequestBodyForWebURLRequest(*request
);
479 params
.has_user_gesture
= request
->hasUserGesture();
484 CommonNavigationParams
MakeCommonNavigationParams(
485 blink::WebURLRequest
* request
) {
486 const RequestExtraData kEmptyData
;
487 const RequestExtraData
* extra_data
=
488 static_cast<RequestExtraData
*>(request
->extraData());
490 extra_data
= &kEmptyData
;
491 CommonNavigationParams params
;
492 params
.url
= request
->url();
493 params
.referrer
= Referrer(
494 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
495 request
->referrerPolicy());
496 params
.transition
= extra_data
->transition_type();
498 // Set the ui timestamp for this navigation. Currently the timestamp here is
499 // only non empty when the navigation was triggered by an Android intent, or
500 // by the user clicking on a link. The timestamp is converted from a double
501 // version supported by blink. It will be passed back to the renderer in the
502 // CommitNavigation IPC, and then back to the browser again in the
503 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
504 params
.ui_timestamp
=
505 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
506 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
507 request
->inputPerfMetricReportPolicy());
511 #if !defined(OS_ANDROID)
512 media::Context3D
GetSharedMainThreadContext3D() {
513 cc::ContextProvider
* provider
=
514 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
516 return media::Context3D();
517 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
521 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
524 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
526 static_cast<int>(content_name) == static_cast<int>(blink_name), \
527 "enum values must match")
529 // Check that blink::WebSandboxFlags is kept in sync with
530 // content::SandboxFlags.
531 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE
,
532 blink::WebSandboxFlags::None
);
533 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION
,
534 blink::WebSandboxFlags::Navigation
);
535 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS
,
536 blink::WebSandboxFlags::Plugins
);
537 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN
,
538 blink::WebSandboxFlags::Origin
);
539 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS
,
540 blink::WebSandboxFlags::Forms
);
541 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS
,
542 blink::WebSandboxFlags::Scripts
);
543 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION
,
544 blink::WebSandboxFlags::TopNavigation
);
545 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS
,
546 blink::WebSandboxFlags::Popups
);
547 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES
,
548 blink::WebSandboxFlags::AutomaticFeatures
);
549 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK
,
550 blink::WebSandboxFlags::PointerLock
);
551 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN
,
552 blink::WebSandboxFlags::DocumentDomain
);
553 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK
,
554 blink::WebSandboxFlags::OrientationLock
);
555 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL
,
556 blink::WebSandboxFlags::All
);
561 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
563 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
565 if (g_create_render_frame_impl
)
566 return g_create_render_frame_impl(render_view
, routing_id
);
568 return new RenderFrameImpl(render_view
, routing_id
);
572 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int32 routing_id
) {
573 RoutingIDFrameMap::iterator iter
=
574 g_routing_id_frame_map
.Get().find(routing_id
);
575 if (iter
!= g_routing_id_frame_map
.Get().end())
581 void RenderFrameImpl::CreateFrame(
583 int parent_routing_id
,
584 int proxy_routing_id
,
585 const FrameReplicationState
& replicated_state
,
586 CompositorDependencies
* compositor_deps
,
587 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
588 // TODO(nasko): For now, this message is only sent for subframes, as the
589 // top level frame is created when the RenderView is created through the
591 CHECK_NE(MSG_ROUTING_NONE
, parent_routing_id
);
593 blink::WebLocalFrame
* web_frame
;
594 RenderFrameImpl
* render_frame
;
595 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
596 RenderFrameProxy
* parent_proxy
=
597 RenderFrameProxy::FromRoutingID(parent_routing_id
);
598 // If the browser is sending a valid parent routing id, it should already
599 // be created and registered.
601 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
603 // Create the RenderFrame and WebLocalFrame, linking the two.
605 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
606 web_frame
= parent_web_frame
->createLocalChild(
607 WebString::fromUTF8(replicated_state
.name
),
608 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
), render_frame
);
610 RenderFrameProxy
* proxy
=
611 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
613 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
614 web_frame
= blink::WebLocalFrame::create(render_frame
);
615 render_frame
->proxy_routing_id_
= proxy_routing_id
;
616 web_frame
->initializeToReplaceRemoteFrame(proxy
->web_frame());
618 render_frame
->SetWebFrame(web_frame
);
620 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
621 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
622 switches::kSitePerProcess
));
623 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
624 widget_params
.routing_id
, widget_params
.surface_id
,
625 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
626 compositor_deps
, web_frame
);
627 // TODO(kenrb): Observing shouldn't be necessary when we sort out
628 // WasShown and WasHidden, separating page-level visibility from
629 // frame-level visibility.
630 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
633 render_frame
->Initialize();
637 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
638 return RenderFrameImpl::FromWebFrame(web_frame
);
642 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
643 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
644 if (iter
!= g_frame_map
.Get().end())
650 void RenderFrameImpl::InstallCreateHook(
651 CreateRenderFrameImplFunction create_render_frame_impl
) {
652 CHECK(!g_create_render_frame_impl
);
653 g_create_render_frame_impl
= create_render_frame_impl
;
657 content::SandboxFlags
RenderFrameImpl::WebToContentSandboxFlags(
658 blink::WebSandboxFlags flags
) {
659 return static_cast<content::SandboxFlags
>(flags
);
663 blink::WebSandboxFlags
RenderFrameImpl::ContentToWebSandboxFlags(
664 content::SandboxFlags flags
) {
665 return static_cast<blink::WebSandboxFlags
>(flags
);
668 // RenderFrameImpl ----------------------------------------------------------
669 RenderFrameImpl::RenderFrameImpl(RenderViewImpl
* render_view
, int routing_id
)
671 render_view_(render_view
->AsWeakPtr()),
672 routing_id_(routing_id
),
673 is_swapped_out_(false),
674 render_frame_proxy_(NULL
),
675 is_detaching_(false),
676 proxy_routing_id_(MSG_ROUTING_NONE
),
677 #if defined(ENABLE_PLUGINS)
678 plugin_power_saver_helper_(NULL
),
681 selection_text_offset_(0),
682 selection_range_(gfx::Range::InvalidRange()),
683 handling_select_range_(false),
684 notification_permission_dispatcher_(NULL
),
685 web_user_media_client_(NULL
),
686 media_permission_dispatcher_(NULL
),
687 midi_dispatcher_(NULL
),
688 #if defined(OS_ANDROID)
689 media_player_manager_(NULL
),
691 #if defined(ENABLE_BROWSER_CDMS)
694 #if defined(VIDEO_HOLE)
695 contains_media_player_(false),
697 geolocation_dispatcher_(NULL
),
698 push_messaging_dispatcher_(NULL
),
699 presentation_dispatcher_(NULL
),
700 screen_orientation_dispatcher_(NULL
),
701 manifest_manager_(NULL
),
702 accessibility_mode_(AccessibilityModeOff
),
703 renderer_accessibility_(NULL
),
704 weak_factory_(this) {
705 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
706 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
707 CHECK(result
.second
) << "Inserting a duplicate item.";
709 RenderThread::Get()->AddRoute(routing_id_
, this);
711 render_view_
->RegisterRenderFrame(this);
713 // Everything below subclasses RenderFrameObserver and is automatically
714 // deleted when the RenderFrame gets deleted.
715 #if defined(OS_ANDROID)
716 new GinJavaBridgeDispatcher(this);
719 #if defined(ENABLE_PLUGINS)
720 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
723 manifest_manager_
= new ManifestManager(this);
726 RenderFrameImpl::~RenderFrameImpl() {
727 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
728 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
730 #if defined(VIDEO_HOLE)
731 if (contains_media_player_
)
732 render_view_
->UnregisterVideoHoleFrame(this);
735 if (render_frame_proxy_
)
736 delete render_frame_proxy_
;
738 render_view_
->UnregisterRenderFrame(this);
739 g_routing_id_frame_map
.Get().erase(routing_id_
);
740 RenderThread::Get()->RemoveRoute(routing_id_
);
743 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
746 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
747 std::make_pair(web_frame
, this));
748 CHECK(result
.second
) << "Inserting a duplicate item.";
753 void RenderFrameImpl::Initialize() {
754 #if defined(ENABLE_PLUGINS)
755 new PepperBrowserConnection(this);
757 new SharedWorkerRepository(this);
759 if (!frame_
->parent())
760 new ImageLoadingHelper(this);
762 // We delay calling this until we have the WebFrame so that any observer or
763 // embedder can call GetWebFrame on any RenderFrame.
764 GetContentClient()->renderer()->RenderFrameCreated(this);
767 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
768 return render_view_
.get();
771 #if defined(ENABLE_PLUGINS)
772 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
773 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
774 DidCreatePepperPlugin(host
));
775 if (host
->GetPluginName() == kFlashPluginName
) {
776 RenderThread::Get()->RecordAction(
777 base::UserMetricsAction("FrameLoadWithFlash"));
781 void RenderFrameImpl::PepperDidChangeCursor(
782 PepperPluginInstanceImpl
* instance
,
783 const blink::WebCursorInfo
& cursor
) {
784 // Update the cursor appearance immediately if the requesting plugin is the
785 // one which receives the last mouse event. Otherwise, the new cursor won't be
786 // picked up until the plugin gets the next input event. That is bad if, e.g.,
787 // the plugin would like to set an invisible cursor when there isn't any user
788 // input for a while.
789 if (instance
== render_view_
->pepper_last_mouse_event_target())
790 GetRenderWidget()->didChangeCursor(cursor
);
793 void RenderFrameImpl::PepperDidReceiveMouseEvent(
794 PepperPluginInstanceImpl
* instance
) {
795 render_view_
->set_pepper_last_mouse_event_target(instance
);
798 void RenderFrameImpl::PepperTextInputTypeChanged(
799 PepperPluginInstanceImpl
* instance
) {
800 if (instance
!= render_view_
->focused_pepper_plugin())
803 GetRenderWidget()->UpdateTextInputType();
805 FocusedNodeChangedForAccessibility(WebNode());
808 void RenderFrameImpl::PepperCaretPositionChanged(
809 PepperPluginInstanceImpl
* instance
) {
810 if (instance
!= render_view_
->focused_pepper_plugin())
812 GetRenderWidget()->UpdateSelectionBounds();
815 void RenderFrameImpl::PepperCancelComposition(
816 PepperPluginInstanceImpl
* instance
) {
817 if (instance
!= render_view_
->focused_pepper_plugin())
819 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
820 #if defined(OS_MACOSX) || defined(USE_AURA)
821 GetRenderWidget()->UpdateCompositionInfo(true);
825 void RenderFrameImpl::PepperSelectionChanged(
826 PepperPluginInstanceImpl
* instance
) {
827 if (instance
!= render_view_
->focused_pepper_plugin())
829 SyncSelectionIfRequired();
832 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
833 PepperPluginInstanceImpl
* plugin
) {
835 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
836 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
837 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
838 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
839 plugin
, active_url
, GetRenderWidget()->screenInfo());
840 widget
->show(blink::WebNavigationPolicyIgnore
);
844 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
845 if (!render_view_
->focused_pepper_plugin())
847 return render_view_
->focused_pepper_plugin()->
848 IsPluginAcceptingCompositionEvents();
851 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
852 base::ProcessId plugin_pid
) {
853 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
854 // routing_id_ as a result.
855 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
858 void RenderFrameImpl::SimulateImeSetComposition(
859 const base::string16
& text
,
860 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
863 render_view_
->OnImeSetComposition(
864 text
, underlines
, selection_start
, selection_end
);
867 void RenderFrameImpl::SimulateImeConfirmComposition(
868 const base::string16
& text
,
869 const gfx::Range
& replacement_range
) {
870 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
873 void RenderFrameImpl::OnImeSetComposition(
874 const base::string16
& text
,
875 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
878 // When a PPAPI plugin has focus, we bypass WebKit.
879 if (!IsPepperAcceptingCompositionEvents()) {
880 pepper_composition_text_
= text
;
882 // TODO(kinaba) currently all composition events are sent directly to
883 // plugins. Use DOM event mechanism after WebKit is made aware about
884 // plugins that support composition.
885 // The code below mimics the behavior of WebCore::Editor::setComposition.
887 // Empty -> nonempty: composition started.
888 if (pepper_composition_text_
.empty() && !text
.empty()) {
889 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
892 // Nonempty -> empty: composition canceled.
893 if (!pepper_composition_text_
.empty() && text
.empty()) {
894 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
897 pepper_composition_text_
= text
;
898 // Nonempty: composition is ongoing.
899 if (!pepper_composition_text_
.empty()) {
900 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
901 pepper_composition_text_
, underlines
, selection_start
,
907 void RenderFrameImpl::OnImeConfirmComposition(
908 const base::string16
& text
,
909 const gfx::Range
& replacement_range
,
910 bool keep_selection
) {
911 // When a PPAPI plugin has focus, we bypass WebKit.
912 // Here, text.empty() has a special meaning. It means to commit the last
913 // update of composition text (see
914 // RenderWidgetHost::ImeConfirmComposition()).
915 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
918 // last_text is empty only when both text and pepper_composition_text_ is.
920 if (last_text
.empty())
923 if (!IsPepperAcceptingCompositionEvents()) {
924 base::i18n::UTF16CharIterator
iterator(&last_text
);
926 while (iterator
.Advance()) {
927 blink::WebKeyboardEvent char_event
;
928 char_event
.type
= blink::WebInputEvent::Char
;
929 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
930 char_event
.modifiers
= 0;
931 char_event
.windowsKeyCode
= last_text
[i
];
932 char_event
.nativeKeyCode
= last_text
[i
];
934 const int32 char_start
= i
;
935 for (; i
< iterator
.array_pos(); ++i
) {
936 char_event
.text
[i
- char_start
] = last_text
[i
];
937 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
940 if (GetRenderWidget()->webwidget())
941 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
944 // Mimics the order of events sent by WebKit.
945 // See WebCore::Editor::setComposition() for the corresponding code.
946 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
947 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
949 pepper_composition_text_
.clear();
951 #endif // defined(ENABLE_PLUGINS)
953 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
954 if (!web_user_media_client_
)
955 InitializeUserMediaClient();
956 return web_user_media_client_
?
957 web_user_media_client_
->media_stream_dispatcher() : NULL
;
960 bool RenderFrameImpl::Send(IPC::Message
* message
) {
965 if (is_swapped_out_
) {
966 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
972 return RenderThread::Get()->Send(message
);
975 #if defined(OS_MACOSX) || defined(OS_ANDROID)
976 void RenderFrameImpl::DidHideExternalPopupMenu() {
977 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
978 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
979 external_popup_menu_
.reset();
983 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
984 // TODO(kenrb): document() should not be null, but as a transitional step
985 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
986 // to this method. This happens for a top-level remote frame, where a
987 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
988 // around and is still able to receive messages.
989 if (!frame_
->document().isNull())
990 GetContentClient()->SetActiveURL(frame_
->document().url());
992 ObserverListBase
<RenderFrameObserver
>::Iterator
it(observers_
);
993 RenderFrameObserver
* observer
;
994 while ((observer
= it
.GetNext()) != NULL
) {
995 if (observer
->OnMessageReceived(msg
))
1000 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1001 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1002 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1003 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1004 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1005 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1006 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1007 OnCustomContextMenuAction
)
1008 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1009 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1010 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1011 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1012 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1013 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1014 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1015 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1016 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1017 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1018 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1019 OnMoveRangeSelectionExtent
)
1020 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1021 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1022 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1023 OnExtendSelectionAndDelete
)
1024 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1025 OnSetCompositionFromExistingText
)
1026 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1027 OnExecuteNoValueEditCommand
)
1028 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1029 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1030 OnJavaScriptExecuteRequest
)
1031 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1032 OnJavaScriptExecuteRequestForTests
)
1033 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1034 OnSetEditableSelectionOffsets
)
1035 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView
, OnSetupTransitionView
)
1036 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition
, OnBeginExitTransition
)
1037 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition
, OnRevertExitTransition
)
1038 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements
,
1039 OnHideTransitionElements
)
1040 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements
,
1041 OnShowTransitionElements
)
1042 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1043 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1044 OnTextSurroundingSelectionRequest
)
1045 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL
,
1046 OnAddStyleSheetByURL
)
1047 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1048 OnSetAccessibilityMode
)
1049 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1050 IPC_MESSAGE_HANDLER(FrameMsg_RequestNavigation
, OnRequestNavigation
)
1051 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1052 #if defined(OS_ANDROID)
1053 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1054 #elif defined(OS_MACOSX)
1055 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1056 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1058 IPC_END_MESSAGE_MAP()
1063 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params
& params
) {
1064 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
1066 "url", params
.common_params
.url
.possibly_invalid_spec());
1069 RenderViewImpl::IsReload(params
.common_params
.navigation_type
);
1070 bool is_history_navigation
= params
.commit_params
.page_state
.IsValid();
1071 WebURLRequest::CachePolicy cache_policy
=
1072 WebURLRequest::UseProtocolCachePolicy
;
1073 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1074 params
.common_params
.url
, true, is_history_navigation
,
1075 params
.current_history_list_offset
, &is_reload
, &cache_policy
)) {
1076 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
1080 render_view_
->history_list_offset_
= params
.current_history_list_offset
;
1081 render_view_
->history_list_length_
= params
.current_history_list_length
;
1082 if (params
.should_clear_history_list
) {
1083 CHECK_EQ(-1, render_view_
->history_list_offset_
);
1084 CHECK_EQ(0, render_view_
->history_list_length_
);
1087 GetContentClient()->SetActiveURL(params
.common_params
.url
);
1089 WebFrame
* frame
= frame_
;
1090 if (!params
.frame_to_navigate
.empty()) {
1091 // TODO(nasko): Move this lookup to the browser process.
1092 frame
= render_view_
->webview()->findFrameByName(
1093 WebString::fromUTF8(params
.frame_to_navigate
));
1094 CHECK(frame
) << "Invalid frame name passed: " << params
.frame_to_navigate
;
1097 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
1098 // We cannot reload if we do not have any history state. This happens, for
1099 // example, when recovering from a crash.
1101 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1104 render_view_
->pending_navigation_params_
.reset(
1105 new FrameMsg_Navigate_Params(params
));
1107 // If we are reloading, then WebKit will use the history state of the current
1108 // page, so we should just ignore any given history state. Otherwise, if we
1109 // have history state, then we need to navigate to it, which corresponds to a
1110 // back/forward navigation event.
1112 bool reload_original_url
=
1113 (params
.common_params
.navigation_type
==
1114 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1115 bool ignore_cache
= (params
.common_params
.navigation_type
==
1116 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1118 if (reload_original_url
)
1119 frame
->reloadWithOverrideURL(params
.common_params
.url
, true);
1121 frame
->reload(ignore_cache
);
1122 } else if (is_history_navigation
) {
1123 // We must know the page ID of the page we are navigating back to.
1124 DCHECK_NE(params
.page_id
, -1);
1125 scoped_ptr
<HistoryEntry
> entry
=
1126 PageStateToHistoryEntry(params
.commit_params
.page_state
);
1128 // Ensure we didn't save the swapped out URL in UpdateState, since the
1129 // browser should never be telling us to navigate to swappedout://.
1130 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
1131 render_view_
->history_controller()->GoToEntry(entry
.Pass(), cache_policy
);
1133 } else if (!params
.base_url_for_data_url
.is_empty()) {
1134 // A loadData request with a specified base URL.
1135 std::string mime_type
, charset
, data
;
1136 if (net::DataURL::Parse(
1137 params
.common_params
.url
, &mime_type
, &charset
, &data
)) {
1139 WebData(data
.c_str(), data
.length()),
1140 WebString::fromUTF8(mime_type
),
1141 WebString::fromUTF8(charset
),
1142 params
.base_url_for_data_url
,
1143 params
.history_url_for_data_url
,
1146 CHECK(false) << "Invalid URL passed: "
1147 << params
.common_params
.url
.possibly_invalid_spec();
1150 // Navigate to the given URL.
1151 WebURLRequest request
=
1152 CreateURLRequestForNavigation(params
.common_params
,
1153 params
.request_params
,
1154 scoped_ptr
<StreamOverrideParameters
>(),
1155 frame
->isViewSourceModeEnabled());
1157 // A session history navigation should have been accompanied by state.
1158 CHECK_EQ(params
.page_id
, -1);
1160 // Record this before starting the load, we need a lower bound of this time
1161 // to sanitize the navigationStart override set below.
1162 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
1163 frame
->loadRequest(request
);
1165 UpdateFrameNavigationTiming(
1166 frame
, params
.commit_params
.browser_navigation_start
,
1167 renderer_navigation_start
);
1170 // In case LoadRequest failed before DidCreateDataSource was called.
1171 render_view_
->pending_navigation_params_
.reset();
1174 void RenderFrameImpl::NavigateToSwappedOutURL() {
1175 // We use loadRequest instead of loadHTMLString because the former commits
1176 // synchronously. Otherwise a new navigation can interrupt the navigation
1177 // to kSwappedOutURL. If that happens to be to the page we had been
1178 // showing, then WebKit will never send a commit and we'll be left spinning.
1179 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1180 // the navigation to swappedout:// is not announced to the browser side.
1181 is_swapped_out_
= true;
1182 GURL
swappedOutURL(kSwappedOutURL
);
1183 WebURLRequest
request(swappedOutURL
);
1184 frame_
->loadRequest(request
);
1187 void RenderFrameImpl::BindServiceRegistry(
1188 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1189 mojo::ServiceProviderPtr exposed_services
) {
1190 service_registry_
.Bind(services
.Pass());
1191 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1194 ManifestManager
* RenderFrameImpl::manifest_manager() {
1195 return manifest_manager_
;
1198 void RenderFrameImpl::OnBeforeUnload() {
1199 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1201 // TODO(creis): Right now, this is only called on the main frame. Make the
1202 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1204 CHECK(!frame_
->parent());
1206 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1207 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1208 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1209 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1210 before_unload_start_time
,
1211 before_unload_end_time
));
1214 void RenderFrameImpl::OnSwapOut(
1215 int proxy_routing_id
,
1217 const FrameReplicationState
& replicated_frame_state
) {
1218 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1219 RenderFrameProxy
* proxy
= NULL
;
1220 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1221 switches::kSitePerProcess
);
1222 bool is_main_frame
= !frame_
->parent();
1224 // Only run unload if we're not swapped out yet, but send the ack either way.
1225 if (!is_swapped_out_
) {
1226 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1227 // a different process. This involves running the unload handler and
1228 // clearing the page. We also allow this process to exit if there are no
1229 // other active RenderFrames in it.
1231 // Send an UpdateState message before we get swapped out.
1232 render_view_
->SyncNavigationState();
1234 // If we need a proxy to replace this, create it now so its routing id is
1235 // registered for receiving IPC messages.
1236 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1237 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(this,
1241 // Synchronously run the unload handler before sending the ACK.
1242 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1243 // unload on subframes as well.
1245 frame_
->dispatchUnloadEvent();
1247 // Swap out and stop sending any IPC messages that are not ACKs.
1249 render_view_
->SetSwappedOut(true);
1250 is_swapped_out_
= true;
1252 // Now that we're swapped out and filtering IPC messages, stop loading to
1253 // ensure that no other in-progress navigation continues. We do this here
1254 // to avoid sending a DidStopLoading message to the browser process.
1255 // TODO(creis): Should we be stopping all frames here and using
1256 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1260 // Transfer settings such as initial drawing parameters to the remote frame,
1261 // if one is created, that will replace this frame.
1262 if (!is_main_frame
&& proxy
)
1263 proxy
->web_frame()->initializeFromFrame(frame_
);
1265 // Replace the page with a blank dummy URL. The unload handler will not be
1266 // run a second time, thanks to a check in FrameLoader::stopLoading.
1267 // TODO(creis): Need to add a better way to do this that avoids running the
1268 // beforeunload handler. For now, we just run it a second time silently.
1269 if (!is_site_per_process
|| is_main_frame
)
1270 NavigateToSwappedOutURL();
1272 // Let WebKit know that this view is hidden so it can drop resources and
1273 // stop compositing.
1274 // TODO(creis): Support this for subframes as well.
1275 if (is_main_frame
) {
1276 render_view_
->webview()->setVisibilityState(
1277 blink::WebPageVisibilityStateHidden
, false);
1281 // It is now safe to show modal dialogs again.
1282 // TODO(creis): Deal with modal dialogs from subframes.
1284 render_view_
->suppress_dialogs_until_swap_out_
= false;
1286 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1288 // Now that all of the cleanup is complete and the browser side is notified,
1289 // start using the RenderFrameProxy, if one is created.
1291 if (!is_main_frame
) {
1292 frame_
->swap(proxy
->web_frame());
1295 proxy
->OnDidStartLoading();
1297 if (is_site_per_process
) {
1298 // TODO(nasko): delete the frame here, since we've replaced it with a
1302 set_render_frame_proxy(proxy
);
1306 // In --site-per-process, initialize the WebRemoteFrame with the replication
1307 // state passed by the process that is now rendering the frame.
1308 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1309 // in that case we leave the LocalFrame as the main frame visible to Blink
1310 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1311 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1312 // When we do an unconditional swap for all frames, we can remove
1313 // !is_main_frame below.
1314 if (is_site_per_process
&& proxy
&& !is_main_frame
)
1315 proxy
->SetReplicatedState(replicated_frame_state
);
1317 // Safe to exit if no one else is using the process.
1319 render_view_
->WasSwappedOut();
1322 void RenderFrameImpl::OnContextMenuClosed(
1323 const CustomContextMenuContext
& custom_context
) {
1324 if (custom_context
.request_id
) {
1325 // External request, should be in our map.
1326 ContextMenuClient
* client
=
1327 pending_context_menus_
.Lookup(custom_context
.request_id
);
1329 client
->OnMenuClosed(custom_context
.request_id
);
1330 pending_context_menus_
.Remove(custom_context
.request_id
);
1333 if (custom_context
.link_followed
.is_valid()) {
1335 DomUtils::ExtractParentAnchorNode(context_menu_node_
),
1336 custom_context
.link_followed
);
1338 // Internal request, forward to WebKit.
1339 context_menu_node_
.reset();
1343 void RenderFrameImpl::OnCustomContextMenuAction(
1344 const CustomContextMenuContext
& custom_context
,
1346 if (custom_context
.request_id
) {
1347 // External context menu request, look in our map.
1348 ContextMenuClient
* client
=
1349 pending_context_menus_
.Lookup(custom_context
.request_id
);
1351 client
->OnMenuAction(custom_context
.request_id
, action
);
1353 // Internal request, forward to WebKit.
1354 render_view_
->webview()->performCustomContextMenuAction(action
);
1358 void RenderFrameImpl::OnUndo() {
1359 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1362 void RenderFrameImpl::OnRedo() {
1363 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1366 void RenderFrameImpl::OnCut() {
1367 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1368 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1371 void RenderFrameImpl::OnCopy() {
1372 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1373 WebNode current_node
= context_menu_node_
.isNull() ?
1374 GetFocusedElement() : context_menu_node_
;
1375 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1378 void RenderFrameImpl::OnPaste() {
1379 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1380 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1383 void RenderFrameImpl::OnPasteAndMatchStyle() {
1384 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1385 frame_
->executeCommand(
1386 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1389 #if defined(OS_MACOSX)
1390 void RenderFrameImpl::OnCopyToFindPboard() {
1391 // Since the find pasteboard supports only plain text, this can be simpler
1392 // than the |OnCopy()| case.
1393 if (frame_
->hasSelection()) {
1394 base::string16 selection
= frame_
->selectionAsText();
1395 RenderThread::Get()->Send(
1396 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1401 void RenderFrameImpl::OnDelete() {
1402 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1405 void RenderFrameImpl::OnSelectAll() {
1406 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1407 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1410 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1411 const gfx::Point
& extent
) {
1412 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1413 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1415 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1416 frame_
->selectRange(base
, extent
);
1419 void RenderFrameImpl::OnUnselect() {
1420 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1421 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1424 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1425 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1426 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1427 GetRenderWidget()->routing_id()));
1429 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1430 frame_
->moveRangeSelectionExtent(point
);
1433 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1434 if (!frame_
->hasSelection())
1435 frame_
->selectWordAroundCaret();
1437 frame_
->replaceSelection(text
);
1440 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1441 if (!frame_
->hasSelection())
1444 frame_
->replaceMisspelledRange(text
);
1447 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1448 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1451 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1452 const base::string16
& jscript
,
1454 bool notify_result
) {
1455 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1456 TRACE_EVENT_SCOPE_THREAD
);
1458 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1459 v8::Handle
<v8::Value
> result
=
1460 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1462 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1465 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1466 const base::string16
& jscript
,
1468 bool notify_result
) {
1469 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1470 TRACE_EVENT_SCOPE_THREAD
);
1472 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1473 v8::Handle
<v8::Value
> result
=
1474 frame_
->executeScriptAndReturnValueForTests(WebScriptSource(jscript
));
1476 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1479 void RenderFrameImpl::HandleJavascriptExecutionResult(
1480 const base::string16
& jscript
,
1483 v8::Handle
<v8::Value
> result
) {
1484 if (notify_result
) {
1485 base::ListValue list
;
1486 if (!result
.IsEmpty()) {
1487 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1488 v8::Context::Scope
context_scope(context
);
1489 V8ValueConverterImpl converter
;
1490 converter
.SetDateAllowed(true);
1491 converter
.SetRegExpAllowed(true);
1492 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
1493 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
1495 list
.Set(0, base::Value::CreateNullValue());
1497 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1501 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1502 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1503 if (!GetRenderWidget()->ShouldHandleImeEvent())
1505 ImeEventGuard
guard(GetRenderWidget());
1506 frame_
->setEditableSelectionOffsets(start
, end
);
1509 void RenderFrameImpl::OnSetCompositionFromExistingText(
1511 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1512 if (!GetRenderWidget()->ShouldHandleImeEvent())
1514 ImeEventGuard
guard(GetRenderWidget());
1515 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1518 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1519 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1522 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1523 if (!GetRenderWidget()->ShouldHandleImeEvent())
1525 ImeEventGuard
guard(GetRenderWidget());
1526 frame_
->extendSelectionAndDelete(before
, after
);
1529 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1530 if (accessibility_mode_
== new_mode
)
1532 accessibility_mode_
= new_mode
;
1533 if (renderer_accessibility_
) {
1534 // Note: this isn't called automatically by the destructor because
1535 // there'd be no point in calling it in frame teardown, only if there's
1536 // an accessibility mode change but the frame is persisting.
1537 renderer_accessibility_
->DisableAccessibility();
1539 delete renderer_accessibility_
;
1540 renderer_accessibility_
= NULL
;
1542 if (accessibility_mode_
== AccessibilityModeOff
)
1545 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1546 renderer_accessibility_
= new RendererAccessibility(this);
1549 void RenderFrameImpl::OnDisownOpener() {
1550 // TODO(creis): We should only see this for main frames for now. To support
1551 // disowning the opener on subframes, we will need to move WebContentsImpl's
1552 // opener_ to FrameTreeNode.
1553 CHECK(!frame_
->parent());
1555 if (frame_
->opener())
1556 frame_
->setOpener(NULL
);
1559 #if defined(OS_ANDROID)
1560 void RenderFrameImpl::OnSelectPopupMenuItems(
1562 const std::vector
<int>& selected_indices
) {
1563 // It is possible to receive more than one of these calls if the user presses
1564 // a select faster than it takes for the show-select-popup IPC message to make
1565 // it to the browser UI thread. Ignore the extra-messages.
1566 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1567 if (!external_popup_menu_
)
1570 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1571 external_popup_menu_
.reset();
1575 #if defined(OS_MACOSX)
1576 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1577 if (external_popup_menu_
== NULL
)
1579 external_popup_menu_
->DidSelectItem(selected_index
);
1580 external_popup_menu_
.reset();
1584 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1585 frame_
->reload(ignore_cache
);
1588 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1589 blink::WebSurroundingText surroundingText
;
1590 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1592 if (surroundingText
.isNull()) {
1593 // |surroundingText| might not be correctly initialized, for example if
1594 // |frame_->selectionRange().isNull()|, in other words, if there was no
1596 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1597 routing_id_
, base::string16(), 0, 0));
1601 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1603 surroundingText
.textContent(),
1604 surroundingText
.startOffsetInTextContent(),
1605 surroundingText
.endOffsetInTextContent()));
1608 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string
& url
) {
1609 frame_
->addStyleSheetByURL(WebString::fromUTF8(url
));
1612 void RenderFrameImpl::OnSetupTransitionView(const std::string
& markup
) {
1613 frame_
->document().setIsTransitionDocument(true);
1614 frame_
->navigateToSandboxedMarkup(WebData(markup
.data(), markup
.length()));
1617 void RenderFrameImpl::OnBeginExitTransition(const std::string
& css_selector
,
1618 bool exit_to_native_app
) {
1619 frame_
->document().setIsTransitionDocument(true);
1620 frame_
->document().beginExitTransition(WebString::fromUTF8(css_selector
),
1621 exit_to_native_app
);
1624 void RenderFrameImpl::OnRevertExitTransition() {
1625 frame_
->document().setIsTransitionDocument(false);
1626 frame_
->document().revertExitTransition();
1629 void RenderFrameImpl::OnHideTransitionElements(
1630 const std::string
& css_selector
) {
1631 frame_
->document().hideTransitionElements(WebString::fromUTF8(css_selector
));
1634 void RenderFrameImpl::OnShowTransitionElements(
1635 const std::string
& css_selector
) {
1636 frame_
->document().showTransitionElements(WebString::fromUTF8(css_selector
));
1639 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1640 const base::string16
& message
,
1641 const base::string16
& default_value
,
1642 const GURL
& frame_url
,
1643 base::string16
* result
) {
1644 // Don't allow further dialogs if we are waiting to swap out, since the
1645 // PageGroupLoadDeferrer in our stack prevents it.
1646 if (render_view()->suppress_dialogs_until_swap_out_
)
1649 bool success
= false;
1650 base::string16 result_temp
;
1652 result
= &result_temp
;
1654 render_view()->SendAndRunNestedMessageLoop(
1655 new FrameHostMsg_RunJavaScriptMessage(
1656 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1661 void RenderFrameImpl::LoadNavigationErrorPage(
1662 const WebURLRequest
& failed_request
,
1663 const WebURLError
& error
,
1665 std::string error_html
;
1666 GetContentClient()->renderer()->GetNavigationErrorStrings(
1667 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1669 frame_
->loadHTMLString(error_html
,
1670 GURL(kUnreachableWebDataURL
),
1671 error
.unreachableURL
,
1675 void RenderFrameImpl::DidCommitCompositorFrame() {
1677 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1680 RenderView
* RenderFrameImpl::GetRenderView() {
1681 return render_view_
.get();
1684 int RenderFrameImpl::GetRoutingID() {
1688 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1693 WebElement
RenderFrameImpl::GetFocusedElement() const {
1694 WebDocument doc
= frame_
->document();
1696 return doc
.focusedElement();
1698 return WebElement();
1701 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1702 return render_view_
->GetWebkitPreferences();
1705 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1706 const ContextMenuParams
& params
) {
1707 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1708 ContextMenuParams
our_params(params
);
1709 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1710 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1711 return our_params
.custom_context
.request_id
;
1714 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1715 DCHECK(pending_context_menus_
.Lookup(request_id
));
1716 pending_context_menus_
.Remove(request_id
);
1719 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1720 return context_menu_node_
;
1723 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1724 blink::WebFrame
* frame
,
1725 const WebPluginInfo
& info
,
1726 const blink::WebPluginParams
& params
,
1727 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1728 DCHECK_EQ(frame_
, frame
);
1729 #if defined(ENABLE_PLUGINS)
1730 bool pepper_plugin_was_registered
= false;
1731 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1732 this, info
, &pepper_plugin_was_registered
));
1733 if (pepper_plugin_was_registered
) {
1734 if (pepper_module
.get()) {
1735 return new PepperWebPluginImpl(
1736 pepper_module
.get(), params
, this,
1738 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1741 #if defined(OS_CHROMEOS)
1742 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1745 // TODO(jam): change to take RenderFrame.
1746 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1753 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1754 const blink::WebURLRequest
& request
,
1755 blink::WebNavigationPolicy policy
) {
1756 DCHECK(!frame_
|| frame_
== frame
);
1757 loadURLExternally(frame
, request
, policy
, WebString());
1760 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1761 OnJavaScriptExecuteRequest(javascript
, 0, false);
1764 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1765 return &service_registry_
;
1768 #if defined(ENABLE_PLUGINS)
1769 void RenderFrameImpl::RegisterPeripheralPlugin(
1770 const GURL
& content_origin
,
1771 const base::Closure
& unthrottle_callback
) {
1772 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1773 content_origin
, unthrottle_callback
);
1776 bool RenderFrameImpl::ShouldThrottleContent(
1777 const blink::WebPluginParams
& params
,
1778 const GURL
& page_frame_url
,
1780 bool* cross_origin_main_content
) const {
1781 return plugin_power_saver_helper_
->ShouldThrottleContent(
1782 params
, page_frame_url
, poster_image
, cross_origin_main_content
);
1785 void RenderFrameImpl::WhitelistContentOrigin(const GURL
& content_origin
) {
1786 return plugin_power_saver_helper_
->WhitelistContentOrigin(content_origin
);
1788 #endif // defined(ENABLE_PLUGINS)
1790 bool RenderFrameImpl::IsFTPDirectoryListing() {
1791 WebURLResponseExtraDataImpl
* extra_data
=
1792 GetExtraDataFromResponse(frame_
->dataSource()->response());
1793 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1796 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1797 BrowserPluginManager::Get()->Attach(element_instance_id
);
1800 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1801 BrowserPluginManager::Get()->Detach(element_instance_id
);
1804 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1806 const gfx::Range
& range
) {
1807 // Use the routing id of Render Widget Host.
1808 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1814 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1815 v8::Isolate
* isolate
,
1816 v8::Handle
<v8::Context
> context
) {
1817 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1818 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1821 v8::HandleScope
handle_scope(isolate
);
1822 registry
->AddBuiltinModule(
1823 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1824 registry
->AddBuiltinModule(isolate
,
1825 mojo::js::Support::kModuleName
,
1826 mojo::js::Support::GetModule(isolate
));
1827 registry
->AddBuiltinModule(
1829 ServiceRegistryJsWrapper::kModuleName
,
1830 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1833 // blink::WebFrameClient implementation ----------------------------------------
1835 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1836 blink::WebLocalFrame
* frame
,
1837 const blink::WebPluginParams
& params
) {
1838 DCHECK_EQ(frame_
, frame
);
1839 return GetContentClient()
1841 ->CreatePluginPlaceholder(this, frame
, params
)
1845 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1846 blink::WebLocalFrame
* frame
,
1847 const blink::WebPluginParams
& params
) {
1848 DCHECK_EQ(frame_
, frame
);
1849 blink::WebPlugin
* plugin
= NULL
;
1850 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1851 this, frame
, params
, &plugin
)) {
1855 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1856 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1857 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1858 kBrowserPluginMimeType
, GURL(params
.url
)));
1859 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1860 this, browser_plugin_delegate
.Pass());
1863 #if defined(ENABLE_PLUGINS)
1865 std::string mime_type
;
1867 Send(new FrameHostMsg_GetPluginInfo(
1868 routing_id_
, params
.url
, frame
->top()->document().url(),
1869 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
1873 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1874 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1875 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1876 this, mime_type
, GURL(params
.url
)));
1877 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1878 this, browser_plugin_delegate
.Pass());
1882 WebPluginParams params_to_use
= params
;
1883 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
1884 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
1887 #endif // defined(ENABLE_PLUGINS)
1890 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1891 blink::WebLocalFrame
* frame
,
1892 const blink::WebURL
& url
,
1893 blink::WebMediaPlayerClient
* client
) {
1894 return createMediaPlayer(frame
, url
, client
, nullptr);
1897 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1898 blink::WebLocalFrame
* frame
,
1899 const blink::WebURL
& url
,
1900 blink::WebMediaPlayerClient
* client
,
1901 blink::WebContentDecryptionModule
* initial_cdm
) {
1902 #if defined(VIDEO_HOLE)
1903 if (!contains_media_player_
) {
1904 render_view_
->RegisterVideoHoleFrame(this);
1905 contains_media_player_
= true;
1907 #endif // defined(VIDEO_HOLE)
1909 blink::WebMediaStream
web_stream(
1910 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
1911 if (!web_stream
.isNull())
1912 return CreateWebMediaPlayerForMediaStream(url
, client
);
1914 if (!media_permission_dispatcher_
)
1915 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
1917 #if defined(OS_ANDROID)
1918 return CreateAndroidWebMediaPlayer(url
, client
, media_permission_dispatcher_
,
1921 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
1924 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
1925 media::WebMediaPlayerParams
params(
1926 base::Bind(&ContentRendererClient::DeferMediaLoad
,
1927 base::Unretained(GetContentClient()->renderer()),
1928 static_cast<RenderFrame
*>(this)),
1929 render_thread
->GetAudioRendererMixerManager()->CreateInput(
1930 render_view_
->routing_id_
, routing_id_
),
1931 media_log
, render_thread
->GetMediaThreadTaskRunner(),
1932 render_thread
->compositor_message_loop_proxy(),
1933 base::Bind(&GetSharedMainThreadContext3D
), media_permission_dispatcher_
,
1936 #if defined(ENABLE_PEPPER_CDMS)
1937 scoped_ptr
<media::CdmFactory
> cdm_factory(
1938 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create
, frame
)));
1939 #elif defined(ENABLE_BROWSER_CDMS)
1940 scoped_ptr
<media::CdmFactory
> cdm_factory(
1941 new RenderCdmFactory(GetCdmManager()));
1943 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
1946 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1947 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
1948 new media::MojoRendererFactory(make_scoped_ptr(
1949 new MediaRendererServiceProvider(GetServiceRegistry()))));
1951 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
1952 GetContentClient()->renderer()->CreateMediaRendererFactory(this);
1954 if (!media_renderer_factory
.get()) {
1955 media_renderer_factory
.reset(new media::DefaultRendererFactory(
1956 media_log
, render_thread
->GetGpuFactories(),
1957 *render_thread
->GetAudioHardwareConfig()));
1959 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
1961 return new media::WebMediaPlayerImpl(
1962 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer_factory
.Pass(),
1963 cdm_factory
.Pass(), params
);
1964 #endif // defined(OS_ANDROID)
1967 // TODO(jrummell): remove once blink uses encryptedMediaClient().
1968 blink::WebContentDecryptionModule
*
1969 RenderFrameImpl::createContentDecryptionModule(
1970 blink::WebLocalFrame
* frame
,
1971 const blink::WebSecurityOrigin
& security_origin
,
1972 const blink::WebString
& key_system
) {
1973 DCHECK(!frame_
|| frame_
== frame
);
1975 #if defined(ENABLE_PEPPER_CDMS)
1976 RenderCdmFactory
cdm_factory(
1977 base::Bind(&PepperCdmWrapperImpl::Create
, frame
));
1978 #elif defined(ENABLE_BROWSER_CDMS)
1979 RenderCdmFactory
cdm_factory(GetCdmManager());
1981 RenderCdmFactory cdm_factory
;
1984 return media::WebContentDecryptionModuleImpl::Create(
1985 &cdm_factory
, security_origin
, key_system
);
1988 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
1989 blink::WebLocalFrame
* frame
,
1990 blink::WebApplicationCacheHostClient
* client
) {
1991 if (!frame
|| !frame
->view())
1993 DCHECK(!frame_
|| frame_
== frame
);
1994 return new RendererWebApplicationCacheHostImpl(
1995 RenderViewImpl::FromWebView(frame
->view()), client
,
1996 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1999 blink::WebWorkerPermissionClientProxy
*
2000 RenderFrameImpl::createWorkerPermissionClientProxy(
2001 blink::WebLocalFrame
* frame
) {
2002 if (!frame
|| !frame
->view())
2004 DCHECK(!frame_
|| frame_
== frame
);
2005 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
2009 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2010 const WebPopupMenuInfo
& popup_menu_info
,
2011 WebExternalPopupMenuClient
* popup_menu_client
) {
2012 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2013 // An IPC message is sent to the browser to build and display the actual
2014 // popup. The user could have time to click a different select by the time
2015 // the popup is shown. In that case external_popup_menu_ is non NULL.
2016 // By returning NULL in that case, we instruct Blink to cancel that new
2017 // popup. So from the user perspective, only the first one will show, and
2018 // will have to close the first one before another one can be shown.
2019 if (external_popup_menu_
)
2021 external_popup_menu_
.reset(
2022 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2023 if (render_view_
->screen_metrics_emulator_
) {
2024 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2025 external_popup_menu_
.get(),
2026 render_view_
->screen_metrics_emulator_
.get());
2028 return external_popup_menu_
.get();
2034 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2035 DCHECK(!frame_
|| frame_
== frame
);
2036 return &cookie_jar_
;
2039 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2040 blink::WebLocalFrame
* frame
) {
2041 DCHECK(!frame_
|| frame_
== frame
);
2042 // At this point we should have non-null data source.
2043 DCHECK(frame
->dataSource());
2044 if (!ChildThreadImpl::current())
2045 return NULL
; // May be null in some tests.
2046 ServiceWorkerNetworkProvider
* provider
=
2047 ServiceWorkerNetworkProvider::FromDocumentState(
2048 DocumentState::FromDataSource(frame
->dataSource()));
2049 return new WebServiceWorkerProviderImpl(
2050 ChildThreadImpl::current()->thread_safe_sender(),
2051 provider
? provider
->context() : NULL
);
2054 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2055 DCHECK(!frame_
|| frame_
== frame
);
2056 // If the request hasn't yet committed, notify the browser process that it is
2057 // no longer safe to show the pending URL of the main frame, since a URL spoof
2058 // is now possible. (If the request has committed, the browser already knows.)
2059 if (!frame
->parent()) {
2060 DocumentState
* document_state
=
2061 DocumentState::FromDataSource(frame
->dataSource());
2062 NavigationState
* navigation_state
= document_state
->navigation_state();
2064 if (!navigation_state
->request_committed()) {
2065 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2070 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2071 blink::WebLocalFrame
* parent
,
2072 const blink::WebString
& name
,
2073 blink::WebSandboxFlags sandbox_flags
) {
2074 // Synchronously notify the browser of a child frame creation to get the
2075 // routing_id for the RenderFrame.
2076 int child_routing_id
= MSG_ROUTING_NONE
;
2077 CHECK(Send(new FrameHostMsg_CreateChildFrame(
2079 base::UTF16ToUTF8(name
),
2080 WebToContentSandboxFlags(sandbox_flags
),
2081 &child_routing_id
)));
2083 // Allocation of routing id failed, so we can't create a child frame. This can
2084 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2085 // out state or synchronous IPC message above has failed.
2086 if (child_routing_id
== MSG_ROUTING_NONE
) {
2087 NOTREACHED() << "Failed to allocate routing id for child frame.";
2091 // Create the RenderFrame and WebLocalFrame, linking the two.
2092 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2093 render_view_
.get(), child_routing_id
);
2094 blink::WebLocalFrame
* web_frame
= WebLocalFrame::create(child_render_frame
);
2095 child_render_frame
->SetWebFrame(web_frame
);
2097 // Add the frame to the frame tree and initialize it.
2098 parent
->appendChild(web_frame
);
2099 child_render_frame
->Initialize();
2104 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2105 DCHECK(!frame_
|| frame_
== frame
);
2106 // We only need to notify the browser if the active, top-level frame clears
2107 // its opener. We can ignore cases where a swapped out frame clears its
2108 // opener after hearing about it from the browser, and the browser does not
2109 // (yet) care about subframe openers.
2110 if (is_swapped_out_
|| frame
->parent())
2113 // Notify WebContents and all its swapped out RenderViews.
2114 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2117 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
) {
2118 // NOTE: This function is called on the frame that is being detached and not
2119 // the parent frame. This is different from createChildFrame() which is
2120 // called on the parent frame.
2121 CHECK(!is_detaching_
);
2122 DCHECK(!frame_
|| frame_
== frame
);
2124 bool is_subframe
= !!frame
->parent();
2126 Send(new FrameHostMsg_Detach(routing_id_
));
2128 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2129 // sent before setting |is_detaching_| to true. In contrast, Observers
2130 // should only be notified afterwards so they cannot call back into here and
2131 // have IPCs fired off.
2132 is_detaching_
= true;
2134 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2135 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2136 FrameDetached(frame
));
2138 // We need to clean up subframes by removing them from the map and deleting
2139 // the RenderFrameImpl. In contrast, the main frame is owned by its
2140 // containing RenderViewHost (so that they have the same lifetime), so only
2141 // removal from the map is needed and no deletion.
2142 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2143 CHECK(it
!= g_frame_map
.Get().end());
2144 CHECK_EQ(it
->second
, this);
2145 g_frame_map
.Get().erase(it
);
2148 frame
->parent()->removeChild(frame
);
2150 // |frame| is invalid after here.
2155 // Object is invalid after this point.
2159 void RenderFrameImpl::frameFocused() {
2160 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2163 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2164 DCHECK(!frame_
|| frame_
== frame
);
2166 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2167 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2168 FrameWillClose(frame
));
2171 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2172 const blink::WebString
& name
) {
2173 DCHECK(!frame_
|| frame_
== frame
);
2174 if (!render_view_
->renderer_preferences_
.report_frame_name_changes
)
2177 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeName(name
));
2180 void RenderFrameImpl::didMatchCSS(
2181 blink::WebLocalFrame
* frame
,
2182 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2183 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2184 DCHECK(!frame_
|| frame_
== frame
);
2186 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2188 newly_matching_selectors
,
2189 stopped_matching_selectors
));
2192 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2193 const blink::WebString
& source
) {
2194 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2198 void RenderFrameImpl::didAddMessageToConsole(
2199 const blink::WebConsoleMessage
& message
,
2200 const blink::WebString
& source_name
,
2201 unsigned source_line
,
2202 const blink::WebString
& stack_trace
) {
2203 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2204 switch (message
.level
) {
2205 case blink::WebConsoleMessage::LevelDebug
:
2206 log_severity
= logging::LOG_VERBOSE
;
2208 case blink::WebConsoleMessage::LevelLog
:
2209 case blink::WebConsoleMessage::LevelInfo
:
2210 log_severity
= logging::LOG_INFO
;
2212 case blink::WebConsoleMessage::LevelWarning
:
2213 log_severity
= logging::LOG_WARNING
;
2215 case blink::WebConsoleMessage::LevelError
:
2216 log_severity
= logging::LOG_ERROR
;
2222 if (shouldReportDetailedMessageForSource(source_name
)) {
2224 RenderFrameObserver
, observers_
,
2225 DetailedConsoleMessageAdded(message
.text
,
2229 static_cast<int32
>(log_severity
)));
2232 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2233 static_cast<int32
>(log_severity
),
2235 static_cast<int32
>(source_line
),
2239 void RenderFrameImpl::loadURLExternally(
2240 blink::WebLocalFrame
* frame
,
2241 const blink::WebURLRequest
& request
,
2242 blink::WebNavigationPolicy policy
,
2243 const blink::WebString
& suggested_name
) {
2244 DCHECK(!frame_
|| frame_
== frame
);
2245 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2246 if (policy
== blink::WebNavigationPolicyDownload
) {
2247 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2248 request
.url(), referrer
,
2251 OpenURL(frame
, request
.url(), referrer
, policy
);
2255 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2256 const NavigationPolicyInfo
& info
) {
2257 DCHECK(!frame_
|| frame_
== info
.frame
);
2258 return DecidePolicyForNavigation(this, info
);
2261 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2262 blink::WebFrame
* frame
) {
2263 DCHECK(!frame_
|| frame_
== frame
);
2264 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2267 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2268 const blink::WebFormElement
& form
) {
2269 DCHECK(!frame_
|| frame_
== frame
);
2271 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2274 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2275 const blink::WebFormElement
& form
) {
2276 DCHECK(!frame_
|| frame_
== frame
);
2277 DocumentState
* document_state
=
2278 DocumentState::FromDataSource(frame
->provisionalDataSource());
2279 NavigationState
* navigation_state
= document_state
->navigation_state();
2280 InternalDocumentStateData
* internal_data
=
2281 InternalDocumentStateData::FromDocumentState(document_state
);
2283 if (ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2284 ui::PAGE_TRANSITION_LINK
)) {
2285 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2288 // Save these to be processed when the ensuing navigation is committed.
2289 WebSearchableFormData
web_searchable_form_data(form
);
2290 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2291 internal_data
->set_searchable_form_encoding(
2292 web_searchable_form_data
.encoding().utf8());
2294 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2297 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2298 blink::WebDataSource
* datasource
) {
2299 DCHECK(!frame_
|| frame_
== frame
);
2301 // TODO(nasko): Move implementation here. Needed state:
2302 // * pending_navigation_params_
2305 // * PopulateDocumentStateFromPending
2306 // * CreateNavigationStateFromPending
2307 render_view_
->didCreateDataSource(frame
, datasource
);
2309 // Create the serviceworker's per-document network observing object if it
2310 // does not exist (When navigation happens within a page, the provider already
2312 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2313 DocumentState::FromDataSource(datasource
))) {
2314 scoped_ptr
<ServiceWorkerNetworkProvider
>
2315 network_provider(new ServiceWorkerNetworkProvider(routing_id_
));
2316 ServiceWorkerNetworkProvider::AttachToDocumentState(
2317 DocumentState::FromDataSource(datasource
),
2318 network_provider
.Pass());
2322 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2323 bool is_transition_navigation
,
2324 double triggering_event_time
) {
2325 DCHECK(!frame_
|| frame_
== frame
);
2326 WebDataSource
* ds
= frame
->provisionalDataSource();
2328 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2329 // callback is invoked.
2333 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2334 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2335 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2337 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2338 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2340 "Heard swappedout:// when not swapped out.";
2342 // Update the request time if WebKit has better knowledge of it.
2343 if (document_state
->request_time().is_null() &&
2344 triggering_event_time
!= 0.0) {
2345 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2348 // Start time is only set after request time.
2349 document_state
->set_start_load_time(Time::Now());
2351 bool is_top_most
= !frame
->parent();
2353 render_view_
->set_navigation_gesture(
2354 WebUserGestureIndicator::isProcessingUserGesture() ?
2355 NavigationGestureUser
: NavigationGestureAuto
);
2356 } else if (ds
->replacesCurrentHistoryItem()) {
2357 // Subframe navigations that don't add session history items must be
2358 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2359 // handle loading of error pages.
2360 document_state
->navigation_state()->set_transition_type(
2361 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2364 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2365 DidStartProvisionalLoad(frame
));
2366 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2368 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2369 routing_id_
, ds
->request().url(), is_transition_navigation
));
2372 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2373 blink::WebLocalFrame
* frame
) {
2374 DCHECK(!frame_
|| frame_
== frame
);
2375 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2378 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame
* frame
,
2379 const blink::WebURLError
& error
) {
2380 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2382 DCHECK(!frame_
|| frame_
== frame
);
2383 WebDataSource
* ds
= frame
->provisionalDataSource();
2386 const WebURLRequest
& failed_request
= ds
->request();
2388 // Notify the browser that we failed a provisional load with an error.
2390 // Note: It is important this notification occur before DidStopLoading so the
2391 // SSL manager can react to the provisional load failure before being
2392 // notified the load stopped.
2394 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2395 DidFailProvisionalLoad(frame
, error
));
2396 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2397 DidFailProvisionalLoad(error
));
2399 bool show_repost_interstitial
=
2400 (error
.reason
== net::ERR_CACHE_MISS
&&
2401 EqualsASCII(failed_request
.httpMethod(), "POST"));
2403 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
2404 params
.error_code
= error
.reason
;
2405 GetContentClient()->renderer()->GetNavigationErrorStrings(
2411 ¶ms
.error_description
);
2412 params
.url
= error
.unreachableURL
;
2413 params
.showing_repost_interstitial
= show_repost_interstitial
;
2414 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2415 routing_id_
, params
));
2417 // Don't display an error page if this is simply a cancelled load. Aside
2418 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2419 if (error
.reason
== net::ERR_ABORTED
)
2422 // Don't display "client blocked" error page if browser has asked us not to.
2423 if (error
.reason
== net::ERR_BLOCKED_BY_CLIENT
&&
2424 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
2428 // Allow the embedder to suppress an error page.
2429 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2430 error
.unreachableURL
)) {
2434 if (RenderThreadImpl::current() &&
2435 RenderThreadImpl::current()->layout_test_mode()) {
2439 // Make sure we never show errors in view source mode.
2440 frame
->enableViewSourceMode(false);
2442 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2443 NavigationState
* navigation_state
= document_state
->navigation_state();
2445 // If this is a failed back/forward/reload navigation, then we need to do a
2446 // 'replace' load. This is necessary to avoid messing up session history.
2447 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2448 // as session history is concerned.
2450 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2453 // TODO(davidben): This should also take the failed navigation's replacement
2454 // state into account, if a location.replace() failed.
2456 navigation_state
->pending_page_id() != -1 ||
2457 ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2458 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2460 // If we failed on a browser initiated request, then make sure that our error
2461 // page load is regarded as the same browser initiated request.
2462 if (!navigation_state
->is_content_initiated()) {
2463 render_view_
->pending_navigation_params_
.reset(
2464 new FrameMsg_Navigate_Params
);
2465 render_view_
->pending_navigation_params_
->page_id
=
2466 navigation_state
->pending_page_id();
2467 render_view_
->pending_navigation_params_
->pending_history_list_offset
=
2468 navigation_state
->pending_history_list_offset();
2469 render_view_
->pending_navigation_params_
->should_clear_history_list
=
2470 navigation_state
->history_list_was_cleared();
2471 render_view_
->pending_navigation_params_
->common_params
.transition
=
2472 navigation_state
->transition_type();
2473 render_view_
->pending_navigation_params_
->request_time
=
2474 document_state
->request_time();
2475 render_view_
->pending_navigation_params_
->should_replace_current_entry
=
2479 // Load an error page.
2480 LoadNavigationErrorPage(failed_request
, error
, replace
);
2483 void RenderFrameImpl::didCommitProvisionalLoad(
2484 blink::WebLocalFrame
* frame
,
2485 const blink::WebHistoryItem
& item
,
2486 blink::WebHistoryCommitType commit_type
) {
2487 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2489 "url", GetLoadingUrl().possibly_invalid_spec());
2490 DCHECK(!frame_
|| frame_
== frame
);
2491 DocumentState
* document_state
=
2492 DocumentState::FromDataSource(frame
->dataSource());
2493 NavigationState
* navigation_state
= document_state
->navigation_state();
2495 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2496 RenderFrameProxy
* proxy
=
2497 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2499 proxy
->web_frame()->swap(frame_
);
2500 proxy_routing_id_
= MSG_ROUTING_NONE
;
2503 // When we perform a new navigation, we need to update the last committed
2504 // session history entry with state for the page we are leaving. Do this
2505 // before updating the HistoryController state.
2506 render_view_
->UpdateSessionHistory(frame
);
2508 render_view_
->history_controller()->UpdateForCommit(this, item
, commit_type
,
2509 navigation_state
->was_within_same_page());
2511 InternalDocumentStateData
* internal_data
=
2512 InternalDocumentStateData::FromDocumentState(document_state
);
2514 if (document_state
->commit_load_time().is_null())
2515 document_state
->set_commit_load_time(Time::Now());
2517 if (internal_data
->must_reset_scroll_and_scale_state()) {
2518 render_view_
->webview()->resetScrollAndScaleState();
2519 internal_data
->set_must_reset_scroll_and_scale_state(false);
2521 internal_data
->set_use_error_page(false);
2523 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2524 if (is_new_navigation
) {
2525 // We bump our Page ID to correspond with the new session history entry.
2526 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2528 // Don't update history list values for kSwappedOutURL, since
2529 // we don't want to forget the entry that was there, and since we will
2530 // never come back to kSwappedOutURL. Note that we have to call
2531 // UpdateSessionHistory and update page_id_ even in this case, so that
2532 // the current entry gets a state update and so that we don't send a
2533 // state update to the wrong entry when we swap back in.
2534 if (GetLoadingUrl() != GURL(kSwappedOutURL
)) {
2535 // Advance our offset in session history, applying the length limit.
2536 // There is now no forward history.
2537 render_view_
->history_list_offset_
++;
2538 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2539 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2540 render_view_
->history_list_length_
=
2541 render_view_
->history_list_offset_
+ 1;
2544 // Inspect the navigation_state on this frame to see if the navigation
2545 // corresponds to a session history navigation... Note: |frame| may or
2546 // may not be the toplevel frame, but for the case of capturing session
2547 // history, the first committed frame suffices. We keep track of whether
2548 // we've seen this commit before so that only capture session history once
2551 // Note that we need to check if the page ID changed. In the case of a
2552 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2553 // previous URL and the current page ID, which would be wrong.
2554 if (navigation_state
->pending_page_id() != -1 &&
2555 navigation_state
->pending_page_id() != render_view_
->page_id_
&&
2556 !navigation_state
->request_committed()) {
2557 // This is a successful session history navigation!
2558 render_view_
->page_id_
= navigation_state
->pending_page_id();
2560 render_view_
->history_list_offset_
=
2561 navigation_state
->pending_history_list_offset();
2566 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2567 CHECK(sent
); // http://crbug.com/407376
2569 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2570 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2571 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2572 DidCommitProvisionalLoad(is_new_navigation
));
2574 if (!frame
->parent()) { // Only for top frames.
2575 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2576 if (render_thread_impl
) { // Can be NULL in tests.
2577 render_thread_impl
->histogram_customizer()->
2578 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2579 RenderViewImpl::GetRenderViewCount());
2583 // Remember that we've already processed this request, so we don't update
2584 // the session history again. We do this regardless of whether this is
2585 // a session history navigation, because if we attempted a session history
2586 // navigation without valid HistoryItem state, WebCore will think it is a
2588 navigation_state
->set_request_committed(true);
2590 SendDidCommitProvisionalLoad(frame
, commit_type
);
2592 // Check whether we have new encoding name.
2593 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2596 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2597 DCHECK(!frame_
|| frame_
== frame
);
2599 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2600 DidCreateNewDocument(frame
));
2603 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2604 DCHECK(!frame_
|| frame_
== frame
);
2605 // TODO(nasko): Move implementation here. Needed state:
2606 // * enabled_bindings_
2607 // * dom_automation_controller_
2608 // * stats_collection_controller_
2610 render_view_
->didClearWindowObject(frame
);
2612 if (render_view_
->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION
)
2613 DomAutomationController::Install(this, frame
);
2615 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2618 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2619 DCHECK(!frame_
|| frame_
== frame
);
2621 // Notify the browser about non-blank documents loading in the top frame.
2622 GURL url
= frame
->document().url();
2623 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2624 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2625 // frame->tree()->top().
2626 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2627 if (frame
== main_frame
) {
2628 // For now, don't remember plugin zoom values. We don't want to mix them
2629 // with normal web content (i.e. a fixed layout plugin would usually want
2631 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2632 render_view_
->GetRoutingID(),
2633 main_frame
->document().isPluginDocument()));
2637 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2638 DidCreateDocumentElement(frame
));
2641 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2642 const blink::WebString
& title
,
2643 blink::WebTextDirection direction
) {
2644 DCHECK(!frame_
|| frame_
== frame
);
2645 // Ignore all but top level navigations.
2646 if (!frame
->parent()) {
2647 base::string16 title16
= title
;
2648 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2649 routing_id_
, base::UTF16ToUTF8(title16
));
2651 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2652 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2653 shortened_title
, direction
));
2656 // Also check whether we have new encoding name.
2657 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2660 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2661 blink::WebIconURL::Type icon_type
) {
2662 DCHECK(!frame_
|| frame_
== frame
);
2663 // TODO(nasko): Investigate wheather implementation should move here.
2664 render_view_
->didChangeIcon(frame
, icon_type
);
2667 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2668 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2670 DCHECK(!frame_
|| frame_
== frame
);
2671 WebDataSource
* ds
= frame
->dataSource();
2672 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2673 document_state
->set_finish_document_load_time(Time::Now());
2675 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2677 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2678 DidFinishDocumentLoad(frame
));
2679 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2681 // Check whether we have new encoding name.
2682 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2685 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2686 DCHECK(!frame_
|| frame_
== frame
);
2687 if (!frame
->parent()) {
2688 FrameMsg_UILoadMetricsReportType::Value report_type
=
2689 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2690 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2691 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2692 base::TimeDelta::FromSecondsD(
2693 frame
->dataSource()->request().uiStartTime());
2695 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2696 routing_id_
, report_type
, ui_timestamp
));
2700 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2701 const blink::WebURLError
& error
) {
2702 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2704 DCHECK(!frame_
|| frame_
== frame
);
2705 // TODO(nasko): Move implementation here. No state needed.
2706 WebDataSource
* ds
= frame
->dataSource();
2709 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2710 DidFailLoad(frame
, error
));
2712 const WebURLRequest
& failed_request
= ds
->request();
2713 base::string16 error_description
;
2714 GetContentClient()->renderer()->GetNavigationErrorStrings(
2720 &error_description
);
2721 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2722 failed_request
.url(),
2724 error_description
));
2727 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2728 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2730 DCHECK(!frame_
|| frame_
== frame
);
2731 WebDataSource
* ds
= frame
->dataSource();
2732 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2733 if (document_state
->finish_load_time().is_null()) {
2734 if (!frame
->parent()) {
2735 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2736 TRACE_EVENT_SCOPE_PROCESS
);
2738 document_state
->set_finish_load_time(Time::Now());
2741 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2742 DidFinishLoad(frame
));
2743 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2745 // Don't send this message while the frame is swapped out.
2746 if (is_swapped_out())
2749 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2750 ds
->request().url()));
2753 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2754 const blink::WebHistoryItem
& item
,
2755 blink::WebHistoryCommitType commit_type
) {
2756 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2758 DCHECK(!frame_
|| frame_
== frame
);
2759 // If this was a reference fragment navigation that we initiated, then we
2760 // could end up having a non-null pending navigation params. We just need to
2761 // update the ExtraData on the datasource so that others who read the
2762 // ExtraData will get the new NavigationState. Similarly, if we did not
2763 // initiate this navigation, then we need to take care to reset any pre-
2764 // existing navigation state to a content-initiated navigation state.
2765 // DidCreateDataSource conveniently takes care of this for us.
2766 didCreateDataSource(frame
, frame
->dataSource());
2768 DocumentState
* document_state
=
2769 DocumentState::FromDataSource(frame
->dataSource());
2770 NavigationState
* new_state
= document_state
->navigation_state();
2771 new_state
->set_was_within_same_page(true);
2773 didCommitProvisionalLoad(frame
, item
, commit_type
);
2776 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2777 DCHECK(!frame_
|| frame_
== frame
);
2778 // TODO(nasko): Move implementation here. Needed methods:
2779 // * StartNavStateSyncTimerIfNecessary
2780 render_view_
->didUpdateCurrentHistoryItem(frame
);
2783 void RenderFrameImpl::addNavigationTransitionData(
2784 const blink::WebTransitionElementData
& data
) {
2785 FrameHostMsg_AddNavigationTransitionData_Params params
;
2786 params
.render_frame_id
= routing_id_
;
2787 params
.allowed_destination_host_pattern
=
2789 params
.selector
= data
.selector
.utf8();
2790 params
.markup
= data
.markup
.utf8();
2791 params
.elements
.resize(data
.elements
.size());
2792 for (size_t i
= 0; i
< data
.elements
.size(); i
++) {
2793 params
.elements
[i
].id
= data
.elements
[i
].id
.utf8();
2794 params
.elements
[i
].rect
= gfx::Rect(data
.elements
[i
].rect
);
2797 Send(new FrameHostMsg_AddNavigationTransitionData(params
));
2800 void RenderFrameImpl::didChangeThemeColor() {
2801 if (frame_
->parent())
2804 Send(new FrameHostMsg_DidChangeThemeColor(
2805 routing_id_
, frame_
->document().themeColor()));
2808 void RenderFrameImpl::requestNotificationPermission(
2809 const blink::WebSecurityOrigin
& origin
,
2810 blink::WebNotificationPermissionCallback
* callback
) {
2811 if (!notification_permission_dispatcher_
) {
2812 notification_permission_dispatcher_
=
2813 new NotificationPermissionDispatcher(this);
2816 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
2819 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
2820 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
2823 if (is_empty_selection
)
2824 selection_text_
.clear();
2826 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2827 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2828 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2829 // to notify the selection was changed. Focus change should be notified
2830 // before selection change.
2831 GetRenderWidget()->UpdateTextInputType();
2832 SyncSelectionIfRequired();
2833 #if defined(OS_ANDROID)
2834 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
2835 RenderWidget::FROM_NON_IME
);
2839 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
2840 blink::WebColorChooserClient
* client
,
2841 const blink::WebColor
& initial_color
,
2842 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
2843 RendererWebColorChooserImpl
* color_chooser
=
2844 new RendererWebColorChooserImpl(this, client
);
2845 std::vector
<ColorSuggestion
> color_suggestions
;
2846 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
2847 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
2849 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
2850 return color_chooser
;
2853 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
2854 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
2857 frame_
->document().url(),
2861 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
2862 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
2865 frame_
->document().url(),
2869 bool RenderFrameImpl::runModalPromptDialog(
2870 const blink::WebString
& message
,
2871 const blink::WebString
& default_value
,
2872 blink::WebString
* actual_value
) {
2873 base::string16 result
;
2874 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
2877 frame_
->document().url(),
2880 actual_value
->assign(result
);
2884 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2886 const blink::WebString
& message
) {
2887 // If we are swapping out, we have already run the beforeunload handler.
2888 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2889 // at all, to avoid running it twice.
2890 if (is_swapped_out_
)
2893 // Don't allow further dialogs if we are waiting to swap out, since the
2894 // PageGroupLoadDeferrer in our stack prevents it.
2895 if (render_view()->suppress_dialogs_until_swap_out_
)
2898 bool success
= false;
2899 // This is an ignored return value, but is included so we can accept the same
2900 // response as RunJavaScriptMessage.
2901 base::string16 ignored_result
;
2902 render_view()->SendAndRunNestedMessageLoop(
2903 new FrameHostMsg_RunBeforeUnloadConfirm(
2904 routing_id_
, frame_
->document().url(), message
, is_reload
,
2905 &success
, &ignored_result
));
2909 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
2910 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
2911 params
.source_type
= GetRenderWidget()->context_menu_source_type();
2912 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
2913 if (GetRenderWidget()->has_host_context_menu_location()) {
2914 params
.x
= GetRenderWidget()->host_context_menu_location().x();
2915 params
.y
= GetRenderWidget()->host_context_menu_location().y();
2918 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2919 // it. We replace it with an empty GURL so the appropriate items are disabled
2920 // in the context menu.
2921 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2922 // data encoded images. We should have a way to save them.
2923 if (params
.src_url
.spec().size() > GetMaxURLChars())
2924 params
.src_url
= GURL();
2925 context_menu_node_
= data
.node
;
2927 #if defined(OS_ANDROID)
2928 gfx::Rect start_rect
;
2930 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
2931 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
2932 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
2935 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
2938 void RenderFrameImpl::clearContextMenu() {
2939 context_menu_node_
.reset();
2942 void RenderFrameImpl::willSendRequest(
2943 blink::WebLocalFrame
* frame
,
2944 unsigned identifier
,
2945 blink::WebURLRequest
& request
,
2946 const blink::WebURLResponse
& redirect_response
) {
2947 DCHECK(!frame_
|| frame_
== frame
);
2948 // The request my be empty during tests.
2949 if (request
.url().isEmpty())
2952 // Set the first party for cookies url if it has not been set yet (new
2953 // requests). For redirects, it is updated by WebURLLoaderImpl.
2954 if (request
.firstPartyForCookies().isEmpty()) {
2955 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
2956 request
.setFirstPartyForCookies(request
.url());
2958 // TODO(nasko): When the top-level frame is remote, there is no document.
2959 // This is broken and should be fixed to propagate the first party.
2960 WebFrame
* top
= frame
->top();
2961 if (top
->isWebLocalFrame()) {
2962 request
.setFirstPartyForCookies(
2963 frame
->top()->document().firstPartyForCookies());
2968 WebFrame
* top_frame
= frame
->top();
2969 // TODO(nasko): Hack around asking about top-frame data source. This means
2970 // for out-of-process iframes we are treating the current frame as the
2971 // top-level frame, which is wrong.
2972 if (!top_frame
|| top_frame
->isWebRemoteFrame())
2974 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
2975 WebDataSource
* top_data_source
= top_frame
->dataSource();
2976 WebDataSource
* data_source
=
2977 provisional_data_source
? provisional_data_source
: top_data_source
;
2979 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
2980 DCHECK(document_state
);
2981 InternalDocumentStateData
* internal_data
=
2982 InternalDocumentStateData::FromDocumentState(document_state
);
2983 NavigationState
* navigation_state
= document_state
->navigation_state();
2984 ui::PageTransition transition_type
= navigation_state
->transition_type();
2985 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
2986 if (frame_ds
&& frame_ds
->isClientRedirect()) {
2987 transition_type
= ui::PageTransitionFromInt(
2988 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
2991 GURL
request_url(request
.url());
2993 if (GetContentClient()->renderer()->WillSendRequest(
2997 request
.firstPartyForCookies(),
2999 request
.setURL(WebURL(new_url
));
3002 if (internal_data
->is_cache_policy_override_set())
3003 request
.setCachePolicy(internal_data
->cache_policy_override());
3005 // The request's extra data may indicate that we should set a custom user
3006 // agent. This needs to be done here, after WebKit is through with setting the
3007 // user agent on its own. Similarly, it may indicate that we should set an
3008 // X-Requested-With header. This must be done here to avoid breaking CORS
3010 // PlzNavigate: there may also be a stream url associated with the request.
3011 WebString custom_user_agent
;
3012 WebString requested_with
;
3013 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3014 if (request
.extraData()) {
3015 RequestExtraData
* old_extra_data
=
3016 static_cast<RequestExtraData
*>(request
.extraData());
3018 custom_user_agent
= old_extra_data
->custom_user_agent();
3019 if (!custom_user_agent
.isNull()) {
3020 if (custom_user_agent
.isEmpty())
3021 request
.clearHTTPHeaderField("User-Agent");
3023 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3026 requested_with
= old_extra_data
->requested_with();
3027 if (!requested_with
.isNull()) {
3028 if (requested_with
.isEmpty())
3029 request
.clearHTTPHeaderField("X-Requested-With");
3031 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3033 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3036 // Add the default accept header for frame request if it has not been set
3038 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3039 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3040 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3041 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3042 WebString::fromUTF8(kDefaultAcceptHeader
));
3045 // Add an empty HTTP origin header for non GET methods if none is currently
3047 request
.addHTTPOriginIfNeeded(WebString());
3049 // Attach |should_replace_current_entry| state to requests so that, should
3050 // this navigation later require a request transfer, all state is preserved
3051 // when it is re-created in the new process.
3052 bool should_replace_current_entry
= false;
3053 if (navigation_state
->is_content_initiated()) {
3054 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3056 // If the navigation is browser-initiated, the NavigationState contains the
3057 // correct value instead of the WebDataSource.
3059 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3060 // NavigationState::should_replace_current_entry().
3061 should_replace_current_entry
=
3062 navigation_state
->should_replace_current_entry();
3065 int provider_id
= kInvalidServiceWorkerProviderId
;
3066 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3067 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3068 // |provisionalDataSource| may be null in some content::ResourceFetcher
3069 // use cases, we don't hook those requests.
3070 if (frame
->provisionalDataSource()) {
3071 ServiceWorkerNetworkProvider
* provider
=
3072 ServiceWorkerNetworkProvider::FromDocumentState(
3073 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3074 provider_id
= provider
->provider_id();
3076 } else if (frame
->dataSource()) {
3077 ServiceWorkerNetworkProvider
* provider
=
3078 ServiceWorkerNetworkProvider::FromDocumentState(
3079 DocumentState::FromDataSource(frame
->dataSource()));
3080 provider_id
= provider
->provider_id();
3083 WebFrame
* parent
= frame
->parent();
3084 int parent_routing_id
= MSG_ROUTING_NONE
;
3086 parent_routing_id
= -1;
3087 } else if (parent
->isWebLocalFrame()) {
3088 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3090 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3093 RequestExtraData
* extra_data
= new RequestExtraData();
3094 extra_data
->set_visibility_state(render_view_
->visibilityState());
3095 extra_data
->set_custom_user_agent(custom_user_agent
);
3096 extra_data
->set_requested_with(requested_with
);
3097 extra_data
->set_render_frame_id(routing_id_
);
3098 extra_data
->set_is_main_frame(!parent
);
3099 extra_data
->set_frame_origin(
3100 GURL(frame
->document().securityOrigin().toString()));
3101 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3102 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3103 extra_data
->set_allow_download(navigation_state
->allow_download());
3104 extra_data
->set_transition_type(transition_type
);
3105 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3106 extra_data
->set_transferred_request_child_id(
3107 navigation_state
->transferred_request_child_id());
3108 extra_data
->set_transferred_request_request_id(
3109 navigation_state
->transferred_request_request_id());
3110 extra_data
->set_service_worker_provider_id(provider_id
);
3111 extra_data
->set_stream_override(stream_override
.Pass());
3112 request
.setExtraData(extra_data
);
3114 DocumentState
* top_document_state
=
3115 DocumentState::FromDataSource(top_data_source
);
3116 if (top_document_state
) {
3117 // TODO(gavinp): separate out prefetching and prerender field trials
3118 // if the rel=prerender rel type is sticking around.
3119 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3120 top_document_state
->set_was_prefetcher(true);
3123 // This is an instance where we embed a copy of the routing id
3124 // into the data portion of the message. This can cause problems if we
3125 // don't register this id on the browser side, since the download manager
3126 // expects to find a RenderViewHost based off the id.
3127 request
.setRequestorID(render_view_
->GetRoutingID());
3128 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3130 if (!navigation_state
->extra_headers().empty()) {
3131 for (net::HttpUtil::HeadersIterator
i(
3132 navigation_state
->extra_headers().begin(),
3133 navigation_state
->extra_headers().end(), "\n");
3135 if (LowerCaseEqualsASCII(i
.name(), "referer")) {
3136 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3137 blink::WebReferrerPolicyDefault
,
3139 WebString::fromUTF8(i
.values()));
3140 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3142 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3143 WebString::fromUTF8(i
.values()));
3148 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3149 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3152 void RenderFrameImpl::didReceiveResponse(
3153 blink::WebLocalFrame
* frame
,
3154 unsigned identifier
,
3155 const blink::WebURLResponse
& response
) {
3156 DCHECK(!frame_
|| frame_
== frame
);
3157 // Only do this for responses that correspond to a provisional data source
3158 // of the top-most frame. If we have a provisional data source, then we
3159 // can't have any sub-resources yet, so we know that this response must
3160 // correspond to a frame load.
3161 if (!frame
->provisionalDataSource() || frame
->parent())
3164 // If we are in view source mode, then just let the user see the source of
3165 // the server's error page.
3166 if (frame
->isViewSourceModeEnabled())
3169 DocumentState
* document_state
=
3170 DocumentState::FromDataSource(frame
->provisionalDataSource());
3171 int http_status_code
= response
.httpStatusCode();
3173 // Record page load flags.
3174 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3176 document_state
->set_was_fetched_via_spdy(
3177 extra_data
->was_fetched_via_spdy());
3178 document_state
->set_was_npn_negotiated(
3179 extra_data
->was_npn_negotiated());
3180 document_state
->set_npn_negotiated_protocol(
3181 extra_data
->npn_negotiated_protocol());
3182 document_state
->set_was_alternate_protocol_available(
3183 extra_data
->was_alternate_protocol_available());
3184 document_state
->set_connection_info(
3185 extra_data
->connection_info());
3186 document_state
->set_was_fetched_via_proxy(
3187 extra_data
->was_fetched_via_proxy());
3188 document_state
->set_proxy_server(
3189 extra_data
->proxy_server());
3191 InternalDocumentStateData
* internal_data
=
3192 InternalDocumentStateData::FromDocumentState(document_state
);
3193 internal_data
->set_http_status_code(http_status_code
);
3194 // Whether or not the http status code actually corresponds to an error is
3195 // only checked when the page is done loading, if |use_error_page| is
3197 internal_data
->set_use_error_page(true);
3200 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3201 unsigned identifier
) {
3202 DCHECK(!frame_
|| frame_
== frame
);
3203 InternalDocumentStateData
* internal_data
=
3204 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3205 if (!internal_data
->use_error_page())
3208 // Do not show error page when DevTools is attached.
3209 if (render_view_
->devtools_agent_
->IsAttached())
3212 // Display error page, if appropriate.
3213 std::string error_domain
= "http";
3214 int http_status_code
= internal_data
->http_status_code();
3215 if (GetContentClient()->renderer()->HasErrorPage(
3216 http_status_code
, &error_domain
)) {
3218 error
.unreachableURL
= frame
->document().url();
3219 error
.domain
= WebString::fromUTF8(error_domain
);
3220 error
.reason
= http_status_code
;
3221 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3225 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3226 blink::WebLocalFrame
* frame
,
3227 const blink::WebURLRequest
& request
,
3228 const blink::WebURLResponse
& response
) {
3229 DCHECK(!frame_
|| frame_
== frame
);
3230 // The recipients of this message have no use for data: URLs: they don't
3231 // affect the page's insecure content list and are not in the disk cache. To
3232 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3233 // filter them out here.
3234 GURL
url(request
.url());
3235 if (url
.SchemeIs(url::kDataScheme
))
3238 // Let the browser know we loaded a resource from the memory cache. This
3239 // message is needed to display the correct SSL indicators.
3240 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3241 render_view_
->GetRoutingID(),
3243 response
.securityInfo(),
3244 request
.httpMethod().utf8(),
3245 response
.mimeType().utf8(),
3246 WebURLRequestToResourceType(request
)));
3249 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3250 DCHECK(!frame_
|| frame_
== frame
);
3251 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3252 render_view_
->GetRoutingID()));
3255 void RenderFrameImpl::didRunInsecureContent(
3256 blink::WebLocalFrame
* frame
,
3257 const blink::WebSecurityOrigin
& origin
,
3258 const blink::WebURL
& target
) {
3259 DCHECK(!frame_
|| frame_
== frame
);
3260 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3261 render_view_
->GetRoutingID(),
3262 origin
.toString().utf8(),
3266 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3267 DCHECK(!frame_
|| frame_
== frame
);
3268 #if defined(ENABLE_PLUGINS)
3269 if (frame
!= render_view_
->webview()->mainFrame())
3271 PluginChannelHost::Broadcast(
3272 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3276 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3277 v8::Handle
<v8::Context
> context
,
3278 int extension_group
,
3280 DCHECK(!frame_
|| frame_
== frame
);
3281 GetContentClient()->renderer()->DidCreateScriptContext(
3282 frame
, context
, extension_group
, world_id
);
3285 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3286 v8::Handle
<v8::Context
> context
,
3288 DCHECK(!frame_
|| frame_
== frame
);
3290 FOR_EACH_OBSERVER(RenderFrameObserver
,
3292 WillReleaseScriptContext(context
, world_id
));
3295 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3296 blink::WebLocalFrame
* frame
) {
3297 DCHECK(!frame_
|| frame_
== frame
);
3298 if (frame
->parent())
3301 InternalDocumentStateData
* data
=
3302 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3303 data
->set_did_first_visually_non_empty_layout(true);
3305 #if defined(OS_ANDROID)
3306 GetRenderWidget()->DidChangeBodyBackgroundColor(
3307 render_view_
->webwidget_
->backgroundColor());
3310 GetRenderWidget()->QueueMessage(
3311 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3312 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3315 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3316 DCHECK(!frame_
|| frame_
== frame
);
3317 // TODO(nasko): Move implementation here. Needed methods:
3318 // * StartNavStateSyncTimerIfNecessary
3319 render_view_
->didChangeScrollOffset(frame
);
3321 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3324 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3325 DCHECK(!frame_
|| frame_
== frame
);
3326 if (!frame
->parent()) {
3327 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3328 render_view_
->GetRoutingID()));
3332 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3334 bool final_update
) {
3335 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3337 active_match_ordinal
= 0;
3339 render_view_
->Send(new ViewHostMsg_Find_Reply(
3340 render_view_
->GetRoutingID(), request_id
, count
,
3341 gfx::Rect(), active_match_ordinal
, final_update
));
3344 void RenderFrameImpl::reportFindInPageSelection(
3346 int active_match_ordinal
,
3347 const blink::WebRect
& selection_rect
) {
3348 render_view_
->Send(new ViewHostMsg_Find_Reply(
3349 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3350 active_match_ordinal
, false));
3353 void RenderFrameImpl::requestStorageQuota(
3354 blink::WebLocalFrame
* frame
,
3355 blink::WebStorageQuotaType type
,
3356 unsigned long long requested_size
,
3357 blink::WebStorageQuotaCallbacks callbacks
) {
3358 DCHECK(!frame_
|| frame_
== frame
);
3359 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3360 if (origin
.isUnique()) {
3361 // Unique origins cannot store persistent state.
3362 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3365 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3366 render_view_
->GetRoutingID(),
3367 GURL(origin
.toString()),
3368 static_cast<storage::StorageType
>(type
),
3370 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3373 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3374 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3375 impl
->set_render_frame_id(routing_id_
);
3378 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3379 if (!geolocation_dispatcher_
)
3380 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3381 return geolocation_dispatcher_
;
3384 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3385 if (!presentation_dispatcher_
)
3386 presentation_dispatcher_
= new PresentationDispatcher(this);
3387 return presentation_dispatcher_
;
3390 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3391 if (!push_messaging_dispatcher_
)
3392 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3393 return push_messaging_dispatcher_
;
3396 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3397 blink::WebLocalFrame
* frame
,
3398 blink::WebRTCPeerConnectionHandler
* handler
) {
3399 DCHECK(!frame_
|| frame_
== frame
);
3400 #if defined(ENABLE_WEBRTC)
3401 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3405 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3406 if (!web_user_media_client_
)
3407 InitializeUserMediaClient();
3408 return web_user_media_client_
;
3411 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3412 if (!web_encrypted_media_client_
) {
3413 #if defined(ENABLE_PEPPER_CDMS)
3414 scoped_ptr
<media::CdmFactory
> cdm_factory(
3415 new RenderCdmFactory(base::Bind(PepperCdmWrapperImpl::Create
, frame_
)));
3416 #elif defined(ENABLE_BROWSER_CDMS)
3417 scoped_ptr
<media::CdmFactory
> cdm_factory(
3418 new RenderCdmFactory(GetCdmManager()));
3420 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
3423 if (!media_permission_dispatcher_
)
3424 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
3426 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3427 cdm_factory
.Pass(), media_permission_dispatcher_
));
3429 return web_encrypted_media_client_
.get();
3432 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3433 if (!midi_dispatcher_
)
3434 midi_dispatcher_
= new MidiDispatcher(this);
3435 return midi_dispatcher_
;
3438 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3439 blink::WebLocalFrame
* source_frame
,
3440 blink::WebFrame
* target_frame
,
3441 blink::WebSecurityOrigin target_origin
,
3442 blink::WebDOMMessageEvent event
) {
3443 DCHECK(!frame_
|| frame_
== target_frame
);
3445 if (!is_swapped_out_
)
3448 ViewMsg_PostMessage_Params params
;
3449 params
.is_data_raw_string
= false;
3450 params
.data
= event
.data().toString();
3451 params
.source_origin
= event
.origin();
3452 if (!target_origin
.isNull())
3453 params
.target_origin
= target_origin
.toString();
3455 blink::WebMessagePortChannelArray channels
= event
.releaseChannels();
3456 if (!channels
.isEmpty()) {
3457 std::vector
<int> message_port_ids(channels
.size());
3458 // Extract the port IDs from the channel array.
3459 for (size_t i
= 0; i
< channels
.size(); ++i
) {
3460 WebMessagePortChannelImpl
* webchannel
=
3461 static_cast<WebMessagePortChannelImpl
*>(channels
[i
]);
3462 message_port_ids
[i
] = webchannel
->message_port_id();
3463 webchannel
->QueueMessages();
3464 DCHECK_NE(message_port_ids
[i
], MSG_ROUTING_NONE
);
3466 params
.message_port_ids
= message_port_ids
;
3469 // Include the routing ID for the source frame (if one exists), which the
3470 // browser process will translate into the routing ID for the equivalent
3471 // frame in the target process.
3472 params
.source_routing_id
= MSG_ROUTING_NONE
;
3474 RenderViewImpl
* source_view
=
3475 RenderViewImpl::FromWebView(source_frame
->view());
3477 params
.source_routing_id
= source_view
->routing_id();
3480 Send(new ViewHostMsg_RouteMessageEvent(render_view_
->routing_id_
, params
));
3484 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3485 const blink::WebURL
& url
) {
3486 DCHECK(!frame_
|| frame_
== frame
);
3487 std::string user_agent_override_for_url
=
3488 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3489 if (!user_agent_override_for_url
.empty())
3490 return WebString::fromUTF8(user_agent_override_for_url
);
3492 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3493 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3494 return blink::WebString();
3497 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3498 // associated with it, so the checks below are not valid. Temporarily
3499 // return early and fix properly as part of https://crbug.com/426555.
3500 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3501 return blink::WebString();
3503 // If we're in the middle of committing a load, the data source we need
3504 // will still be provisional.
3505 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3506 WebDataSource
* data_source
= NULL
;
3507 if (main_frame
->provisionalDataSource())
3508 data_source
= main_frame
->provisionalDataSource();
3510 data_source
= main_frame
->dataSource();
3512 InternalDocumentStateData
* internal_data
= data_source
?
3513 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3514 if (internal_data
&& internal_data
->is_overriding_user_agent())
3515 return WebString::fromUTF8(
3516 render_view_
->renderer_preferences_
.user_agent_override
);
3517 return blink::WebString();
3520 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3521 DCHECK(!frame_
|| frame_
== frame
);
3522 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3523 return WebString::fromUTF8("1");
3527 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3528 bool default_value
) {
3529 DCHECK(!frame_
|| frame_
== frame
);
3533 bool blocked
= true;
3534 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3535 render_view_
->GetRoutingID(),
3536 GURL(frame
->top()->document().securityOrigin().toString()),
3537 THREE_D_API_TYPE_WEBGL
,
3542 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3543 int arb_robustness_status_code
) {
3544 DCHECK(!frame_
|| frame_
== frame
);
3545 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3546 GURL(frame
->top()->document().securityOrigin().toString()),
3547 THREE_D_API_TYPE_WEBGL
,
3548 arb_robustness_status_code
));
3551 blink::WebScreenOrientationClient
*
3552 RenderFrameImpl::webScreenOrientationClient() {
3553 if (!screen_orientation_dispatcher_
)
3554 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3555 return screen_orientation_dispatcher_
;
3558 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3559 ServiceWorkerNetworkProvider
* provider
=
3560 ServiceWorkerNetworkProvider::FromDocumentState(
3561 DocumentState::FromDataSource(&data_source
));
3562 return provider
->context()->controller_handle_id() !=
3563 kInvalidServiceWorkerHandleId
;
3566 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3567 ServiceWorkerNetworkProvider
* provider
=
3568 ServiceWorkerNetworkProvider::FromDocumentState(
3569 DocumentState::FromDataSource(&data_source
));
3571 if (provider
->context()->controller())
3572 return provider
->context()->controller()->version_id();
3573 return kInvalidServiceWorkerVersionId
;
3576 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3577 blink::WebAXEvent event
) {
3578 HandleWebAccessibilityEvent(obj
, event
);
3581 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3584 const blink::WebAXObject
& start_object
,
3586 const blink::WebAXObject
& end_object
,
3588 if (renderer_accessibility_
) {
3589 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3590 identifier
, match_index
, start_object
, start_offset
,
3591 end_object
, end_offset
);
3595 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3596 DCHECK(!frame_
|| frame_
== frame
);
3598 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3601 bool RenderFrameImpl::enterFullscreen() {
3602 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3606 bool RenderFrameImpl::exitFullscreen() {
3607 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3611 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3612 Send(new FrameHostMsg_MediaPlayingNotification(
3613 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3614 player
->hasAudio(), player
->isRemote()));
3617 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3618 Send(new FrameHostMsg_MediaPausedNotification(
3619 routing_id_
, reinterpret_cast<int64
>(player
)));
3622 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3626 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3627 observers_
.AddObserver(observer
);
3630 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3631 observer
->RenderFrameGone();
3632 observers_
.RemoveObserver(observer
);
3635 void RenderFrameImpl::OnStop() {
3637 frame_
->stopLoading();
3638 if (!frame_
->parent())
3639 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3641 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3644 void RenderFrameImpl::WasHidden() {
3645 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3648 void RenderFrameImpl::WasShown() {
3649 // TODO(kenrb): Need to figure out how to do this better. Should
3650 // VisibilityState remain a page-level concept or move to frames?
3651 // The semantics of 'Show' might have to change here.
3652 if (render_widget_
) {
3653 render_view()->webview()->setVisibilityState(
3654 blink::WebPageVisibilityStateVisible
, false);
3656 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3659 bool RenderFrameImpl::IsHidden() {
3660 return GetRenderWidget()->is_hidden();
3663 // Tell the embedding application that the URL of the active page has changed.
3664 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3665 blink::WebFrame
* frame
,
3666 blink::WebHistoryCommitType commit_type
) {
3667 DCHECK(!frame_
|| frame_
== frame
);
3668 WebDataSource
* ds
= frame
->dataSource();
3671 const WebURLRequest
& request
= ds
->request();
3672 const WebURLResponse
& response
= ds
->response();
3674 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3675 NavigationState
* navigation_state
= document_state
->navigation_state();
3676 InternalDocumentStateData
* internal_data
=
3677 InternalDocumentStateData::FromDocumentState(document_state
);
3679 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3680 params
.http_status_code
= response
.httpStatusCode();
3681 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3682 params
.is_post
= false;
3683 params
.post_id
= -1;
3684 params
.page_id
= render_view_
->page_id_
;
3685 // We need to track the RenderViewHost routing_id because of downstream
3686 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3687 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3688 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3689 // based on the ID stored in the resource requests. Once those dependencies
3690 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3691 // client to be based on the routing_id of the RenderFrameHost.
3692 params
.render_view_routing_id
= render_view_
->routing_id();
3693 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3694 params
.socket_address
.set_port(response
.remotePort());
3695 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3697 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3698 params
.was_within_same_page
= navigation_state
->was_within_same_page();
3699 params
.security_info
= response
.securityInfo();
3701 // Set the URL to be displayed in the browser UI to the user.
3702 params
.url
= GetLoadingUrl();
3703 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3705 // Set the origin of the frame. This will be replicated to the corresponding
3706 // RenderFrameProxies in other processes.
3707 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3708 // to https://crbug.com/439608 and will be replicated as unique origins.
3709 if (!is_swapped_out_
) {
3710 WebString
serialized_origin(frame
->document().securityOrigin().toString());
3711 if (GURL(serialized_origin
).IsStandard())
3712 params
.origin
= url::Origin(serialized_origin
.utf8());
3715 if (frame
->document().baseURL() != params
.url
)
3716 params
.base_url
= frame
->document().baseURL();
3718 GetRedirectChain(ds
, ¶ms
.redirects
);
3719 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3720 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3722 params
.searchable_form_url
= internal_data
->searchable_form_url();
3723 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3725 params
.gesture
= render_view_
->navigation_gesture_
;
3726 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3728 // Make navigation state a part of the DidCommitProvisionalLoad message so
3729 // that committed entry has it at all times.
3730 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3732 params
.page_state
= HistoryEntryToPageState(entry
);
3734 params
.page_state
= PageState::CreateFromURL(request
.url());
3736 if (!frame
->parent()) {
3737 // Top-level navigation.
3739 // Reset the zoom limits in case a plugin had changed them previously. This
3740 // will also call us back which will cause us to send a message to
3741 // update WebContentsImpl.
3742 render_view_
->webview()->zoomLimitsChanged(
3743 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3744 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3746 // Set zoom level, but don't do it for full-page plugin since they don't use
3747 // the same zoom settings.
3748 HostZoomLevels::iterator host_zoom
=
3749 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3750 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3751 // Reset the zoom levels for plugins.
3752 render_view_
->webview()->setZoomLevel(0);
3754 // If the zoom level is not found, then do nothing. In-page navigation
3755 // relies on not changing the zoom level in this case.
3756 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3757 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3760 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3761 // This zoom level was merely recorded transiently for this load. We can
3762 // erase it now. If at some point we reload this page, the browser will
3763 // send us a new, up-to-date zoom level.
3764 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3767 // Update contents MIME type for main frame.
3768 params
.contents_mime_type
= ds
->response().mimeType().utf8();
3770 params
.transition
= navigation_state
->transition_type();
3771 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
3772 // If the main frame does a load, it should not be reported as a subframe
3773 // navigation. This can occur in the following case:
3774 // 1. You're on a site with frames.
3775 // 2. You do a subframe navigation. This is stored with transition type
3777 // 3. You navigate to some non-frame site, say, google.com.
3778 // 4. You navigate back to the page from step 2. Since it was initially
3779 // MANUAL_SUBFRAME, it will be that same transition type here.
3780 // We don't want that, because any navigation that changes the toplevel
3781 // frame should be tracked as a toplevel navigation (this allows us to
3782 // update the URL bar, etc).
3783 params
.transition
= ui::PAGE_TRANSITION_LINK
;
3786 // If the page contained a client redirect (meta refresh, document.loc...),
3787 // set the referrer and transition appropriately.
3788 if (ds
->isClientRedirect()) {
3790 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
3791 params
.transition
= ui::PageTransitionFromInt(
3792 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3794 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
3795 frame
, ds
->request());
3798 base::string16 method
= request
.httpMethod();
3799 if (EqualsASCII(method
, "POST")) {
3800 params
.is_post
= true;
3801 params
.post_id
= ExtractPostId(entry
->root());
3804 // Send the user agent override back.
3805 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
3807 // Track the URL of the original request. We use the first entry of the
3808 // redirect chain if it exists because the chain may have started in another
3810 params
.original_request_url
= GetOriginalRequestURL(ds
);
3812 params
.history_list_was_cleared
=
3813 navigation_state
->history_list_was_cleared();
3815 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
3816 frame
->dataSource()->request().inputPerfMetricReportPolicy());
3817 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
3818 frame
->dataSource()->request().uiStartTime());
3820 // Save some histogram data so we can compute the average memory used per
3821 // page load of the glyphs.
3822 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3823 blink::WebGlyphCache::pageCount());
3825 // This message needs to be sent before any of allowScripts(),
3826 // allowImages(), allowPlugins() is called for the new page, so that when
3827 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3828 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3829 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3831 // Subframe navigation: the type depends on whether this navigation
3832 // generated a new session history entry. When they do generate a session
3833 // history entry, it means the user initiated the navigation and we should
3835 bool is_history_navigation
= commit_type
== blink::WebBackForwardCommit
;
3836 if (is_history_navigation
|| ds
->replacesCurrentHistoryItem())
3837 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
3839 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
3841 DCHECK(!navigation_state
->history_list_was_cleared());
3842 params
.history_list_was_cleared
= false;
3843 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
3845 // Don't send this message while the subframe is swapped out.
3846 if (!is_swapped_out())
3847 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3850 // If we end up reusing this WebRequest (for example, due to a #ref click),
3851 // we don't want the transition type to persist. Just clear it.
3852 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
3855 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
3856 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3858 render_view_
->FrameDidStartLoading(frame_
);
3859 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
3862 void RenderFrameImpl::didStopLoading() {
3863 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3865 render_view_
->FrameDidStopLoading(frame_
);
3866 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
3869 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
3870 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
3873 void RenderFrameImpl::HandleWebAccessibilityEvent(
3874 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
3875 if (renderer_accessibility_
)
3876 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
3879 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
3880 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
3883 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
3884 if (renderer_accessibility())
3885 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
3889 void RenderFrameImpl::OnRequestNavigation(
3890 const CommonNavigationParams
& common_params
,
3891 const RequestNavigationParams
& request_params
) {
3892 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3893 switches::kEnableBrowserSideNavigation
));
3894 WebURLRequest request
=
3895 CreateURLRequestForNavigation(common_params
,
3897 scoped_ptr
<StreamOverrideParameters
>(),
3898 frame_
->isViewSourceModeEnabled());
3899 BeginNavigation(&request
);
3903 void RenderFrameImpl::OnCommitNavigation(
3904 const ResourceResponseHead
& response
,
3905 const GURL
& stream_url
,
3906 const CommonNavigationParams
& common_params
,
3907 const CommitNavigationParams
& commit_params
) {
3908 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3909 switches::kEnableBrowserSideNavigation
));
3910 bool is_reload
= false;
3911 bool is_history_navigation
= commit_params
.page_state
.IsValid();
3912 WebURLRequest::CachePolicy cache_policy
=
3913 WebURLRequest::UseProtocolCachePolicy
;
3914 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3915 common_params
.url
, false /* check_for_stale_navigation */,
3916 is_history_navigation
, -1 /* current_history_list_offset; TODO(clamy)*/,
3917 &is_reload
, &cache_policy
)) {
3921 GetContentClient()->SetActiveURL(common_params
.url
);
3923 // Create a WebURLRequest that blink can use to get access to the body of the
3924 // response through a stream in the browser. Blink will then commit the
3926 // TODO(clamy): Have the navigation commit directly, without going through
3927 // loading a WebURLRequest.
3928 scoped_ptr
<StreamOverrideParameters
> stream_override(
3929 new StreamOverrideParameters());
3930 stream_override
->stream_url
= stream_url
;
3931 stream_override
->response
= response
;
3932 WebURLRequest request
=
3933 CreateURLRequestForNavigation(common_params
,
3934 RequestNavigationParams(),
3935 stream_override
.Pass(),
3936 frame_
->isViewSourceModeEnabled());
3938 // Make sure that blink loader will not try to use browser side navigation for
3939 // this request (since it already went to the browser).
3940 request
.setCheckForBrowserSideNavigation(false);
3942 // Record this before starting the load. A lower bound of this time is needed
3943 // to sanitize the navigationStart override set below.
3944 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
3945 frame_
->loadRequest(request
);
3946 UpdateFrameNavigationTiming(
3947 frame_
, commit_params
.browser_navigation_start
,
3948 renderer_navigation_start
);
3951 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
3952 RenderFrame
* render_frame
,
3953 const NavigationPolicyInfo
& info
) {
3955 // The handlenavigation API is deprecated and will be removed once
3956 // crbug.com/325351 is resolved.
3957 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
3958 GetContentClient()->renderer()->HandleNavigation(
3960 static_cast<DocumentState
*>(info
.extraData
),
3961 render_view_
->opener_id_
,
3964 info
.navigationType
,
3967 return blink::WebNavigationPolicyIgnore
;
3971 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
3973 const base::CommandLine
& command_line
=
3974 *base::CommandLine::ForCurrentProcess();
3976 bool is_subframe
= !!info
.frame
->parent();
3978 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe
) {
3979 // There's no reason to ignore navigations on subframes, since the swap out
3980 // logic no longer applies.
3982 if (is_swapped_out_
) {
3983 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
3984 // Targeted links may try to navigate a swapped out frame. Allow the
3985 // browser process to navigate the tab instead. Note that it is also
3986 // possible for non-targeted navigations (from this view) to arrive
3987 // here just after we are swapped out. It's ok to send them to the
3988 // browser, as long as they're for the top level frame.
3989 // TODO(creis): Ensure this supports targeted form submissions when
3990 // fixing http://crbug.com/101395.
3991 if (info
.frame
->parent() == NULL
) {
3992 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
3993 info
.defaultPolicy
);
3994 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3997 // We should otherwise ignore in-process iframe navigations, if they
3998 // arrive just after we are swapped out.
3999 return blink::WebNavigationPolicyIgnore
;
4002 // Allow kSwappedOutURL to complete.
4003 return info
.defaultPolicy
;
4007 // Webkit is asking whether to navigate to a new URL.
4008 // This is fine normally, except if we're showing UI from one security
4009 // context and they're trying to navigate to a different context.
4010 const GURL
& url
= info
.urlRequest
.url();
4012 // A content initiated navigation may have originated from a link-click,
4013 // script, drag-n-drop operation, etc.
4014 bool is_content_initiated
= static_cast<DocumentState
*>(info
.extraData
)->
4015 navigation_state()->is_content_initiated();
4018 // If --enable-strict-site-isolation is enabled, send all top-level
4019 // navigations to the browser to let it swap processes when crossing site
4020 // boundaries. This is currently expected to break some script calls and
4021 // navigations, such as form submissions.
4022 bool force_swap_due_to_flag
=
4023 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
);
4024 if (force_swap_due_to_flag
&&
4025 !info
.frame
->parent() && (is_content_initiated
|| info
.isRedirect
)) {
4026 WebString origin_str
= info
.frame
->document().securityOrigin().toString();
4027 GURL
frame_url(origin_str
.utf8().data());
4028 // TODO(cevans): revisit whether this site check is still necessary once
4029 // crbug.com/101395 is fixed.
4030 bool same_domain_or_host
=
4031 net::registry_controlled_domains::SameDomainOrHost(
4034 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
4035 // Only keep same-site (domain + scheme) and data URLs in the same process.
4037 (same_domain_or_host
&& frame_url
.scheme() == url
.scheme()) ||
4038 url
.SchemeIs(url::kDataScheme
);
4039 if (!is_same_site
) {
4040 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4041 return blink::WebNavigationPolicyIgnore
;
4045 // If the browser is interested, then give it a chance to look at the request.
4046 if (is_content_initiated
) {
4048 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4049 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4050 EqualsASCII(info
.urlRequest
.httpMethod(), "POST");
4051 bool browser_handles_request
=
4052 render_view_
->renderer_preferences_
4053 .browser_handles_non_local_top_level_requests
4054 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4056 if (!browser_handles_request
) {
4057 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4058 render_view_
->renderer_preferences_
4059 .browser_handles_all_top_level_requests
;
4062 if (browser_handles_request
) {
4063 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4064 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4068 // Use the frame's original request's URL rather than the document's URL for
4069 // subsequent checks. For a popup, the document's URL may become the opener
4070 // window's URL if the opener has called document.write().
4071 // See http://crbug.com/93517.
4072 GURL
old_url(info
.frame
->dataSource()->request().url());
4074 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4075 // an extension or app origin, leaving a WebUI page, etc). We only care about
4076 // top-level navigations (not iframes). But we sometimes navigate to
4077 // about:blank to clear a tab, and we want to still allow that.
4079 // Note: this is known to break POST submissions when crossing process
4080 // boundaries until http://crbug.com/101395 is fixed. This is better for
4081 // security than loading a WebUI, extension or app page in the wrong process.
4082 // POST requests don't work because this mechanism does not preserve form
4083 // POST data. We will need to send the request's httpBody data up to the
4084 // browser process, and issue a special POST navigation in WebKit (via
4085 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4086 // for examples of how to send the httpBody data.
4087 if (!info
.frame
->parent() && is_content_initiated
&&
4088 !url
.SchemeIs(url::kAboutScheme
)) {
4089 bool send_referrer
= false;
4091 // All navigations to or from WebUI URLs or within WebUI-enabled
4092 // RenderProcesses must be handled by the browser process so that the
4093 // correct bindings and data sources can be registered.
4094 // Similarly, navigations to view-source URLs or within ViewSource mode
4095 // must be handled by the browser process (except for reloads - those are
4096 // safe to leave within the renderer).
4097 // Lastly, access to file:// URLs from non-file:// URL pages must be
4098 // handled by the browser so that ordinary renderer processes don't get
4099 // blessed with file permissions.
4100 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4101 bool is_initial_navigation
= render_view_
->page_id_
== -1;
4102 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4103 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4104 url
.SchemeIs(kViewSourceScheme
) ||
4105 (info
.frame
->isViewSourceModeEnabled() &&
4106 info
.navigationType
!= blink::WebNavigationTypeReload
);
4108 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4109 // Fork non-file to file opens. Check the opener URL if this is the
4110 // initial navigation in a newly opened window.
4111 GURL
source_url(old_url
);
4112 if (is_initial_navigation
&& source_url
.is_empty() &&
4113 info
.frame
->opener())
4114 source_url
= info
.frame
->opener()->top()->document().url();
4115 DCHECK(!source_url
.is_empty());
4116 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4120 // Give the embedder a chance.
4121 should_fork
= GetContentClient()->renderer()->ShouldFork(
4122 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4123 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4127 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4128 info
.defaultPolicy
);
4129 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4133 // Detect when a page is "forking" a new tab that can be safely rendered in
4134 // its own process. This is done by sites like Gmail that try to open links
4135 // in new windows without script connections back to the original page. We
4136 // treat such cases as browser navigations (in which we will create a new
4137 // renderer for a cross-site navigation), rather than WebKit navigations.
4139 // We use the following heuristic to decide whether to fork a new page in its
4141 // The parent page must open a new tab to about:blank, set the new tab's
4142 // window.opener to null, and then redirect the tab to a cross-site URL using
4145 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4148 // Must start from a tab showing about:blank, which is later redirected.
4149 old_url
== GURL(url::kAboutBlankURL
) &&
4150 // Must be the first real navigation of the tab.
4151 render_view_
->historyBackListCount() < 1 &&
4152 render_view_
->historyForwardListCount() < 1 &&
4153 // The parent page must have set the child's window.opener to null before
4154 // redirecting to the desired URL.
4155 info
.frame
->opener() == NULL
&&
4156 // Must be a top-level frame.
4157 info
.frame
->parent() == NULL
&&
4158 // Must not have issued the request from this page.
4159 is_content_initiated
&&
4160 // Must be targeted at the current tab.
4161 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4162 // Must be a JavaScript navigation, which appears as "other".
4163 info
.navigationType
== blink::WebNavigationTypeOther
;
4166 // Open the URL via the browser, not via WebKit.
4167 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4168 return blink::WebNavigationPolicyIgnore
;
4171 // PlzNavigate: send the request to the browser if needed.
4172 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4173 switches::kEnableBrowserSideNavigation
) &&
4174 info
.urlRequest
.checkForBrowserSideNavigation()) {
4175 BeginNavigation(&info
.urlRequest
);
4176 return blink::WebNavigationPolicyIgnore
;
4179 return info
.defaultPolicy
;
4182 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4184 const Referrer
& referrer
,
4185 WebNavigationPolicy policy
) {
4186 DCHECK_EQ(frame_
, frame
);
4188 FrameHostMsg_OpenURL_Params params
;
4190 params
.referrer
= referrer
;
4191 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4192 WebDataSource
* ds
= frame
->provisionalDataSource();
4194 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4195 NavigationState
* navigation_state
= document_state
->navigation_state();
4196 if (navigation_state
->is_content_initiated()) {
4197 params
.should_replace_current_entry
= ds
->replacesCurrentHistoryItem();
4199 // This is necessary to preserve the should_replace_current_entry value on
4200 // cross-process redirects, in the event it was set by a previous process.
4202 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4203 // NavigationState::should_replace_current_entry().
4204 params
.should_replace_current_entry
=
4205 navigation_state
->should_replace_current_entry();
4208 params
.should_replace_current_entry
= false;
4210 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4211 if (GetContentClient()->renderer()->AllowPopup())
4212 params
.user_gesture
= true;
4214 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4215 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4216 policy
== blink::WebNavigationPolicyNewWindow
||
4217 policy
== blink::WebNavigationPolicyNewPopup
) {
4218 WebUserGestureIndicator::consumeUserGesture();
4221 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4224 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4225 const std::string
& encoding_name
) {
4226 // Only update main frame's encoding_name.
4227 if (!frame
->parent())
4228 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4231 void RenderFrameImpl::SyncSelectionIfRequired() {
4232 base::string16 text
;
4235 #if defined(ENABLE_PLUGINS)
4236 if (render_view_
->focused_pepper_plugin_
) {
4237 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4238 offset
= 0; // Pepper API does not support offset reporting.
4239 // TODO(kinaba): cut as needed.
4243 size_t location
, length
;
4244 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4245 &location
, &length
)) {
4249 range
= gfx::Range(location
, location
+ length
);
4251 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4252 blink::WebTextInputTypeNone
) {
4253 // If current focused element is editable, we will send 100 more chars
4254 // before and after selection. It is for input method surrounding text
4256 if (location
> kExtraCharsBeforeAndAfterSelection
)
4257 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4260 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4261 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4262 if (!webrange
.isNull())
4263 text
= webrange
.toPlainText();
4266 text
= frame_
->selectionAsText();
4267 // http://crbug.com/101435
4268 // In some case, frame->selectionAsText() returned text's length is not
4269 // equal to the length returned from webwidget()->caretOrSelectionRange().
4270 // So we have to set the range according to text.length().
4271 range
.set_end(range
.start() + text
.length());
4275 // Sometimes we get repeated didChangeSelection calls from webkit when
4276 // the selection hasn't actually changed. We don't want to report these
4277 // because it will cause us to continually claim the X clipboard.
4278 if (selection_text_offset_
!= offset
||
4279 selection_range_
!= range
||
4280 selection_text_
!= text
) {
4281 selection_text_
= text
;
4282 selection_text_offset_
= offset
;
4283 selection_range_
= range
;
4284 SetSelectedText(text
, offset
, range
);
4286 GetRenderWidget()->UpdateSelectionBounds();
4289 void RenderFrameImpl::InitializeUserMediaClient() {
4290 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4293 #if defined(OS_ANDROID)
4294 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4295 switches::kDisableWebRTC
))
4299 #if defined(ENABLE_WEBRTC)
4300 DCHECK(!web_user_media_client_
);
4301 web_user_media_client_
= new UserMediaClientImpl(
4303 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4304 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4308 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4309 const blink::WebURL
& url
,
4310 WebMediaPlayerClient
* client
) {
4311 #if defined(ENABLE_WEBRTC)
4312 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4314 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4315 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4316 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4317 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4318 new RenderMediaLog(),
4319 CreateRendererFactory());
4322 #endif // defined(ENABLE_WEBRTC)
4325 scoped_ptr
<MediaStreamRendererFactory
>
4326 RenderFrameImpl::CreateRendererFactory() {
4327 #if defined(ENABLE_WEBRTC)
4328 return scoped_ptr
<MediaStreamRendererFactory
>(
4329 new MediaStreamRendererFactory());
4331 return scoped_ptr
<MediaStreamRendererFactory
>(
4332 static_cast<MediaStreamRendererFactory
*>(NULL
));
4336 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4338 bool check_for_stale_navigation
,
4339 bool is_history_navigation
,
4340 int current_history_list_offset
,
4342 WebURLRequest::CachePolicy
* cache_policy
) {
4343 MaybeHandleDebugURL(url
);
4344 if (!render_view_
->webview())
4348 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4350 // If this is a stale back/forward (due to a recent navigation the browser
4351 // didn't know about), ignore it. Only check if swapped in because if the
4352 // frame is swapped out, it won't commit before asking the browser.
4353 // TODO(clamy): remove check_for_stale_navigation
4354 if (check_for_stale_navigation
&&
4355 !render_view_
->is_swapped_out() && is_history_navigation
&&
4356 render_view_
->history_list_offset_
!= current_history_list_offset
) {
4360 if (!is_swapped_out_
|| frame_
->parent())
4363 // This is a swapped out main frame, so swap the renderer back in.
4364 // We marked the view as hidden when swapping the view out, so be sure to
4365 // reset the visibility state before navigating to the new URL.
4366 render_view_
->webview()->setVisibilityState(
4367 render_view_
->visibilityState(), false);
4369 // If this is an attempt to reload while we are swapped out, we should not
4370 // reload swappedout://, but the previous page, which is stored in
4371 // params.state. Setting is_reload to false will treat this like a back
4372 // navigation to accomplish that.
4374 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4376 // We refresh timezone when a view is swapped in since timezone
4377 // can get out of sync when the system timezone is updated while
4378 // the view is swapped out.
4379 RenderThreadImpl::NotifyTimezoneChange();
4381 render_view_
->SetSwappedOut(false);
4382 is_swapped_out_
= false;
4386 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4387 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4388 switches::kEnableBrowserSideNavigation
));
4390 // TODO(clamy): Execute the beforeunload event.
4392 // Note: At this stage, the goal is to apply all the modifications the
4393 // renderer wants to make to the request, and then send it to the browser, so
4394 // that the actual network request can be started. Ideally, all such
4395 // modifications should take place in willSendRequest, and in the
4396 // implementation of willSendRequest for the various InspectorAgents
4399 // TODO(clamy): Apply devtools override.
4400 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4402 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4404 // TODO(clamy): Same-document navigations should not be sent back to the
4406 // TODO(clamy): Data urls should not be sent back to the browser either.
4407 Send(new FrameHostMsg_DidStartLoading(routing_id_
, true));
4408 Send(new FrameHostMsg_BeginNavigation(routing_id_
,
4409 MakeBeginNavigationParams(request
),
4410 MakeCommonNavigationParams(request
)));
4413 GURL
RenderFrameImpl::GetLoadingUrl() const {
4414 WebDataSource
* ds
= frame_
->dataSource();
4415 if (ds
->hasUnreachableURL())
4416 return ds
->unreachableURL();
4418 const WebURLRequest
& request
= ds
->request();
4419 return request
.url();
4422 #if defined(OS_ANDROID)
4424 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4425 const blink::WebURL
& url
,
4426 WebMediaPlayerClient
* client
,
4427 media::MediaPermission
* media_permission
,
4428 blink::WebContentDecryptionModule
* initial_cdm
) {
4429 GpuChannelHost
* gpu_channel_host
=
4430 RenderThreadImpl::current()->EstablishGpuChannelSync(
4431 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4432 if (!gpu_channel_host
) {
4433 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4437 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4438 if (SynchronousCompositorFactory
* factory
=
4439 SynchronousCompositorFactory::GetInstance()) {
4440 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4442 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4443 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4445 if (!context_provider
.get()) {
4446 LOG(ERROR
) << "Failed to get context3d for media player";
4450 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4451 context_provider
, gpu_channel_host
, routing_id_
);
4454 return new WebMediaPlayerAndroid(
4457 weak_factory_
.GetWeakPtr(),
4458 GetMediaPlayerManager(),
4462 stream_texture_factory
,
4463 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4464 new RenderMediaLog());
4467 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4468 if (!media_player_manager_
)
4469 media_player_manager_
= new RendererMediaPlayerManager(this);
4470 return media_player_manager_
;
4473 #endif // defined(OS_ANDROID)
4475 #if defined(ENABLE_BROWSER_CDMS)
4476 RendererCdmManager
* RenderFrameImpl::GetCdmManager() {
4478 cdm_manager_
= new RendererCdmManager(this);
4479 return cdm_manager_
;
4481 #endif // defined(ENABLE_BROWSER_CDMS)
4483 } // namespace content