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_stream_dispatcher.h"
76 #include "content/renderer/media/media_stream_renderer_factory.h"
77 #include "content/renderer/media/midi_dispatcher.h"
78 #include "content/renderer/media/render_media_log.h"
79 #include "content/renderer/media/user_media_client_impl.h"
80 #include "content/renderer/media/webmediaplayer_ms.h"
81 #include "content/renderer/mojo/service_registry_js_wrapper.h"
82 #include "content/renderer/notification_permission_dispatcher.h"
83 #include "content/renderer/npapi/plugin_channel_host.h"
84 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
85 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
86 #include "content/renderer/render_frame_proxy.h"
87 #include "content/renderer/render_process.h"
88 #include "content/renderer/render_thread_impl.h"
89 #include "content/renderer/render_view_impl.h"
90 #include "content/renderer/render_widget_fullscreen_pepper.h"
91 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
92 #include "content/renderer/renderer_webcolorchooser_impl.h"
93 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
94 #include "content/renderer/shared_worker_repository.h"
95 #include "content/renderer/v8_value_converter_impl.h"
96 #include "content/renderer/websharedworker_proxy.h"
97 #include "gin/modules/module_registry.h"
98 #include "media/base/audio_renderer_mixer_input.h"
99 #include "media/base/media_log.h"
100 #include "media/blink/webcontentdecryptionmodule_impl.h"
101 #include "media/blink/webencryptedmediaclient_impl.h"
102 #include "media/blink/webmediaplayer_impl.h"
103 #include "media/blink/webmediaplayer_params.h"
104 #include "media/filters/default_renderer_factory.h"
105 #include "media/filters/gpu_video_accelerator_factories.h"
106 #include "net/base/data_url.h"
107 #include "net/base/net_errors.h"
108 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
109 #include "net/http/http_util.h"
110 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
111 #include "third_party/WebKit/public/platform/WebString.h"
112 #include "third_party/WebKit/public/platform/WebURL.h"
113 #include "third_party/WebKit/public/platform/WebURLError.h"
114 #include "third_party/WebKit/public/platform/WebURLResponse.h"
115 #include "third_party/WebKit/public/platform/WebVector.h"
116 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
117 #include "third_party/WebKit/public/web/WebDocument.h"
118 #include "third_party/WebKit/public/web/WebFrameWidget.h"
119 #include "third_party/WebKit/public/web/WebGlyphCache.h"
120 #include "third_party/WebKit/public/web/WebLocalFrame.h"
121 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
122 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
123 #include "third_party/WebKit/public/web/WebPlugin.h"
124 #include "third_party/WebKit/public/web/WebPluginParams.h"
125 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
126 #include "third_party/WebKit/public/web/WebRange.h"
127 #include "third_party/WebKit/public/web/WebScriptSource.h"
128 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
129 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
130 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
131 #include "third_party/WebKit/public/web/WebSurroundingText.h"
132 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
133 #include "third_party/WebKit/public/web/WebView.h"
134 #include "third_party/mojo/src/mojo/edk/js/core.h"
135 #include "third_party/mojo/src/mojo/edk/js/support.h"
137 #if defined(ENABLE_PLUGINS)
138 #include "content/renderer/npapi/webplugin_impl.h"
139 #include "content/renderer/pepper/pepper_browser_connection.h"
140 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
141 #include "content/renderer/pepper/pepper_webplugin_impl.h"
142 #include "content/renderer/pepper/plugin_module.h"
145 #if defined(ENABLE_WEBRTC)
146 #include "content/renderer/media/rtc_peer_connection_handler.h"
149 #if defined(OS_ANDROID)
150 #include <cpu-features.h>
152 #include "content/common/gpu/client/context_provider_command_buffer.h"
153 #include "content/renderer/android/synchronous_compositor_factory.h"
154 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
155 #include "content/renderer/media/android/renderer_media_player_manager.h"
156 #include "content/renderer/media/android/stream_texture_factory_impl.h"
157 #include "content/renderer/media/android/webmediaplayer_android.h"
159 #include "webkit/common/gpu/context_provider_web_context.h"
162 #if defined(ENABLE_PEPPER_CDMS)
163 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
164 #elif defined(ENABLE_BROWSER_CDMS)
165 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
168 using blink::WebContextMenuData
;
169 using blink::WebData
;
170 using blink::WebDataSource
;
171 using blink::WebDocument
;
172 using blink::WebElement
;
173 using blink::WebExternalPopupMenu
;
174 using blink::WebExternalPopupMenuClient
;
175 using blink::WebFrame
;
176 using blink::WebHistoryItem
;
177 using blink::WebHTTPBody
;
178 using blink::WebLocalFrame
;
179 using blink::WebMediaPlayer
;
180 using blink::WebMediaPlayerClient
;
181 using blink::WebNavigationPolicy
;
182 using blink::WebNavigationType
;
183 using blink::WebNode
;
184 using blink::WebPluginParams
;
185 using blink::WebPopupMenuInfo
;
186 using blink::WebRange
;
187 using blink::WebReferrerPolicy
;
188 using blink::WebScriptSource
;
189 using blink::WebSearchableFormData
;
190 using blink::WebSecurityOrigin
;
191 using blink::WebSecurityPolicy
;
192 using blink::WebServiceWorkerProvider
;
193 using blink::WebStorageQuotaCallbacks
;
194 using blink::WebString
;
196 using blink::WebURLError
;
197 using blink::WebURLRequest
;
198 using blink::WebURLResponse
;
199 using blink::WebUserGestureIndicator
;
200 using blink::WebVector
;
201 using blink::WebView
;
203 using base::TimeDelta
;
209 const char kDefaultAcceptHeader
[] =
210 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
212 const char kAcceptHeader
[] = "Accept";
214 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
216 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
217 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
218 LAZY_INSTANCE_INITIALIZER
;
220 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
221 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
223 int64
ExtractPostId(const WebHistoryItem
& item
) {
227 if (item
.httpBody().isNull())
230 return item
.httpBody().identifier();
233 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
234 const WebURLResponse
& response
) {
235 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
238 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
239 // Replace any occurrences of swappedout:// with about:blank.
240 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
241 WebVector
<WebURL
> urls
;
242 ds
->redirectChain(urls
);
243 result
->reserve(urls
.size());
244 for (size_t i
= 0; i
< urls
.size(); ++i
) {
245 if (urls
[i
] != GURL(kSwappedOutURL
))
246 result
->push_back(urls
[i
]);
248 result
->push_back(blank_url
);
252 // Returns the original request url. If there is no redirect, the original
253 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
254 // frame was loaded by loadData, the original url will be ds->unreachableURL()
255 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
256 // WebDataSource has unreachable URL means that the frame is loaded through
257 // blink::WebFrame::loadData(), and the base URL will be in the redirect
258 // chain. However, we never visited the baseURL. So in this case, we should
259 // use the unreachable URL as the original URL.
260 if (ds
->hasUnreachableURL())
261 return ds
->unreachableURL();
263 std::vector
<GURL
> redirects
;
264 GetRedirectChain(ds
, &redirects
);
265 if (!redirects
.empty())
266 return redirects
.at(0);
268 return ds
->originalRequest().url();
271 NOINLINE
void CrashIntentionally() {
272 // NOTE(shess): Crash directly rather than using NOTREACHED() so
273 // that the signature is easier to triage in crash reports.
274 volatile int* zero
= NULL
;
278 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
279 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
280 // NOTE(rogerm): We intentionally perform an invalid heap access here in
281 // order to trigger an Address Sanitizer (ASAN) error report.
282 const char kCrashDomain
[] = "crash";
283 const char kHeapOverflow
[] = "/heap-overflow";
284 const char kHeapUnderflow
[] = "/heap-underflow";
285 const char kUseAfterFree
[] = "/use-after-free";
286 #if defined(SYZYASAN)
287 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
288 const char kCorruptHeap
[] = "/corrupt-heap";
291 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
297 std::string
crash_type(url
.path());
298 if (crash_type
== kHeapOverflow
) {
299 base::debug::AsanHeapOverflow();
300 } else if (crash_type
== kHeapUnderflow
) {
301 base::debug::AsanHeapUnderflow();
302 } else if (crash_type
== kUseAfterFree
) {
303 base::debug::AsanHeapUseAfterFree();
304 #if defined(SYZYASAN)
305 } else if (crash_type
== kCorruptHeapBlock
) {
306 base::debug::AsanCorruptHeapBlock();
307 } else if (crash_type
== kCorruptHeap
) {
308 base::debug::AsanCorruptHeap();
312 #endif // ADDRESS_SANITIZER || SYZYASAN
314 void MaybeHandleDebugURL(const GURL
& url
) {
315 if (!url
.SchemeIs(kChromeUIScheme
))
317 if (url
== GURL(kChromeUICrashURL
)) {
318 CrashIntentionally();
319 } else if (url
== GURL(kChromeUIDumpURL
)) {
320 // This URL will only correctly create a crash dump file if content is
321 // hosted in a process that has correctly called
322 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
323 // of base::debug::DumpWithoutCrashing for more details.
324 base::debug::DumpWithoutCrashing();
325 } else if (url
== GURL(kChromeUIKillURL
)) {
326 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
327 } else if (url
== GURL(kChromeUIHangURL
)) {
329 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
331 } else if (url
== GURL(kChromeUIShorthangURL
)) {
332 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
335 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
336 MaybeTriggerAsanError(url
);
337 #endif // ADDRESS_SANITIZER || SYZYASAN
340 // Returns false unless this is a top-level navigation.
341 bool IsTopLevelNavigation(WebFrame
* frame
) {
342 return frame
->parent() == NULL
;
345 // Returns false unless this is a top-level navigation that crosses origins.
346 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
348 WebNavigationType type
,
350 if (!IsTopLevelNavigation(frame
))
353 // Navigations initiated within Webkit are not sent out to the external host
354 // in the following cases.
355 // 1. The url scheme is not http/https
356 // 2. The origin of the url and the opener is the same in which case the
357 // opener relationship is maintained.
358 // 3. Reloads/form submits/back forward navigations
359 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
362 if (type
!= blink::WebNavigationTypeReload
&&
363 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
364 // The opener relationship between the new window and the parent allows the
365 // new window to script the parent and vice versa. This is not allowed if
366 // the origins of the two domains are different. This can be treated as a
367 // top level navigation and routed back to the host.
368 blink::WebFrame
* opener
= frame
->opener();
372 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
378 WebURLRequest
CreateURLRequestForNavigation(
379 const CommonNavigationParams
& common_params
,
380 const RequestNavigationParams
& request_params
,
381 scoped_ptr
<StreamOverrideParameters
> stream_override
,
382 bool is_view_source_mode_enabled
) {
383 WebURLRequest
request(common_params
.url
);
384 if (is_view_source_mode_enabled
)
385 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
387 if (common_params
.referrer
.url
.is_valid()) {
388 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
389 common_params
.referrer
.policy
,
391 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
392 if (!web_referrer
.isEmpty())
393 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
396 if (!request_params
.extra_headers
.empty()) {
397 for (net::HttpUtil::HeadersIterator
i(request_params
.extra_headers
.begin(),
398 request_params
.extra_headers
.end(),
401 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
402 WebString::fromUTF8(i
.values()));
406 if (request_params
.is_post
) {
407 request
.setHTTPMethod(WebString::fromUTF8("POST"));
410 WebHTTPBody http_body
;
411 http_body
.initialize();
412 const char* data
= NULL
;
413 if (request_params
.browser_initiated_post_data
.size()) {
414 data
= reinterpret_cast<const char*>(
415 &request_params
.browser_initiated_post_data
.front());
417 http_body
.appendData(
418 WebData(data
, request_params
.browser_initiated_post_data
.size()));
419 request
.setHTTPBody(http_body
);
422 RequestExtraData
* extra_data
= new RequestExtraData();
423 extra_data
->set_stream_override(stream_override
.Pass());
424 request
.setExtraData(extra_data
);
428 void UpdateFrameNavigationTiming(WebFrame
* frame
,
429 base::TimeTicks browser_navigation_start
,
430 base::TimeTicks renderer_navigation_start
) {
431 // The browser provides the navigation_start time to bootstrap the
432 // Navigation Timing information for the browser-initiated navigations. In
433 // case of cross-process navigations, this carries over the time of
434 // finishing the onbeforeunload handler of the previous page.
435 DCHECK(!browser_navigation_start
.is_null());
436 if (frame
->provisionalDataSource()) {
437 // |browser_navigation_start| is likely before this process existed, so we
438 // can't use InterProcessTimeTicksConverter. We need at least to ensure
439 // that the browser-side navigation start we set is not later than the one
440 // on the renderer side.
441 base::TimeTicks navigation_start
= std::min(
442 browser_navigation_start
, renderer_navigation_start
);
443 double navigation_start_seconds
=
444 (navigation_start
- base::TimeTicks()).InSecondsF();
445 frame
->provisionalDataSource()->setNavigationStartTime(
446 navigation_start_seconds
);
447 // TODO(clamy): We need to provide additional timing values for the
448 // Navigation Timing API to work with browser-side navigations.
453 FrameHostMsg_BeginNavigation_Params
MakeBeginNavigationParams(
454 blink::WebURLRequest
* request
) {
455 FrameHostMsg_BeginNavigation_Params params
;
456 params
.method
= request
->httpMethod().latin1();
457 params
.headers
= GetWebURLRequestHeaders(*request
);
458 params
.load_flags
= GetLoadFlagsForWebURLRequest(*request
);
459 params
.request_body
= GetRequestBodyForWebURLRequest(*request
);
460 params
.has_user_gesture
= request
->hasUserGesture();
465 CommonNavigationParams
MakeCommonNavigationParams(
466 blink::WebURLRequest
* request
) {
467 const RequestExtraData kEmptyData
;
468 const RequestExtraData
* extra_data
=
469 static_cast<RequestExtraData
*>(request
->extraData());
471 extra_data
= &kEmptyData
;
472 CommonNavigationParams params
;
473 params
.url
= request
->url();
474 params
.referrer
= Referrer(
475 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
476 request
->referrerPolicy());
477 params
.transition
= extra_data
->transition_type();
481 #if !defined(OS_ANDROID)
482 media::Context3D
GetSharedMainThreadContext3D() {
483 cc::ContextProvider
* provider
=
484 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
486 return media::Context3D();
487 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
491 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
494 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
496 static_cast<int>(content_name) == static_cast<int>(blink_name), \
497 "enum values must match")
499 // Check that blink::WebSandboxFlags is kept in sync with
500 // content::SandboxFlags.
501 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE
,
502 blink::WebSandboxFlags::None
);
503 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION
,
504 blink::WebSandboxFlags::Navigation
);
505 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS
,
506 blink::WebSandboxFlags::Plugins
);
507 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN
,
508 blink::WebSandboxFlags::Origin
);
509 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS
,
510 blink::WebSandboxFlags::Forms
);
511 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS
,
512 blink::WebSandboxFlags::Scripts
);
513 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION
,
514 blink::WebSandboxFlags::TopNavigation
);
515 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS
,
516 blink::WebSandboxFlags::Popups
);
517 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES
,
518 blink::WebSandboxFlags::AutomaticFeatures
);
519 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK
,
520 blink::WebSandboxFlags::PointerLock
);
521 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN
,
522 blink::WebSandboxFlags::DocumentDomain
);
523 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK
,
524 blink::WebSandboxFlags::OrientationLock
);
525 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL
,
526 blink::WebSandboxFlags::All
);
531 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
533 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
535 if (g_create_render_frame_impl
)
536 return g_create_render_frame_impl(render_view
, routing_id
);
538 return new RenderFrameImpl(render_view
, routing_id
);
542 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int32 routing_id
) {
543 RoutingIDFrameMap::iterator iter
=
544 g_routing_id_frame_map
.Get().find(routing_id
);
545 if (iter
!= g_routing_id_frame_map
.Get().end())
551 void RenderFrameImpl::CreateFrame(
553 int parent_routing_id
,
554 int proxy_routing_id
,
555 const FrameReplicationState
& replicated_state
,
556 CompositorDependencies
* compositor_deps
,
557 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
558 // TODO(nasko): For now, this message is only sent for subframes, as the
559 // top level frame is created when the RenderView is created through the
561 CHECK_NE(MSG_ROUTING_NONE
, parent_routing_id
);
563 blink::WebLocalFrame
* web_frame
;
564 RenderFrameImpl
* render_frame
;
565 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
566 RenderFrameProxy
* parent_proxy
=
567 RenderFrameProxy::FromRoutingID(parent_routing_id
);
568 // If the browser is sending a valid parent routing id, it should already
569 // be created and registered.
571 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
573 // Create the RenderFrame and WebLocalFrame, linking the two.
575 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
576 web_frame
= parent_web_frame
->createLocalChild(
577 WebString::fromUTF8(replicated_state
.name
),
578 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
), render_frame
);
580 RenderFrameProxy
* proxy
=
581 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
583 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
584 web_frame
= blink::WebLocalFrame::create(render_frame
);
585 render_frame
->proxy_routing_id_
= proxy_routing_id
;
586 web_frame
->initializeToReplaceRemoteFrame(proxy
->web_frame());
588 render_frame
->SetWebFrame(web_frame
);
590 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
591 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
592 switches::kSitePerProcess
));
593 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
594 widget_params
.routing_id
, widget_params
.surface_id
,
595 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
596 compositor_deps
, web_frame
);
597 // TODO(kenrb): Observing shouldn't be necessary when we sort out
598 // WasShown and WasHidden, separating page-level visibility from
599 // frame-level visibility.
600 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
603 render_frame
->Initialize();
607 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
608 return RenderFrameImpl::FromWebFrame(web_frame
);
612 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
613 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
614 if (iter
!= g_frame_map
.Get().end())
620 void RenderFrameImpl::InstallCreateHook(
621 CreateRenderFrameImplFunction create_render_frame_impl
) {
622 CHECK(!g_create_render_frame_impl
);
623 g_create_render_frame_impl
= create_render_frame_impl
;
627 content::SandboxFlags
RenderFrameImpl::WebToContentSandboxFlags(
628 blink::WebSandboxFlags flags
) {
629 return static_cast<content::SandboxFlags
>(flags
);
633 blink::WebSandboxFlags
RenderFrameImpl::ContentToWebSandboxFlags(
634 content::SandboxFlags flags
) {
635 return static_cast<blink::WebSandboxFlags
>(flags
);
638 // RenderFrameImpl ----------------------------------------------------------
639 RenderFrameImpl::RenderFrameImpl(RenderViewImpl
* render_view
, int routing_id
)
641 render_view_(render_view
->AsWeakPtr()),
642 routing_id_(routing_id
),
643 is_swapped_out_(false),
644 render_frame_proxy_(NULL
),
645 is_detaching_(false),
646 proxy_routing_id_(MSG_ROUTING_NONE
),
647 #if defined(ENABLE_PLUGINS)
648 plugin_power_saver_helper_(NULL
),
651 selection_text_offset_(0),
652 selection_range_(gfx::Range::InvalidRange()),
653 handling_select_range_(false),
654 notification_permission_dispatcher_(NULL
),
655 web_user_media_client_(NULL
),
656 midi_dispatcher_(NULL
),
657 #if defined(OS_ANDROID)
658 media_player_manager_(NULL
),
660 #if defined(ENABLE_BROWSER_CDMS)
663 #if defined(VIDEO_HOLE)
664 contains_media_player_(false),
666 geolocation_dispatcher_(NULL
),
667 push_messaging_dispatcher_(NULL
),
668 screen_orientation_dispatcher_(NULL
),
669 manifest_manager_(NULL
),
670 accessibility_mode_(AccessibilityModeOff
),
671 renderer_accessibility_(NULL
),
672 weak_factory_(this) {
673 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
674 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
675 CHECK(result
.second
) << "Inserting a duplicate item.";
677 RenderThread::Get()->AddRoute(routing_id_
, this);
679 render_view_
->RegisterRenderFrame(this);
681 // Everything below subclasses RenderFrameObserver and is automatically
682 // deleted when the RenderFrame gets deleted.
683 #if defined(OS_ANDROID)
684 new GinJavaBridgeDispatcher(this);
687 #if defined(ENABLE_PLUGINS)
688 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
691 manifest_manager_
= new ManifestManager(this);
694 RenderFrameImpl::~RenderFrameImpl() {
695 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
696 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
698 #if defined(VIDEO_HOLE)
699 if (contains_media_player_
)
700 render_view_
->UnregisterVideoHoleFrame(this);
703 if (render_frame_proxy_
)
704 delete render_frame_proxy_
;
706 render_view_
->UnregisterRenderFrame(this);
707 g_routing_id_frame_map
.Get().erase(routing_id_
);
708 RenderThread::Get()->RemoveRoute(routing_id_
);
711 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
714 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
715 std::make_pair(web_frame
, this));
716 CHECK(result
.second
) << "Inserting a duplicate item.";
721 void RenderFrameImpl::Initialize() {
722 #if defined(ENABLE_PLUGINS)
723 new PepperBrowserConnection(this);
725 new SharedWorkerRepository(this);
727 if (!frame_
->parent())
728 new ImageLoadingHelper(this);
730 // We delay calling this until we have the WebFrame so that any observer or
731 // embedder can call GetWebFrame on any RenderFrame.
732 GetContentClient()->renderer()->RenderFrameCreated(this);
735 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
736 return render_view_
.get();
739 #if defined(ENABLE_PLUGINS)
740 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
741 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
742 DidCreatePepperPlugin(host
));
743 if (host
->GetPluginName() == kFlashPluginName
) {
744 RenderThread::Get()->RecordAction(
745 base::UserMetricsAction("FrameLoadWithFlash"));
749 void RenderFrameImpl::PepperDidChangeCursor(
750 PepperPluginInstanceImpl
* instance
,
751 const blink::WebCursorInfo
& cursor
) {
752 // Update the cursor appearance immediately if the requesting plugin is the
753 // one which receives the last mouse event. Otherwise, the new cursor won't be
754 // picked up until the plugin gets the next input event. That is bad if, e.g.,
755 // the plugin would like to set an invisible cursor when there isn't any user
756 // input for a while.
757 if (instance
== render_view_
->pepper_last_mouse_event_target())
758 GetRenderWidget()->didChangeCursor(cursor
);
761 void RenderFrameImpl::PepperDidReceiveMouseEvent(
762 PepperPluginInstanceImpl
* instance
) {
763 render_view_
->set_pepper_last_mouse_event_target(instance
);
766 void RenderFrameImpl::PepperTextInputTypeChanged(
767 PepperPluginInstanceImpl
* instance
) {
768 if (instance
!= render_view_
->focused_pepper_plugin())
771 GetRenderWidget()->UpdateTextInputType();
773 FocusedNodeChangedForAccessibility(WebNode());
776 void RenderFrameImpl::PepperCaretPositionChanged(
777 PepperPluginInstanceImpl
* instance
) {
778 if (instance
!= render_view_
->focused_pepper_plugin())
780 GetRenderWidget()->UpdateSelectionBounds();
783 void RenderFrameImpl::PepperCancelComposition(
784 PepperPluginInstanceImpl
* instance
) {
785 if (instance
!= render_view_
->focused_pepper_plugin())
787 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
788 #if defined(OS_MACOSX) || defined(USE_AURA)
789 GetRenderWidget()->UpdateCompositionInfo(true);
793 void RenderFrameImpl::PepperSelectionChanged(
794 PepperPluginInstanceImpl
* instance
) {
795 if (instance
!= render_view_
->focused_pepper_plugin())
797 SyncSelectionIfRequired();
800 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
801 PepperPluginInstanceImpl
* plugin
) {
803 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
804 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
805 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
806 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
807 plugin
, active_url
, GetRenderWidget()->screenInfo());
808 widget
->show(blink::WebNavigationPolicyIgnore
);
812 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
813 if (!render_view_
->focused_pepper_plugin())
815 return render_view_
->focused_pepper_plugin()->
816 IsPluginAcceptingCompositionEvents();
819 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
820 base::ProcessId plugin_pid
) {
821 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
822 // routing_id_ as a result.
823 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
826 void RenderFrameImpl::SimulateImeSetComposition(
827 const base::string16
& text
,
828 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
831 render_view_
->OnImeSetComposition(
832 text
, underlines
, selection_start
, selection_end
);
835 void RenderFrameImpl::SimulateImeConfirmComposition(
836 const base::string16
& text
,
837 const gfx::Range
& replacement_range
) {
838 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
841 void RenderFrameImpl::OnImeSetComposition(
842 const base::string16
& text
,
843 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
846 // When a PPAPI plugin has focus, we bypass WebKit.
847 if (!IsPepperAcceptingCompositionEvents()) {
848 pepper_composition_text_
= text
;
850 // TODO(kinaba) currently all composition events are sent directly to
851 // plugins. Use DOM event mechanism after WebKit is made aware about
852 // plugins that support composition.
853 // The code below mimics the behavior of WebCore::Editor::setComposition.
855 // Empty -> nonempty: composition started.
856 if (pepper_composition_text_
.empty() && !text
.empty()) {
857 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
860 // Nonempty -> empty: composition canceled.
861 if (!pepper_composition_text_
.empty() && text
.empty()) {
862 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
865 pepper_composition_text_
= text
;
866 // Nonempty: composition is ongoing.
867 if (!pepper_composition_text_
.empty()) {
868 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
869 pepper_composition_text_
, underlines
, selection_start
,
875 void RenderFrameImpl::OnImeConfirmComposition(
876 const base::string16
& text
,
877 const gfx::Range
& replacement_range
,
878 bool keep_selection
) {
879 // When a PPAPI plugin has focus, we bypass WebKit.
880 // Here, text.empty() has a special meaning. It means to commit the last
881 // update of composition text (see
882 // RenderWidgetHost::ImeConfirmComposition()).
883 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
886 // last_text is empty only when both text and pepper_composition_text_ is.
888 if (last_text
.empty())
891 if (!IsPepperAcceptingCompositionEvents()) {
892 base::i18n::UTF16CharIterator
iterator(&last_text
);
894 while (iterator
.Advance()) {
895 blink::WebKeyboardEvent char_event
;
896 char_event
.type
= blink::WebInputEvent::Char
;
897 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
898 char_event
.modifiers
= 0;
899 char_event
.windowsKeyCode
= last_text
[i
];
900 char_event
.nativeKeyCode
= last_text
[i
];
902 const int32 char_start
= i
;
903 for (; i
< iterator
.array_pos(); ++i
) {
904 char_event
.text
[i
- char_start
] = last_text
[i
];
905 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
908 if (GetRenderWidget()->webwidget())
909 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
912 // Mimics the order of events sent by WebKit.
913 // See WebCore::Editor::setComposition() for the corresponding code.
914 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
915 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
917 pepper_composition_text_
.clear();
919 #endif // defined(ENABLE_PLUGINS)
921 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
922 if (!web_user_media_client_
)
923 InitializeUserMediaClient();
924 return web_user_media_client_
?
925 web_user_media_client_
->media_stream_dispatcher() : NULL
;
928 bool RenderFrameImpl::Send(IPC::Message
* message
) {
933 if (is_swapped_out_
) {
934 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
940 return RenderThread::Get()->Send(message
);
943 #if defined(OS_MACOSX) || defined(OS_ANDROID)
944 void RenderFrameImpl::DidHideExternalPopupMenu() {
945 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
946 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
947 external_popup_menu_
.reset();
951 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
952 // TODO(kenrb): document() should not be null, but as a transitional step
953 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
954 // to this method. This happens for a top-level remote frame, where a
955 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
956 // around and is still able to receive messages.
957 if (!frame_
->document().isNull())
958 GetContentClient()->SetActiveURL(frame_
->document().url());
960 ObserverListBase
<RenderFrameObserver
>::Iterator
it(observers_
);
961 RenderFrameObserver
* observer
;
962 while ((observer
= it
.GetNext()) != NULL
) {
963 if (observer
->OnMessageReceived(msg
))
968 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
969 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
970 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
971 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
972 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
973 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
974 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
975 OnCustomContextMenuAction
)
976 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
977 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
978 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
979 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
980 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
981 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
982 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
983 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
984 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
985 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
986 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
987 OnMoveRangeSelectionExtent
)
988 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
989 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
990 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
991 OnExtendSelectionAndDelete
)
992 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
993 OnSetCompositionFromExistingText
)
994 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
995 OnExecuteNoValueEditCommand
)
996 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
997 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
998 OnJavaScriptExecuteRequest
)
999 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1000 OnJavaScriptExecuteRequestForTests
)
1001 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1002 OnSetEditableSelectionOffsets
)
1003 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView
, OnSetupTransitionView
)
1004 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition
, OnBeginExitTransition
)
1005 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition
, OnRevertExitTransition
)
1006 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements
,
1007 OnHideTransitionElements
)
1008 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements
,
1009 OnShowTransitionElements
)
1010 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1011 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1012 OnTextSurroundingSelectionRequest
)
1013 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL
,
1014 OnAddStyleSheetByURL
)
1015 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1016 OnSetAccessibilityMode
)
1017 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1018 IPC_MESSAGE_HANDLER(FrameMsg_RequestNavigation
, OnRequestNavigation
)
1019 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1020 #if defined(OS_ANDROID)
1021 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1022 #elif defined(OS_MACOSX)
1023 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1024 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1026 IPC_END_MESSAGE_MAP()
1031 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params
& params
) {
1032 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
1034 "url", params
.common_params
.url
.possibly_invalid_spec());
1037 RenderViewImpl::IsReload(params
.common_params
.navigation_type
);
1038 bool is_history_navigation
= params
.commit_params
.page_state
.IsValid();
1039 WebURLRequest::CachePolicy cache_policy
=
1040 WebURLRequest::UseProtocolCachePolicy
;
1041 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1042 params
.common_params
.url
, true, is_history_navigation
,
1043 params
.current_history_list_offset
, &is_reload
, &cache_policy
)) {
1044 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
1048 render_view_
->history_list_offset_
= params
.current_history_list_offset
;
1049 render_view_
->history_list_length_
= params
.current_history_list_length
;
1050 if (params
.should_clear_history_list
) {
1051 CHECK_EQ(-1, render_view_
->history_list_offset_
);
1052 CHECK_EQ(0, render_view_
->history_list_length_
);
1055 GetContentClient()->SetActiveURL(params
.common_params
.url
);
1057 WebFrame
* frame
= frame_
;
1058 if (!params
.frame_to_navigate
.empty()) {
1059 // TODO(nasko): Move this lookup to the browser process.
1060 frame
= render_view_
->webview()->findFrameByName(
1061 WebString::fromUTF8(params
.frame_to_navigate
));
1062 CHECK(frame
) << "Invalid frame name passed: " << params
.frame_to_navigate
;
1065 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
1066 // We cannot reload if we do not have any history state. This happens, for
1067 // example, when recovering from a crash.
1069 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1072 render_view_
->pending_navigation_params_
.reset(
1073 new FrameMsg_Navigate_Params(params
));
1075 // If we are reloading, then WebKit will use the history state of the current
1076 // page, so we should just ignore any given history state. Otherwise, if we
1077 // have history state, then we need to navigate to it, which corresponds to a
1078 // back/forward navigation event.
1080 bool reload_original_url
=
1081 (params
.common_params
.navigation_type
==
1082 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1083 bool ignore_cache
= (params
.common_params
.navigation_type
==
1084 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1086 if (reload_original_url
)
1087 frame
->reloadWithOverrideURL(params
.common_params
.url
, true);
1089 frame
->reload(ignore_cache
);
1090 } else if (is_history_navigation
) {
1091 // We must know the page ID of the page we are navigating back to.
1092 DCHECK_NE(params
.page_id
, -1);
1093 scoped_ptr
<HistoryEntry
> entry
=
1094 PageStateToHistoryEntry(params
.commit_params
.page_state
);
1096 // Ensure we didn't save the swapped out URL in UpdateState, since the
1097 // browser should never be telling us to navigate to swappedout://.
1098 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
1099 render_view_
->history_controller()->GoToEntry(entry
.Pass(), cache_policy
);
1101 } else if (!params
.base_url_for_data_url
.is_empty()) {
1102 // A loadData request with a specified base URL.
1103 std::string mime_type
, charset
, data
;
1104 if (net::DataURL::Parse(
1105 params
.common_params
.url
, &mime_type
, &charset
, &data
)) {
1107 WebData(data
.c_str(), data
.length()),
1108 WebString::fromUTF8(mime_type
),
1109 WebString::fromUTF8(charset
),
1110 params
.base_url_for_data_url
,
1111 params
.history_url_for_data_url
,
1114 CHECK(false) << "Invalid URL passed: "
1115 << params
.common_params
.url
.possibly_invalid_spec();
1118 // Navigate to the given URL.
1119 WebURLRequest request
=
1120 CreateURLRequestForNavigation(params
.common_params
,
1121 params
.request_params
,
1122 scoped_ptr
<StreamOverrideParameters
>(),
1123 frame
->isViewSourceModeEnabled());
1125 // A session history navigation should have been accompanied by state.
1126 CHECK_EQ(params
.page_id
, -1);
1128 // Record this before starting the load, we need a lower bound of this time
1129 // to sanitize the navigationStart override set below.
1130 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
1131 frame
->loadRequest(request
);
1133 UpdateFrameNavigationTiming(
1134 frame
, params
.commit_params
.browser_navigation_start
,
1135 renderer_navigation_start
);
1138 // In case LoadRequest failed before DidCreateDataSource was called.
1139 render_view_
->pending_navigation_params_
.reset();
1142 void RenderFrameImpl::NavigateToSwappedOutURL() {
1143 // We use loadRequest instead of loadHTMLString because the former commits
1144 // synchronously. Otherwise a new navigation can interrupt the navigation
1145 // to kSwappedOutURL. If that happens to be to the page we had been
1146 // showing, then WebKit will never send a commit and we'll be left spinning.
1147 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1148 // the navigation to swappedout:// is not announced to the browser side.
1149 is_swapped_out_
= true;
1150 GURL
swappedOutURL(kSwappedOutURL
);
1151 WebURLRequest
request(swappedOutURL
);
1152 frame_
->loadRequest(request
);
1155 void RenderFrameImpl::BindServiceRegistry(
1156 mojo::ScopedMessagePipeHandle service_provider_handle
) {
1157 service_registry_
.BindRemoteServiceProvider(service_provider_handle
.Pass());
1160 ManifestManager
* RenderFrameImpl::manifest_manager() {
1161 return manifest_manager_
;
1164 void RenderFrameImpl::OnBeforeUnload() {
1165 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1167 // TODO(creis): Right now, this is only called on the main frame. Make the
1168 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1170 CHECK(!frame_
->parent());
1172 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1173 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1174 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1175 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1176 before_unload_start_time
,
1177 before_unload_end_time
));
1180 void RenderFrameImpl::OnSwapOut(
1181 int proxy_routing_id
,
1183 const FrameReplicationState
& replicated_frame_state
) {
1184 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1185 RenderFrameProxy
* proxy
= NULL
;
1186 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1187 switches::kSitePerProcess
);
1188 bool is_main_frame
= !frame_
->parent();
1190 // Only run unload if we're not swapped out yet, but send the ack either way.
1191 if (!is_swapped_out_
) {
1192 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1193 // a different process. This involves running the unload handler and
1194 // clearing the page. We also allow this process to exit if there are no
1195 // other active RenderFrames in it.
1197 // Send an UpdateState message before we get swapped out.
1198 render_view_
->SyncNavigationState();
1200 // If we need a proxy to replace this, create it now so its routing id is
1201 // registered for receiving IPC messages.
1202 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1203 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(this,
1207 // Synchronously run the unload handler before sending the ACK.
1208 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1209 // unload on subframes as well.
1211 frame_
->dispatchUnloadEvent();
1213 // Swap out and stop sending any IPC messages that are not ACKs.
1215 render_view_
->SetSwappedOut(true);
1216 is_swapped_out_
= true;
1218 // Now that we're swapped out and filtering IPC messages, stop loading to
1219 // ensure that no other in-progress navigation continues. We do this here
1220 // to avoid sending a DidStopLoading message to the browser process.
1221 // TODO(creis): Should we be stopping all frames here and using
1222 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1226 // Transfer settings such as initial drawing parameters to the remote frame,
1227 // if one is created, that will replace this frame.
1228 if (!is_main_frame
&& proxy
)
1229 proxy
->web_frame()->initializeFromFrame(frame_
);
1231 // Replace the page with a blank dummy URL. The unload handler will not be
1232 // run a second time, thanks to a check in FrameLoader::stopLoading.
1233 // TODO(creis): Need to add a better way to do this that avoids running the
1234 // beforeunload handler. For now, we just run it a second time silently.
1235 if (!is_site_per_process
|| is_main_frame
)
1236 NavigateToSwappedOutURL();
1238 // Let WebKit know that this view is hidden so it can drop resources and
1239 // stop compositing.
1240 // TODO(creis): Support this for subframes as well.
1241 if (is_main_frame
) {
1242 render_view_
->webview()->setVisibilityState(
1243 blink::WebPageVisibilityStateHidden
, false);
1247 // It is now safe to show modal dialogs again.
1248 // TODO(creis): Deal with modal dialogs from subframes.
1250 render_view_
->suppress_dialogs_until_swap_out_
= false;
1252 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1254 // Now that all of the cleanup is complete and the browser side is notified,
1255 // start using the RenderFrameProxy, if one is created.
1257 if (!is_main_frame
) {
1258 frame_
->swap(proxy
->web_frame());
1261 proxy
->OnDidStartLoading();
1263 if (is_site_per_process
) {
1264 // TODO(nasko): delete the frame here, since we've replaced it with a
1268 set_render_frame_proxy(proxy
);
1272 // In --site-per-process, initialize the WebRemoteFrame with the replication
1273 // state passed by the process that is now rendering the frame.
1274 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1275 // in that case we leave the LocalFrame as the main frame visible to Blink
1276 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1277 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1278 // When we do an unconditional swap for all frames, we can remove
1279 // !is_main_frame below.
1280 if (is_site_per_process
&& proxy
&& !is_main_frame
)
1281 proxy
->SetReplicatedState(replicated_frame_state
);
1283 // Safe to exit if no one else is using the process.
1285 render_view_
->WasSwappedOut();
1288 void RenderFrameImpl::OnContextMenuClosed(
1289 const CustomContextMenuContext
& custom_context
) {
1290 if (custom_context
.request_id
) {
1291 // External request, should be in our map.
1292 ContextMenuClient
* client
=
1293 pending_context_menus_
.Lookup(custom_context
.request_id
);
1295 client
->OnMenuClosed(custom_context
.request_id
);
1296 pending_context_menus_
.Remove(custom_context
.request_id
);
1299 if (custom_context
.link_followed
.is_valid()) {
1301 DomUtils::ExtractParentAnchorNode(context_menu_node_
),
1302 custom_context
.link_followed
);
1304 // Internal request, forward to WebKit.
1305 context_menu_node_
.reset();
1309 void RenderFrameImpl::OnCustomContextMenuAction(
1310 const CustomContextMenuContext
& custom_context
,
1312 if (custom_context
.request_id
) {
1313 // External context menu request, look in our map.
1314 ContextMenuClient
* client
=
1315 pending_context_menus_
.Lookup(custom_context
.request_id
);
1317 client
->OnMenuAction(custom_context
.request_id
, action
);
1319 // Internal request, forward to WebKit.
1320 render_view_
->webview()->performCustomContextMenuAction(action
);
1324 void RenderFrameImpl::OnUndo() {
1325 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1328 void RenderFrameImpl::OnRedo() {
1329 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1332 void RenderFrameImpl::OnCut() {
1333 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1334 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1337 void RenderFrameImpl::OnCopy() {
1338 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1339 WebNode current_node
= context_menu_node_
.isNull() ?
1340 GetFocusedElement() : context_menu_node_
;
1341 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1344 void RenderFrameImpl::OnPaste() {
1345 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1346 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1349 void RenderFrameImpl::OnPasteAndMatchStyle() {
1350 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1351 frame_
->executeCommand(
1352 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1355 #if defined(OS_MACOSX)
1356 void RenderFrameImpl::OnCopyToFindPboard() {
1357 // Since the find pasteboard supports only plain text, this can be simpler
1358 // than the |OnCopy()| case.
1359 if (frame_
->hasSelection()) {
1360 base::string16 selection
= frame_
->selectionAsText();
1361 RenderThread::Get()->Send(
1362 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1367 void RenderFrameImpl::OnDelete() {
1368 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1371 void RenderFrameImpl::OnSelectAll() {
1372 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1373 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1376 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1377 const gfx::Point
& extent
) {
1378 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1379 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1381 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1382 frame_
->selectRange(base
, extent
);
1385 void RenderFrameImpl::OnUnselect() {
1386 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1387 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1390 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1391 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1392 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1393 GetRenderWidget()->routing_id()));
1395 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1396 frame_
->moveRangeSelectionExtent(point
);
1399 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1400 if (!frame_
->hasSelection())
1401 frame_
->selectWordAroundCaret();
1403 frame_
->replaceSelection(text
);
1406 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1407 if (!frame_
->hasSelection())
1410 frame_
->replaceMisspelledRange(text
);
1413 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1414 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1417 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1418 const base::string16
& jscript
,
1420 bool notify_result
) {
1421 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1422 TRACE_EVENT_SCOPE_THREAD
);
1424 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1425 v8::Handle
<v8::Value
> result
=
1426 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1428 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1431 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1432 const base::string16
& jscript
,
1434 bool notify_result
) {
1435 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1436 TRACE_EVENT_SCOPE_THREAD
);
1438 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1439 v8::Handle
<v8::Value
> result
=
1440 frame_
->executeScriptAndReturnValueForTests(WebScriptSource(jscript
));
1442 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1445 void RenderFrameImpl::HandleJavascriptExecutionResult(
1446 const base::string16
& jscript
,
1449 v8::Handle
<v8::Value
> result
) {
1450 if (notify_result
) {
1451 base::ListValue list
;
1452 if (!result
.IsEmpty()) {
1453 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1454 v8::Context::Scope
context_scope(context
);
1455 V8ValueConverterImpl converter
;
1456 converter
.SetDateAllowed(true);
1457 converter
.SetRegExpAllowed(true);
1458 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
1459 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
1461 list
.Set(0, base::Value::CreateNullValue());
1463 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1467 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1468 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1469 if (!GetRenderWidget()->ShouldHandleImeEvent())
1471 ImeEventGuard
guard(GetRenderWidget());
1472 frame_
->setEditableSelectionOffsets(start
, end
);
1475 void RenderFrameImpl::OnSetCompositionFromExistingText(
1477 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1478 if (!GetRenderWidget()->ShouldHandleImeEvent())
1480 ImeEventGuard
guard(GetRenderWidget());
1481 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1484 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1485 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1488 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1489 if (!GetRenderWidget()->ShouldHandleImeEvent())
1491 ImeEventGuard
guard(GetRenderWidget());
1492 frame_
->extendSelectionAndDelete(before
, after
);
1495 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1496 if (accessibility_mode_
== new_mode
)
1498 accessibility_mode_
= new_mode
;
1499 if (renderer_accessibility_
) {
1500 // Note: this isn't called automatically by the destructor because
1501 // there'd be no point in calling it in frame teardown, only if there's
1502 // an accessibility mode change but the frame is persisting.
1503 renderer_accessibility_
->DisableAccessibility();
1505 delete renderer_accessibility_
;
1506 renderer_accessibility_
= NULL
;
1508 if (accessibility_mode_
== AccessibilityModeOff
)
1511 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1512 renderer_accessibility_
= new RendererAccessibility(this);
1515 void RenderFrameImpl::OnDisownOpener() {
1516 // TODO(creis): We should only see this for main frames for now. To support
1517 // disowning the opener on subframes, we will need to move WebContentsImpl's
1518 // opener_ to FrameTreeNode.
1519 CHECK(!frame_
->parent());
1521 if (frame_
->opener())
1522 frame_
->setOpener(NULL
);
1525 #if defined(OS_ANDROID)
1526 void RenderFrameImpl::OnSelectPopupMenuItems(
1528 const std::vector
<int>& selected_indices
) {
1529 // It is possible to receive more than one of these calls if the user presses
1530 // a select faster than it takes for the show-select-popup IPC message to make
1531 // it to the browser UI thread. Ignore the extra-messages.
1532 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1533 if (!external_popup_menu_
)
1536 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1537 external_popup_menu_
.reset();
1541 #if defined(OS_MACOSX)
1542 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1543 if (external_popup_menu_
== NULL
)
1545 external_popup_menu_
->DidSelectItem(selected_index
);
1546 external_popup_menu_
.reset();
1550 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1551 frame_
->reload(ignore_cache
);
1554 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1555 blink::WebSurroundingText surroundingText
;
1556 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1558 if (surroundingText
.isNull()) {
1559 // |surroundingText| might not be correctly initialized, for example if
1560 // |frame_->selectionRange().isNull()|, in other words, if there was no
1562 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1563 routing_id_
, base::string16(), 0, 0));
1567 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1569 surroundingText
.textContent(),
1570 surroundingText
.startOffsetInTextContent(),
1571 surroundingText
.endOffsetInTextContent()));
1574 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string
& url
) {
1575 frame_
->addStyleSheetByURL(WebString::fromUTF8(url
));
1578 void RenderFrameImpl::OnSetupTransitionView(const std::string
& markup
) {
1579 frame_
->document().setIsTransitionDocument(true);
1580 frame_
->navigateToSandboxedMarkup(WebData(markup
.data(), markup
.length()));
1583 void RenderFrameImpl::OnBeginExitTransition(const std::string
& css_selector
,
1584 bool exit_to_native_app
) {
1585 frame_
->document().setIsTransitionDocument(true);
1586 frame_
->document().beginExitTransition(WebString::fromUTF8(css_selector
),
1587 exit_to_native_app
);
1590 void RenderFrameImpl::OnRevertExitTransition() {
1591 frame_
->document().setIsTransitionDocument(false);
1592 frame_
->document().revertExitTransition();
1595 void RenderFrameImpl::OnHideTransitionElements(
1596 const std::string
& css_selector
) {
1597 frame_
->document().hideTransitionElements(WebString::fromUTF8(css_selector
));
1600 void RenderFrameImpl::OnShowTransitionElements(
1601 const std::string
& css_selector
) {
1602 frame_
->document().showTransitionElements(WebString::fromUTF8(css_selector
));
1605 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1606 const base::string16
& message
,
1607 const base::string16
& default_value
,
1608 const GURL
& frame_url
,
1609 base::string16
* result
) {
1610 // Don't allow further dialogs if we are waiting to swap out, since the
1611 // PageGroupLoadDeferrer in our stack prevents it.
1612 if (render_view()->suppress_dialogs_until_swap_out_
)
1615 bool success
= false;
1616 base::string16 result_temp
;
1618 result
= &result_temp
;
1620 render_view()->SendAndRunNestedMessageLoop(
1621 new FrameHostMsg_RunJavaScriptMessage(
1622 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1627 void RenderFrameImpl::LoadNavigationErrorPage(
1628 const WebURLRequest
& failed_request
,
1629 const WebURLError
& error
,
1631 std::string error_html
;
1632 GetContentClient()->renderer()->GetNavigationErrorStrings(
1633 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1635 frame_
->loadHTMLString(error_html
,
1636 GURL(kUnreachableWebDataURL
),
1637 error
.unreachableURL
,
1641 void RenderFrameImpl::DidCommitCompositorFrame() {
1643 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1646 RenderView
* RenderFrameImpl::GetRenderView() {
1647 return render_view_
.get();
1650 int RenderFrameImpl::GetRoutingID() {
1654 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1659 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1660 return render_view_
->GetWebkitPreferences();
1663 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1664 const ContextMenuParams
& params
) {
1665 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1666 ContextMenuParams
our_params(params
);
1667 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1668 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1669 return our_params
.custom_context
.request_id
;
1672 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1673 DCHECK(pending_context_menus_
.Lookup(request_id
));
1674 pending_context_menus_
.Remove(request_id
);
1677 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1678 return context_menu_node_
;
1681 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1682 blink::WebFrame
* frame
,
1683 const WebPluginInfo
& info
,
1684 const blink::WebPluginParams
& params
,
1685 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1686 DCHECK_EQ(frame_
, frame
);
1687 #if defined(ENABLE_PLUGINS)
1688 bool pepper_plugin_was_registered
= false;
1689 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1690 this, info
, &pepper_plugin_was_registered
));
1691 if (pepper_plugin_was_registered
) {
1692 if (pepper_module
.get()) {
1693 return new PepperWebPluginImpl(
1694 pepper_module
.get(), params
, this,
1696 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1699 #if defined(OS_CHROMEOS)
1700 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1703 // TODO(jam): change to take RenderFrame.
1704 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1711 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1712 const blink::WebURLRequest
& request
,
1713 blink::WebNavigationPolicy policy
) {
1714 DCHECK(!frame_
|| frame_
== frame
);
1715 loadURLExternally(frame
, request
, policy
, WebString());
1718 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1719 OnJavaScriptExecuteRequest(javascript
, 0, false);
1722 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1723 return &service_registry_
;
1726 #if defined(ENABLE_PLUGINS)
1727 void RenderFrameImpl::RegisterPeripheralPlugin(
1728 const GURL
& content_origin
,
1729 const base::Closure
& unthrottle_callback
) {
1730 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1731 content_origin
, unthrottle_callback
);
1734 bool RenderFrameImpl::ShouldThrottleContent(
1735 const blink::WebPluginParams
& params
,
1736 const GURL
& page_frame_url
,
1738 bool* cross_origin_main_content
) const {
1739 return plugin_power_saver_helper_
->ShouldThrottleContent(
1740 params
, page_frame_url
, poster_image
, cross_origin_main_content
);
1743 void RenderFrameImpl::WhitelistContentOrigin(const GURL
& content_origin
) {
1744 return plugin_power_saver_helper_
->WhitelistContentOrigin(content_origin
);
1746 #endif // defined(ENABLE_PLUGINS)
1748 bool RenderFrameImpl::IsFTPDirectoryListing() {
1749 WebURLResponseExtraDataImpl
* extra_data
=
1750 GetExtraDataFromResponse(frame_
->dataSource()->response());
1751 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1754 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1755 BrowserPluginManager::Get()->Attach(element_instance_id
);
1758 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1759 BrowserPluginManager::Get()->Detach(element_instance_id
);
1762 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1764 const gfx::Range
& range
) {
1765 // Use the routing id of Render Widget Host.
1766 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1772 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1773 v8::Isolate
* isolate
,
1774 v8::Handle
<v8::Context
> context
) {
1775 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1776 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1779 v8::HandleScope
handle_scope(isolate
);
1780 registry
->AddBuiltinModule(
1781 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1782 registry
->AddBuiltinModule(isolate
,
1783 mojo::js::Support::kModuleName
,
1784 mojo::js::Support::GetModule(isolate
));
1785 registry
->AddBuiltinModule(
1787 ServiceRegistryJsWrapper::kModuleName
,
1788 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1791 // blink::WebFrameClient implementation ----------------------------------------
1793 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1794 blink::WebLocalFrame
* frame
,
1795 const blink::WebPluginParams
& params
) {
1796 DCHECK_EQ(frame_
, frame
);
1797 return GetContentClient()
1799 ->CreatePluginPlaceholder(this, frame
, params
)
1803 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1804 blink::WebLocalFrame
* frame
,
1805 const blink::WebPluginParams
& params
) {
1806 DCHECK_EQ(frame_
, frame
);
1807 blink::WebPlugin
* plugin
= NULL
;
1808 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1809 this, frame
, params
, &plugin
)) {
1813 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1814 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1815 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1816 kBrowserPluginMimeType
, GURL(params
.url
)));
1817 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1818 this, browser_plugin_delegate
.Pass());
1821 #if defined(ENABLE_PLUGINS)
1823 std::string mime_type
;
1825 Send(new FrameHostMsg_GetPluginInfo(
1826 routing_id_
, params
.url
, frame
->top()->document().url(),
1827 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
1831 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1832 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1833 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1834 this, mime_type
, GURL(params
.url
)));
1835 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1836 this, browser_plugin_delegate
.Pass());
1840 WebPluginParams params_to_use
= params
;
1841 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
1842 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
1845 #endif // defined(ENABLE_PLUGINS)
1848 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1849 blink::WebLocalFrame
* frame
,
1850 const blink::WebURL
& url
,
1851 blink::WebMediaPlayerClient
* client
) {
1852 return createMediaPlayer(frame
, url
, client
, NULL
);
1855 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1856 blink::WebLocalFrame
* frame
,
1857 const blink::WebURL
& url
,
1858 blink::WebMediaPlayerClient
* client
,
1859 blink::WebContentDecryptionModule
* initial_cdm
) {
1860 #if defined(VIDEO_HOLE)
1861 if (!contains_media_player_
) {
1862 render_view_
->RegisterVideoHoleFrame(this);
1863 contains_media_player_
= true;
1865 #endif // defined(VIDEO_HOLE)
1867 blink::WebMediaStream
web_stream(
1868 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
1869 if (!web_stream
.isNull())
1870 return CreateWebMediaPlayerForMediaStream(url
, client
);
1872 #if defined(OS_ANDROID)
1873 return CreateAndroidWebMediaPlayer(url
, client
, initial_cdm
);
1875 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
1877 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
1878 media::WebMediaPlayerParams
params(
1879 base::Bind(&ContentRendererClient::DeferMediaLoad
,
1880 base::Unretained(GetContentClient()->renderer()),
1881 static_cast<RenderFrame
*>(this)),
1882 render_thread
->GetAudioRendererMixerManager()->CreateInput(
1883 render_view_
->routing_id_
, routing_id_
),
1884 media_log
, render_thread
->GetMediaThreadTaskRunner(),
1885 render_thread
->compositor_message_loop_proxy(),
1886 base::Bind(&GetSharedMainThreadContext3D
), initial_cdm
);
1888 #if defined(ENABLE_PEPPER_CDMS)
1889 scoped_ptr
<media::CdmFactory
> cdm_factory(
1890 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create
, frame
)));
1891 #elif defined(ENABLE_BROWSER_CDMS)
1892 scoped_ptr
<media::CdmFactory
> cdm_factory(
1893 new RenderCdmFactory(GetCdmManager()));
1895 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
1898 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
1899 GetContentClient()->renderer()->CreateMediaRendererFactory(this);
1901 if (!media_renderer_factory
.get()) {
1902 media_renderer_factory
.reset(new media::DefaultRendererFactory(
1903 media_log
, render_thread
->GetGpuFactories(),
1904 *render_thread
->GetAudioHardwareConfig()));
1907 return new media::WebMediaPlayerImpl(
1908 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer_factory
.Pass(),
1909 cdm_factory
.Pass(), params
);
1910 #endif // defined(OS_ANDROID)
1913 // TODO(jrummell): remove once blink uses encryptedMediaClient().
1914 blink::WebContentDecryptionModule
*
1915 RenderFrameImpl::createContentDecryptionModule(
1916 blink::WebLocalFrame
* frame
,
1917 const blink::WebSecurityOrigin
& security_origin
,
1918 const blink::WebString
& key_system
) {
1919 DCHECK(!frame_
|| frame_
== frame
);
1921 #if defined(ENABLE_PEPPER_CDMS)
1922 RenderCdmFactory
cdm_factory(
1923 base::Bind(&PepperCdmWrapperImpl::Create
, frame
));
1924 #elif defined(ENABLE_BROWSER_CDMS)
1925 RenderCdmFactory
cdm_factory(GetCdmManager());
1927 RenderCdmFactory cdm_factory
;
1930 return media::WebContentDecryptionModuleImpl::Create(
1931 &cdm_factory
, security_origin
, key_system
);
1934 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
1935 blink::WebLocalFrame
* frame
,
1936 blink::WebApplicationCacheHostClient
* client
) {
1937 if (!frame
|| !frame
->view())
1939 DCHECK(!frame_
|| frame_
== frame
);
1940 return new RendererWebApplicationCacheHostImpl(
1941 RenderViewImpl::FromWebView(frame
->view()), client
,
1942 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1945 blink::WebWorkerPermissionClientProxy
*
1946 RenderFrameImpl::createWorkerPermissionClientProxy(
1947 blink::WebLocalFrame
* frame
) {
1948 if (!frame
|| !frame
->view())
1950 DCHECK(!frame_
|| frame_
== frame
);
1951 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1955 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
1956 const WebPopupMenuInfo
& popup_menu_info
,
1957 WebExternalPopupMenuClient
* popup_menu_client
) {
1958 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1959 // An IPC message is sent to the browser to build and display the actual
1960 // popup. The user could have time to click a different select by the time
1961 // the popup is shown. In that case external_popup_menu_ is non NULL.
1962 // By returning NULL in that case, we instruct Blink to cancel that new
1963 // popup. So from the user perspective, only the first one will show, and
1964 // will have to close the first one before another one can be shown.
1965 if (external_popup_menu_
)
1967 external_popup_menu_
.reset(
1968 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
1969 if (render_view_
->screen_metrics_emulator_
) {
1970 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
1971 external_popup_menu_
.get(),
1972 render_view_
->screen_metrics_emulator_
.get());
1974 return external_popup_menu_
.get();
1980 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
1981 DCHECK(!frame_
|| frame_
== frame
);
1982 return &cookie_jar_
;
1985 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
1986 blink::WebLocalFrame
* frame
) {
1987 DCHECK(!frame_
|| frame_
== frame
);
1988 // At this point we should have non-null data source.
1989 DCHECK(frame
->dataSource());
1990 if (!ChildThread::current())
1991 return NULL
; // May be null in some tests.
1992 ServiceWorkerNetworkProvider
* provider
=
1993 ServiceWorkerNetworkProvider::FromDocumentState(
1994 DocumentState::FromDataSource(frame
->dataSource()));
1995 return new WebServiceWorkerProviderImpl(
1996 ChildThread::current()->thread_safe_sender(),
1997 provider
? provider
->context() : NULL
);
2000 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2001 DCHECK(!frame_
|| frame_
== frame
);
2002 // Notify the browser process that it is no longer safe to show the pending
2003 // URL of the main frame, since a URL spoof is now possible.
2004 if (!frame
->parent() && render_view_
->page_id_
== -1)
2005 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2008 // TODO(alexmos): Remove once Blink is updated to use the version that takes
2010 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2011 blink::WebLocalFrame
* parent
,
2012 const blink::WebString
& name
) {
2013 return createChildFrame(parent
, name
, blink::WebSandboxFlags::None
);
2016 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2017 blink::WebLocalFrame
* parent
,
2018 const blink::WebString
& name
,
2019 blink::WebSandboxFlags sandbox_flags
) {
2020 // Synchronously notify the browser of a child frame creation to get the
2021 // routing_id for the RenderFrame.
2022 int child_routing_id
= MSG_ROUTING_NONE
;
2023 CHECK(Send(new FrameHostMsg_CreateChildFrame(
2025 base::UTF16ToUTF8(name
),
2026 WebToContentSandboxFlags(sandbox_flags
),
2027 &child_routing_id
)));
2029 // Allocation of routing id failed, so we can't create a child frame. This can
2030 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2031 // out state or synchronous IPC message above has failed.
2032 if (child_routing_id
== MSG_ROUTING_NONE
) {
2033 NOTREACHED() << "Failed to allocate routing id for child frame.";
2037 // Create the RenderFrame and WebLocalFrame, linking the two.
2038 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2039 render_view_
.get(), child_routing_id
);
2040 blink::WebLocalFrame
* web_frame
= WebLocalFrame::create(child_render_frame
);
2041 child_render_frame
->SetWebFrame(web_frame
);
2043 // Add the frame to the frame tree and initialize it.
2044 parent
->appendChild(web_frame
);
2045 child_render_frame
->Initialize();
2050 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2051 DCHECK(!frame_
|| frame_
== frame
);
2052 // We only need to notify the browser if the active, top-level frame clears
2053 // its opener. We can ignore cases where a swapped out frame clears its
2054 // opener after hearing about it from the browser, and the browser does not
2055 // (yet) care about subframe openers.
2056 if (is_swapped_out_
|| frame
->parent())
2059 // Notify WebContents and all its swapped out RenderViews.
2060 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2063 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
) {
2064 // NOTE: This function is called on the frame that is being detached and not
2065 // the parent frame. This is different from createChildFrame() which is
2066 // called on the parent frame.
2067 CHECK(!is_detaching_
);
2068 DCHECK(!frame_
|| frame_
== frame
);
2070 bool is_subframe
= !!frame
->parent();
2072 Send(new FrameHostMsg_Detach(routing_id_
));
2074 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2075 // sent before setting |is_detaching_| to true. In contrast, Observers
2076 // should only be notified afterwards so they cannot call back into here and
2077 // have IPCs fired off.
2078 is_detaching_
= true;
2080 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2081 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2082 FrameDetached(frame
));
2084 // We need to clean up subframes by removing them from the map and deleting
2085 // the RenderFrameImpl. In contrast, the main frame is owned by its
2086 // containing RenderViewHost (so that they have the same lifetime), so only
2087 // removal from the map is needed and no deletion.
2088 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2089 CHECK(it
!= g_frame_map
.Get().end());
2090 CHECK_EQ(it
->second
, this);
2091 g_frame_map
.Get().erase(it
);
2094 frame
->parent()->removeChild(frame
);
2096 // |frame| is invalid after here.
2101 // Object is invalid after this point.
2105 void RenderFrameImpl::frameFocused() {
2106 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2109 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2110 DCHECK(!frame_
|| frame_
== frame
);
2112 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2113 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2114 FrameWillClose(frame
));
2117 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2118 const blink::WebString
& name
) {
2119 DCHECK(!frame_
|| frame_
== frame
);
2120 if (!render_view_
->renderer_preferences_
.report_frame_name_changes
)
2123 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeName(name
));
2126 void RenderFrameImpl::didMatchCSS(
2127 blink::WebLocalFrame
* frame
,
2128 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2129 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2130 DCHECK(!frame_
|| frame_
== frame
);
2132 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2134 newly_matching_selectors
,
2135 stopped_matching_selectors
));
2138 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2139 const blink::WebString
& source
) {
2140 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2144 void RenderFrameImpl::didAddMessageToConsole(
2145 const blink::WebConsoleMessage
& message
,
2146 const blink::WebString
& source_name
,
2147 unsigned source_line
,
2148 const blink::WebString
& stack_trace
) {
2149 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2150 switch (message
.level
) {
2151 case blink::WebConsoleMessage::LevelDebug
:
2152 log_severity
= logging::LOG_VERBOSE
;
2154 case blink::WebConsoleMessage::LevelLog
:
2155 case blink::WebConsoleMessage::LevelInfo
:
2156 log_severity
= logging::LOG_INFO
;
2158 case blink::WebConsoleMessage::LevelWarning
:
2159 log_severity
= logging::LOG_WARNING
;
2161 case blink::WebConsoleMessage::LevelError
:
2162 log_severity
= logging::LOG_ERROR
;
2168 if (shouldReportDetailedMessageForSource(source_name
)) {
2170 RenderFrameObserver
, observers_
,
2171 DetailedConsoleMessageAdded(message
.text
,
2175 static_cast<int32
>(log_severity
)));
2178 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2179 static_cast<int32
>(log_severity
),
2181 static_cast<int32
>(source_line
),
2185 void RenderFrameImpl::loadURLExternally(
2186 blink::WebLocalFrame
* frame
,
2187 const blink::WebURLRequest
& request
,
2188 blink::WebNavigationPolicy policy
,
2189 const blink::WebString
& suggested_name
) {
2190 DCHECK(!frame_
|| frame_
== frame
);
2191 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2192 if (policy
== blink::WebNavigationPolicyDownload
) {
2193 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2194 request
.url(), referrer
,
2197 OpenURL(frame
, request
.url(), referrer
, policy
);
2201 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2202 const NavigationPolicyInfo
& info
) {
2203 DCHECK(!frame_
|| frame_
== info
.frame
);
2204 return DecidePolicyForNavigation(this, info
);
2207 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2208 blink::WebFrame
* frame
) {
2209 DCHECK(!frame_
|| frame_
== frame
);
2210 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2213 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2214 const blink::WebFormElement
& form
) {
2215 DCHECK(!frame_
|| frame_
== frame
);
2217 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2220 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2221 const blink::WebFormElement
& form
) {
2222 DCHECK(!frame_
|| frame_
== frame
);
2223 DocumentState
* document_state
=
2224 DocumentState::FromDataSource(frame
->provisionalDataSource());
2225 NavigationState
* navigation_state
= document_state
->navigation_state();
2226 InternalDocumentStateData
* internal_data
=
2227 InternalDocumentStateData::FromDocumentState(document_state
);
2229 if (ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2230 ui::PAGE_TRANSITION_LINK
)) {
2231 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2234 // Save these to be processed when the ensuing navigation is committed.
2235 WebSearchableFormData
web_searchable_form_data(form
);
2236 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2237 internal_data
->set_searchable_form_encoding(
2238 web_searchable_form_data
.encoding().utf8());
2240 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2243 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2244 blink::WebDataSource
* datasource
) {
2245 DCHECK(!frame_
|| frame_
== frame
);
2247 // TODO(nasko): Move implementation here. Needed state:
2248 // * pending_navigation_params_
2251 // * PopulateDocumentStateFromPending
2252 // * CreateNavigationStateFromPending
2253 render_view_
->didCreateDataSource(frame
, datasource
);
2255 // Create the serviceworker's per-document network observing object if it
2256 // does not exist (When navigation happens within a page, the provider already
2258 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2259 DocumentState::FromDataSource(datasource
))) {
2260 scoped_ptr
<ServiceWorkerNetworkProvider
>
2261 network_provider(new ServiceWorkerNetworkProvider(routing_id_
));
2262 ServiceWorkerNetworkProvider::AttachToDocumentState(
2263 DocumentState::FromDataSource(datasource
),
2264 network_provider
.Pass());
2268 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2269 bool is_transition_navigation
,
2270 double triggering_event_time
) {
2271 DCHECK(!frame_
|| frame_
== frame
);
2272 WebDataSource
* ds
= frame
->provisionalDataSource();
2274 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2275 // callback is invoked.
2279 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2280 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2281 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2283 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2284 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2286 "Heard swappedout:// when not swapped out.";
2288 // Update the request time if WebKit has better knowledge of it.
2289 if (document_state
->request_time().is_null() &&
2290 triggering_event_time
!= 0.0) {
2291 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2294 // Start time is only set after request time.
2295 document_state
->set_start_load_time(Time::Now());
2297 bool is_top_most
= !frame
->parent();
2299 render_view_
->set_navigation_gesture(
2300 WebUserGestureIndicator::isProcessingUserGesture() ?
2301 NavigationGestureUser
: NavigationGestureAuto
);
2302 } else if (ds
->replacesCurrentHistoryItem()) {
2303 // Subframe navigations that don't add session history items must be
2304 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2305 // handle loading of error pages.
2306 document_state
->navigation_state()->set_transition_type(
2307 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2310 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2311 DidStartProvisionalLoad(frame
));
2312 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2314 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2315 routing_id_
, ds
->request().url(), is_transition_navigation
));
2318 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2319 blink::WebLocalFrame
* frame
) {
2320 DCHECK(!frame_
|| frame_
== frame
);
2321 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2324 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame
* frame
,
2325 const blink::WebURLError
& error
) {
2326 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2328 DCHECK(!frame_
|| frame_
== frame
);
2329 WebDataSource
* ds
= frame
->provisionalDataSource();
2332 const WebURLRequest
& failed_request
= ds
->request();
2334 // Notify the browser that we failed a provisional load with an error.
2336 // Note: It is important this notification occur before DidStopLoading so the
2337 // SSL manager can react to the provisional load failure before being
2338 // notified the load stopped.
2340 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2341 DidFailProvisionalLoad(frame
, error
));
2342 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2343 DidFailProvisionalLoad(error
));
2345 bool show_repost_interstitial
=
2346 (error
.reason
== net::ERR_CACHE_MISS
&&
2347 EqualsASCII(failed_request
.httpMethod(), "POST"));
2349 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
2350 params
.error_code
= error
.reason
;
2351 GetContentClient()->renderer()->GetNavigationErrorStrings(
2357 ¶ms
.error_description
);
2358 params
.url
= error
.unreachableURL
;
2359 params
.showing_repost_interstitial
= show_repost_interstitial
;
2360 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2361 routing_id_
, params
));
2363 // Don't display an error page if this is simply a cancelled load. Aside
2364 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2365 if (error
.reason
== net::ERR_ABORTED
)
2368 // Don't display "client blocked" error page if browser has asked us not to.
2369 if (error
.reason
== net::ERR_BLOCKED_BY_CLIENT
&&
2370 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
2374 // Allow the embedder to suppress an error page.
2375 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2376 error
.unreachableURL
)) {
2380 if (RenderThreadImpl::current() &&
2381 RenderThreadImpl::current()->layout_test_mode()) {
2385 // Make sure we never show errors in view source mode.
2386 frame
->enableViewSourceMode(false);
2388 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2389 NavigationState
* navigation_state
= document_state
->navigation_state();
2391 // If this is a failed back/forward/reload navigation, then we need to do a
2392 // 'replace' load. This is necessary to avoid messing up session history.
2393 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2394 // as session history is concerned.
2396 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2399 // TODO(davidben): This should also take the failed navigation's replacement
2400 // state into account, if a location.replace() failed.
2402 navigation_state
->pending_page_id() != -1 ||
2403 ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2404 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2406 // If we failed on a browser initiated request, then make sure that our error
2407 // page load is regarded as the same browser initiated request.
2408 if (!navigation_state
->is_content_initiated()) {
2409 render_view_
->pending_navigation_params_
.reset(
2410 new FrameMsg_Navigate_Params
);
2411 render_view_
->pending_navigation_params_
->page_id
=
2412 navigation_state
->pending_page_id();
2413 render_view_
->pending_navigation_params_
->pending_history_list_offset
=
2414 navigation_state
->pending_history_list_offset();
2415 render_view_
->pending_navigation_params_
->should_clear_history_list
=
2416 navigation_state
->history_list_was_cleared();
2417 render_view_
->pending_navigation_params_
->common_params
.transition
=
2418 navigation_state
->transition_type();
2419 render_view_
->pending_navigation_params_
->request_time
=
2420 document_state
->request_time();
2421 render_view_
->pending_navigation_params_
->should_replace_current_entry
=
2425 // Load an error page.
2426 LoadNavigationErrorPage(failed_request
, error
, replace
);
2429 void RenderFrameImpl::didCommitProvisionalLoad(
2430 blink::WebLocalFrame
* frame
,
2431 const blink::WebHistoryItem
& item
,
2432 blink::WebHistoryCommitType commit_type
) {
2433 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2435 "url", GetLoadingUrl().possibly_invalid_spec());
2436 DCHECK(!frame_
|| frame_
== frame
);
2437 DocumentState
* document_state
=
2438 DocumentState::FromDataSource(frame
->dataSource());
2439 NavigationState
* navigation_state
= document_state
->navigation_state();
2441 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2442 RenderFrameProxy
* proxy
=
2443 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2445 proxy
->web_frame()->swap(frame_
);
2446 proxy_routing_id_
= MSG_ROUTING_NONE
;
2449 // When we perform a new navigation, we need to update the last committed
2450 // session history entry with state for the page we are leaving. Do this
2451 // before updating the HistoryController state.
2452 render_view_
->UpdateSessionHistory(frame
);
2454 render_view_
->history_controller()->UpdateForCommit(this, item
, commit_type
,
2455 navigation_state
->was_within_same_page());
2457 InternalDocumentStateData
* internal_data
=
2458 InternalDocumentStateData::FromDocumentState(document_state
);
2460 if (document_state
->commit_load_time().is_null())
2461 document_state
->set_commit_load_time(Time::Now());
2463 if (internal_data
->must_reset_scroll_and_scale_state()) {
2464 render_view_
->webview()->resetScrollAndScaleState();
2465 internal_data
->set_must_reset_scroll_and_scale_state(false);
2467 internal_data
->set_use_error_page(false);
2469 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2470 if (is_new_navigation
) {
2471 // We bump our Page ID to correspond with the new session history entry.
2472 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2474 // Don't update history list values for kSwappedOutURL, since
2475 // we don't want to forget the entry that was there, and since we will
2476 // never come back to kSwappedOutURL. Note that we have to call
2477 // UpdateSessionHistory and update page_id_ even in this case, so that
2478 // the current entry gets a state update and so that we don't send a
2479 // state update to the wrong entry when we swap back in.
2480 if (GetLoadingUrl() != GURL(kSwappedOutURL
)) {
2481 // Advance our offset in session history, applying the length limit.
2482 // There is now no forward history.
2483 render_view_
->history_list_offset_
++;
2484 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2485 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2486 render_view_
->history_list_length_
=
2487 render_view_
->history_list_offset_
+ 1;
2490 // Inspect the navigation_state on this frame to see if the navigation
2491 // corresponds to a session history navigation... Note: |frame| may or
2492 // may not be the toplevel frame, but for the case of capturing session
2493 // history, the first committed frame suffices. We keep track of whether
2494 // we've seen this commit before so that only capture session history once
2497 // Note that we need to check if the page ID changed. In the case of a
2498 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2499 // previous URL and the current page ID, which would be wrong.
2500 if (navigation_state
->pending_page_id() != -1 &&
2501 navigation_state
->pending_page_id() != render_view_
->page_id_
&&
2502 !navigation_state
->request_committed()) {
2503 // This is a successful session history navigation!
2504 render_view_
->page_id_
= navigation_state
->pending_page_id();
2506 render_view_
->history_list_offset_
=
2507 navigation_state
->pending_history_list_offset();
2512 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2513 CHECK(sent
); // http://crbug.com/407376
2515 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2516 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2517 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2518 DidCommitProvisionalLoad(is_new_navigation
));
2520 if (!frame
->parent()) { // Only for top frames.
2521 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2522 if (render_thread_impl
) { // Can be NULL in tests.
2523 render_thread_impl
->histogram_customizer()->
2524 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2525 RenderViewImpl::GetRenderViewCount());
2529 // Remember that we've already processed this request, so we don't update
2530 // the session history again. We do this regardless of whether this is
2531 // a session history navigation, because if we attempted a session history
2532 // navigation without valid HistoryItem state, WebCore will think it is a
2534 navigation_state
->set_request_committed(true);
2536 SendDidCommitProvisionalLoad(frame
);
2538 // Check whether we have new encoding name.
2539 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2542 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2543 DCHECK(!frame_
|| frame_
== frame
);
2545 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2546 DidCreateNewDocument(frame
));
2549 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2550 DCHECK(!frame_
|| frame_
== frame
);
2551 // TODO(nasko): Move implementation here. Needed state:
2552 // * enabled_bindings_
2553 // * dom_automation_controller_
2554 // * stats_collection_controller_
2556 render_view_
->didClearWindowObject(frame
);
2558 if (render_view_
->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION
)
2559 DomAutomationController::Install(this, frame
);
2561 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2564 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2565 DCHECK(!frame_
|| frame_
== frame
);
2567 // Notify the browser about non-blank documents loading in the top frame.
2568 GURL url
= frame
->document().url();
2569 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2570 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2571 // frame->tree()->top().
2572 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2573 if (frame
== main_frame
) {
2574 // For now, don't remember plugin zoom values. We don't want to mix them
2575 // with normal web content (i.e. a fixed layout plugin would usually want
2577 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2578 render_view_
->GetRoutingID(),
2579 main_frame
->document().isPluginDocument()));
2583 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2584 DidCreateDocumentElement(frame
));
2587 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2588 const blink::WebString
& title
,
2589 blink::WebTextDirection direction
) {
2590 DCHECK(!frame_
|| frame_
== frame
);
2591 // Ignore all but top level navigations.
2592 if (!frame
->parent()) {
2593 base::string16 title16
= title
;
2594 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2595 routing_id_
, base::UTF16ToUTF8(title16
));
2597 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2598 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2599 shortened_title
, direction
));
2602 // Also check whether we have new encoding name.
2603 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2606 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2607 blink::WebIconURL::Type icon_type
) {
2608 DCHECK(!frame_
|| frame_
== frame
);
2609 // TODO(nasko): Investigate wheather implementation should move here.
2610 render_view_
->didChangeIcon(frame
, icon_type
);
2613 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2614 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2616 DCHECK(!frame_
|| frame_
== frame
);
2617 WebDataSource
* ds
= frame
->dataSource();
2618 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2619 document_state
->set_finish_document_load_time(Time::Now());
2621 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2623 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2624 DidFinishDocumentLoad(frame
));
2625 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2627 // Check whether we have new encoding name.
2628 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2631 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2632 DCHECK(!frame_
|| frame_
== frame
);
2633 if (!frame
->parent()) {
2634 FrameMsg_UILoadMetricsReportType::Value report_type
=
2635 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2636 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2637 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2638 base::TimeDelta::FromSecondsD(
2639 frame
->dataSource()->request().uiStartTime());
2641 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2642 routing_id_
, report_type
, ui_timestamp
));
2646 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2647 const blink::WebURLError
& error
) {
2648 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2650 DCHECK(!frame_
|| frame_
== frame
);
2651 // TODO(nasko): Move implementation here. No state needed.
2652 WebDataSource
* ds
= frame
->dataSource();
2655 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2656 DidFailLoad(frame
, error
));
2658 const WebURLRequest
& failed_request
= ds
->request();
2659 base::string16 error_description
;
2660 GetContentClient()->renderer()->GetNavigationErrorStrings(
2666 &error_description
);
2667 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2668 failed_request
.url(),
2670 error_description
));
2673 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2674 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2676 DCHECK(!frame_
|| frame_
== frame
);
2677 WebDataSource
* ds
= frame
->dataSource();
2678 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2679 if (document_state
->finish_load_time().is_null()) {
2680 if (!frame
->parent()) {
2681 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2682 TRACE_EVENT_SCOPE_PROCESS
);
2684 document_state
->set_finish_load_time(Time::Now());
2687 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2688 DidFinishLoad(frame
));
2689 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2691 // Don't send this message while the frame is swapped out.
2692 if (is_swapped_out())
2695 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2696 ds
->request().url()));
2699 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2700 const blink::WebHistoryItem
& item
,
2701 blink::WebHistoryCommitType commit_type
) {
2702 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2704 DCHECK(!frame_
|| frame_
== frame
);
2705 // If this was a reference fragment navigation that we initiated, then we
2706 // could end up having a non-null pending navigation params. We just need to
2707 // update the ExtraData on the datasource so that others who read the
2708 // ExtraData will get the new NavigationState. Similarly, if we did not
2709 // initiate this navigation, then we need to take care to reset any pre-
2710 // existing navigation state to a content-initiated navigation state.
2711 // DidCreateDataSource conveniently takes care of this for us.
2712 didCreateDataSource(frame
, frame
->dataSource());
2714 DocumentState
* document_state
=
2715 DocumentState::FromDataSource(frame
->dataSource());
2716 NavigationState
* new_state
= document_state
->navigation_state();
2717 new_state
->set_was_within_same_page(true);
2719 didCommitProvisionalLoad(frame
, item
, commit_type
);
2722 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2723 DCHECK(!frame_
|| frame_
== frame
);
2724 // TODO(nasko): Move implementation here. Needed methods:
2725 // * StartNavStateSyncTimerIfNecessary
2726 render_view_
->didUpdateCurrentHistoryItem(frame
);
2729 void RenderFrameImpl::addNavigationTransitionData(
2730 const blink::WebTransitionElementData
& data
) {
2731 FrameHostMsg_AddNavigationTransitionData_Params params
;
2732 params
.render_frame_id
= routing_id_
;
2733 params
.allowed_destination_host_pattern
=
2735 params
.selector
= data
.selector
.utf8();
2736 params
.markup
= data
.markup
.utf8();
2737 params
.elements
.resize(data
.elements
.size());
2738 for (size_t i
= 0; i
< data
.elements
.size(); i
++) {
2739 params
.elements
[i
].id
= data
.elements
[i
].id
.utf8();
2740 params
.elements
[i
].rect
= gfx::Rect(data
.elements
[i
].rect
);
2743 Send(new FrameHostMsg_AddNavigationTransitionData(params
));
2746 void RenderFrameImpl::didChangeThemeColor() {
2747 if (frame_
->parent())
2750 Send(new FrameHostMsg_DidChangeThemeColor(
2751 routing_id_
, frame_
->document().themeColor()));
2754 void RenderFrameImpl::requestNotificationPermission(
2755 const blink::WebSecurityOrigin
& origin
,
2756 blink::WebNotificationPermissionCallback
* callback
) {
2757 if (!notification_permission_dispatcher_
) {
2758 notification_permission_dispatcher_
=
2759 new NotificationPermissionDispatcher(this);
2762 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
2765 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
2766 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
2769 if (is_empty_selection
)
2770 selection_text_
.clear();
2772 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2773 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2774 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2775 // to notify the selection was changed. Focus change should be notified
2776 // before selection change.
2777 GetRenderWidget()->UpdateTextInputType();
2778 SyncSelectionIfRequired();
2779 #if defined(OS_ANDROID)
2780 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
2781 RenderWidget::FROM_NON_IME
);
2785 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
2786 blink::WebColorChooserClient
* client
,
2787 const blink::WebColor
& initial_color
,
2788 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
2789 RendererWebColorChooserImpl
* color_chooser
=
2790 new RendererWebColorChooserImpl(this, client
);
2791 std::vector
<ColorSuggestion
> color_suggestions
;
2792 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
2793 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
2795 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
2796 return color_chooser
;
2799 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
2800 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
2803 frame_
->document().url(),
2807 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
2808 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
2811 frame_
->document().url(),
2815 bool RenderFrameImpl::runModalPromptDialog(
2816 const blink::WebString
& message
,
2817 const blink::WebString
& default_value
,
2818 blink::WebString
* actual_value
) {
2819 base::string16 result
;
2820 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
2823 frame_
->document().url(),
2826 actual_value
->assign(result
);
2830 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2832 const blink::WebString
& message
) {
2833 // If we are swapping out, we have already run the beforeunload handler.
2834 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2835 // at all, to avoid running it twice.
2836 if (is_swapped_out_
)
2839 // Don't allow further dialogs if we are waiting to swap out, since the
2840 // PageGroupLoadDeferrer in our stack prevents it.
2841 if (render_view()->suppress_dialogs_until_swap_out_
)
2844 bool success
= false;
2845 // This is an ignored return value, but is included so we can accept the same
2846 // response as RunJavaScriptMessage.
2847 base::string16 ignored_result
;
2848 render_view()->SendAndRunNestedMessageLoop(
2849 new FrameHostMsg_RunBeforeUnloadConfirm(
2850 routing_id_
, frame_
->document().url(), message
, is_reload
,
2851 &success
, &ignored_result
));
2855 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
2856 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
2857 params
.source_type
= GetRenderWidget()->context_menu_source_type();
2858 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
2859 if (GetRenderWidget()->has_host_context_menu_location()) {
2860 params
.x
= GetRenderWidget()->host_context_menu_location().x();
2861 params
.y
= GetRenderWidget()->host_context_menu_location().y();
2864 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2865 // it. We replace it with an empty GURL so the appropriate items are disabled
2866 // in the context menu.
2867 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2868 // data encoded images. We should have a way to save them.
2869 if (params
.src_url
.spec().size() > GetMaxURLChars())
2870 params
.src_url
= GURL();
2871 context_menu_node_
= data
.node
;
2873 #if defined(OS_ANDROID)
2874 gfx::Rect start_rect
;
2876 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
2877 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
2878 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
2881 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
2884 void RenderFrameImpl::clearContextMenu() {
2885 context_menu_node_
.reset();
2888 void RenderFrameImpl::willSendRequest(
2889 blink::WebLocalFrame
* frame
,
2890 unsigned identifier
,
2891 blink::WebURLRequest
& request
,
2892 const blink::WebURLResponse
& redirect_response
) {
2893 DCHECK(!frame_
|| frame_
== frame
);
2894 // The request my be empty during tests.
2895 if (request
.url().isEmpty())
2898 // Set the first party for cookies url if it has not been set yet (new
2899 // requests). For redirects, it is updated by WebURLLoaderImpl.
2900 if (request
.firstPartyForCookies().isEmpty()) {
2901 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
2902 request
.setFirstPartyForCookies(request
.url());
2904 // TODO(nasko): When the top-level frame is remote, there is no document.
2905 // This is broken and should be fixed to propagate the first party.
2906 WebFrame
* top
= frame
->top();
2907 if (top
->isWebLocalFrame()) {
2908 request
.setFirstPartyForCookies(
2909 frame
->top()->document().firstPartyForCookies());
2914 WebFrame
* top_frame
= frame
->top();
2915 // TODO(nasko): Hack around asking about top-frame data source. This means
2916 // for out-of-process iframes we are treating the current frame as the
2917 // top-level frame, which is wrong.
2918 if (!top_frame
|| top_frame
->isWebRemoteFrame())
2920 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
2921 WebDataSource
* top_data_source
= top_frame
->dataSource();
2922 WebDataSource
* data_source
=
2923 provisional_data_source
? provisional_data_source
: top_data_source
;
2925 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
2926 DCHECK(document_state
);
2927 InternalDocumentStateData
* internal_data
=
2928 InternalDocumentStateData::FromDocumentState(document_state
);
2929 NavigationState
* navigation_state
= document_state
->navigation_state();
2930 ui::PageTransition transition_type
= navigation_state
->transition_type();
2931 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
2932 if (frame_ds
&& frame_ds
->isClientRedirect()) {
2933 transition_type
= ui::PageTransitionFromInt(
2934 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
2937 GURL
request_url(request
.url());
2939 if (GetContentClient()->renderer()->WillSendRequest(
2943 request
.firstPartyForCookies(),
2945 request
.setURL(WebURL(new_url
));
2948 if (internal_data
->is_cache_policy_override_set())
2949 request
.setCachePolicy(internal_data
->cache_policy_override());
2951 // The request's extra data may indicate that we should set a custom user
2952 // agent. This needs to be done here, after WebKit is through with setting the
2953 // user agent on its own. Similarly, it may indicate that we should set an
2954 // X-Requested-With header. This must be done here to avoid breaking CORS
2956 // PlzNavigate: there may also be a stream url associated with the request.
2957 WebString custom_user_agent
;
2958 WebString requested_with
;
2959 scoped_ptr
<StreamOverrideParameters
> stream_override
;
2960 if (request
.extraData()) {
2961 RequestExtraData
* old_extra_data
=
2962 static_cast<RequestExtraData
*>(request
.extraData());
2964 custom_user_agent
= old_extra_data
->custom_user_agent();
2965 if (!custom_user_agent
.isNull()) {
2966 if (custom_user_agent
.isEmpty())
2967 request
.clearHTTPHeaderField("User-Agent");
2969 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
2972 requested_with
= old_extra_data
->requested_with();
2973 if (!requested_with
.isNull()) {
2974 if (requested_with
.isEmpty())
2975 request
.clearHTTPHeaderField("X-Requested-With");
2977 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
2979 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
2982 // Add the default accept header for frame request if it has not been set
2984 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
2985 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
2986 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
2987 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
2988 WebString::fromUTF8(kDefaultAcceptHeader
));
2991 // Add an empty HTTP origin header for non GET methods if none is currently
2993 request
.addHTTPOriginIfNeeded(WebString());
2995 // Attach |should_replace_current_entry| state to requests so that, should
2996 // this navigation later require a request transfer, all state is preserved
2997 // when it is re-created in the new process.
2998 bool should_replace_current_entry
= false;
2999 if (navigation_state
->is_content_initiated()) {
3000 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3002 // If the navigation is browser-initiated, the NavigationState contains the
3003 // correct value instead of the WebDataSource.
3005 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3006 // NavigationState::should_replace_current_entry().
3007 should_replace_current_entry
=
3008 navigation_state
->should_replace_current_entry();
3011 int provider_id
= kInvalidServiceWorkerProviderId
;
3012 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3013 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3014 // |provisionalDataSource| may be null in some content::ResourceFetcher
3015 // use cases, we don't hook those requests.
3016 if (frame
->provisionalDataSource()) {
3017 ServiceWorkerNetworkProvider
* provider
=
3018 ServiceWorkerNetworkProvider::FromDocumentState(
3019 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3020 provider_id
= provider
->provider_id();
3022 } else if (frame
->dataSource()) {
3023 ServiceWorkerNetworkProvider
* provider
=
3024 ServiceWorkerNetworkProvider::FromDocumentState(
3025 DocumentState::FromDataSource(frame
->dataSource()));
3026 provider_id
= provider
->provider_id();
3029 WebFrame
* parent
= frame
->parent();
3030 int parent_routing_id
= MSG_ROUTING_NONE
;
3032 parent_routing_id
= -1;
3033 } else if (parent
->isWebLocalFrame()) {
3034 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3036 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3039 RequestExtraData
* extra_data
= new RequestExtraData();
3040 extra_data
->set_visibility_state(render_view_
->visibilityState());
3041 extra_data
->set_custom_user_agent(custom_user_agent
);
3042 extra_data
->set_requested_with(requested_with
);
3043 extra_data
->set_render_frame_id(routing_id_
);
3044 extra_data
->set_is_main_frame(!parent
);
3045 extra_data
->set_frame_origin(
3046 GURL(frame
->document().securityOrigin().toString()));
3047 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3048 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3049 extra_data
->set_allow_download(navigation_state
->allow_download());
3050 extra_data
->set_transition_type(transition_type
);
3051 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3052 extra_data
->set_transferred_request_child_id(
3053 navigation_state
->transferred_request_child_id());
3054 extra_data
->set_transferred_request_request_id(
3055 navigation_state
->transferred_request_request_id());
3056 extra_data
->set_service_worker_provider_id(provider_id
);
3057 extra_data
->set_stream_override(stream_override
.Pass());
3058 request
.setExtraData(extra_data
);
3060 DocumentState
* top_document_state
=
3061 DocumentState::FromDataSource(top_data_source
);
3062 if (top_document_state
) {
3063 // TODO(gavinp): separate out prefetching and prerender field trials
3064 // if the rel=prerender rel type is sticking around.
3065 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3066 top_document_state
->set_was_prefetcher(true);
3069 // This is an instance where we embed a copy of the routing id
3070 // into the data portion of the message. This can cause problems if we
3071 // don't register this id on the browser side, since the download manager
3072 // expects to find a RenderViewHost based off the id.
3073 request
.setRequestorID(render_view_
->GetRoutingID());
3074 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3076 if (!navigation_state
->extra_headers().empty()) {
3077 for (net::HttpUtil::HeadersIterator
i(
3078 navigation_state
->extra_headers().begin(),
3079 navigation_state
->extra_headers().end(), "\n");
3081 if (LowerCaseEqualsASCII(i
.name(), "referer")) {
3082 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3083 blink::WebReferrerPolicyDefault
,
3085 WebString::fromUTF8(i
.values()));
3086 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3088 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3089 WebString::fromUTF8(i
.values()));
3094 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3095 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3098 void RenderFrameImpl::didReceiveResponse(
3099 blink::WebLocalFrame
* frame
,
3100 unsigned identifier
,
3101 const blink::WebURLResponse
& response
) {
3102 DCHECK(!frame_
|| frame_
== frame
);
3103 // Only do this for responses that correspond to a provisional data source
3104 // of the top-most frame. If we have a provisional data source, then we
3105 // can't have any sub-resources yet, so we know that this response must
3106 // correspond to a frame load.
3107 if (!frame
->provisionalDataSource() || frame
->parent())
3110 // If we are in view source mode, then just let the user see the source of
3111 // the server's error page.
3112 if (frame
->isViewSourceModeEnabled())
3115 DocumentState
* document_state
=
3116 DocumentState::FromDataSource(frame
->provisionalDataSource());
3117 int http_status_code
= response
.httpStatusCode();
3119 // Record page load flags.
3120 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3122 document_state
->set_was_fetched_via_spdy(
3123 extra_data
->was_fetched_via_spdy());
3124 document_state
->set_was_npn_negotiated(
3125 extra_data
->was_npn_negotiated());
3126 document_state
->set_npn_negotiated_protocol(
3127 extra_data
->npn_negotiated_protocol());
3128 document_state
->set_was_alternate_protocol_available(
3129 extra_data
->was_alternate_protocol_available());
3130 document_state
->set_connection_info(
3131 extra_data
->connection_info());
3132 document_state
->set_was_fetched_via_proxy(
3133 extra_data
->was_fetched_via_proxy());
3134 document_state
->set_proxy_server(
3135 extra_data
->proxy_server());
3137 InternalDocumentStateData
* internal_data
=
3138 InternalDocumentStateData::FromDocumentState(document_state
);
3139 internal_data
->set_http_status_code(http_status_code
);
3140 // Whether or not the http status code actually corresponds to an error is
3141 // only checked when the page is done loading, if |use_error_page| is
3143 internal_data
->set_use_error_page(true);
3146 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3147 unsigned identifier
) {
3148 DCHECK(!frame_
|| frame_
== frame
);
3149 InternalDocumentStateData
* internal_data
=
3150 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3151 if (!internal_data
->use_error_page())
3154 // Do not show error page when DevTools is attached.
3155 if (render_view_
->devtools_agent_
->IsAttached())
3158 // Display error page, if appropriate.
3159 std::string error_domain
= "http";
3160 int http_status_code
= internal_data
->http_status_code();
3161 if (GetContentClient()->renderer()->HasErrorPage(
3162 http_status_code
, &error_domain
)) {
3164 error
.unreachableURL
= frame
->document().url();
3165 error
.domain
= WebString::fromUTF8(error_domain
);
3166 error
.reason
= http_status_code
;
3167 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3171 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3172 blink::WebLocalFrame
* frame
,
3173 const blink::WebURLRequest
& request
,
3174 const blink::WebURLResponse
& response
) {
3175 DCHECK(!frame_
|| frame_
== frame
);
3176 // The recipients of this message have no use for data: URLs: they don't
3177 // affect the page's insecure content list and are not in the disk cache. To
3178 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3179 // filter them out here.
3180 GURL
url(request
.url());
3181 if (url
.SchemeIs(url::kDataScheme
))
3184 // Let the browser know we loaded a resource from the memory cache. This
3185 // message is needed to display the correct SSL indicators.
3186 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3187 render_view_
->GetRoutingID(),
3189 response
.securityInfo(),
3190 request
.httpMethod().utf8(),
3191 response
.mimeType().utf8(),
3192 WebURLRequestToResourceType(request
)));
3195 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3196 DCHECK(!frame_
|| frame_
== frame
);
3197 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3198 render_view_
->GetRoutingID()));
3201 void RenderFrameImpl::didRunInsecureContent(
3202 blink::WebLocalFrame
* frame
,
3203 const blink::WebSecurityOrigin
& origin
,
3204 const blink::WebURL
& target
) {
3205 DCHECK(!frame_
|| frame_
== frame
);
3206 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3207 render_view_
->GetRoutingID(),
3208 origin
.toString().utf8(),
3212 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3213 DCHECK(!frame_
|| frame_
== frame
);
3214 #if defined(ENABLE_PLUGINS)
3215 if (frame
!= render_view_
->webview()->mainFrame())
3217 PluginChannelHost::Broadcast(
3218 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3222 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3223 v8::Handle
<v8::Context
> context
,
3224 int extension_group
,
3226 DCHECK(!frame_
|| frame_
== frame
);
3227 GetContentClient()->renderer()->DidCreateScriptContext(
3228 frame
, context
, extension_group
, world_id
);
3231 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3232 v8::Handle
<v8::Context
> context
,
3234 DCHECK(!frame_
|| frame_
== frame
);
3236 FOR_EACH_OBSERVER(RenderFrameObserver
,
3238 WillReleaseScriptContext(context
, world_id
));
3241 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3242 blink::WebLocalFrame
* frame
) {
3243 DCHECK(!frame_
|| frame_
== frame
);
3244 if (frame
->parent())
3247 InternalDocumentStateData
* data
=
3248 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3249 data
->set_did_first_visually_non_empty_layout(true);
3251 #if defined(OS_ANDROID)
3252 GetRenderWidget()->DidChangeBodyBackgroundColor(
3253 render_view_
->webwidget_
->backgroundColor());
3256 GetRenderWidget()->QueueMessage(
3257 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3258 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3261 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3262 DCHECK(!frame_
|| frame_
== frame
);
3263 // TODO(nasko): Move implementation here. Needed methods:
3264 // * StartNavStateSyncTimerIfNecessary
3265 render_view_
->didChangeScrollOffset(frame
);
3267 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3270 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3271 DCHECK(!frame_
|| frame_
== frame
);
3272 if (!frame
->parent()) {
3273 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3274 render_view_
->GetRoutingID()));
3278 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3280 bool final_update
) {
3281 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3283 active_match_ordinal
= 0;
3285 render_view_
->Send(new ViewHostMsg_Find_Reply(
3286 render_view_
->GetRoutingID(), request_id
, count
,
3287 gfx::Rect(), active_match_ordinal
, final_update
));
3290 void RenderFrameImpl::reportFindInPageSelection(
3292 int active_match_ordinal
,
3293 const blink::WebRect
& selection_rect
) {
3294 render_view_
->Send(new ViewHostMsg_Find_Reply(
3295 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3296 active_match_ordinal
, false));
3299 void RenderFrameImpl::requestStorageQuota(
3300 blink::WebLocalFrame
* frame
,
3301 blink::WebStorageQuotaType type
,
3302 unsigned long long requested_size
,
3303 blink::WebStorageQuotaCallbacks callbacks
) {
3304 DCHECK(!frame_
|| frame_
== frame
);
3305 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3306 if (origin
.isUnique()) {
3307 // Unique origins cannot store persistent state.
3308 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3311 ChildThread::current()->quota_dispatcher()->RequestStorageQuota(
3312 render_view_
->GetRoutingID(),
3313 GURL(origin
.toString()),
3314 static_cast<storage::StorageType
>(type
),
3316 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3319 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3320 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3321 impl
->set_render_frame_id(routing_id_
);
3324 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3325 if (!geolocation_dispatcher_
)
3326 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3327 return geolocation_dispatcher_
;
3330 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3331 if (!push_messaging_dispatcher_
)
3332 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3333 return push_messaging_dispatcher_
;
3336 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3337 blink::WebLocalFrame
* frame
,
3338 blink::WebRTCPeerConnectionHandler
* handler
) {
3339 DCHECK(!frame_
|| frame_
== frame
);
3340 #if defined(ENABLE_WEBRTC)
3341 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3345 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3346 if (!web_user_media_client_
)
3347 InitializeUserMediaClient();
3348 return web_user_media_client_
;
3351 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3352 if (!web_encrypted_media_client_
) {
3353 #if defined(ENABLE_PEPPER_CDMS)
3354 scoped_ptr
<media::CdmFactory
> cdm_factory(
3355 new RenderCdmFactory(base::Bind(PepperCdmWrapperImpl::Create
, frame_
)));
3356 #elif defined(ENABLE_BROWSER_CDMS)
3357 scoped_ptr
<media::CdmFactory
> cdm_factory(
3358 new RenderCdmFactory(GetCdmManager()));
3360 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
3362 web_encrypted_media_client_
.reset(
3363 new media::WebEncryptedMediaClientImpl(cdm_factory
.Pass()));
3365 return web_encrypted_media_client_
.get();
3368 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3369 if (!midi_dispatcher_
)
3370 midi_dispatcher_
= new MidiDispatcher(this);
3371 return midi_dispatcher_
;
3374 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3375 blink::WebLocalFrame
* source_frame
,
3376 blink::WebFrame
* target_frame
,
3377 blink::WebSecurityOrigin target_origin
,
3378 blink::WebDOMMessageEvent event
) {
3379 DCHECK(!frame_
|| frame_
== target_frame
);
3381 if (!is_swapped_out_
)
3384 ViewMsg_PostMessage_Params params
;
3385 params
.is_data_raw_string
= false;
3386 params
.data
= event
.data().toString();
3387 params
.source_origin
= event
.origin();
3388 if (!target_origin
.isNull())
3389 params
.target_origin
= target_origin
.toString();
3391 blink::WebMessagePortChannelArray channels
= event
.releaseChannels();
3392 if (!channels
.isEmpty()) {
3393 std::vector
<int> message_port_ids(channels
.size());
3394 // Extract the port IDs from the channel array.
3395 for (size_t i
= 0; i
< channels
.size(); ++i
) {
3396 WebMessagePortChannelImpl
* webchannel
=
3397 static_cast<WebMessagePortChannelImpl
*>(channels
[i
]);
3398 message_port_ids
[i
] = webchannel
->message_port_id();
3399 webchannel
->QueueMessages();
3400 DCHECK_NE(message_port_ids
[i
], MSG_ROUTING_NONE
);
3402 params
.message_port_ids
= message_port_ids
;
3405 // Include the routing ID for the source frame (if one exists), which the
3406 // browser process will translate into the routing ID for the equivalent
3407 // frame in the target process.
3408 params
.source_routing_id
= MSG_ROUTING_NONE
;
3410 RenderViewImpl
* source_view
=
3411 RenderViewImpl::FromWebView(source_frame
->view());
3413 params
.source_routing_id
= source_view
->routing_id();
3416 Send(new ViewHostMsg_RouteMessageEvent(render_view_
->routing_id_
, params
));
3420 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3421 const blink::WebURL
& url
) {
3422 DCHECK(!frame_
|| frame_
== frame
);
3423 std::string user_agent_override_for_url
=
3424 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3425 if (!user_agent_override_for_url
.empty())
3426 return WebString::fromUTF8(user_agent_override_for_url
);
3428 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3429 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3430 return blink::WebString();
3433 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3434 // associated with it, so the checks below are not valid. Temporarily
3435 // return early and fix properly as part of https://crbug.com/426555.
3436 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3437 return blink::WebString();
3439 // If we're in the middle of committing a load, the data source we need
3440 // will still be provisional.
3441 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3442 WebDataSource
* data_source
= NULL
;
3443 if (main_frame
->provisionalDataSource())
3444 data_source
= main_frame
->provisionalDataSource();
3446 data_source
= main_frame
->dataSource();
3448 InternalDocumentStateData
* internal_data
= data_source
?
3449 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3450 if (internal_data
&& internal_data
->is_overriding_user_agent())
3451 return WebString::fromUTF8(
3452 render_view_
->renderer_preferences_
.user_agent_override
);
3453 return blink::WebString();
3456 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3457 DCHECK(!frame_
|| frame_
== frame
);
3458 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3459 return WebString::fromUTF8("1");
3463 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3464 bool default_value
) {
3465 DCHECK(!frame_
|| frame_
== frame
);
3469 bool blocked
= true;
3470 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3471 render_view_
->GetRoutingID(),
3472 GURL(frame
->top()->document().securityOrigin().toString()),
3473 THREE_D_API_TYPE_WEBGL
,
3478 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3479 int arb_robustness_status_code
) {
3480 DCHECK(!frame_
|| frame_
== frame
);
3481 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3482 GURL(frame
->top()->document().securityOrigin().toString()),
3483 THREE_D_API_TYPE_WEBGL
,
3484 arb_robustness_status_code
));
3487 blink::WebScreenOrientationClient
*
3488 RenderFrameImpl::webScreenOrientationClient() {
3489 if (!screen_orientation_dispatcher_
)
3490 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3491 return screen_orientation_dispatcher_
;
3494 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3495 ServiceWorkerNetworkProvider
* provider
=
3496 ServiceWorkerNetworkProvider::FromDocumentState(
3497 DocumentState::FromDataSource(&data_source
));
3498 return provider
->context()->controller_handle_id() !=
3499 kInvalidServiceWorkerHandleId
;
3502 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3503 ServiceWorkerNetworkProvider
* provider
=
3504 ServiceWorkerNetworkProvider::FromDocumentState(
3505 DocumentState::FromDataSource(&data_source
));
3507 if (provider
->context()->controller())
3508 return provider
->context()->controller()->version_id();
3509 return kInvalidServiceWorkerVersionId
;
3512 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3513 blink::WebAXEvent event
) {
3514 HandleWebAccessibilityEvent(obj
, event
);
3517 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3520 const blink::WebAXObject
& start_object
,
3522 const blink::WebAXObject
& end_object
,
3524 if (renderer_accessibility_
) {
3525 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3526 identifier
, match_index
, start_object
, start_offset
,
3527 end_object
, end_offset
);
3531 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3532 DCHECK(!frame_
|| frame_
== frame
);
3534 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3537 bool RenderFrameImpl::enterFullscreen() {
3538 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3542 bool RenderFrameImpl::exitFullscreen() {
3543 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3547 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3548 Send(new FrameHostMsg_MediaPlayingNotification(
3549 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3550 player
->hasAudio(), player
->isRemote()));
3553 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3554 Send(new FrameHostMsg_MediaPausedNotification(
3555 routing_id_
, reinterpret_cast<int64
>(player
)));
3558 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3562 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3563 observers_
.AddObserver(observer
);
3566 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3567 observer
->RenderFrameGone();
3568 observers_
.RemoveObserver(observer
);
3571 void RenderFrameImpl::OnStop() {
3573 frame_
->stopLoading();
3574 if (!frame_
->parent())
3575 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3577 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3580 void RenderFrameImpl::WasHidden() {
3581 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3584 void RenderFrameImpl::WasShown() {
3585 // TODO(kenrb): Need to figure out how to do this better. Should
3586 // VisibilityState remain a page-level concept or move to frames?
3587 // The semantics of 'Show' might have to change here.
3588 if (render_widget_
) {
3589 render_view()->webview()->setVisibilityState(
3590 blink::WebPageVisibilityStateVisible
, false);
3592 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3595 bool RenderFrameImpl::IsHidden() {
3596 return GetRenderWidget()->is_hidden();
3599 // Tell the embedding application that the URL of the active page has changed.
3600 void RenderFrameImpl::SendDidCommitProvisionalLoad(blink::WebFrame
* frame
) {
3601 DCHECK(!frame_
|| frame_
== frame
);
3602 WebDataSource
* ds
= frame
->dataSource();
3605 const WebURLRequest
& request
= ds
->request();
3606 const WebURLResponse
& response
= ds
->response();
3608 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3609 NavigationState
* navigation_state
= document_state
->navigation_state();
3610 InternalDocumentStateData
* internal_data
=
3611 InternalDocumentStateData::FromDocumentState(document_state
);
3613 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3614 params
.http_status_code
= response
.httpStatusCode();
3615 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3616 params
.is_post
= false;
3617 params
.post_id
= -1;
3618 params
.page_id
= render_view_
->page_id_
;
3619 // We need to track the RenderViewHost routing_id because of downstream
3620 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3621 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3622 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3623 // based on the ID stored in the resource requests. Once those dependencies
3624 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3625 // client to be based on the routing_id of the RenderFrameHost.
3626 params
.render_view_routing_id
= render_view_
->routing_id();
3627 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3628 params
.socket_address
.set_port(response
.remotePort());
3629 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3631 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3632 params
.was_within_same_page
= navigation_state
->was_within_same_page();
3633 params
.security_info
= response
.securityInfo();
3635 // Set the URL to be displayed in the browser UI to the user.
3636 params
.url
= GetLoadingUrl();
3637 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3639 // Set the origin of the frame. This will be replicated to the corresponding
3640 // RenderFrameProxies in other processes.
3641 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3642 // to https://crbug.com/439608 and will be replicated as unique origins.
3643 if (!is_swapped_out_
) {
3644 WebString
serialized_origin(frame
->document().securityOrigin().toString());
3645 if (GURL(serialized_origin
).IsStandard())
3646 params
.origin
= url::Origin(serialized_origin
.utf8());
3649 if (frame
->document().baseURL() != params
.url
)
3650 params
.base_url
= frame
->document().baseURL();
3652 GetRedirectChain(ds
, ¶ms
.redirects
);
3653 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3654 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3656 params
.searchable_form_url
= internal_data
->searchable_form_url();
3657 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3659 params
.gesture
= render_view_
->navigation_gesture_
;
3660 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3662 // Make navigation state a part of the DidCommitProvisionalLoad message so
3663 // that commited entry has it at all times.
3664 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3666 params
.page_state
= HistoryEntryToPageState(entry
);
3668 params
.page_state
= PageState::CreateFromURL(request
.url());
3670 if (!frame
->parent()) {
3671 // Top-level navigation.
3673 // Reset the zoom limits in case a plugin had changed them previously. This
3674 // will also call us back which will cause us to send a message to
3675 // update WebContentsImpl.
3676 render_view_
->webview()->zoomLimitsChanged(
3677 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3678 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3680 // Set zoom level, but don't do it for full-page plugin since they don't use
3681 // the same zoom settings.
3682 HostZoomLevels::iterator host_zoom
=
3683 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3684 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3685 // Reset the zoom levels for plugins.
3686 render_view_
->webview()->setZoomLevel(0);
3688 // If the zoom level is not found, then do nothing. In-page navigation
3689 // relies on not changing the zoom level in this case.
3690 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3691 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3694 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3695 // This zoom level was merely recorded transiently for this load. We can
3696 // erase it now. If at some point we reload this page, the browser will
3697 // send us a new, up-to-date zoom level.
3698 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3701 // Update contents MIME type for main frame.
3702 params
.contents_mime_type
= ds
->response().mimeType().utf8();
3704 params
.transition
= navigation_state
->transition_type();
3705 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
3706 // If the main frame does a load, it should not be reported as a subframe
3707 // navigation. This can occur in the following case:
3708 // 1. You're on a site with frames.
3709 // 2. You do a subframe navigation. This is stored with transition type
3711 // 3. You navigate to some non-frame site, say, google.com.
3712 // 4. You navigate back to the page from step 2. Since it was initially
3713 // MANUAL_SUBFRAME, it will be that same transition type here.
3714 // We don't want that, because any navigation that changes the toplevel
3715 // frame should be tracked as a toplevel navigation (this allows us to
3716 // update the URL bar, etc).
3717 params
.transition
= ui::PAGE_TRANSITION_LINK
;
3720 // If the page contained a client redirect (meta refresh, document.loc...),
3721 // set the referrer and transition appropriately.
3722 if (ds
->isClientRedirect()) {
3724 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
3725 params
.transition
= ui::PageTransitionFromInt(
3726 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3728 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
3729 frame
, ds
->request());
3732 base::string16 method
= request
.httpMethod();
3733 if (EqualsASCII(method
, "POST")) {
3734 params
.is_post
= true;
3735 params
.post_id
= ExtractPostId(entry
->root());
3738 // Send the user agent override back.
3739 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
3741 // Track the URL of the original request. We use the first entry of the
3742 // redirect chain if it exists because the chain may have started in another
3744 params
.original_request_url
= GetOriginalRequestURL(ds
);
3746 params
.history_list_was_cleared
=
3747 navigation_state
->history_list_was_cleared();
3749 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
3750 frame
->dataSource()->request().inputPerfMetricReportPolicy());
3751 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
3752 frame
->dataSource()->request().uiStartTime());
3754 // Save some histogram data so we can compute the average memory used per
3755 // page load of the glyphs.
3756 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3757 blink::WebGlyphCache::pageCount());
3759 // This message needs to be sent before any of allowScripts(),
3760 // allowImages(), allowPlugins() is called for the new page, so that when
3761 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3762 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3763 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3765 // Subframe navigation: the type depends on whether this navigation
3766 // generated a new session history entry. When they do generate a session
3767 // history entry, it means the user initiated the navigation and we should
3768 // mark it as such. This test checks if this is the first time
3769 // SendDidCommitProvisionalLoad has been called since WillNavigateToURL was
3770 // called to initiate the load.
3771 if (render_view_
->page_id_
> render_view_
->last_page_id_sent_to_browser_
)
3772 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
3774 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
3776 DCHECK(!navigation_state
->history_list_was_cleared());
3777 params
.history_list_was_cleared
= false;
3778 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
3780 // Don't send this message while the subframe is swapped out.
3781 if (!is_swapped_out())
3782 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3785 render_view_
->last_page_id_sent_to_browser_
=
3786 std::max(render_view_
->last_page_id_sent_to_browser_
,
3787 render_view_
->page_id_
);
3789 // If we end up reusing this WebRequest (for example, due to a #ref click),
3790 // we don't want the transition type to persist. Just clear it.
3791 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
3794 WebElement
RenderFrameImpl::GetFocusedElement() {
3795 WebDocument doc
= frame_
->document();
3797 return doc
.focusedElement();
3799 return WebElement();
3802 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
3803 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3805 render_view_
->FrameDidStartLoading(frame_
);
3806 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
3809 void RenderFrameImpl::didStopLoading() {
3810 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3812 render_view_
->FrameDidStopLoading(frame_
);
3813 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
3816 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
3817 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
3820 void RenderFrameImpl::HandleWebAccessibilityEvent(
3821 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
3822 if (renderer_accessibility_
)
3823 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
3826 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
3827 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
3830 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
3831 if (renderer_accessibility())
3832 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
3836 void RenderFrameImpl::OnRequestNavigation(
3837 const CommonNavigationParams
& common_params
,
3838 const RequestNavigationParams
& request_params
) {
3839 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3840 switches::kEnableBrowserSideNavigation
));
3841 WebURLRequest request
=
3842 CreateURLRequestForNavigation(common_params
,
3844 scoped_ptr
<StreamOverrideParameters
>(),
3845 frame_
->isViewSourceModeEnabled());
3846 BeginNavigation(&request
);
3850 void RenderFrameImpl::OnCommitNavigation(
3851 const ResourceResponseHead
& response
,
3852 const GURL
& stream_url
,
3853 const CommonNavigationParams
& common_params
,
3854 const CommitNavigationParams
& commit_params
) {
3855 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3856 switches::kEnableBrowserSideNavigation
));
3857 bool is_reload
= false;
3858 bool is_history_navigation
= commit_params
.page_state
.IsValid();
3859 WebURLRequest::CachePolicy cache_policy
=
3860 WebURLRequest::UseProtocolCachePolicy
;
3861 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3862 common_params
.url
, false /* check_for_stale_navigation */,
3863 is_history_navigation
, -1 /* current_history_list_offset; TODO(clamy)*/,
3864 &is_reload
, &cache_policy
)) {
3868 GetContentClient()->SetActiveURL(common_params
.url
);
3870 // Create a WebURLRequest that blink can use to get access to the body of the
3871 // response through a stream in the browser. Blink will then commit the
3873 // TODO(clamy): Have the navigation commit directly, without going through
3874 // loading a WebURLRequest.
3875 scoped_ptr
<StreamOverrideParameters
> stream_override(
3876 new StreamOverrideParameters());
3877 stream_override
->stream_url
= stream_url
;
3878 stream_override
->response
= response
;
3879 WebURLRequest request
=
3880 CreateURLRequestForNavigation(common_params
,
3881 RequestNavigationParams(),
3882 stream_override
.Pass(),
3883 frame_
->isViewSourceModeEnabled());
3885 // Make sure that blink loader will not try to use browser side navigation for
3886 // this request (since it already went to the browser).
3887 request
.setCheckForBrowserSideNavigation(false);
3889 // Record this before starting the load. A lower bound of this time is needed
3890 // to sanitize the navigationStart override set below.
3891 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
3892 frame_
->loadRequest(request
);
3893 UpdateFrameNavigationTiming(
3894 frame_
, commit_params
.browser_navigation_start
,
3895 renderer_navigation_start
);
3898 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
3899 RenderFrame
* render_frame
,
3900 const NavigationPolicyInfo
& info
) {
3902 // The handlenavigation API is deprecated and will be removed once
3903 // crbug.com/325351 is resolved.
3904 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
3905 GetContentClient()->renderer()->HandleNavigation(
3907 static_cast<DocumentState
*>(info
.extraData
),
3908 render_view_
->opener_id_
,
3911 info
.navigationType
,
3914 return blink::WebNavigationPolicyIgnore
;
3918 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
3920 const base::CommandLine
& command_line
=
3921 *base::CommandLine::ForCurrentProcess();
3923 bool is_subframe
= !!info
.frame
->parent();
3925 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe
) {
3926 // There's no reason to ignore navigations on subframes, since the swap out
3927 // logic no longer applies.
3929 if (is_swapped_out_
) {
3930 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
3931 // Targeted links may try to navigate a swapped out frame. Allow the
3932 // browser process to navigate the tab instead. Note that it is also
3933 // possible for non-targeted navigations (from this view) to arrive
3934 // here just after we are swapped out. It's ok to send them to the
3935 // browser, as long as they're for the top level frame.
3936 // TODO(creis): Ensure this supports targeted form submissions when
3937 // fixing http://crbug.com/101395.
3938 if (info
.frame
->parent() == NULL
) {
3939 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
3940 info
.defaultPolicy
);
3941 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3944 // We should otherwise ignore in-process iframe navigations, if they
3945 // arrive just after we are swapped out.
3946 return blink::WebNavigationPolicyIgnore
;
3949 // Allow kSwappedOutURL to complete.
3950 return info
.defaultPolicy
;
3954 // Webkit is asking whether to navigate to a new URL.
3955 // This is fine normally, except if we're showing UI from one security
3956 // context and they're trying to navigate to a different context.
3957 const GURL
& url
= info
.urlRequest
.url();
3959 // A content initiated navigation may have originated from a link-click,
3960 // script, drag-n-drop operation, etc.
3961 bool is_content_initiated
= static_cast<DocumentState
*>(info
.extraData
)->
3962 navigation_state()->is_content_initiated();
3965 // If --enable-strict-site-isolation is enabled, send all top-level
3966 // navigations to the browser to let it swap processes when crossing site
3967 // boundaries. This is currently expected to break some script calls and
3968 // navigations, such as form submissions.
3969 bool force_swap_due_to_flag
=
3970 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
);
3971 if (force_swap_due_to_flag
&&
3972 !info
.frame
->parent() && (is_content_initiated
|| info
.isRedirect
)) {
3973 WebString origin_str
= info
.frame
->document().securityOrigin().toString();
3974 GURL
frame_url(origin_str
.utf8().data());
3975 // TODO(cevans): revisit whether this site check is still necessary once
3976 // crbug.com/101395 is fixed.
3977 bool same_domain_or_host
=
3978 net::registry_controlled_domains::SameDomainOrHost(
3981 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
3982 // Only keep same-site (domain + scheme) and data URLs in the same process.
3984 (same_domain_or_host
&& frame_url
.scheme() == url
.scheme()) ||
3985 url
.SchemeIs(url::kDataScheme
);
3986 if (!is_same_site
) {
3987 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
3988 return blink::WebNavigationPolicyIgnore
;
3992 // If the browser is interested, then give it a chance to look at the request.
3993 if (is_content_initiated
) {
3995 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
3996 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
3997 EqualsASCII(info
.urlRequest
.httpMethod(), "POST");
3998 bool browser_handles_request
=
3999 render_view_
->renderer_preferences_
4000 .browser_handles_non_local_top_level_requests
4001 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4003 if (!browser_handles_request
) {
4004 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4005 render_view_
->renderer_preferences_
4006 .browser_handles_all_top_level_requests
;
4009 if (browser_handles_request
) {
4010 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4011 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4015 // Use the frame's original request's URL rather than the document's URL for
4016 // subsequent checks. For a popup, the document's URL may become the opener
4017 // window's URL if the opener has called document.write().
4018 // See http://crbug.com/93517.
4019 GURL
old_url(info
.frame
->dataSource()->request().url());
4021 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4022 // an extension or app origin, leaving a WebUI page, etc). We only care about
4023 // top-level navigations (not iframes). But we sometimes navigate to
4024 // about:blank to clear a tab, and we want to still allow that.
4026 // Note: this is known to break POST submissions when crossing process
4027 // boundaries until http://crbug.com/101395 is fixed. This is better for
4028 // security than loading a WebUI, extension or app page in the wrong process.
4029 // POST requests don't work because this mechanism does not preserve form
4030 // POST data. We will need to send the request's httpBody data up to the
4031 // browser process, and issue a special POST navigation in WebKit (via
4032 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4033 // for examples of how to send the httpBody data.
4034 if (!info
.frame
->parent() && is_content_initiated
&&
4035 !url
.SchemeIs(url::kAboutScheme
)) {
4036 bool send_referrer
= false;
4038 // All navigations to or from WebUI URLs or within WebUI-enabled
4039 // RenderProcesses must be handled by the browser process so that the
4040 // correct bindings and data sources can be registered.
4041 // Similarly, navigations to view-source URLs or within ViewSource mode
4042 // must be handled by the browser process (except for reloads - those are
4043 // safe to leave within the renderer).
4044 // Lastly, access to file:// URLs from non-file:// URL pages must be
4045 // handled by the browser so that ordinary renderer processes don't get
4046 // blessed with file permissions.
4047 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4048 bool is_initial_navigation
= render_view_
->page_id_
== -1;
4049 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4050 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4051 url
.SchemeIs(kViewSourceScheme
) ||
4052 (info
.frame
->isViewSourceModeEnabled() &&
4053 info
.navigationType
!= blink::WebNavigationTypeReload
);
4055 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4056 // Fork non-file to file opens. Check the opener URL if this is the
4057 // initial navigation in a newly opened window.
4058 GURL
source_url(old_url
);
4059 if (is_initial_navigation
&& source_url
.is_empty() &&
4060 info
.frame
->opener())
4061 source_url
= info
.frame
->opener()->top()->document().url();
4062 DCHECK(!source_url
.is_empty());
4063 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4067 // Give the embedder a chance.
4068 should_fork
= GetContentClient()->renderer()->ShouldFork(
4069 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4070 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4074 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4075 info
.defaultPolicy
);
4076 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4080 // Detect when a page is "forking" a new tab that can be safely rendered in
4081 // its own process. This is done by sites like Gmail that try to open links
4082 // in new windows without script connections back to the original page. We
4083 // treat such cases as browser navigations (in which we will create a new
4084 // renderer for a cross-site navigation), rather than WebKit navigations.
4086 // We use the following heuristic to decide whether to fork a new page in its
4088 // The parent page must open a new tab to about:blank, set the new tab's
4089 // window.opener to null, and then redirect the tab to a cross-site URL using
4092 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4095 // Must start from a tab showing about:blank, which is later redirected.
4096 old_url
== GURL(url::kAboutBlankURL
) &&
4097 // Must be the first real navigation of the tab.
4098 render_view_
->historyBackListCount() < 1 &&
4099 render_view_
->historyForwardListCount() < 1 &&
4100 // The parent page must have set the child's window.opener to null before
4101 // redirecting to the desired URL.
4102 info
.frame
->opener() == NULL
&&
4103 // Must be a top-level frame.
4104 info
.frame
->parent() == NULL
&&
4105 // Must not have issued the request from this page.
4106 is_content_initiated
&&
4107 // Must be targeted at the current tab.
4108 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4109 // Must be a JavaScript navigation, which appears as "other".
4110 info
.navigationType
== blink::WebNavigationTypeOther
;
4113 // Open the URL via the browser, not via WebKit.
4114 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4115 return blink::WebNavigationPolicyIgnore
;
4118 // PlzNavigate: send the request to the browser if needed.
4119 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4120 switches::kEnableBrowserSideNavigation
) &&
4121 info
.urlRequest
.checkForBrowserSideNavigation()) {
4122 BeginNavigation(&info
.urlRequest
);
4123 return blink::WebNavigationPolicyIgnore
;
4126 return info
.defaultPolicy
;
4129 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4131 const Referrer
& referrer
,
4132 WebNavigationPolicy policy
) {
4133 DCHECK_EQ(frame_
, frame
);
4135 FrameHostMsg_OpenURL_Params params
;
4137 params
.referrer
= referrer
;
4138 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4139 WebDataSource
* ds
= frame
->provisionalDataSource();
4141 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4142 NavigationState
* navigation_state
= document_state
->navigation_state();
4143 if (navigation_state
->is_content_initiated()) {
4144 params
.should_replace_current_entry
= ds
->replacesCurrentHistoryItem();
4146 // This is necessary to preserve the should_replace_current_entry value on
4147 // cross-process redirects, in the event it was set by a previous process.
4149 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4150 // NavigationState::should_replace_current_entry().
4151 params
.should_replace_current_entry
=
4152 navigation_state
->should_replace_current_entry();
4155 params
.should_replace_current_entry
= false;
4157 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4158 if (GetContentClient()->renderer()->AllowPopup())
4159 params
.user_gesture
= true;
4161 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4162 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4163 policy
== blink::WebNavigationPolicyNewWindow
||
4164 policy
== blink::WebNavigationPolicyNewPopup
) {
4165 WebUserGestureIndicator::consumeUserGesture();
4168 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4171 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4172 const std::string
& encoding_name
) {
4173 // Only update main frame's encoding_name.
4174 if (!frame
->parent())
4175 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4178 void RenderFrameImpl::SyncSelectionIfRequired() {
4179 base::string16 text
;
4182 #if defined(ENABLE_PLUGINS)
4183 if (render_view_
->focused_pepper_plugin_
) {
4184 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4185 offset
= 0; // Pepper API does not support offset reporting.
4186 // TODO(kinaba): cut as needed.
4190 size_t location
, length
;
4191 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4192 &location
, &length
)) {
4196 range
= gfx::Range(location
, location
+ length
);
4198 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4199 blink::WebTextInputTypeNone
) {
4200 // If current focused element is editable, we will send 100 more chars
4201 // before and after selection. It is for input method surrounding text
4203 if (location
> kExtraCharsBeforeAndAfterSelection
)
4204 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4207 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4208 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4209 if (!webrange
.isNull())
4210 text
= webrange
.toPlainText();
4213 text
= frame_
->selectionAsText();
4214 // http://crbug.com/101435
4215 // In some case, frame->selectionAsText() returned text's length is not
4216 // equal to the length returned from webwidget()->caretOrSelectionRange().
4217 // So we have to set the range according to text.length().
4218 range
.set_end(range
.start() + text
.length());
4222 // Sometimes we get repeated didChangeSelection calls from webkit when
4223 // the selection hasn't actually changed. We don't want to report these
4224 // because it will cause us to continually claim the X clipboard.
4225 if (selection_text_offset_
!= offset
||
4226 selection_range_
!= range
||
4227 selection_text_
!= text
) {
4228 selection_text_
= text
;
4229 selection_text_offset_
= offset
;
4230 selection_range_
= range
;
4231 SetSelectedText(text
, offset
, range
);
4233 GetRenderWidget()->UpdateSelectionBounds();
4236 void RenderFrameImpl::InitializeUserMediaClient() {
4237 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4240 #if defined(OS_ANDROID)
4241 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4242 switches::kDisableWebRTC
))
4246 #if defined(ENABLE_WEBRTC)
4247 DCHECK(!web_user_media_client_
);
4248 web_user_media_client_
= new UserMediaClientImpl(
4250 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4251 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4255 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4256 const blink::WebURL
& url
,
4257 WebMediaPlayerClient
* client
) {
4258 #if defined(ENABLE_WEBRTC)
4259 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4261 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4262 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4263 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4264 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4265 new RenderMediaLog(),
4266 CreateRendererFactory());
4269 #endif // defined(ENABLE_WEBRTC)
4272 scoped_ptr
<MediaStreamRendererFactory
>
4273 RenderFrameImpl::CreateRendererFactory() {
4274 #if defined(ENABLE_WEBRTC)
4275 return scoped_ptr
<MediaStreamRendererFactory
>(
4276 new MediaStreamRendererFactory());
4278 return scoped_ptr
<MediaStreamRendererFactory
>(
4279 static_cast<MediaStreamRendererFactory
*>(NULL
));
4283 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4285 bool check_for_stale_navigation
,
4286 bool is_history_navigation
,
4287 int current_history_list_offset
,
4289 WebURLRequest::CachePolicy
* cache_policy
) {
4290 MaybeHandleDebugURL(url
);
4291 if (!render_view_
->webview())
4295 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4297 // If this is a stale back/forward (due to a recent navigation the browser
4298 // didn't know about), ignore it. Only check if swapped in because if the
4299 // frame is swapped out, it won't commit before asking the browser.
4300 // TODO(clamy): remove check_for_stale_navigation
4301 if (check_for_stale_navigation
&&
4302 !render_view_
->is_swapped_out() && is_history_navigation
&&
4303 render_view_
->history_list_offset_
!= current_history_list_offset
) {
4307 if (!is_swapped_out_
|| frame_
->parent())
4310 // This is a swapped out main frame, so swap the renderer back in.
4311 // We marked the view as hidden when swapping the view out, so be sure to
4312 // reset the visibility state before navigating to the new URL.
4313 render_view_
->webview()->setVisibilityState(
4314 render_view_
->visibilityState(), false);
4316 // If this is an attempt to reload while we are swapped out, we should not
4317 // reload swappedout://, but the previous page, which is stored in
4318 // params.state. Setting is_reload to false will treat this like a back
4319 // navigation to accomplish that.
4321 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4323 // We refresh timezone when a view is swapped in since timezone
4324 // can get out of sync when the system timezone is updated while
4325 // the view is swapped out.
4326 RenderThreadImpl::NotifyTimezoneChange();
4328 render_view_
->SetSwappedOut(false);
4329 is_swapped_out_
= false;
4333 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4334 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4335 switches::kEnableBrowserSideNavigation
));
4337 // TODO(clamy): Execute the beforeunload event.
4339 // Note: At this stage, the goal is to apply all the modifications the
4340 // renderer wants to make to the request, and then send it to the browser, so
4341 // that the actual network request can be started. Ideally, all such
4342 // modifications should take place in willSendRequest, and in the
4343 // implementation of willSendRequest for the various InspectorAgents
4346 // TODO(clamy): Apply devtools override.
4347 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4349 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4351 // TODO(clamy): Same-document navigations should not be sent back to the
4353 // TODO(clamy): Data urls should not be sent back to the browser either.
4354 Send(new FrameHostMsg_BeginNavigation(routing_id_
,
4355 MakeBeginNavigationParams(request
),
4356 MakeCommonNavigationParams(request
)));
4359 GURL
RenderFrameImpl::GetLoadingUrl() const {
4360 WebDataSource
* ds
= frame_
->dataSource();
4361 if (ds
->hasUnreachableURL())
4362 return ds
->unreachableURL();
4364 const WebURLRequest
& request
= ds
->request();
4365 return request
.url();
4368 #if defined(OS_ANDROID)
4370 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4371 const blink::WebURL
& url
,
4372 WebMediaPlayerClient
* client
,
4373 blink::WebContentDecryptionModule
* initial_cdm
) {
4374 GpuChannelHost
* gpu_channel_host
=
4375 RenderThreadImpl::current()->EstablishGpuChannelSync(
4376 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4377 if (!gpu_channel_host
) {
4378 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4382 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4383 if (SynchronousCompositorFactory
* factory
=
4384 SynchronousCompositorFactory::GetInstance()) {
4385 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4387 scoped_refptr
<webkit::gpu::ContextProviderWebContext
> context_provider
=
4388 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4390 if (!context_provider
.get()) {
4391 LOG(ERROR
) << "Failed to get context3d for media player";
4395 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4396 context_provider
, gpu_channel_host
, routing_id_
);
4399 return new WebMediaPlayerAndroid(
4402 weak_factory_
.GetWeakPtr(),
4403 GetMediaPlayerManager(),
4406 stream_texture_factory
,
4407 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4408 new RenderMediaLog());
4411 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4412 if (!media_player_manager_
)
4413 media_player_manager_
= new RendererMediaPlayerManager(this);
4414 return media_player_manager_
;
4417 #endif // defined(OS_ANDROID)
4419 #if defined(ENABLE_BROWSER_CDMS)
4420 RendererCdmManager
* RenderFrameImpl::GetCdmManager() {
4422 cdm_manager_
= new RendererCdmManager(this);
4423 return cdm_manager_
;
4425 #endif // defined(ENABLE_BROWSER_CDMS)
4427 } // namespace content