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 "cc/base/switches.h"
23 #include "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/plugin_messages.h"
25 #include "content/child/quota_dispatcher.h"
26 #include "content/child/request_extra_data.h"
27 #include "content/child/service_worker/service_worker_handle_reference.h"
28 #include "content/child/service_worker/service_worker_network_provider.h"
29 #include "content/child/service_worker/service_worker_provider_context.h"
30 #include "content/child/service_worker/web_service_worker_provider_impl.h"
31 #include "content/child/v8_value_converter_impl.h"
32 #include "content/child/web_url_loader_impl.h"
33 #include "content/child/web_url_request_util.h"
34 #include "content/child/webmessageportchannel_impl.h"
35 #include "content/child/websocket_bridge.h"
36 #include "content/child/weburlresponse_extradata_impl.h"
37 #include "content/common/clipboard_messages.h"
38 #include "content/common/frame_messages.h"
39 #include "content/common/frame_replication_state.h"
40 #include "content/common/input_messages.h"
41 #include "content/common/service_worker/service_worker_types.h"
42 #include "content/common/swapped_out_messages.h"
43 #include "content/common/view_messages.h"
44 #include "content/public/common/bindings_policy.h"
45 #include "content/public/common/content_constants.h"
46 #include "content/public/common/content_switches.h"
47 #include "content/public/common/context_menu_params.h"
48 #include "content/public/common/page_state.h"
49 #include "content/public/common/resource_response.h"
50 #include "content/public/common/url_constants.h"
51 #include "content/public/common/url_utils.h"
52 #include "content/public/renderer/browser_plugin_delegate.h"
53 #include "content/public/renderer/content_renderer_client.h"
54 #include "content/public/renderer/context_menu_client.h"
55 #include "content/public/renderer/document_state.h"
56 #include "content/public/renderer/navigation_state.h"
57 #include "content/public/renderer/render_frame_observer.h"
58 #include "content/public/renderer/renderer_ppapi_host.h"
59 #include "content/renderer/accessibility/renderer_accessibility.h"
60 #include "content/renderer/browser_plugin/browser_plugin.h"
61 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
62 #include "content/renderer/child_frame_compositing_helper.h"
63 #include "content/renderer/context_menu_params_builder.h"
64 #include "content/renderer/devtools/devtools_agent.h"
65 #include "content/renderer/dom_automation_controller.h"
66 #include "content/renderer/dom_utils.h"
67 #include "content/renderer/external_popup_menu.h"
68 #include "content/renderer/geolocation_dispatcher.h"
69 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
70 #include "content/renderer/history_controller.h"
71 #include "content/renderer/history_serialization.h"
72 #include "content/renderer/image_loading_helper.h"
73 #include "content/renderer/ime_event_guard.h"
74 #include "content/renderer/internal_document_state_data.h"
75 #include "content/renderer/manifest/manifest_manager.h"
76 #include "content/renderer/media/audio_renderer_mixer_manager.h"
77 #include "content/renderer/media/crypto/render_cdm_factory.h"
78 #include "content/renderer/media/media_permission_dispatcher.h"
79 #include "content/renderer/media/media_stream_dispatcher.h"
80 #include "content/renderer/media/media_stream_renderer_factory.h"
81 #include "content/renderer/media/midi_dispatcher.h"
82 #include "content/renderer/media/render_media_log.h"
83 #include "content/renderer/media/user_media_client_impl.h"
84 #include "content/renderer/media/webmediaplayer_ms.h"
85 #include "content/renderer/memory_benchmarking_extension.h"
86 #include "content/renderer/mojo/service_registry_js_wrapper.h"
87 #include "content/renderer/notification_permission_dispatcher.h"
88 #include "content/renderer/npapi/plugin_channel_host.h"
89 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
90 #include "content/renderer/presentation/presentation_dispatcher.h"
91 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
92 #include "content/renderer/render_frame_proxy.h"
93 #include "content/renderer/render_process.h"
94 #include "content/renderer/render_thread_impl.h"
95 #include "content/renderer/render_view_impl.h"
96 #include "content/renderer/render_widget_fullscreen_pepper.h"
97 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
98 #include "content/renderer/renderer_webcolorchooser_impl.h"
99 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
100 #include "content/renderer/shared_worker_repository.h"
101 #include "content/renderer/skia_benchmarking_extension.h"
102 #include "content/renderer/stats_collection_controller.h"
103 #include "content/renderer/web_ui_extension.h"
104 #include "content/renderer/websharedworker_proxy.h"
105 #include "gin/modules/module_registry.h"
106 #include "media/base/audio_renderer_mixer_input.h"
107 #include "media/base/media_log.h"
108 #include "media/blink/webencryptedmediaclient_impl.h"
109 #include "media/blink/webmediaplayer_impl.h"
110 #include "media/blink/webmediaplayer_params.h"
111 #include "media/renderers/gpu_video_accelerator_factories.h"
112 #include "net/base/data_url.h"
113 #include "net/base/net_errors.h"
114 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
115 #include "net/http/http_util.h"
116 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
117 #include "third_party/WebKit/public/platform/WebString.h"
118 #include "third_party/WebKit/public/platform/WebURL.h"
119 #include "third_party/WebKit/public/platform/WebURLError.h"
120 #include "third_party/WebKit/public/platform/WebURLResponse.h"
121 #include "third_party/WebKit/public/platform/WebVector.h"
122 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
123 #include "third_party/WebKit/public/web/WebDocument.h"
124 #include "third_party/WebKit/public/web/WebFrameWidget.h"
125 #include "third_party/WebKit/public/web/WebGlyphCache.h"
126 #include "third_party/WebKit/public/web/WebLocalFrame.h"
127 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
128 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
129 #include "third_party/WebKit/public/web/WebPlugin.h"
130 #include "third_party/WebKit/public/web/WebPluginParams.h"
131 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
132 #include "third_party/WebKit/public/web/WebRange.h"
133 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
134 #include "third_party/WebKit/public/web/WebScriptSource.h"
135 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
136 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
137 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
138 #include "third_party/WebKit/public/web/WebSurroundingText.h"
139 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
140 #include "third_party/WebKit/public/web/WebView.h"
141 #include "third_party/mojo/src/mojo/edk/js/core.h"
142 #include "third_party/mojo/src/mojo/edk/js/support.h"
144 #if defined(ENABLE_PLUGINS)
145 #include "content/renderer/npapi/webplugin_impl.h"
146 #include "content/renderer/pepper/pepper_browser_connection.h"
147 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
148 #include "content/renderer/pepper/pepper_webplugin_impl.h"
149 #include "content/renderer/pepper/plugin_module.h"
152 #if defined(ENABLE_WEBRTC)
153 #include "content/renderer/media/rtc_peer_connection_handler.h"
156 #if defined(OS_ANDROID)
157 #include <cpu-features.h>
159 #include "content/common/gpu/client/context_provider_command_buffer.h"
160 #include "content/renderer/android/synchronous_compositor_factory.h"
161 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
162 #include "content/renderer/media/android/renderer_media_player_manager.h"
163 #include "content/renderer/media/android/stream_texture_factory_impl.h"
164 #include "content/renderer/media/android/webmediaplayer_android.h"
166 #include "cc/blink/context_provider_web_context.h"
169 #if defined(ENABLE_PEPPER_CDMS)
170 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
171 #elif defined(ENABLE_BROWSER_CDMS)
172 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
175 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
176 #include "content/renderer/media/media_renderer_service_provider.h"
177 #include "media/mojo/services/mojo_renderer_factory.h"
179 #include "media/renderers/default_renderer_factory.h"
182 using blink::WebContextMenuData
;
183 using blink::WebData
;
184 using blink::WebDataSource
;
185 using blink::WebDocument
;
186 using blink::WebElement
;
187 using blink::WebExternalPopupMenu
;
188 using blink::WebExternalPopupMenuClient
;
189 using blink::WebFrame
;
190 using blink::WebHistoryItem
;
191 using blink::WebHTTPBody
;
192 using blink::WebLocalFrame
;
193 using blink::WebMediaPlayer
;
194 using blink::WebMediaPlayerClient
;
195 using blink::WebNavigationPolicy
;
196 using blink::WebNavigationType
;
197 using blink::WebNode
;
198 using blink::WebPluginParams
;
199 using blink::WebPopupMenuInfo
;
200 using blink::WebRange
;
201 using blink::WebReferrerPolicy
;
202 using blink::WebScriptSource
;
203 using blink::WebSearchableFormData
;
204 using blink::WebSecurityOrigin
;
205 using blink::WebSecurityPolicy
;
206 using blink::WebServiceWorkerProvider
;
207 using blink::WebStorageQuotaCallbacks
;
208 using blink::WebString
;
210 using blink::WebURLError
;
211 using blink::WebURLRequest
;
212 using blink::WebURLResponse
;
213 using blink::WebUserGestureIndicator
;
214 using blink::WebVector
;
215 using blink::WebView
;
217 using base::TimeDelta
;
223 const char kDefaultAcceptHeader
[] =
224 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
226 const char kAcceptHeader
[] = "Accept";
228 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
230 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
231 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
232 LAZY_INSTANCE_INITIALIZER
;
234 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
235 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
237 int64
ExtractPostId(HistoryEntry
* entry
) {
241 const WebHistoryItem
& item
= entry
->root();
242 if (item
.isNull() || item
.httpBody().isNull())
245 return item
.httpBody().identifier();
248 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
249 const WebURLResponse
& response
) {
250 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
253 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
254 // Replace any occurrences of swappedout:// with about:blank.
255 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
256 WebVector
<WebURL
> urls
;
257 ds
->redirectChain(urls
);
258 result
->reserve(urls
.size());
259 for (size_t i
= 0; i
< urls
.size(); ++i
) {
260 if (urls
[i
] != GURL(kSwappedOutURL
))
261 result
->push_back(urls
[i
]);
263 result
->push_back(blank_url
);
267 // Returns the original request url. If there is no redirect, the original
268 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
269 // frame was loaded by loadData, the original url will be ds->unreachableURL()
270 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
271 // WebDataSource has unreachable URL means that the frame is loaded through
272 // blink::WebFrame::loadData(), and the base URL will be in the redirect
273 // chain. However, we never visited the baseURL. So in this case, we should
274 // use the unreachable URL as the original URL.
275 if (ds
->hasUnreachableURL())
276 return ds
->unreachableURL();
278 std::vector
<GURL
> redirects
;
279 GetRedirectChain(ds
, &redirects
);
280 if (!redirects
.empty())
281 return redirects
.at(0);
283 return ds
->originalRequest().url();
286 NOINLINE
void CrashIntentionally() {
287 // NOTE(shess): Crash directly rather than using NOTREACHED() so
288 // that the signature is easier to triage in crash reports.
289 volatile int* zero
= NULL
;
293 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
294 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
295 // NOTE(rogerm): We intentionally perform an invalid heap access here in
296 // order to trigger an Address Sanitizer (ASAN) error report.
297 const char kCrashDomain
[] = "crash";
298 const char kHeapOverflow
[] = "/heap-overflow";
299 const char kHeapUnderflow
[] = "/heap-underflow";
300 const char kUseAfterFree
[] = "/use-after-free";
301 #if defined(SYZYASAN)
302 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
303 const char kCorruptHeap
[] = "/corrupt-heap";
306 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
312 std::string
crash_type(url
.path());
313 if (crash_type
== kHeapOverflow
) {
314 base::debug::AsanHeapOverflow();
315 } else if (crash_type
== kHeapUnderflow
) {
316 base::debug::AsanHeapUnderflow();
317 } else if (crash_type
== kUseAfterFree
) {
318 base::debug::AsanHeapUseAfterFree();
319 #if defined(SYZYASAN)
320 } else if (crash_type
== kCorruptHeapBlock
) {
321 base::debug::AsanCorruptHeapBlock();
322 } else if (crash_type
== kCorruptHeap
) {
323 base::debug::AsanCorruptHeap();
327 #endif // ADDRESS_SANITIZER || SYZYASAN
329 void MaybeHandleDebugURL(const GURL
& url
) {
330 if (!url
.SchemeIs(kChromeUIScheme
))
332 if (url
== GURL(kChromeUICrashURL
)) {
333 CrashIntentionally();
334 } else if (url
== GURL(kChromeUIDumpURL
)) {
335 // This URL will only correctly create a crash dump file if content is
336 // hosted in a process that has correctly called
337 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
338 // of base::debug::DumpWithoutCrashing for more details.
339 base::debug::DumpWithoutCrashing();
340 } else if (url
== GURL(kChromeUIKillURL
)) {
341 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
342 } else if (url
== GURL(kChromeUIHangURL
)) {
344 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
346 } else if (url
== GURL(kChromeUIShorthangURL
)) {
347 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
350 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
351 MaybeTriggerAsanError(url
);
352 #endif // ADDRESS_SANITIZER || SYZYASAN
355 // Returns false unless this is a top-level navigation.
356 bool IsTopLevelNavigation(WebFrame
* frame
) {
357 return frame
->parent() == NULL
;
360 // Returns false unless this is a top-level navigation that crosses origins.
361 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
363 WebNavigationType type
,
365 if (!IsTopLevelNavigation(frame
))
368 // Navigations initiated within Webkit are not sent out to the external host
369 // in the following cases.
370 // 1. The url scheme is not http/https
371 // 2. The origin of the url and the opener is the same in which case the
372 // opener relationship is maintained.
373 // 3. Reloads/form submits/back forward navigations
374 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
377 if (type
!= blink::WebNavigationTypeReload
&&
378 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
379 // The opener relationship between the new window and the parent allows the
380 // new window to script the parent and vice versa. This is not allowed if
381 // the origins of the two domains are different. This can be treated as a
382 // top level navigation and routed back to the host.
383 blink::WebFrame
* opener
= frame
->opener();
387 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
393 WebURLRequest
CreateURLRequestForNavigation(
394 const CommonNavigationParams
& common_params
,
395 scoped_ptr
<StreamOverrideParameters
> stream_override
,
396 bool is_view_source_mode_enabled
) {
397 WebURLRequest
request(common_params
.url
);
398 if (is_view_source_mode_enabled
)
399 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
401 if (common_params
.referrer
.url
.is_valid()) {
402 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
403 common_params
.referrer
.policy
,
405 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
406 if (!web_referrer
.isEmpty())
407 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
410 RequestExtraData
* extra_data
= new RequestExtraData();
411 extra_data
->set_stream_override(stream_override
.Pass());
412 request
.setExtraData(extra_data
);
414 // Set the ui timestamp for this navigation. Currently the timestamp here is
415 // only non empty when the navigation was triggered by an Android intent. The
416 // timestamp is converted to a double version supported by blink. It will be
417 // passed back to the browser in the DidCommitProvisionalLoad and the
418 // DocumentLoadComplete IPCs.
419 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
420 request
.setUiStartTime(ui_timestamp
.InSecondsF());
421 request
.setInputPerfMetricReportPolicy(
422 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
423 common_params
.report_type
));
427 void UpdateFrameNavigationTiming(WebFrame
* frame
,
428 base::TimeTicks browser_navigation_start
,
429 base::TimeTicks renderer_navigation_start
) {
430 // The browser provides the navigation_start time to bootstrap the
431 // Navigation Timing information for the browser-initiated navigations. In
432 // case of cross-process navigations, this carries over the time of
433 // finishing the onbeforeunload handler of the previous page.
434 DCHECK(!browser_navigation_start
.is_null());
435 if (frame
->provisionalDataSource()) {
436 // |browser_navigation_start| is likely before this process existed, so we
437 // can't use InterProcessTimeTicksConverter. We need at least to ensure
438 // that the browser-side navigation start we set is not later than the one
439 // on the renderer side.
440 base::TimeTicks navigation_start
= std::min(
441 browser_navigation_start
, renderer_navigation_start
);
442 double navigation_start_seconds
=
443 (navigation_start
- base::TimeTicks()).InSecondsF();
444 frame
->provisionalDataSource()->setNavigationStartTime(
445 navigation_start_seconds
);
446 // TODO(clamy): We need to provide additional timing values for the
447 // Navigation Timing API to work with browser-side navigations.
452 CommonNavigationParams
MakeCommonNavigationParams(
453 blink::WebURLRequest
* request
) {
454 const RequestExtraData kEmptyData
;
455 const RequestExtraData
* extra_data
=
456 static_cast<RequestExtraData
*>(request
->extraData());
458 extra_data
= &kEmptyData
;
459 CommonNavigationParams params
;
460 params
.url
= request
->url();
461 params
.referrer
= Referrer(
462 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
463 request
->referrerPolicy());
464 params
.transition
= extra_data
->transition_type();
466 // Set the ui timestamp for this navigation. Currently the timestamp here is
467 // only non empty when the navigation was triggered by an Android intent, or
468 // by the user clicking on a link. The timestamp is converted from a double
469 // version supported by blink. It will be passed back to the renderer in the
470 // CommitNavigation IPC, and then back to the browser again in the
471 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
472 params
.ui_timestamp
=
473 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
474 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
475 request
->inputPerfMetricReportPolicy());
479 #if !defined(OS_ANDROID)
480 media::Context3D
GetSharedMainThreadContext3D() {
481 cc::ContextProvider
* provider
=
482 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
484 return media::Context3D();
485 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
489 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
492 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
494 static_cast<int>(content_name) == static_cast<int>(blink_name), \
495 "enum values must match")
497 // Check that blink::WebSandboxFlags is kept in sync with
498 // content::SandboxFlags.
499 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE
,
500 blink::WebSandboxFlags::None
);
501 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION
,
502 blink::WebSandboxFlags::Navigation
);
503 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS
,
504 blink::WebSandboxFlags::Plugins
);
505 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN
,
506 blink::WebSandboxFlags::Origin
);
507 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS
,
508 blink::WebSandboxFlags::Forms
);
509 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS
,
510 blink::WebSandboxFlags::Scripts
);
511 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION
,
512 blink::WebSandboxFlags::TopNavigation
);
513 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS
,
514 blink::WebSandboxFlags::Popups
);
515 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES
,
516 blink::WebSandboxFlags::AutomaticFeatures
);
517 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK
,
518 blink::WebSandboxFlags::PointerLock
);
519 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN
,
520 blink::WebSandboxFlags::DocumentDomain
);
521 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK
,
522 blink::WebSandboxFlags::OrientationLock
);
523 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL
,
524 blink::WebSandboxFlags::All
);
529 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
531 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
533 if (g_create_render_frame_impl
)
534 return g_create_render_frame_impl(render_view
, routing_id
);
536 return new RenderFrameImpl(render_view
, routing_id
);
540 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int32 routing_id
) {
541 RoutingIDFrameMap::iterator iter
=
542 g_routing_id_frame_map
.Get().find(routing_id
);
543 if (iter
!= g_routing_id_frame_map
.Get().end())
549 void RenderFrameImpl::CreateFrame(
551 int parent_routing_id
,
552 int proxy_routing_id
,
553 const FrameReplicationState
& replicated_state
,
554 CompositorDependencies
* compositor_deps
,
555 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
556 // TODO(nasko): For now, this message is only sent for subframes, as the
557 // top level frame is created when the RenderView is created through the
559 CHECK_NE(MSG_ROUTING_NONE
, parent_routing_id
);
561 blink::WebLocalFrame
* web_frame
;
562 RenderFrameImpl
* render_frame
;
563 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
564 RenderFrameProxy
* parent_proxy
=
565 RenderFrameProxy::FromRoutingID(parent_routing_id
);
566 // If the browser is sending a valid parent routing id, it should already
567 // be created and registered.
569 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
571 // Create the RenderFrame and WebLocalFrame, linking the two.
573 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
574 web_frame
= parent_web_frame
->createLocalChild(
575 WebString::fromUTF8(replicated_state
.name
),
576 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
), render_frame
);
578 RenderFrameProxy
* proxy
=
579 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
581 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
582 web_frame
= blink::WebLocalFrame::create(render_frame
);
583 render_frame
->proxy_routing_id_
= proxy_routing_id
;
584 web_frame
->initializeToReplaceRemoteFrame(
585 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
586 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
));
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 media_permission_dispatcher_(NULL
),
657 midi_dispatcher_(NULL
),
658 #if defined(OS_ANDROID)
659 media_player_manager_(NULL
),
661 #if defined(ENABLE_BROWSER_CDMS)
664 #if defined(VIDEO_HOLE)
665 contains_media_player_(false),
667 geolocation_dispatcher_(NULL
),
668 push_messaging_dispatcher_(NULL
),
669 presentation_dispatcher_(NULL
),
670 screen_orientation_dispatcher_(NULL
),
671 manifest_manager_(NULL
),
672 accessibility_mode_(AccessibilityModeOff
),
673 renderer_accessibility_(NULL
),
674 weak_factory_(this) {
675 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
676 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
677 CHECK(result
.second
) << "Inserting a duplicate item.";
679 RenderThread::Get()->AddRoute(routing_id_
, this);
681 render_view_
->RegisterRenderFrame(this);
683 // Everything below subclasses RenderFrameObserver and is automatically
684 // deleted when the RenderFrame gets deleted.
685 #if defined(OS_ANDROID)
686 new GinJavaBridgeDispatcher(this);
689 #if defined(ENABLE_PLUGINS)
690 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
693 manifest_manager_
= new ManifestManager(this);
696 RenderFrameImpl::~RenderFrameImpl() {
697 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
698 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
700 #if defined(VIDEO_HOLE)
701 if (contains_media_player_
)
702 render_view_
->UnregisterVideoHoleFrame(this);
705 if (render_frame_proxy_
)
706 delete render_frame_proxy_
;
708 render_view_
->UnregisterRenderFrame(this);
709 g_routing_id_frame_map
.Get().erase(routing_id_
);
710 RenderThread::Get()->RemoveRoute(routing_id_
);
713 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
716 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
717 std::make_pair(web_frame
, this));
718 CHECK(result
.second
) << "Inserting a duplicate item.";
723 void RenderFrameImpl::Initialize() {
724 #if defined(ENABLE_PLUGINS)
725 new PepperBrowserConnection(this);
727 new SharedWorkerRepository(this);
729 if (!frame_
->parent())
730 new ImageLoadingHelper(this);
732 // We delay calling this until we have the WebFrame so that any observer or
733 // embedder can call GetWebFrame on any RenderFrame.
734 GetContentClient()->renderer()->RenderFrameCreated(this);
737 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
738 return render_view_
.get();
741 #if defined(ENABLE_PLUGINS)
742 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
743 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
744 DidCreatePepperPlugin(host
));
745 if (host
->GetPluginName() == kFlashPluginName
) {
746 RenderThread::Get()->RecordAction(
747 base::UserMetricsAction("FrameLoadWithFlash"));
751 void RenderFrameImpl::PepperDidChangeCursor(
752 PepperPluginInstanceImpl
* instance
,
753 const blink::WebCursorInfo
& cursor
) {
754 // Update the cursor appearance immediately if the requesting plugin is the
755 // one which receives the last mouse event. Otherwise, the new cursor won't be
756 // picked up until the plugin gets the next input event. That is bad if, e.g.,
757 // the plugin would like to set an invisible cursor when there isn't any user
758 // input for a while.
759 if (instance
== render_view_
->pepper_last_mouse_event_target())
760 GetRenderWidget()->didChangeCursor(cursor
);
763 void RenderFrameImpl::PepperDidReceiveMouseEvent(
764 PepperPluginInstanceImpl
* instance
) {
765 render_view_
->set_pepper_last_mouse_event_target(instance
);
768 void RenderFrameImpl::PepperTextInputTypeChanged(
769 PepperPluginInstanceImpl
* instance
) {
770 if (instance
!= render_view_
->focused_pepper_plugin())
773 GetRenderWidget()->UpdateTextInputType();
775 FocusedNodeChangedForAccessibility(WebNode());
778 void RenderFrameImpl::PepperCaretPositionChanged(
779 PepperPluginInstanceImpl
* instance
) {
780 if (instance
!= render_view_
->focused_pepper_plugin())
782 GetRenderWidget()->UpdateSelectionBounds();
785 void RenderFrameImpl::PepperCancelComposition(
786 PepperPluginInstanceImpl
* instance
) {
787 if (instance
!= render_view_
->focused_pepper_plugin())
789 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
790 #if defined(OS_MACOSX) || defined(USE_AURA)
791 GetRenderWidget()->UpdateCompositionInfo(true);
795 void RenderFrameImpl::PepperSelectionChanged(
796 PepperPluginInstanceImpl
* instance
) {
797 if (instance
!= render_view_
->focused_pepper_plugin())
799 SyncSelectionIfRequired();
802 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
803 PepperPluginInstanceImpl
* plugin
) {
805 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
806 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
807 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
808 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
809 plugin
, active_url
, GetRenderWidget()->screenInfo());
810 widget
->show(blink::WebNavigationPolicyIgnore
);
814 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
815 if (!render_view_
->focused_pepper_plugin())
817 return render_view_
->focused_pepper_plugin()->
818 IsPluginAcceptingCompositionEvents();
821 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
822 base::ProcessId plugin_pid
) {
823 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
824 // routing_id_ as a result.
825 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
828 void RenderFrameImpl::SimulateImeSetComposition(
829 const base::string16
& text
,
830 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
833 render_view_
->OnImeSetComposition(
834 text
, underlines
, selection_start
, selection_end
);
837 void RenderFrameImpl::SimulateImeConfirmComposition(
838 const base::string16
& text
,
839 const gfx::Range
& replacement_range
) {
840 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
843 void RenderFrameImpl::OnImeSetComposition(
844 const base::string16
& text
,
845 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
848 // When a PPAPI plugin has focus, we bypass WebKit.
849 if (!IsPepperAcceptingCompositionEvents()) {
850 pepper_composition_text_
= text
;
852 // TODO(kinaba) currently all composition events are sent directly to
853 // plugins. Use DOM event mechanism after WebKit is made aware about
854 // plugins that support composition.
855 // The code below mimics the behavior of WebCore::Editor::setComposition.
857 // Empty -> nonempty: composition started.
858 if (pepper_composition_text_
.empty() && !text
.empty()) {
859 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
862 // Nonempty -> empty: composition canceled.
863 if (!pepper_composition_text_
.empty() && text
.empty()) {
864 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
867 pepper_composition_text_
= text
;
868 // Nonempty: composition is ongoing.
869 if (!pepper_composition_text_
.empty()) {
870 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
871 pepper_composition_text_
, underlines
, selection_start
,
877 void RenderFrameImpl::OnImeConfirmComposition(
878 const base::string16
& text
,
879 const gfx::Range
& replacement_range
,
880 bool keep_selection
) {
881 // When a PPAPI plugin has focus, we bypass WebKit.
882 // Here, text.empty() has a special meaning. It means to commit the last
883 // update of composition text (see
884 // RenderWidgetHost::ImeConfirmComposition()).
885 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
888 // last_text is empty only when both text and pepper_composition_text_ is.
890 if (last_text
.empty())
893 if (!IsPepperAcceptingCompositionEvents()) {
894 base::i18n::UTF16CharIterator
iterator(&last_text
);
896 while (iterator
.Advance()) {
897 blink::WebKeyboardEvent char_event
;
898 char_event
.type
= blink::WebInputEvent::Char
;
899 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
900 char_event
.modifiers
= 0;
901 char_event
.windowsKeyCode
= last_text
[i
];
902 char_event
.nativeKeyCode
= last_text
[i
];
904 const int32 char_start
= i
;
905 for (; i
< iterator
.array_pos(); ++i
) {
906 char_event
.text
[i
- char_start
] = last_text
[i
];
907 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
910 if (GetRenderWidget()->webwidget())
911 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
914 // Mimics the order of events sent by WebKit.
915 // See WebCore::Editor::setComposition() for the corresponding code.
916 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
917 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
919 pepper_composition_text_
.clear();
921 #endif // defined(ENABLE_PLUGINS)
923 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
924 if (!web_user_media_client_
)
925 InitializeUserMediaClient();
926 return web_user_media_client_
?
927 web_user_media_client_
->media_stream_dispatcher() : NULL
;
930 bool RenderFrameImpl::Send(IPC::Message
* message
) {
935 if (is_swapped_out_
) {
936 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
942 return RenderThread::Get()->Send(message
);
945 #if defined(OS_MACOSX) || defined(OS_ANDROID)
946 void RenderFrameImpl::DidHideExternalPopupMenu() {
947 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
948 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
949 external_popup_menu_
.reset();
953 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
954 // TODO(kenrb): document() should not be null, but as a transitional step
955 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
956 // to this method. This happens for a top-level remote frame, where a
957 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
958 // around and is still able to receive messages.
959 if (!frame_
->document().isNull())
960 GetContentClient()->SetActiveURL(frame_
->document().url());
962 ObserverListBase
<RenderFrameObserver
>::Iterator
it(observers_
);
963 RenderFrameObserver
* observer
;
964 while ((observer
= it
.GetNext()) != NULL
) {
965 if (observer
->OnMessageReceived(msg
))
970 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
971 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
972 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
973 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
974 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
975 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
976 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
977 OnCustomContextMenuAction
)
978 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
979 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
980 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
981 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
982 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
983 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
984 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
985 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
986 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
987 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
988 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
989 OnMoveRangeSelectionExtent
)
990 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
991 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
992 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
993 OnExtendSelectionAndDelete
)
994 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
995 OnSetCompositionFromExistingText
)
996 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
997 OnExecuteNoValueEditCommand
)
998 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
999 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1000 OnJavaScriptExecuteRequest
)
1001 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1002 OnJavaScriptExecuteRequestForTests
)
1003 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1004 OnVisualStateRequest
)
1005 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1006 OnSetEditableSelectionOffsets
)
1007 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView
, OnSetupTransitionView
)
1008 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition
, OnBeginExitTransition
)
1009 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition
, OnRevertExitTransition
)
1010 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements
,
1011 OnHideTransitionElements
)
1012 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements
,
1013 OnShowTransitionElements
)
1014 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1015 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1016 OnTextSurroundingSelectionRequest
)
1017 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL
,
1018 OnAddStyleSheetByURL
)
1019 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1020 OnSetAccessibilityMode
)
1021 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1022 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1023 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1024 #if defined(OS_ANDROID)
1025 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1026 #elif defined(OS_MACOSX)
1027 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1028 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1030 IPC_END_MESSAGE_MAP()
1035 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params
& params
) {
1036 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
1038 "url", params
.common_params
.url
.possibly_invalid_spec());
1041 RenderViewImpl::IsReload(params
.common_params
.navigation_type
);
1042 bool is_history_navigation
= params
.history_params
.page_state
.IsValid();
1043 WebURLRequest::CachePolicy cache_policy
=
1044 WebURLRequest::UseProtocolCachePolicy
;
1045 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1046 params
.common_params
.url
, is_history_navigation
,
1047 params
.history_params
, &is_reload
, &cache_policy
)) {
1048 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
1052 GetContentClient()->SetActiveURL(params
.common_params
.url
);
1054 WebFrame
* frame
= frame_
;
1055 if (!params
.frame_to_navigate
.empty()) {
1056 // TODO(nasko): Move this lookup to the browser process.
1057 frame
= render_view_
->webview()->findFrameByName(
1058 WebString::fromUTF8(params
.frame_to_navigate
));
1059 CHECK(frame
) << "Invalid frame name passed: " << params
.frame_to_navigate
;
1062 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
1063 // We cannot reload if we do not have any history state. This happens, for
1064 // example, when recovering from a crash.
1066 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1069 render_view_
->pending_navigation_params_
.reset(
1070 new FrameMsg_Navigate_Params(params
));
1072 // If we are reloading, then WebKit will use the history state of the current
1073 // page, so we should just ignore any given history state. Otherwise, if we
1074 // have history state, then we need to navigate to it, which corresponds to a
1075 // back/forward navigation event.
1077 bool reload_original_url
=
1078 (params
.common_params
.navigation_type
==
1079 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1080 bool ignore_cache
= (params
.common_params
.navigation_type
==
1081 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1083 if (reload_original_url
)
1084 frame
->reloadWithOverrideURL(params
.common_params
.url
, true);
1086 frame
->reload(ignore_cache
);
1087 } else if (is_history_navigation
) {
1088 // We must know the page ID of the page we are navigating back to.
1089 DCHECK_NE(params
.history_params
.page_id
, -1);
1090 scoped_ptr
<HistoryEntry
> entry
=
1091 PageStateToHistoryEntry(params
.history_params
.page_state
);
1093 // Ensure we didn't save the swapped out URL in UpdateState, since the
1094 // browser should never be telling us to navigate to swappedout://.
1095 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
1096 render_view_
->history_controller()->GoToEntry(entry
.Pass(), cache_policy
);
1098 } else if (!params
.common_params
.base_url_for_data_url
.is_empty()) {
1099 LoadDataURL(params
.common_params
, frame
);
1101 // Navigate to the given URL.
1102 WebURLRequest request
=
1103 CreateURLRequestForNavigation(params
.common_params
,
1104 scoped_ptr
<StreamOverrideParameters
>(),
1105 frame
->isViewSourceModeEnabled());
1107 if (!params
.extra_headers
.empty()) {
1108 for (net::HttpUtil::HeadersIterator
i(params
.extra_headers
.begin(),
1109 params
.extra_headers
.end(),
1112 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
1113 WebString::fromUTF8(i
.values()));
1117 if (params
.is_post
) {
1118 request
.setHTTPMethod(WebString::fromUTF8("POST"));
1121 WebHTTPBody http_body
;
1122 http_body
.initialize();
1123 const char* data
= NULL
;
1124 if (params
.browser_initiated_post_data
.size()) {
1125 data
= reinterpret_cast<const char*>(
1126 ¶ms
.browser_initiated_post_data
.front());
1128 http_body
.appendData(
1129 WebData(data
, params
.browser_initiated_post_data
.size()));
1130 request
.setHTTPBody(http_body
);
1133 // A session history navigation should have been accompanied by state.
1134 CHECK_EQ(params
.history_params
.page_id
, -1);
1136 // Record this before starting the load, we need a lower bound of this time
1137 // to sanitize the navigationStart override set below.
1138 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
1139 frame
->loadRequest(request
);
1141 UpdateFrameNavigationTiming(
1142 frame
, params
.commit_params
.browser_navigation_start
,
1143 renderer_navigation_start
);
1146 // In case LoadRequest failed before DidCreateDataSource was called.
1147 render_view_
->pending_navigation_params_
.reset();
1150 void RenderFrameImpl::NavigateToSwappedOutURL() {
1151 // We use loadRequest instead of loadHTMLString because the former commits
1152 // synchronously. Otherwise a new navigation can interrupt the navigation
1153 // to kSwappedOutURL. If that happens to be to the page we had been
1154 // showing, then WebKit will never send a commit and we'll be left spinning.
1155 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1156 // the navigation to swappedout:// is not announced to the browser side.
1157 is_swapped_out_
= true;
1158 GURL
swappedOutURL(kSwappedOutURL
);
1159 WebURLRequest
request(swappedOutURL
);
1160 frame_
->loadRequest(request
);
1163 void RenderFrameImpl::BindServiceRegistry(
1164 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1165 mojo::ServiceProviderPtr exposed_services
) {
1166 service_registry_
.Bind(services
.Pass());
1167 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1170 ManifestManager
* RenderFrameImpl::manifest_manager() {
1171 return manifest_manager_
;
1174 void RenderFrameImpl::OnBeforeUnload() {
1175 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1177 // TODO(creis): Right now, this is only called on the main frame. Make the
1178 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1180 CHECK(!frame_
->parent());
1182 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1183 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1184 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1185 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1186 before_unload_start_time
,
1187 before_unload_end_time
));
1190 void RenderFrameImpl::OnSwapOut(
1191 int proxy_routing_id
,
1193 const FrameReplicationState
& replicated_frame_state
) {
1194 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1195 RenderFrameProxy
* proxy
= NULL
;
1196 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1197 switches::kSitePerProcess
);
1198 bool is_main_frame
= !frame_
->parent();
1200 // Only run unload if we're not swapped out yet, but send the ack either way.
1201 if (!is_swapped_out_
) {
1202 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1203 // a different process. This involves running the unload handler and
1204 // clearing the page. We also allow this process to exit if there are no
1205 // other active RenderFrames in it.
1207 // Send an UpdateState message before we get swapped out.
1208 render_view_
->SyncNavigationState();
1210 // If we need a proxy to replace this, create it now so its routing id is
1211 // registered for receiving IPC messages.
1212 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1213 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(this,
1217 // Synchronously run the unload handler before sending the ACK.
1218 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1219 // unload on subframes as well.
1221 frame_
->dispatchUnloadEvent();
1223 // Swap out and stop sending any IPC messages that are not ACKs.
1225 render_view_
->SetSwappedOut(true);
1226 is_swapped_out_
= true;
1228 // Now that we're swapped out and filtering IPC messages, stop loading to
1229 // ensure that no other in-progress navigation continues. We do this here
1230 // to avoid sending a DidStopLoading message to the browser process.
1231 // TODO(creis): Should we be stopping all frames here and using
1232 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1236 // Transfer settings such as initial drawing parameters to the remote frame,
1237 // if one is created, that will replace this frame.
1238 if (!is_main_frame
&& proxy
)
1239 proxy
->web_frame()->initializeFromFrame(frame_
);
1241 // Replace the page with a blank dummy URL. The unload handler will not be
1242 // run a second time, thanks to a check in FrameLoader::stopLoading.
1243 // TODO(creis): Need to add a better way to do this that avoids running the
1244 // beforeunload handler. For now, we just run it a second time silently.
1245 if (!is_site_per_process
|| is_main_frame
)
1246 NavigateToSwappedOutURL();
1248 // Let WebKit know that this view is hidden so it can drop resources and
1249 // stop compositing.
1250 // TODO(creis): Support this for subframes as well.
1251 if (is_main_frame
) {
1252 render_view_
->webview()->setVisibilityState(
1253 blink::WebPageVisibilityStateHidden
, false);
1257 // It is now safe to show modal dialogs again.
1258 // TODO(creis): Deal with modal dialogs from subframes.
1260 render_view_
->suppress_dialogs_until_swap_out_
= false;
1262 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1264 // Now that all of the cleanup is complete and the browser side is notified,
1265 // start using the RenderFrameProxy, if one is created.
1267 if (!is_main_frame
) {
1268 frame_
->swap(proxy
->web_frame());
1271 proxy
->OnDidStartLoading();
1273 if (is_site_per_process
) {
1274 // TODO(nasko): delete the frame here, since we've replaced it with a
1278 set_render_frame_proxy(proxy
);
1282 // In --site-per-process, initialize the WebRemoteFrame with the replication
1283 // state passed by the process that is now rendering the frame.
1284 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1285 // in that case we leave the LocalFrame as the main frame visible to Blink
1286 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1287 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1288 // When we do an unconditional swap for all frames, we can remove
1289 // !is_main_frame below.
1290 if (is_site_per_process
&& proxy
&& !is_main_frame
)
1291 proxy
->SetReplicatedState(replicated_frame_state
);
1293 // Safe to exit if no one else is using the process.
1295 render_view_
->WasSwappedOut();
1298 void RenderFrameImpl::OnContextMenuClosed(
1299 const CustomContextMenuContext
& custom_context
) {
1300 if (custom_context
.request_id
) {
1301 // External request, should be in our map.
1302 ContextMenuClient
* client
=
1303 pending_context_menus_
.Lookup(custom_context
.request_id
);
1305 client
->OnMenuClosed(custom_context
.request_id
);
1306 pending_context_menus_
.Remove(custom_context
.request_id
);
1309 if (custom_context
.link_followed
.is_valid()) {
1311 DomUtils::ExtractParentAnchorNode(context_menu_node_
),
1312 custom_context
.link_followed
);
1314 // Internal request, forward to WebKit.
1315 context_menu_node_
.reset();
1319 void RenderFrameImpl::OnCustomContextMenuAction(
1320 const CustomContextMenuContext
& custom_context
,
1322 if (custom_context
.request_id
) {
1323 // External context menu request, look in our map.
1324 ContextMenuClient
* client
=
1325 pending_context_menus_
.Lookup(custom_context
.request_id
);
1327 client
->OnMenuAction(custom_context
.request_id
, action
);
1329 // Internal request, forward to WebKit.
1330 render_view_
->webview()->performCustomContextMenuAction(action
);
1334 void RenderFrameImpl::OnUndo() {
1335 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1338 void RenderFrameImpl::OnRedo() {
1339 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1342 void RenderFrameImpl::OnCut() {
1343 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1344 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1347 void RenderFrameImpl::OnCopy() {
1348 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1349 WebNode current_node
= context_menu_node_
.isNull() ?
1350 GetFocusedElement() : context_menu_node_
;
1351 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1354 void RenderFrameImpl::OnPaste() {
1355 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1356 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1359 void RenderFrameImpl::OnPasteAndMatchStyle() {
1360 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1361 frame_
->executeCommand(
1362 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1365 #if defined(OS_MACOSX)
1366 void RenderFrameImpl::OnCopyToFindPboard() {
1367 // Since the find pasteboard supports only plain text, this can be simpler
1368 // than the |OnCopy()| case.
1369 if (frame_
->hasSelection()) {
1370 base::string16 selection
= frame_
->selectionAsText();
1371 RenderThread::Get()->Send(
1372 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1377 void RenderFrameImpl::OnDelete() {
1378 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1381 void RenderFrameImpl::OnSelectAll() {
1382 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1383 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1386 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1387 const gfx::Point
& extent
) {
1388 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1389 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1391 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1392 frame_
->selectRange(base
, extent
);
1395 void RenderFrameImpl::OnUnselect() {
1396 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1397 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1400 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1401 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1402 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1403 GetRenderWidget()->routing_id()));
1405 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1406 frame_
->moveRangeSelectionExtent(point
);
1409 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1410 if (!frame_
->hasSelection())
1411 frame_
->selectWordAroundCaret();
1413 frame_
->replaceSelection(text
);
1416 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1417 if (!frame_
->hasSelection())
1420 frame_
->replaceMisspelledRange(text
);
1423 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1424 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1427 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1428 const base::string16
& jscript
,
1430 bool notify_result
) {
1431 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1432 TRACE_EVENT_SCOPE_THREAD
);
1434 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1435 v8::Handle
<v8::Value
> result
=
1436 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1438 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1441 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1442 const base::string16
& jscript
,
1444 bool notify_result
) {
1445 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1446 TRACE_EVENT_SCOPE_THREAD
);
1448 // A bunch of tests expect to run code in the context of a user gesture, which
1449 // can grant additional privileges (e.g. the ability to create popups).
1450 blink::WebScopedUserGesture gesture
;
1451 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1452 v8::Handle
<v8::Value
> result
=
1453 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1455 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1458 void RenderFrameImpl::HandleJavascriptExecutionResult(
1459 const base::string16
& jscript
,
1462 v8::Handle
<v8::Value
> result
) {
1463 if (notify_result
) {
1464 base::ListValue list
;
1465 if (!result
.IsEmpty()) {
1466 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1467 v8::Context::Scope
context_scope(context
);
1468 V8ValueConverterImpl converter
;
1469 converter
.SetDateAllowed(true);
1470 converter
.SetRegExpAllowed(true);
1471 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
1472 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
1474 list
.Set(0, base::Value::CreateNullValue());
1476 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1480 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1481 GetRenderWidget()->QueueMessage(
1482 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1483 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1486 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1487 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1488 if (!GetRenderWidget()->ShouldHandleImeEvent())
1490 ImeEventGuard
guard(GetRenderWidget());
1491 frame_
->setEditableSelectionOffsets(start
, end
);
1494 void RenderFrameImpl::OnSetCompositionFromExistingText(
1496 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1497 if (!GetRenderWidget()->ShouldHandleImeEvent())
1499 ImeEventGuard
guard(GetRenderWidget());
1500 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1503 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1504 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1507 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1508 if (!GetRenderWidget()->ShouldHandleImeEvent())
1510 ImeEventGuard
guard(GetRenderWidget());
1511 frame_
->extendSelectionAndDelete(before
, after
);
1514 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1515 if (accessibility_mode_
== new_mode
)
1517 accessibility_mode_
= new_mode
;
1518 if (renderer_accessibility_
) {
1519 // Note: this isn't called automatically by the destructor because
1520 // there'd be no point in calling it in frame teardown, only if there's
1521 // an accessibility mode change but the frame is persisting.
1522 renderer_accessibility_
->DisableAccessibility();
1524 delete renderer_accessibility_
;
1525 renderer_accessibility_
= NULL
;
1527 if (accessibility_mode_
== AccessibilityModeOff
)
1530 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1531 renderer_accessibility_
= new RendererAccessibility(this);
1534 void RenderFrameImpl::OnDisownOpener() {
1535 // TODO(creis): We should only see this for main frames for now. To support
1536 // disowning the opener on subframes, we will need to move WebContentsImpl's
1537 // opener_ to FrameTreeNode.
1538 CHECK(!frame_
->parent());
1540 if (frame_
->opener())
1541 frame_
->setOpener(NULL
);
1544 void RenderFrameImpl::OnDidUpdateSandboxFlags(SandboxFlags flags
) {
1545 frame_
->setFrameOwnerSandboxFlags(ContentToWebSandboxFlags(flags
));
1548 #if defined(OS_ANDROID)
1549 void RenderFrameImpl::OnSelectPopupMenuItems(
1551 const std::vector
<int>& selected_indices
) {
1552 // It is possible to receive more than one of these calls if the user presses
1553 // a select faster than it takes for the show-select-popup IPC message to make
1554 // it to the browser UI thread. Ignore the extra-messages.
1555 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1556 if (!external_popup_menu_
)
1559 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1560 external_popup_menu_
.reset();
1564 #if defined(OS_MACOSX)
1565 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1566 if (external_popup_menu_
== NULL
)
1568 external_popup_menu_
->DidSelectItem(selected_index
);
1569 external_popup_menu_
.reset();
1573 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1574 frame_
->reload(ignore_cache
);
1577 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1578 blink::WebSurroundingText surroundingText
;
1579 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1581 if (surroundingText
.isNull()) {
1582 // |surroundingText| might not be correctly initialized, for example if
1583 // |frame_->selectionRange().isNull()|, in other words, if there was no
1585 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1586 routing_id_
, base::string16(), 0, 0));
1590 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1592 surroundingText
.textContent(),
1593 surroundingText
.startOffsetInTextContent(),
1594 surroundingText
.endOffsetInTextContent()));
1597 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string
& url
) {
1598 frame_
->addStyleSheetByURL(WebString::fromUTF8(url
));
1601 void RenderFrameImpl::OnSetupTransitionView(const std::string
& markup
) {
1602 frame_
->document().setIsTransitionDocument(true);
1603 frame_
->navigateToSandboxedMarkup(WebData(markup
.data(), markup
.length()));
1606 void RenderFrameImpl::OnBeginExitTransition(const std::string
& css_selector
,
1607 bool exit_to_native_app
) {
1608 frame_
->document().setIsTransitionDocument(true);
1609 frame_
->document().beginExitTransition(WebString::fromUTF8(css_selector
),
1610 exit_to_native_app
);
1613 void RenderFrameImpl::OnRevertExitTransition() {
1614 frame_
->document().setIsTransitionDocument(false);
1615 frame_
->document().revertExitTransition();
1618 void RenderFrameImpl::OnHideTransitionElements(
1619 const std::string
& css_selector
) {
1620 frame_
->document().hideTransitionElements(WebString::fromUTF8(css_selector
));
1623 void RenderFrameImpl::OnShowTransitionElements(
1624 const std::string
& css_selector
) {
1625 frame_
->document().showTransitionElements(WebString::fromUTF8(css_selector
));
1628 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1629 const base::string16
& message
,
1630 const base::string16
& default_value
,
1631 const GURL
& frame_url
,
1632 base::string16
* result
) {
1633 // Don't allow further dialogs if we are waiting to swap out, since the
1634 // PageGroupLoadDeferrer in our stack prevents it.
1635 if (render_view()->suppress_dialogs_until_swap_out_
)
1638 bool success
= false;
1639 base::string16 result_temp
;
1641 result
= &result_temp
;
1643 render_view()->SendAndRunNestedMessageLoop(
1644 new FrameHostMsg_RunJavaScriptMessage(
1645 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1650 void RenderFrameImpl::LoadNavigationErrorPage(
1651 const WebURLRequest
& failed_request
,
1652 const WebURLError
& error
,
1654 std::string error_html
;
1655 GetContentClient()->renderer()->GetNavigationErrorStrings(
1656 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1658 frame_
->loadHTMLString(error_html
,
1659 GURL(kUnreachableWebDataURL
),
1660 error
.unreachableURL
,
1664 void RenderFrameImpl::DidCommitCompositorFrame() {
1665 if (BrowserPluginManager::Get())
1666 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1668 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1671 RenderView
* RenderFrameImpl::GetRenderView() {
1672 return render_view_
.get();
1675 int RenderFrameImpl::GetRoutingID() {
1679 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1684 WebElement
RenderFrameImpl::GetFocusedElement() const {
1685 WebDocument doc
= frame_
->document();
1687 return doc
.focusedElement();
1689 return WebElement();
1692 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1693 return render_view_
->GetWebkitPreferences();
1696 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1697 const ContextMenuParams
& params
) {
1698 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1699 ContextMenuParams
our_params(params
);
1700 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1701 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1702 return our_params
.custom_context
.request_id
;
1705 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1706 DCHECK(pending_context_menus_
.Lookup(request_id
));
1707 pending_context_menus_
.Remove(request_id
);
1710 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1711 return context_menu_node_
;
1714 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1715 blink::WebFrame
* frame
,
1716 const WebPluginInfo
& info
,
1717 const blink::WebPluginParams
& params
,
1718 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1719 DCHECK_EQ(frame_
, frame
);
1720 #if defined(ENABLE_PLUGINS)
1721 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1722 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1723 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1724 this, params
.mimeType
.utf8(), GURL(params
.url
)));
1725 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1726 this, browser_plugin_delegate
.Pass());
1729 bool pepper_plugin_was_registered
= false;
1730 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1731 this, info
, &pepper_plugin_was_registered
));
1732 if (pepper_plugin_was_registered
) {
1733 if (pepper_module
.get()) {
1734 return new PepperWebPluginImpl(
1735 pepper_module
.get(), params
, this,
1737 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1740 #if defined(OS_CHROMEOS)
1741 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1744 // TODO(jam): change to take RenderFrame.
1745 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1752 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1753 const blink::WebURLRequest
& request
,
1754 blink::WebNavigationPolicy policy
) {
1755 DCHECK(!frame_
|| frame_
== frame
);
1756 loadURLExternally(frame
, request
, policy
, WebString());
1759 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1760 OnJavaScriptExecuteRequest(javascript
, 0, false);
1763 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1764 return &service_registry_
;
1767 #if defined(ENABLE_PLUGINS)
1768 void RenderFrameImpl::RegisterPeripheralPlugin(
1769 const GURL
& content_origin
,
1770 const base::Closure
& unthrottle_callback
) {
1771 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1772 content_origin
, unthrottle_callback
);
1774 #endif // defined(ENABLE_PLUGINS)
1776 bool RenderFrameImpl::IsFTPDirectoryListing() {
1777 WebURLResponseExtraDataImpl
* extra_data
=
1778 GetExtraDataFromResponse(frame_
->dataSource()->response());
1779 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1782 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1783 BrowserPluginManager::Get()->Attach(element_instance_id
);
1786 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1787 BrowserPluginManager::Get()->Detach(element_instance_id
);
1790 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1792 const gfx::Range
& range
) {
1793 // Use the routing id of Render Widget Host.
1794 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1800 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1801 v8::Isolate
* isolate
,
1802 v8::Handle
<v8::Context
> context
) {
1803 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1804 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1807 v8::HandleScope
handle_scope(isolate
);
1808 registry
->AddBuiltinModule(
1809 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1810 registry
->AddBuiltinModule(isolate
,
1811 mojo::js::Support::kModuleName
,
1812 mojo::js::Support::GetModule(isolate
));
1813 registry
->AddBuiltinModule(
1815 ServiceRegistryJsWrapper::kModuleName
,
1816 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1819 // blink::WebFrameClient implementation ----------------------------------------
1821 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1822 blink::WebLocalFrame
* frame
,
1823 const blink::WebPluginParams
& params
) {
1824 DCHECK_EQ(frame_
, frame
);
1825 return GetContentClient()
1827 ->CreatePluginPlaceholder(this, frame
, params
)
1831 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1832 blink::WebLocalFrame
* frame
,
1833 const blink::WebPluginParams
& params
) {
1834 DCHECK_EQ(frame_
, frame
);
1835 blink::WebPlugin
* plugin
= NULL
;
1836 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1837 this, frame
, params
, &plugin
)) {
1841 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1842 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1843 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1844 kBrowserPluginMimeType
, GURL(params
.url
)));
1845 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1846 this, browser_plugin_delegate
.Pass());
1849 #if defined(ENABLE_PLUGINS)
1851 std::string mime_type
;
1853 Send(new FrameHostMsg_GetPluginInfo(
1854 routing_id_
, params
.url
, frame
->top()->document().url(),
1855 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
1859 WebPluginParams params_to_use
= params
;
1860 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
1861 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
1864 #endif // defined(ENABLE_PLUGINS)
1867 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1868 blink::WebLocalFrame
* frame
,
1869 const blink::WebURL
& url
,
1870 blink::WebMediaPlayerClient
* client
) {
1871 return createMediaPlayer(frame
, url
, client
, nullptr);
1874 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1875 blink::WebLocalFrame
* frame
,
1876 const blink::WebURL
& url
,
1877 blink::WebMediaPlayerClient
* client
,
1878 blink::WebContentDecryptionModule
* initial_cdm
) {
1879 #if defined(VIDEO_HOLE)
1880 if (!contains_media_player_
) {
1881 render_view_
->RegisterVideoHoleFrame(this);
1882 contains_media_player_
= true;
1884 #endif // defined(VIDEO_HOLE)
1886 blink::WebMediaStream
web_stream(
1887 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
1888 if (!web_stream
.isNull())
1889 return CreateWebMediaPlayerForMediaStream(url
, client
);
1891 if (!media_permission_dispatcher_
)
1892 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
1894 #if defined(OS_ANDROID)
1895 return CreateAndroidWebMediaPlayer(url
, client
, media_permission_dispatcher_
,
1898 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
1901 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
1902 media::WebMediaPlayerParams
params(
1903 base::Bind(&ContentRendererClient::DeferMediaLoad
,
1904 base::Unretained(GetContentClient()->renderer()),
1905 static_cast<RenderFrame
*>(this)),
1906 render_thread
->GetAudioRendererMixerManager()->CreateInput(
1907 render_view_
->routing_id_
, routing_id_
),
1908 media_log
, render_thread
->GetMediaThreadTaskRunner(),
1909 render_thread
->compositor_message_loop_proxy(),
1910 base::Bind(&GetSharedMainThreadContext3D
), media_permission_dispatcher_
,
1913 #if defined(ENABLE_PEPPER_CDMS)
1914 scoped_ptr
<media::CdmFactory
> cdm_factory(
1915 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create
, frame
)));
1916 #elif defined(ENABLE_BROWSER_CDMS)
1917 scoped_ptr
<media::CdmFactory
> cdm_factory(
1918 new RenderCdmFactory(GetCdmManager()));
1920 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
1923 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1924 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
1925 new media::MojoRendererFactory(make_scoped_ptr(
1926 new MediaRendererServiceProvider(GetServiceRegistry()))));
1928 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
1929 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
1932 if (!media_renderer_factory
.get()) {
1933 media_renderer_factory
.reset(new media::DefaultRendererFactory(
1934 media_log
, render_thread
->GetGpuFactories(),
1935 *render_thread
->GetAudioHardwareConfig()));
1937 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
1939 return new media::WebMediaPlayerImpl(
1940 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer_factory
.Pass(),
1941 cdm_factory
.Pass(), params
);
1942 #endif // defined(OS_ANDROID)
1945 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
1946 blink::WebLocalFrame
* frame
,
1947 blink::WebApplicationCacheHostClient
* client
) {
1948 if (!frame
|| !frame
->view())
1950 DCHECK(!frame_
|| frame_
== frame
);
1951 return new RendererWebApplicationCacheHostImpl(
1952 RenderViewImpl::FromWebView(frame
->view()), client
,
1953 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1956 blink::WebWorkerPermissionClientProxy
*
1957 RenderFrameImpl::createWorkerPermissionClientProxy(
1958 blink::WebLocalFrame
* frame
) {
1959 if (!frame
|| !frame
->view())
1961 DCHECK(!frame_
|| frame_
== frame
);
1962 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1966 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
1967 const WebPopupMenuInfo
& popup_menu_info
,
1968 WebExternalPopupMenuClient
* popup_menu_client
) {
1969 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1970 // An IPC message is sent to the browser to build and display the actual
1971 // popup. The user could have time to click a different select by the time
1972 // the popup is shown. In that case external_popup_menu_ is non NULL.
1973 // By returning NULL in that case, we instruct Blink to cancel that new
1974 // popup. So from the user perspective, only the first one will show, and
1975 // will have to close the first one before another one can be shown.
1976 if (external_popup_menu_
)
1978 external_popup_menu_
.reset(
1979 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
1980 if (render_view_
->screen_metrics_emulator_
) {
1981 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
1982 external_popup_menu_
.get(),
1983 render_view_
->screen_metrics_emulator_
.get());
1985 return external_popup_menu_
.get();
1991 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
1992 DCHECK(!frame_
|| frame_
== frame
);
1993 return &cookie_jar_
;
1996 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
1997 blink::WebLocalFrame
* frame
) {
1998 DCHECK(!frame_
|| frame_
== frame
);
1999 // At this point we should have non-null data source.
2000 DCHECK(frame
->dataSource());
2001 if (!ChildThreadImpl::current())
2002 return NULL
; // May be null in some tests.
2003 ServiceWorkerNetworkProvider
* provider
=
2004 ServiceWorkerNetworkProvider::FromDocumentState(
2005 DocumentState::FromDataSource(frame
->dataSource()));
2006 return new WebServiceWorkerProviderImpl(
2007 ChildThreadImpl::current()->thread_safe_sender(),
2008 provider
? provider
->context() : NULL
);
2011 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2012 DCHECK(!frame_
|| frame_
== frame
);
2013 // If the request hasn't yet committed, notify the browser process that it is
2014 // no longer safe to show the pending URL of the main frame, since a URL spoof
2015 // is now possible. (If the request has committed, the browser already knows.)
2016 if (!frame
->parent()) {
2017 DocumentState
* document_state
=
2018 DocumentState::FromDataSource(frame
->dataSource());
2019 NavigationState
* navigation_state
= document_state
->navigation_state();
2021 if (!navigation_state
->request_committed()) {
2022 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2027 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2028 blink::WebLocalFrame
* parent
,
2029 const blink::WebString
& name
,
2030 blink::WebSandboxFlags sandbox_flags
) {
2031 // Synchronously notify the browser of a child frame creation to get the
2032 // routing_id for the RenderFrame.
2033 int child_routing_id
= MSG_ROUTING_NONE
;
2034 Send(new FrameHostMsg_CreateChildFrame(
2035 routing_id_
, base::UTF16ToUTF8(name
),
2036 WebToContentSandboxFlags(sandbox_flags
), &child_routing_id
));
2038 // Allocation of routing id failed, so we can't create a child frame. This can
2039 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2040 // out state or synchronous IPC message above has failed.
2041 if (child_routing_id
== MSG_ROUTING_NONE
) {
2042 NOTREACHED() << "Failed to allocate routing id for child frame.";
2046 // Create the RenderFrame and WebLocalFrame, linking the two.
2047 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2048 render_view_
.get(), child_routing_id
);
2049 blink::WebLocalFrame
* web_frame
= WebLocalFrame::create(child_render_frame
);
2050 child_render_frame
->SetWebFrame(web_frame
);
2052 // Add the frame to the frame tree and initialize it.
2053 parent
->appendChild(web_frame
);
2054 child_render_frame
->Initialize();
2059 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2060 DCHECK(!frame_
|| frame_
== frame
);
2061 // We only need to notify the browser if the active, top-level frame clears
2062 // its opener. We can ignore cases where a swapped out frame clears its
2063 // opener after hearing about it from the browser, and the browser does not
2064 // (yet) care about subframe openers.
2065 if (is_swapped_out_
|| frame
->parent())
2068 // Notify WebContents and all its swapped out RenderViews.
2069 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2072 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
) {
2073 // NOTE: This function is called on the frame that is being detached and not
2074 // the parent frame. This is different from createChildFrame() which is
2075 // called on the parent frame.
2076 CHECK(!is_detaching_
);
2077 DCHECK(!frame_
|| frame_
== frame
);
2079 bool is_subframe
= !!frame
->parent();
2081 Send(new FrameHostMsg_Detach(routing_id_
));
2083 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2084 // sent before setting |is_detaching_| to true. In contrast, Observers
2085 // should only be notified afterwards so they cannot call back into here and
2086 // have IPCs fired off.
2087 is_detaching_
= true;
2089 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2090 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2091 FrameDetached(frame
));
2093 // We need to clean up subframes by removing them from the map and deleting
2094 // the RenderFrameImpl. In contrast, the main frame is owned by its
2095 // containing RenderViewHost (so that they have the same lifetime), so only
2096 // removal from the map is needed and no deletion.
2097 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2098 CHECK(it
!= g_frame_map
.Get().end());
2099 CHECK_EQ(it
->second
, this);
2100 g_frame_map
.Get().erase(it
);
2103 frame
->parent()->removeChild(frame
);
2105 // |frame| is invalid after here.
2110 // Object is invalid after this point.
2114 void RenderFrameImpl::frameFocused() {
2115 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2118 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2119 DCHECK(!frame_
|| frame_
== frame
);
2121 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2122 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2123 FrameWillClose(frame
));
2126 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2127 const blink::WebString
& name
) {
2128 DCHECK(!frame_
|| frame_
== frame
);
2129 if (!render_view_
->renderer_preferences_
.report_frame_name_changes
)
2132 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeName(name
));
2135 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2136 blink::WebSandboxFlags flags
) {
2137 int frame_routing_id
= MSG_ROUTING_NONE
;
2138 if (child_frame
->isWebRemoteFrame()) {
2140 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2143 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2146 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2147 WebToContentSandboxFlags(flags
)));
2150 void RenderFrameImpl::didMatchCSS(
2151 blink::WebLocalFrame
* frame
,
2152 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2153 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2154 DCHECK(!frame_
|| frame_
== frame
);
2156 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2158 newly_matching_selectors
,
2159 stopped_matching_selectors
));
2162 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2163 const blink::WebString
& source
) {
2164 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2168 void RenderFrameImpl::didAddMessageToConsole(
2169 const blink::WebConsoleMessage
& message
,
2170 const blink::WebString
& source_name
,
2171 unsigned source_line
,
2172 const blink::WebString
& stack_trace
) {
2173 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2174 switch (message
.level
) {
2175 case blink::WebConsoleMessage::LevelDebug
:
2176 log_severity
= logging::LOG_VERBOSE
;
2178 case blink::WebConsoleMessage::LevelLog
:
2179 case blink::WebConsoleMessage::LevelInfo
:
2180 log_severity
= logging::LOG_INFO
;
2182 case blink::WebConsoleMessage::LevelWarning
:
2183 log_severity
= logging::LOG_WARNING
;
2185 case blink::WebConsoleMessage::LevelError
:
2186 log_severity
= logging::LOG_ERROR
;
2192 if (shouldReportDetailedMessageForSource(source_name
)) {
2194 RenderFrameObserver
, observers_
,
2195 DetailedConsoleMessageAdded(message
.text
,
2199 static_cast<int32
>(log_severity
)));
2202 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2203 static_cast<int32
>(log_severity
),
2205 static_cast<int32
>(source_line
),
2209 void RenderFrameImpl::loadURLExternally(
2210 blink::WebLocalFrame
* frame
,
2211 const blink::WebURLRequest
& request
,
2212 blink::WebNavigationPolicy policy
,
2213 const blink::WebString
& suggested_name
) {
2214 DCHECK(!frame_
|| frame_
== frame
);
2215 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2216 if (policy
== blink::WebNavigationPolicyDownload
) {
2217 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2218 request
.url(), referrer
,
2221 OpenURL(frame
, request
.url(), referrer
, policy
);
2225 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2226 const NavigationPolicyInfo
& info
) {
2227 DCHECK(!frame_
|| frame_
== info
.frame
);
2228 return DecidePolicyForNavigation(this, info
);
2231 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2232 blink::WebFrame
* frame
) {
2233 DCHECK(!frame_
|| frame_
== frame
);
2234 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2237 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2238 const blink::WebFormElement
& form
) {
2239 DCHECK(!frame_
|| frame_
== frame
);
2241 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2244 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2245 const blink::WebFormElement
& form
) {
2246 DCHECK(!frame_
|| frame_
== frame
);
2247 DocumentState
* document_state
=
2248 DocumentState::FromDataSource(frame
->provisionalDataSource());
2249 NavigationState
* navigation_state
= document_state
->navigation_state();
2250 InternalDocumentStateData
* internal_data
=
2251 InternalDocumentStateData::FromDocumentState(document_state
);
2253 if (ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2254 ui::PAGE_TRANSITION_LINK
)) {
2255 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2258 // Save these to be processed when the ensuing navigation is committed.
2259 WebSearchableFormData
web_searchable_form_data(form
);
2260 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2261 internal_data
->set_searchable_form_encoding(
2262 web_searchable_form_data
.encoding().utf8());
2264 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2267 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2268 blink::WebDataSource
* datasource
) {
2269 DCHECK(!frame_
|| frame_
== frame
);
2271 // TODO(nasko): Move implementation here. Needed state:
2272 // * pending_navigation_params_
2275 // * PopulateDocumentStateFromPending
2276 // * CreateNavigationStateFromPending
2277 render_view_
->didCreateDataSource(frame
, datasource
);
2279 // Create the serviceworker's per-document network observing object if it
2280 // does not exist (When navigation happens within a page, the provider already
2282 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2283 DocumentState::FromDataSource(datasource
))) {
2284 scoped_ptr
<ServiceWorkerNetworkProvider
>
2285 network_provider(new ServiceWorkerNetworkProvider(
2286 routing_id_
, SERVICE_WORKER_PROVIDER_FOR_CONTROLLEE
));
2287 ServiceWorkerNetworkProvider::AttachToDocumentState(
2288 DocumentState::FromDataSource(datasource
),
2289 network_provider
.Pass());
2293 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2294 bool is_transition_navigation
,
2295 double triggering_event_time
) {
2296 DCHECK(!frame_
|| frame_
== frame
);
2297 WebDataSource
* ds
= frame
->provisionalDataSource();
2299 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2300 // callback is invoked.
2304 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2305 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2306 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2308 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2309 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2311 "Heard swappedout:// when not swapped out.";
2313 // Update the request time if WebKit has better knowledge of it.
2314 if (document_state
->request_time().is_null() &&
2315 triggering_event_time
!= 0.0) {
2316 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2319 // Start time is only set after request time.
2320 document_state
->set_start_load_time(Time::Now());
2322 bool is_top_most
= !frame
->parent();
2324 render_view_
->set_navigation_gesture(
2325 WebUserGestureIndicator::isProcessingUserGesture() ?
2326 NavigationGestureUser
: NavigationGestureAuto
);
2327 } else if (ds
->replacesCurrentHistoryItem()) {
2328 // Subframe navigations that don't add session history items must be
2329 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2330 // handle loading of error pages.
2331 document_state
->navigation_state()->set_transition_type(
2332 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2335 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2336 DidStartProvisionalLoad(frame
));
2337 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2339 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2340 routing_id_
, ds
->request().url(), is_transition_navigation
));
2343 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2344 blink::WebLocalFrame
* frame
) {
2345 DCHECK(!frame_
|| frame_
== frame
);
2346 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2349 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame
* frame
,
2350 const blink::WebURLError
& error
) {
2351 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2353 DCHECK(!frame_
|| frame_
== frame
);
2354 WebDataSource
* ds
= frame
->provisionalDataSource();
2357 const WebURLRequest
& failed_request
= ds
->request();
2359 // Notify the browser that we failed a provisional load with an error.
2361 // Note: It is important this notification occur before DidStopLoading so the
2362 // SSL manager can react to the provisional load failure before being
2363 // notified the load stopped.
2365 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2366 DidFailProvisionalLoad(frame
, error
));
2367 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2368 DidFailProvisionalLoad(error
));
2370 bool show_repost_interstitial
=
2371 (error
.reason
== net::ERR_CACHE_MISS
&&
2372 EqualsASCII(failed_request
.httpMethod(), "POST"));
2374 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
2375 params
.error_code
= error
.reason
;
2376 GetContentClient()->renderer()->GetNavigationErrorStrings(
2382 ¶ms
.error_description
);
2383 params
.url
= error
.unreachableURL
;
2384 params
.showing_repost_interstitial
= show_repost_interstitial
;
2385 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2386 routing_id_
, params
));
2388 // Don't display an error page if this is simply a cancelled load. Aside
2389 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2390 if (error
.reason
== net::ERR_ABORTED
)
2393 // Don't display "client blocked" error page if browser has asked us not to.
2394 if (error
.reason
== net::ERR_BLOCKED_BY_CLIENT
&&
2395 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
2399 // Allow the embedder to suppress an error page.
2400 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2401 error
.unreachableURL
)) {
2405 if (RenderThreadImpl::current() &&
2406 RenderThreadImpl::current()->layout_test_mode()) {
2410 // Make sure we never show errors in view source mode.
2411 frame
->enableViewSourceMode(false);
2413 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2414 NavigationState
* navigation_state
= document_state
->navigation_state();
2416 // If this is a failed back/forward/reload navigation, then we need to do a
2417 // 'replace' load. This is necessary to avoid messing up session history.
2418 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2419 // as session history is concerned.
2421 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2424 // TODO(davidben): This should also take the failed navigation's replacement
2425 // state into account, if a location.replace() failed.
2427 navigation_state
->pending_page_id() != -1 ||
2428 ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2429 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2431 // If we failed on a browser initiated request, then make sure that our error
2432 // page load is regarded as the same browser initiated request.
2433 if (!navigation_state
->is_content_initiated()) {
2434 render_view_
->pending_navigation_params_
.reset(
2435 new FrameMsg_Navigate_Params
);
2436 FrameMsg_Navigate_Params
* pending_params
=
2437 render_view_
->pending_navigation_params_
.get();
2438 pending_params
->history_params
.page_id
=
2439 navigation_state
->pending_page_id();
2440 pending_params
->history_params
.pending_history_list_offset
=
2441 navigation_state
->pending_history_list_offset();
2442 pending_params
->history_params
.should_clear_history_list
=
2443 navigation_state
->history_list_was_cleared();
2444 pending_params
->common_params
.transition
=
2445 navigation_state
->transition_type();
2446 pending_params
->request_time
= document_state
->request_time();
2447 pending_params
->should_replace_current_entry
= replace
;
2450 // Load an error page.
2451 LoadNavigationErrorPage(failed_request
, error
, replace
);
2454 void RenderFrameImpl::didCommitProvisionalLoad(
2455 blink::WebLocalFrame
* frame
,
2456 const blink::WebHistoryItem
& item
,
2457 blink::WebHistoryCommitType commit_type
) {
2458 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2460 "url", GetLoadingUrl().possibly_invalid_spec());
2461 DCHECK(!frame_
|| frame_
== frame
);
2462 DocumentState
* document_state
=
2463 DocumentState::FromDataSource(frame
->dataSource());
2464 NavigationState
* navigation_state
= document_state
->navigation_state();
2466 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2467 RenderFrameProxy
* proxy
=
2468 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2470 proxy
->web_frame()->swap(frame_
);
2471 proxy_routing_id_
= MSG_ROUTING_NONE
;
2474 // When we perform a new navigation, we need to update the last committed
2475 // session history entry with state for the page we are leaving. Do this
2476 // before updating the HistoryController state.
2477 render_view_
->UpdateSessionHistory(frame
);
2479 render_view_
->history_controller()->UpdateForCommit(this, item
, commit_type
,
2480 navigation_state
->was_within_same_page());
2482 InternalDocumentStateData
* internal_data
=
2483 InternalDocumentStateData::FromDocumentState(document_state
);
2485 if (document_state
->commit_load_time().is_null())
2486 document_state
->set_commit_load_time(Time::Now());
2488 if (internal_data
->must_reset_scroll_and_scale_state()) {
2489 render_view_
->webview()->resetScrollAndScaleState();
2490 internal_data
->set_must_reset_scroll_and_scale_state(false);
2492 internal_data
->set_use_error_page(false);
2494 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2495 if (is_new_navigation
) {
2496 // We bump our Page ID to correspond with the new session history entry.
2497 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2499 // Don't update history list values for kSwappedOutURL, since
2500 // we don't want to forget the entry that was there, and since we will
2501 // never come back to kSwappedOutURL. Note that we have to call
2502 // UpdateSessionHistory and update page_id_ even in this case, so that
2503 // the current entry gets a state update and so that we don't send a
2504 // state update to the wrong entry when we swap back in.
2505 DCHECK_IMPLIES(navigation_state
->should_replace_current_entry(),
2506 render_view_
->history_list_length_
> 0);
2507 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2508 !navigation_state
->should_replace_current_entry()) {
2509 // Advance our offset in session history, applying the length limit.
2510 // There is now no forward history.
2511 render_view_
->history_list_offset_
++;
2512 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2513 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2514 render_view_
->history_list_length_
=
2515 render_view_
->history_list_offset_
+ 1;
2518 // Inspect the navigation_state on this frame to see if the navigation
2519 // corresponds to a session history navigation... Note: |frame| may or
2520 // may not be the toplevel frame, but for the case of capturing session
2521 // history, the first committed frame suffices. We keep track of whether
2522 // we've seen this commit before so that only capture session history once
2525 // Note that we need to check if the page ID changed. In the case of a
2526 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2527 // previous URL and the current page ID, which would be wrong.
2528 if (navigation_state
->pending_page_id() != -1 &&
2529 navigation_state
->pending_page_id() != render_view_
->page_id_
&&
2530 !navigation_state
->request_committed()) {
2531 // This is a successful session history navigation!
2532 render_view_
->page_id_
= navigation_state
->pending_page_id();
2534 render_view_
->history_list_offset_
=
2535 navigation_state
->pending_history_list_offset();
2540 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2541 CHECK(sent
); // http://crbug.com/407376
2543 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2544 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2545 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2546 DidCommitProvisionalLoad(
2548 navigation_state
->was_within_same_page()));
2550 if (!frame
->parent()) { // Only for top frames.
2551 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2552 if (render_thread_impl
) { // Can be NULL in tests.
2553 render_thread_impl
->histogram_customizer()->
2554 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2555 RenderViewImpl::GetRenderViewCount());
2559 // Remember that we've already processed this request, so we don't update
2560 // the session history again. We do this regardless of whether this is
2561 // a session history navigation, because if we attempted a session history
2562 // navigation without valid HistoryItem state, WebCore will think it is a
2564 navigation_state
->set_request_committed(true);
2566 SendDidCommitProvisionalLoad(frame
, commit_type
);
2568 // Check whether we have new encoding name.
2569 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2572 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2573 DCHECK(!frame_
|| frame_
== frame
);
2575 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2576 DidCreateNewDocument(frame
));
2579 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2580 DCHECK(!frame_
|| frame_
== frame
);
2582 int enabled_bindings
= render_view_
->GetEnabledBindings();
2584 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2585 WebUIExtension::Install(frame
);
2587 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2588 DomAutomationController::Install(this, frame
);
2590 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2591 StatsCollectionController::Install(frame
);
2593 const base::CommandLine
& command_line
=
2594 *base::CommandLine::ForCurrentProcess();
2596 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2597 GpuBenchmarking::Install(frame
);
2599 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2600 MemoryBenchmarkingExtension::Install(frame
);
2602 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2603 SkiaBenchmarking::Install(frame
);
2605 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2606 DidClearWindowObject(frame
));
2607 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2610 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2611 DCHECK(!frame_
|| frame_
== frame
);
2613 // Notify the browser about non-blank documents loading in the top frame.
2614 GURL url
= frame
->document().url();
2615 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2616 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2617 // frame->tree()->top().
2618 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2619 if (frame
== main_frame
) {
2620 // For now, don't remember plugin zoom values. We don't want to mix them
2621 // with normal web content (i.e. a fixed layout plugin would usually want
2623 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2624 render_view_
->GetRoutingID(),
2625 main_frame
->document().isPluginDocument()));
2629 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2630 DidCreateDocumentElement(frame
));
2633 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2634 const blink::WebString
& title
,
2635 blink::WebTextDirection direction
) {
2636 DCHECK(!frame_
|| frame_
== frame
);
2637 // Ignore all but top level navigations.
2638 if (!frame
->parent()) {
2639 base::string16 title16
= title
;
2640 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2641 routing_id_
, base::UTF16ToUTF8(title16
));
2643 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2644 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2645 shortened_title
, direction
));
2648 // Also check whether we have new encoding name.
2649 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2652 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2653 blink::WebIconURL::Type icon_type
) {
2654 DCHECK(!frame_
|| frame_
== frame
);
2655 // TODO(nasko): Investigate wheather implementation should move here.
2656 render_view_
->didChangeIcon(frame
, icon_type
);
2659 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2660 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2662 DCHECK(!frame_
|| frame_
== frame
);
2663 WebDataSource
* ds
= frame
->dataSource();
2664 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2665 document_state
->set_finish_document_load_time(Time::Now());
2667 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2669 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2670 DidFinishDocumentLoad(frame
));
2671 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2673 // Check whether we have new encoding name.
2674 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2677 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2678 DCHECK(!frame_
|| frame_
== frame
);
2679 if (!frame
->parent()) {
2680 FrameMsg_UILoadMetricsReportType::Value report_type
=
2681 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2682 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2683 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2684 base::TimeDelta::FromSecondsD(
2685 frame
->dataSource()->request().uiStartTime());
2687 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2688 routing_id_
, report_type
, ui_timestamp
));
2692 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2693 const blink::WebURLError
& error
) {
2694 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2696 DCHECK(!frame_
|| frame_
== frame
);
2697 // TODO(nasko): Move implementation here. No state needed.
2698 WebDataSource
* ds
= frame
->dataSource();
2701 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2702 DidFailLoad(frame
, error
));
2704 const WebURLRequest
& failed_request
= ds
->request();
2705 base::string16 error_description
;
2706 GetContentClient()->renderer()->GetNavigationErrorStrings(
2712 &error_description
);
2713 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2714 failed_request
.url(),
2716 error_description
));
2719 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2720 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2722 DCHECK(!frame_
|| frame_
== frame
);
2723 WebDataSource
* ds
= frame
->dataSource();
2724 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2725 if (document_state
->finish_load_time().is_null()) {
2726 if (!frame
->parent()) {
2727 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2728 TRACE_EVENT_SCOPE_PROCESS
);
2730 document_state
->set_finish_load_time(Time::Now());
2733 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2734 DidFinishLoad(frame
));
2735 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2737 // Don't send this message while the frame is swapped out.
2738 if (is_swapped_out())
2741 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2742 ds
->request().url()));
2745 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2746 const blink::WebHistoryItem
& item
,
2747 blink::WebHistoryCommitType commit_type
) {
2748 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2750 DCHECK(!frame_
|| frame_
== frame
);
2751 // If this was a reference fragment navigation that we initiated, then we
2752 // could end up having a non-null pending navigation params. We just need to
2753 // update the ExtraData on the datasource so that others who read the
2754 // ExtraData will get the new NavigationState. Similarly, if we did not
2755 // initiate this navigation, then we need to take care to reset any pre-
2756 // existing navigation state to a content-initiated navigation state.
2757 // DidCreateDataSource conveniently takes care of this for us.
2758 didCreateDataSource(frame
, frame
->dataSource());
2760 DocumentState
* document_state
=
2761 DocumentState::FromDataSource(frame
->dataSource());
2762 NavigationState
* new_state
= document_state
->navigation_state();
2763 new_state
->set_was_within_same_page(true);
2765 didCommitProvisionalLoad(frame
, item
, commit_type
);
2768 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2769 DCHECK(!frame_
|| frame_
== frame
);
2770 // TODO(nasko): Move implementation here. Needed methods:
2771 // * StartNavStateSyncTimerIfNecessary
2772 render_view_
->didUpdateCurrentHistoryItem(frame
);
2775 void RenderFrameImpl::addNavigationTransitionData(
2776 const blink::WebTransitionElementData
& data
) {
2777 FrameHostMsg_AddNavigationTransitionData_Params params
;
2778 params
.render_frame_id
= routing_id_
;
2779 params
.allowed_destination_host_pattern
=
2781 params
.selector
= data
.selector
.utf8();
2782 params
.markup
= data
.markup
.utf8();
2783 params
.elements
.resize(data
.elements
.size());
2784 for (size_t i
= 0; i
< data
.elements
.size(); i
++) {
2785 params
.elements
[i
].id
= data
.elements
[i
].id
.utf8();
2786 params
.elements
[i
].rect
= gfx::Rect(data
.elements
[i
].rect
);
2789 Send(new FrameHostMsg_AddNavigationTransitionData(params
));
2792 void RenderFrameImpl::didChangeThemeColor() {
2793 if (frame_
->parent())
2796 Send(new FrameHostMsg_DidChangeThemeColor(
2797 routing_id_
, frame_
->document().themeColor()));
2800 void RenderFrameImpl::dispatchLoad() {
2801 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
2804 void RenderFrameImpl::requestNotificationPermission(
2805 const blink::WebSecurityOrigin
& origin
,
2806 blink::WebNotificationPermissionCallback
* callback
) {
2807 if (!notification_permission_dispatcher_
) {
2808 notification_permission_dispatcher_
=
2809 new NotificationPermissionDispatcher(this);
2812 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
2815 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
2816 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
2819 if (is_empty_selection
)
2820 selection_text_
.clear();
2822 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2823 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2824 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2825 // to notify the selection was changed. Focus change should be notified
2826 // before selection change.
2827 GetRenderWidget()->UpdateTextInputType();
2828 SyncSelectionIfRequired();
2829 #if defined(OS_ANDROID)
2830 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
2831 RenderWidget::FROM_NON_IME
);
2835 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
2836 blink::WebColorChooserClient
* client
,
2837 const blink::WebColor
& initial_color
,
2838 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
2839 RendererWebColorChooserImpl
* color_chooser
=
2840 new RendererWebColorChooserImpl(this, client
);
2841 std::vector
<ColorSuggestion
> color_suggestions
;
2842 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
2843 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
2845 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
2846 return color_chooser
;
2849 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
2850 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
2853 frame_
->document().url(),
2857 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
2858 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
2861 frame_
->document().url(),
2865 bool RenderFrameImpl::runModalPromptDialog(
2866 const blink::WebString
& message
,
2867 const blink::WebString
& default_value
,
2868 blink::WebString
* actual_value
) {
2869 base::string16 result
;
2870 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
2873 frame_
->document().url(),
2876 actual_value
->assign(result
);
2880 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2882 const blink::WebString
& message
) {
2883 // If we are swapping out, we have already run the beforeunload handler.
2884 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2885 // at all, to avoid running it twice.
2886 if (is_swapped_out_
)
2889 // Don't allow further dialogs if we are waiting to swap out, since the
2890 // PageGroupLoadDeferrer in our stack prevents it.
2891 if (render_view()->suppress_dialogs_until_swap_out_
)
2894 bool success
= false;
2895 // This is an ignored return value, but is included so we can accept the same
2896 // response as RunJavaScriptMessage.
2897 base::string16 ignored_result
;
2898 render_view()->SendAndRunNestedMessageLoop(
2899 new FrameHostMsg_RunBeforeUnloadConfirm(
2900 routing_id_
, frame_
->document().url(), message
, is_reload
,
2901 &success
, &ignored_result
));
2905 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
2906 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
2907 params
.source_type
= GetRenderWidget()->context_menu_source_type();
2908 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
2909 if (GetRenderWidget()->has_host_context_menu_location()) {
2910 params
.x
= GetRenderWidget()->host_context_menu_location().x();
2911 params
.y
= GetRenderWidget()->host_context_menu_location().y();
2914 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2915 // it. We replace it with an empty GURL so the appropriate items are disabled
2916 // in the context menu.
2917 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2918 // data encoded images. We should have a way to save them.
2919 if (params
.src_url
.spec().size() > GetMaxURLChars())
2920 params
.src_url
= GURL();
2921 context_menu_node_
= data
.node
;
2923 #if defined(OS_ANDROID)
2924 gfx::Rect start_rect
;
2926 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
2927 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
2928 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
2931 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
2934 void RenderFrameImpl::clearContextMenu() {
2935 context_menu_node_
.reset();
2938 void RenderFrameImpl::willSendRequest(
2939 blink::WebLocalFrame
* frame
,
2940 unsigned identifier
,
2941 blink::WebURLRequest
& request
,
2942 const blink::WebURLResponse
& redirect_response
) {
2943 DCHECK(!frame_
|| frame_
== frame
);
2944 // The request my be empty during tests.
2945 if (request
.url().isEmpty())
2948 // Set the first party for cookies url if it has not been set yet (new
2949 // requests). For redirects, it is updated by WebURLLoaderImpl.
2950 if (request
.firstPartyForCookies().isEmpty()) {
2951 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
2952 request
.setFirstPartyForCookies(request
.url());
2954 // TODO(nasko): When the top-level frame is remote, there is no document.
2955 // This is broken and should be fixed to propagate the first party.
2956 WebFrame
* top
= frame
->top();
2957 if (top
->isWebLocalFrame()) {
2958 request
.setFirstPartyForCookies(
2959 frame
->top()->document().firstPartyForCookies());
2964 WebFrame
* top_frame
= frame
->top();
2965 // TODO(nasko): Hack around asking about top-frame data source. This means
2966 // for out-of-process iframes we are treating the current frame as the
2967 // top-level frame, which is wrong.
2968 if (!top_frame
|| top_frame
->isWebRemoteFrame())
2970 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
2971 WebDataSource
* top_data_source
= top_frame
->dataSource();
2972 WebDataSource
* data_source
=
2973 provisional_data_source
? provisional_data_source
: top_data_source
;
2975 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
2976 DCHECK(document_state
);
2977 InternalDocumentStateData
* internal_data
=
2978 InternalDocumentStateData::FromDocumentState(document_state
);
2979 NavigationState
* navigation_state
= document_state
->navigation_state();
2980 ui::PageTransition transition_type
= navigation_state
->transition_type();
2981 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
2982 if (frame_ds
&& frame_ds
->isClientRedirect()) {
2983 transition_type
= ui::PageTransitionFromInt(
2984 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
2987 GURL
request_url(request
.url());
2989 if (GetContentClient()->renderer()->WillSendRequest(
2993 request
.firstPartyForCookies(),
2995 request
.setURL(WebURL(new_url
));
2998 if (internal_data
->is_cache_policy_override_set())
2999 request
.setCachePolicy(internal_data
->cache_policy_override());
3001 // The request's extra data may indicate that we should set a custom user
3002 // agent. This needs to be done here, after WebKit is through with setting the
3003 // user agent on its own. Similarly, it may indicate that we should set an
3004 // X-Requested-With header. This must be done here to avoid breaking CORS
3006 // PlzNavigate: there may also be a stream url associated with the request.
3007 WebString custom_user_agent
;
3008 WebString requested_with
;
3009 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3010 if (request
.extraData()) {
3011 RequestExtraData
* old_extra_data
=
3012 static_cast<RequestExtraData
*>(request
.extraData());
3014 custom_user_agent
= old_extra_data
->custom_user_agent();
3015 if (!custom_user_agent
.isNull()) {
3016 if (custom_user_agent
.isEmpty())
3017 request
.clearHTTPHeaderField("User-Agent");
3019 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3022 requested_with
= old_extra_data
->requested_with();
3023 if (!requested_with
.isNull()) {
3024 if (requested_with
.isEmpty())
3025 request
.clearHTTPHeaderField("X-Requested-With");
3027 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3029 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3032 // Add the default accept header for frame request if it has not been set
3034 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3035 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3036 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3037 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3038 WebString::fromUTF8(kDefaultAcceptHeader
));
3041 // Add an empty HTTP origin header for non GET methods if none is currently
3043 request
.addHTTPOriginIfNeeded(WebString());
3045 // Attach |should_replace_current_entry| state to requests so that, should
3046 // this navigation later require a request transfer, all state is preserved
3047 // when it is re-created in the new process.
3048 bool should_replace_current_entry
= false;
3049 if (navigation_state
->is_content_initiated()) {
3050 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3052 // If the navigation is browser-initiated, the NavigationState contains the
3053 // correct value instead of the WebDataSource.
3055 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3056 // NavigationState::should_replace_current_entry().
3057 should_replace_current_entry
=
3058 navigation_state
->should_replace_current_entry();
3061 int provider_id
= kInvalidServiceWorkerProviderId
;
3062 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3063 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3064 // |provisionalDataSource| may be null in some content::ResourceFetcher
3065 // use cases, we don't hook those requests.
3066 if (frame
->provisionalDataSource()) {
3067 ServiceWorkerNetworkProvider
* provider
=
3068 ServiceWorkerNetworkProvider::FromDocumentState(
3069 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3070 provider_id
= provider
->provider_id();
3072 } else if (frame
->dataSource()) {
3073 ServiceWorkerNetworkProvider
* provider
=
3074 ServiceWorkerNetworkProvider::FromDocumentState(
3075 DocumentState::FromDataSource(frame
->dataSource()));
3076 provider_id
= provider
->provider_id();
3079 WebFrame
* parent
= frame
->parent();
3080 int parent_routing_id
= MSG_ROUTING_NONE
;
3082 parent_routing_id
= -1;
3083 } else if (parent
->isWebLocalFrame()) {
3084 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3086 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3089 RequestExtraData
* extra_data
= new RequestExtraData();
3090 extra_data
->set_visibility_state(render_view_
->visibilityState());
3091 extra_data
->set_custom_user_agent(custom_user_agent
);
3092 extra_data
->set_requested_with(requested_with
);
3093 extra_data
->set_render_frame_id(routing_id_
);
3094 extra_data
->set_is_main_frame(!parent
);
3095 extra_data
->set_frame_origin(
3096 GURL(frame
->document().securityOrigin().toString()));
3097 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3098 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3099 extra_data
->set_allow_download(navigation_state
->allow_download());
3100 extra_data
->set_transition_type(transition_type
);
3101 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3102 extra_data
->set_transferred_request_child_id(
3103 navigation_state
->transferred_request_child_id());
3104 extra_data
->set_transferred_request_request_id(
3105 navigation_state
->transferred_request_request_id());
3106 extra_data
->set_service_worker_provider_id(provider_id
);
3107 extra_data
->set_stream_override(stream_override
.Pass());
3108 request
.setExtraData(extra_data
);
3110 DocumentState
* top_document_state
=
3111 DocumentState::FromDataSource(top_data_source
);
3112 if (top_document_state
) {
3113 // TODO(gavinp): separate out prefetching and prerender field trials
3114 // if the rel=prerender rel type is sticking around.
3115 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3116 top_document_state
->set_was_prefetcher(true);
3119 // This is an instance where we embed a copy of the routing id
3120 // into the data portion of the message. This can cause problems if we
3121 // don't register this id on the browser side, since the download manager
3122 // expects to find a RenderViewHost based off the id.
3123 request
.setRequestorID(render_view_
->GetRoutingID());
3124 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3126 if (!navigation_state
->extra_headers().empty()) {
3127 for (net::HttpUtil::HeadersIterator
i(
3128 navigation_state
->extra_headers().begin(),
3129 navigation_state
->extra_headers().end(), "\n");
3131 if (LowerCaseEqualsASCII(i
.name(), "referer")) {
3132 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3133 blink::WebReferrerPolicyDefault
,
3135 WebString::fromUTF8(i
.values()));
3136 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3138 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3139 WebString::fromUTF8(i
.values()));
3144 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3145 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3148 void RenderFrameImpl::didReceiveResponse(
3149 blink::WebLocalFrame
* frame
,
3150 unsigned identifier
,
3151 const blink::WebURLResponse
& response
) {
3152 DCHECK(!frame_
|| frame_
== frame
);
3153 // Only do this for responses that correspond to a provisional data source
3154 // of the top-most frame. If we have a provisional data source, then we
3155 // can't have any sub-resources yet, so we know that this response must
3156 // correspond to a frame load.
3157 if (!frame
->provisionalDataSource() || frame
->parent())
3160 // If we are in view source mode, then just let the user see the source of
3161 // the server's error page.
3162 if (frame
->isViewSourceModeEnabled())
3165 DocumentState
* document_state
=
3166 DocumentState::FromDataSource(frame
->provisionalDataSource());
3167 int http_status_code
= response
.httpStatusCode();
3169 // Record page load flags.
3170 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3172 document_state
->set_was_fetched_via_spdy(
3173 extra_data
->was_fetched_via_spdy());
3174 document_state
->set_was_npn_negotiated(
3175 extra_data
->was_npn_negotiated());
3176 document_state
->set_npn_negotiated_protocol(
3177 extra_data
->npn_negotiated_protocol());
3178 document_state
->set_was_alternate_protocol_available(
3179 extra_data
->was_alternate_protocol_available());
3180 document_state
->set_connection_info(
3181 extra_data
->connection_info());
3182 document_state
->set_was_fetched_via_proxy(
3183 extra_data
->was_fetched_via_proxy());
3184 document_state
->set_proxy_server(
3185 extra_data
->proxy_server());
3187 InternalDocumentStateData
* internal_data
=
3188 InternalDocumentStateData::FromDocumentState(document_state
);
3189 internal_data
->set_http_status_code(http_status_code
);
3190 // Whether or not the http status code actually corresponds to an error is
3191 // only checked when the page is done loading, if |use_error_page| is
3193 internal_data
->set_use_error_page(true);
3196 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3197 unsigned identifier
) {
3198 DCHECK(!frame_
|| frame_
== frame
);
3199 InternalDocumentStateData
* internal_data
=
3200 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3201 if (!internal_data
->use_error_page())
3204 // Do not show error page when DevTools is attached.
3205 if (render_view_
->devtools_agent_
->IsAttached())
3208 // Display error page, if appropriate.
3209 std::string error_domain
= "http";
3210 int http_status_code
= internal_data
->http_status_code();
3211 if (GetContentClient()->renderer()->HasErrorPage(
3212 http_status_code
, &error_domain
)) {
3214 error
.unreachableURL
= frame
->document().url();
3215 error
.domain
= WebString::fromUTF8(error_domain
);
3216 error
.reason
= http_status_code
;
3217 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3221 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3222 blink::WebLocalFrame
* frame
,
3223 const blink::WebURLRequest
& request
,
3224 const blink::WebURLResponse
& response
) {
3225 DCHECK(!frame_
|| frame_
== frame
);
3226 // The recipients of this message have no use for data: URLs: they don't
3227 // affect the page's insecure content list and are not in the disk cache. To
3228 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3229 // filter them out here.
3230 GURL
url(request
.url());
3231 if (url
.SchemeIs(url::kDataScheme
))
3234 // Let the browser know we loaded a resource from the memory cache. This
3235 // message is needed to display the correct SSL indicators.
3236 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3237 render_view_
->GetRoutingID(),
3239 response
.securityInfo(),
3240 request
.httpMethod().utf8(),
3241 response
.mimeType().utf8(),
3242 WebURLRequestToResourceType(request
)));
3245 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3246 DCHECK(!frame_
|| frame_
== frame
);
3247 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3248 render_view_
->GetRoutingID()));
3251 void RenderFrameImpl::didRunInsecureContent(
3252 blink::WebLocalFrame
* frame
,
3253 const blink::WebSecurityOrigin
& origin
,
3254 const blink::WebURL
& target
) {
3255 DCHECK(!frame_
|| frame_
== frame
);
3256 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3257 render_view_
->GetRoutingID(),
3258 origin
.toString().utf8(),
3262 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3263 DCHECK(!frame_
|| frame_
== frame
);
3264 #if defined(ENABLE_PLUGINS)
3265 if (frame
!= render_view_
->webview()->mainFrame())
3267 PluginChannelHost::Broadcast(
3268 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3272 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3273 v8::Handle
<v8::Context
> context
,
3274 int extension_group
,
3276 DCHECK(!frame_
|| frame_
== frame
);
3277 GetContentClient()->renderer()->DidCreateScriptContext(
3278 frame
, context
, extension_group
, world_id
);
3281 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3282 v8::Handle
<v8::Context
> context
,
3284 DCHECK(!frame_
|| frame_
== frame
);
3286 FOR_EACH_OBSERVER(RenderFrameObserver
,
3288 WillReleaseScriptContext(context
, world_id
));
3291 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3292 blink::WebLocalFrame
* frame
) {
3293 DCHECK(!frame_
|| frame_
== frame
);
3294 if (frame
->parent())
3297 InternalDocumentStateData
* data
=
3298 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3299 data
->set_did_first_visually_non_empty_layout(true);
3301 #if defined(OS_ANDROID)
3302 GetRenderWidget()->DidChangeBodyBackgroundColor(
3303 render_view_
->webwidget_
->backgroundColor());
3306 GetRenderWidget()->QueueMessage(
3307 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3308 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3311 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3312 DCHECK(!frame_
|| frame_
== frame
);
3313 // TODO(nasko): Move implementation here. Needed methods:
3314 // * StartNavStateSyncTimerIfNecessary
3315 render_view_
->didChangeScrollOffset(frame
);
3317 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3320 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3321 DCHECK(!frame_
|| frame_
== frame
);
3322 if (!frame
->parent()) {
3323 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3324 render_view_
->GetRoutingID()));
3328 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3330 bool final_update
) {
3331 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3333 active_match_ordinal
= 0;
3335 render_view_
->Send(new ViewHostMsg_Find_Reply(
3336 render_view_
->GetRoutingID(), request_id
, count
,
3337 gfx::Rect(), active_match_ordinal
, final_update
));
3340 void RenderFrameImpl::reportFindInPageSelection(
3342 int active_match_ordinal
,
3343 const blink::WebRect
& selection_rect
) {
3344 render_view_
->Send(new ViewHostMsg_Find_Reply(
3345 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3346 active_match_ordinal
, false));
3349 void RenderFrameImpl::requestStorageQuota(
3350 blink::WebLocalFrame
* frame
,
3351 blink::WebStorageQuotaType type
,
3352 unsigned long long requested_size
,
3353 blink::WebStorageQuotaCallbacks callbacks
) {
3354 DCHECK(!frame_
|| frame_
== frame
);
3355 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3356 if (origin
.isUnique()) {
3357 // Unique origins cannot store persistent state.
3358 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3361 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3362 render_view_
->GetRoutingID(),
3363 GURL(origin
.toString()),
3364 static_cast<storage::StorageType
>(type
),
3366 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3369 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3370 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3371 impl
->set_render_frame_id(routing_id_
);
3374 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3375 if (!geolocation_dispatcher_
)
3376 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3377 return geolocation_dispatcher_
;
3380 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3381 if (!presentation_dispatcher_
)
3382 presentation_dispatcher_
= new PresentationDispatcher(this);
3383 return presentation_dispatcher_
;
3386 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3387 if (!push_messaging_dispatcher_
)
3388 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3389 return push_messaging_dispatcher_
;
3392 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3393 blink::WebLocalFrame
* frame
,
3394 blink::WebRTCPeerConnectionHandler
* handler
) {
3395 DCHECK(!frame_
|| frame_
== frame
);
3396 #if defined(ENABLE_WEBRTC)
3397 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3401 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3402 if (!web_user_media_client_
)
3403 InitializeUserMediaClient();
3404 return web_user_media_client_
;
3407 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3408 if (!web_encrypted_media_client_
) {
3409 #if defined(ENABLE_PEPPER_CDMS)
3410 scoped_ptr
<media::CdmFactory
> cdm_factory(
3411 new RenderCdmFactory(base::Bind(PepperCdmWrapperImpl::Create
, frame_
)));
3412 #elif defined(ENABLE_BROWSER_CDMS)
3413 scoped_ptr
<media::CdmFactory
> cdm_factory(
3414 new RenderCdmFactory(GetCdmManager()));
3416 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
3419 if (!media_permission_dispatcher_
)
3420 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
3422 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3423 cdm_factory
.Pass(), media_permission_dispatcher_
));
3425 return web_encrypted_media_client_
.get();
3428 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3429 if (!midi_dispatcher_
)
3430 midi_dispatcher_
= new MidiDispatcher(this);
3431 return midi_dispatcher_
;
3434 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3435 blink::WebLocalFrame
* source_frame
,
3436 blink::WebFrame
* target_frame
,
3437 blink::WebSecurityOrigin target_origin
,
3438 blink::WebDOMMessageEvent event
) {
3439 DCHECK(!frame_
|| frame_
== target_frame
);
3441 if (!is_swapped_out_
)
3444 ViewMsg_PostMessage_Params params
;
3445 params
.is_data_raw_string
= false;
3446 params
.data
= event
.data().toString();
3447 params
.source_origin
= event
.origin();
3448 if (!target_origin
.isNull())
3449 params
.target_origin
= target_origin
.toString();
3451 params
.message_ports
=
3452 WebMessagePortChannelImpl::ExtractMessagePortIDs(event
.releaseChannels());
3454 // Include the routing ID for the source frame (if one exists), which the
3455 // browser process will translate into the routing ID for the equivalent
3456 // frame in the target process.
3457 params
.source_routing_id
= MSG_ROUTING_NONE
;
3459 RenderViewImpl
* source_view
=
3460 RenderViewImpl::FromWebView(source_frame
->view());
3462 params
.source_routing_id
= source_view
->routing_id();
3465 Send(new ViewHostMsg_RouteMessageEvent(render_view_
->routing_id_
, params
));
3469 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3470 const blink::WebURL
& url
) {
3471 DCHECK(!frame_
|| frame_
== frame
);
3472 std::string user_agent_override_for_url
=
3473 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3474 if (!user_agent_override_for_url
.empty())
3475 return WebString::fromUTF8(user_agent_override_for_url
);
3477 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3478 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3479 return blink::WebString();
3482 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3483 // associated with it, so the checks below are not valid. Temporarily
3484 // return early and fix properly as part of https://crbug.com/426555.
3485 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3486 return blink::WebString();
3488 // If we're in the middle of committing a load, the data source we need
3489 // will still be provisional.
3490 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3491 WebDataSource
* data_source
= NULL
;
3492 if (main_frame
->provisionalDataSource())
3493 data_source
= main_frame
->provisionalDataSource();
3495 data_source
= main_frame
->dataSource();
3497 InternalDocumentStateData
* internal_data
= data_source
?
3498 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3499 if (internal_data
&& internal_data
->is_overriding_user_agent())
3500 return WebString::fromUTF8(
3501 render_view_
->renderer_preferences_
.user_agent_override
);
3502 return blink::WebString();
3505 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3506 DCHECK(!frame_
|| frame_
== frame
);
3507 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3508 return WebString::fromUTF8("1");
3512 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3513 bool default_value
) {
3514 DCHECK(!frame_
|| frame_
== frame
);
3518 bool blocked
= true;
3519 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3520 render_view_
->GetRoutingID(),
3521 GURL(frame
->top()->document().securityOrigin().toString()),
3522 THREE_D_API_TYPE_WEBGL
,
3527 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3528 int arb_robustness_status_code
) {
3529 DCHECK(!frame_
|| frame_
== frame
);
3530 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3531 GURL(frame
->top()->document().securityOrigin().toString()),
3532 THREE_D_API_TYPE_WEBGL
,
3533 arb_robustness_status_code
));
3536 blink::WebScreenOrientationClient
*
3537 RenderFrameImpl::webScreenOrientationClient() {
3538 if (!screen_orientation_dispatcher_
)
3539 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3540 return screen_orientation_dispatcher_
;
3543 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3544 ServiceWorkerNetworkProvider
* provider
=
3545 ServiceWorkerNetworkProvider::FromDocumentState(
3546 DocumentState::FromDataSource(&data_source
));
3547 return provider
->context()->controller_handle_id() !=
3548 kInvalidServiceWorkerHandleId
;
3551 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3552 ServiceWorkerNetworkProvider
* provider
=
3553 ServiceWorkerNetworkProvider::FromDocumentState(
3554 DocumentState::FromDataSource(&data_source
));
3556 if (provider
->context()->controller())
3557 return provider
->context()->controller()->version_id();
3558 return kInvalidServiceWorkerVersionId
;
3561 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3562 blink::WebAXEvent event
) {
3563 HandleWebAccessibilityEvent(obj
, event
);
3566 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3569 const blink::WebAXObject
& start_object
,
3571 const blink::WebAXObject
& end_object
,
3573 if (renderer_accessibility_
) {
3574 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3575 identifier
, match_index
, start_object
, start_offset
,
3576 end_object
, end_offset
);
3580 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3581 DCHECK(!frame_
|| frame_
== frame
);
3583 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3586 bool RenderFrameImpl::enterFullscreen() {
3587 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3591 bool RenderFrameImpl::exitFullscreen() {
3592 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3596 void RenderFrameImpl::suddenTerminationDisablerChanged(
3598 blink::WebFrameClient::SuddenTerminationDisablerType type
) {
3600 case blink::WebFrameClient::BeforeUnloadHandler
:
3601 Send(new FrameHostMsg_BeforeUnloadHandlersPresent(
3602 routing_id_
, present
));
3604 case blink::WebFrameClient::UnloadHandler
:
3605 Send(new FrameHostMsg_UnloadHandlersPresent(
3606 routing_id_
, present
));
3613 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3614 Send(new FrameHostMsg_MediaPlayingNotification(
3615 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3616 player
->hasAudio(), player
->isRemote()));
3619 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3620 Send(new FrameHostMsg_MediaPausedNotification(
3621 routing_id_
, reinterpret_cast<int64
>(player
)));
3624 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3628 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3629 observers_
.AddObserver(observer
);
3632 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3633 observer
->RenderFrameGone();
3634 observers_
.RemoveObserver(observer
);
3637 void RenderFrameImpl::OnStop() {
3639 frame_
->stopLoading();
3640 if (!frame_
->parent())
3641 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3643 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3646 void RenderFrameImpl::WasHidden() {
3647 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3650 void RenderFrameImpl::WasShown() {
3651 // TODO(kenrb): Need to figure out how to do this better. Should
3652 // VisibilityState remain a page-level concept or move to frames?
3653 // The semantics of 'Show' might have to change here.
3654 if (render_widget_
) {
3655 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3656 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3658 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3661 bool RenderFrameImpl::IsHidden() {
3662 return GetRenderWidget()->is_hidden();
3665 // Tell the embedding application that the URL of the active page has changed.
3666 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3667 blink::WebFrame
* frame
,
3668 blink::WebHistoryCommitType commit_type
) {
3669 DCHECK(!frame_
|| frame_
== frame
);
3670 WebDataSource
* ds
= frame
->dataSource();
3673 const WebURLRequest
& request
= ds
->request();
3674 const WebURLResponse
& response
= ds
->response();
3676 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3677 NavigationState
* navigation_state
= document_state
->navigation_state();
3678 InternalDocumentStateData
* internal_data
=
3679 InternalDocumentStateData::FromDocumentState(document_state
);
3681 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3682 params
.http_status_code
= response
.httpStatusCode();
3683 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3684 params
.is_post
= false;
3685 params
.post_id
= -1;
3686 params
.page_id
= render_view_
->page_id_
;
3687 // We need to track the RenderViewHost routing_id because of downstream
3688 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3689 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3690 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3691 // based on the ID stored in the resource requests. Once those dependencies
3692 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3693 // client to be based on the routing_id of the RenderFrameHost.
3694 params
.render_view_routing_id
= render_view_
->routing_id();
3695 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3696 params
.socket_address
.set_port(response
.remotePort());
3697 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3699 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3700 params
.was_within_same_page
= navigation_state
->was_within_same_page();
3701 params
.security_info
= response
.securityInfo();
3703 // Set the URL to be displayed in the browser UI to the user.
3704 params
.url
= GetLoadingUrl();
3705 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3707 // Set the origin of the frame. This will be replicated to the corresponding
3708 // RenderFrameProxies in other processes.
3709 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3710 // to https://crbug.com/439608 and will be replicated as unique origins.
3711 if (!is_swapped_out_
) {
3712 WebString
serialized_origin(frame
->document().securityOrigin().toString());
3713 if (GURL(serialized_origin
).IsStandard())
3714 params
.origin
= url::Origin(serialized_origin
.utf8());
3717 if (frame
->document().baseURL() != params
.url
)
3718 params
.base_url
= frame
->document().baseURL();
3720 GetRedirectChain(ds
, ¶ms
.redirects
);
3721 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3722 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3724 params
.searchable_form_url
= internal_data
->searchable_form_url();
3725 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3727 params
.gesture
= render_view_
->navigation_gesture_
;
3728 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3730 // Make navigation state a part of the DidCommitProvisionalLoad message so
3731 // that committed entry has it at all times.
3732 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3734 params
.page_state
= HistoryEntryToPageState(entry
);
3736 params
.page_state
= PageState::CreateFromURL(request
.url());
3738 if (!frame
->parent()) {
3739 // Top-level navigation.
3741 // Reset the zoom limits in case a plugin had changed them previously. This
3742 // will also call us back which will cause us to send a message to
3743 // update WebContentsImpl.
3744 render_view_
->webview()->zoomLimitsChanged(
3745 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3746 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3748 // Set zoom level, but don't do it for full-page plugin since they don't use
3749 // the same zoom settings.
3750 HostZoomLevels::iterator host_zoom
=
3751 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3752 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3753 // Reset the zoom levels for plugins.
3754 render_view_
->webview()->setZoomLevel(0);
3756 // If the zoom level is not found, then do nothing. In-page navigation
3757 // relies on not changing the zoom level in this case.
3758 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3759 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3762 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3763 // This zoom level was merely recorded transiently for this load. We can
3764 // erase it now. If at some point we reload this page, the browser will
3765 // send us a new, up-to-date zoom level.
3766 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3769 // Update contents MIME type for main frame.
3770 params
.contents_mime_type
= ds
->response().mimeType().utf8();
3772 params
.transition
= navigation_state
->transition_type();
3773 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
3774 // If the main frame does a load, it should not be reported as a subframe
3775 // navigation. This can occur in the following case:
3776 // 1. You're on a site with frames.
3777 // 2. You do a subframe navigation. This is stored with transition type
3779 // 3. You navigate to some non-frame site, say, google.com.
3780 // 4. You navigate back to the page from step 2. Since it was initially
3781 // MANUAL_SUBFRAME, it will be that same transition type here.
3782 // We don't want that, because any navigation that changes the toplevel
3783 // frame should be tracked as a toplevel navigation (this allows us to
3784 // update the URL bar, etc).
3785 params
.transition
= ui::PAGE_TRANSITION_LINK
;
3788 // If the page contained a client redirect (meta refresh, document.loc...),
3789 // set the referrer and transition appropriately.
3790 if (ds
->isClientRedirect()) {
3792 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
3793 params
.transition
= ui::PageTransitionFromInt(
3794 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3796 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
3797 frame
, ds
->request());
3800 base::string16 method
= request
.httpMethod();
3801 if (EqualsASCII(method
, "POST")) {
3802 params
.is_post
= true;
3803 params
.post_id
= ExtractPostId(entry
);
3806 // Send the user agent override back.
3807 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
3809 // Track the URL of the original request. We use the first entry of the
3810 // redirect chain if it exists because the chain may have started in another
3812 params
.original_request_url
= GetOriginalRequestURL(ds
);
3814 params
.history_list_was_cleared
=
3815 navigation_state
->history_list_was_cleared();
3817 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
3818 frame
->dataSource()->request().inputPerfMetricReportPolicy());
3819 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
3820 frame
->dataSource()->request().uiStartTime());
3822 // Save some histogram data so we can compute the average memory used per
3823 // page load of the glyphs.
3824 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3825 blink::WebGlyphCache::pageCount());
3827 // This message needs to be sent before any of allowScripts(),
3828 // allowImages(), allowPlugins() is called for the new page, so that when
3829 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3830 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3831 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3833 // Subframe navigation: the type depends on whether this navigation
3834 // generated a new session history entry. When they do generate a session
3835 // history entry, it means the user initiated the navigation and we should
3837 if (commit_type
== blink::WebStandardCommit
)
3838 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
3840 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
3842 DCHECK(!navigation_state
->history_list_was_cleared());
3843 params
.history_list_was_cleared
= false;
3844 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
3846 // Don't send this message while the subframe is swapped out.
3847 if (!is_swapped_out())
3848 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3851 // If we end up reusing this WebRequest (for example, due to a #ref click),
3852 // we don't want the transition type to persist. Just clear it.
3853 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
3856 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
3857 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3859 render_view_
->FrameDidStartLoading(frame_
);
3860 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
3863 void RenderFrameImpl::didStopLoading() {
3864 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3866 render_view_
->FrameDidStopLoading(frame_
);
3867 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
3870 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
3871 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
3874 void RenderFrameImpl::HandleWebAccessibilityEvent(
3875 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
3876 if (renderer_accessibility_
)
3877 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
3880 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
3881 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
3884 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
3885 if (renderer_accessibility())
3886 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
3890 void RenderFrameImpl::OnCommitNavigation(
3891 const ResourceResponseHead
& response
,
3892 const GURL
& stream_url
,
3893 const CommonNavigationParams
& common_params
,
3894 const CommitNavigationParams
& commit_params
,
3895 const HistoryNavigationParams
& history_params
) {
3896 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3897 switches::kEnableBrowserSideNavigation
));
3898 bool is_reload
= false;
3899 bool is_history_navigation
= history_params
.page_state
.IsValid();
3900 WebURLRequest::CachePolicy cache_policy
=
3901 WebURLRequest::UseProtocolCachePolicy
;
3902 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3903 common_params
.url
, is_history_navigation
, history_params
, &is_reload
,
3908 GetContentClient()->SetActiveURL(common_params
.url
);
3910 if (!common_params
.base_url_for_data_url
.is_empty() ||
3911 common_params
.url
.SchemeIs(url::kDataScheme
)) {
3912 LoadDataURL(common_params
, frame_
);
3916 // Create a WebURLRequest that blink can use to get access to the body of the
3917 // response through a stream in the browser. Blink will then commit the
3919 // TODO(clamy): Have the navigation commit directly, without going through
3920 // loading a WebURLRequest.
3921 scoped_ptr
<StreamOverrideParameters
> stream_override(
3922 new StreamOverrideParameters());
3923 stream_override
->stream_url
= stream_url
;
3924 stream_override
->response
= response
;
3925 WebURLRequest request
=
3926 CreateURLRequestForNavigation(common_params
,
3927 stream_override
.Pass(),
3928 frame_
->isViewSourceModeEnabled());
3930 // Make sure that blink loader will not try to use browser side navigation for
3931 // this request (since it already went to the browser).
3932 request
.setCheckForBrowserSideNavigation(false);
3934 // Record this before starting the load. A lower bound of this time is needed
3935 // to sanitize the navigationStart override set below.
3936 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
3937 frame_
->loadRequest(request
);
3938 UpdateFrameNavigationTiming(
3939 frame_
, commit_params
.browser_navigation_start
,
3940 renderer_navigation_start
);
3943 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
3944 RenderFrame
* render_frame
,
3945 const NavigationPolicyInfo
& info
) {
3947 // The handlenavigation API is deprecated and will be removed once
3948 // crbug.com/325351 is resolved.
3949 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
3950 GetContentClient()->renderer()->HandleNavigation(
3952 static_cast<DocumentState
*>(info
.extraData
),
3953 render_view_
->opener_id_
,
3956 info
.navigationType
,
3959 return blink::WebNavigationPolicyIgnore
;
3963 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
3965 const base::CommandLine
& command_line
=
3966 *base::CommandLine::ForCurrentProcess();
3968 bool is_subframe
= !!info
.frame
->parent();
3970 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe
) {
3971 // There's no reason to ignore navigations on subframes, since the swap out
3972 // logic no longer applies.
3974 if (is_swapped_out_
) {
3975 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
3976 // Targeted links may try to navigate a swapped out frame. Allow the
3977 // browser process to navigate the tab instead. Note that it is also
3978 // possible for non-targeted navigations (from this view) to arrive
3979 // here just after we are swapped out. It's ok to send them to the
3980 // browser, as long as they're for the top level frame.
3981 // TODO(creis): Ensure this supports targeted form submissions when
3982 // fixing http://crbug.com/101395.
3983 if (info
.frame
->parent() == NULL
) {
3984 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
3985 info
.defaultPolicy
);
3986 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3989 // We should otherwise ignore in-process iframe navigations, if they
3990 // arrive just after we are swapped out.
3991 return blink::WebNavigationPolicyIgnore
;
3994 // Allow kSwappedOutURL to complete.
3995 return info
.defaultPolicy
;
3999 // Webkit is asking whether to navigate to a new URL.
4000 // This is fine normally, except if we're showing UI from one security
4001 // context and they're trying to navigate to a different context.
4002 const GURL
& url
= info
.urlRequest
.url();
4004 // A content initiated navigation may have originated from a link-click,
4005 // script, drag-n-drop operation, etc.
4006 bool is_content_initiated
= static_cast<DocumentState
*>(info
.extraData
)->
4007 navigation_state()->is_content_initiated();
4010 // If --enable-strict-site-isolation is enabled, send all top-level
4011 // navigations to the browser to let it swap processes when crossing site
4012 // boundaries. This is currently expected to break some script calls and
4013 // navigations, such as form submissions.
4014 bool force_swap_due_to_flag
=
4015 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
);
4016 if (force_swap_due_to_flag
&&
4017 !info
.frame
->parent() && (is_content_initiated
|| info
.isRedirect
)) {
4018 WebString origin_str
= info
.frame
->document().securityOrigin().toString();
4019 GURL
frame_url(origin_str
.utf8().data());
4020 // TODO(cevans): revisit whether this site check is still necessary once
4021 // crbug.com/101395 is fixed.
4022 bool same_domain_or_host
=
4023 net::registry_controlled_domains::SameDomainOrHost(
4026 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
4027 // Only keep same-site (domain + scheme) and data URLs in the same process.
4029 (same_domain_or_host
&& frame_url
.scheme() == url
.scheme()) ||
4030 url
.SchemeIs(url::kDataScheme
);
4031 if (!is_same_site
) {
4032 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4033 return blink::WebNavigationPolicyIgnore
;
4037 // If the browser is interested, then give it a chance to look at the request.
4038 if (is_content_initiated
) {
4040 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4041 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4042 EqualsASCII(info
.urlRequest
.httpMethod(), "POST");
4043 bool browser_handles_request
=
4044 render_view_
->renderer_preferences_
4045 .browser_handles_non_local_top_level_requests
4046 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4048 if (!browser_handles_request
) {
4049 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4050 render_view_
->renderer_preferences_
4051 .browser_handles_all_top_level_requests
;
4054 if (browser_handles_request
) {
4055 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4056 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4060 // Use the frame's original request's URL rather than the document's URL for
4061 // subsequent checks. For a popup, the document's URL may become the opener
4062 // window's URL if the opener has called document.write().
4063 // See http://crbug.com/93517.
4064 GURL
old_url(info
.frame
->dataSource()->request().url());
4066 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4067 // an extension or app origin, leaving a WebUI page, etc). We only care about
4068 // top-level navigations (not iframes). But we sometimes navigate to
4069 // about:blank to clear a tab, and we want to still allow that.
4071 // Note: this is known to break POST submissions when crossing process
4072 // boundaries until http://crbug.com/101395 is fixed. This is better for
4073 // security than loading a WebUI, extension or app page in the wrong process.
4074 // POST requests don't work because this mechanism does not preserve form
4075 // POST data. We will need to send the request's httpBody data up to the
4076 // browser process, and issue a special POST navigation in WebKit (via
4077 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4078 // for examples of how to send the httpBody data.
4079 if (!info
.frame
->parent() && is_content_initiated
&&
4080 !url
.SchemeIs(url::kAboutScheme
)) {
4081 bool send_referrer
= false;
4083 // All navigations to or from WebUI URLs or within WebUI-enabled
4084 // RenderProcesses must be handled by the browser process so that the
4085 // correct bindings and data sources can be registered.
4086 // Similarly, navigations to view-source URLs or within ViewSource mode
4087 // must be handled by the browser process (except for reloads - those are
4088 // safe to leave within the renderer).
4089 // Lastly, access to file:// URLs from non-file:// URL pages must be
4090 // handled by the browser so that ordinary renderer processes don't get
4091 // blessed with file permissions.
4092 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4093 bool is_initial_navigation
= render_view_
->page_id_
== -1;
4094 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4095 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4096 url
.SchemeIs(kViewSourceScheme
) ||
4097 (info
.frame
->isViewSourceModeEnabled() &&
4098 info
.navigationType
!= blink::WebNavigationTypeReload
);
4100 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4101 // Fork non-file to file opens. Check the opener URL if this is the
4102 // initial navigation in a newly opened window.
4103 GURL
source_url(old_url
);
4104 if (is_initial_navigation
&& source_url
.is_empty() &&
4105 info
.frame
->opener())
4106 source_url
= info
.frame
->opener()->top()->document().url();
4107 DCHECK(!source_url
.is_empty());
4108 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4112 // Give the embedder a chance.
4113 should_fork
= GetContentClient()->renderer()->ShouldFork(
4114 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4115 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4119 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4120 info
.defaultPolicy
);
4121 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4125 // Detect when a page is "forking" a new tab that can be safely rendered in
4126 // its own process. This is done by sites like Gmail that try to open links
4127 // in new windows without script connections back to the original page. We
4128 // treat such cases as browser navigations (in which we will create a new
4129 // renderer for a cross-site navigation), rather than WebKit navigations.
4131 // We use the following heuristic to decide whether to fork a new page in its
4133 // The parent page must open a new tab to about:blank, set the new tab's
4134 // window.opener to null, and then redirect the tab to a cross-site URL using
4137 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4140 // Must start from a tab showing about:blank, which is later redirected.
4141 old_url
== GURL(url::kAboutBlankURL
) &&
4142 // Must be the first real navigation of the tab.
4143 render_view_
->historyBackListCount() < 1 &&
4144 render_view_
->historyForwardListCount() < 1 &&
4145 // The parent page must have set the child's window.opener to null before
4146 // redirecting to the desired URL.
4147 info
.frame
->opener() == NULL
&&
4148 // Must be a top-level frame.
4149 info
.frame
->parent() == NULL
&&
4150 // Must not have issued the request from this page.
4151 is_content_initiated
&&
4152 // Must be targeted at the current tab.
4153 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4154 // Must be a JavaScript navigation, which appears as "other".
4155 info
.navigationType
== blink::WebNavigationTypeOther
;
4158 // Open the URL via the browser, not via WebKit.
4159 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4160 return blink::WebNavigationPolicyIgnore
;
4163 // PlzNavigate: send the request to the browser if needed.
4164 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4165 switches::kEnableBrowserSideNavigation
) &&
4166 info
.urlRequest
.checkForBrowserSideNavigation()) {
4167 BeginNavigation(&info
.urlRequest
);
4168 return blink::WebNavigationPolicyIgnore
;
4171 return info
.defaultPolicy
;
4174 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4176 const Referrer
& referrer
,
4177 WebNavigationPolicy policy
) {
4178 DCHECK_EQ(frame_
, frame
);
4180 FrameHostMsg_OpenURL_Params params
;
4182 params
.referrer
= referrer
;
4183 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4184 WebDataSource
* ds
= frame
->provisionalDataSource();
4186 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4187 NavigationState
* navigation_state
= document_state
->navigation_state();
4188 if (navigation_state
->is_content_initiated()) {
4189 params
.should_replace_current_entry
=
4190 ds
->replacesCurrentHistoryItem() &&
4191 render_view_
->history_list_length_
;
4193 // This is necessary to preserve the should_replace_current_entry value on
4194 // cross-process redirects, in the event it was set by a previous process.
4196 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4197 // NavigationState::should_replace_current_entry().
4198 params
.should_replace_current_entry
=
4199 navigation_state
->should_replace_current_entry();
4202 params
.should_replace_current_entry
= false;
4204 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4205 if (GetContentClient()->renderer()->AllowPopup())
4206 params
.user_gesture
= true;
4208 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4209 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4210 policy
== blink::WebNavigationPolicyNewWindow
||
4211 policy
== blink::WebNavigationPolicyNewPopup
) {
4212 WebUserGestureIndicator::consumeUserGesture();
4215 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4218 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4219 const std::string
& encoding_name
) {
4220 // Only update main frame's encoding_name.
4221 if (!frame
->parent())
4222 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4225 void RenderFrameImpl::SyncSelectionIfRequired() {
4226 base::string16 text
;
4229 #if defined(ENABLE_PLUGINS)
4230 if (render_view_
->focused_pepper_plugin_
) {
4231 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4232 offset
= 0; // Pepper API does not support offset reporting.
4233 // TODO(kinaba): cut as needed.
4237 size_t location
, length
;
4238 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4239 &location
, &length
)) {
4243 range
= gfx::Range(location
, location
+ length
);
4245 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4246 blink::WebTextInputTypeNone
) {
4247 // If current focused element is editable, we will send 100 more chars
4248 // before and after selection. It is for input method surrounding text
4250 if (location
> kExtraCharsBeforeAndAfterSelection
)
4251 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4254 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4255 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4256 if (!webrange
.isNull())
4257 text
= webrange
.toPlainText();
4260 text
= frame_
->selectionAsText();
4261 // http://crbug.com/101435
4262 // In some case, frame->selectionAsText() returned text's length is not
4263 // equal to the length returned from webwidget()->caretOrSelectionRange().
4264 // So we have to set the range according to text.length().
4265 range
.set_end(range
.start() + text
.length());
4269 // Sometimes we get repeated didChangeSelection calls from webkit when
4270 // the selection hasn't actually changed. We don't want to report these
4271 // because it will cause us to continually claim the X clipboard.
4272 if (selection_text_offset_
!= offset
||
4273 selection_range_
!= range
||
4274 selection_text_
!= text
) {
4275 selection_text_
= text
;
4276 selection_text_offset_
= offset
;
4277 selection_range_
= range
;
4278 SetSelectedText(text
, offset
, range
);
4280 GetRenderWidget()->UpdateSelectionBounds();
4283 void RenderFrameImpl::InitializeUserMediaClient() {
4284 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4287 #if defined(OS_ANDROID)
4288 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4289 switches::kDisableWebRTC
))
4293 #if defined(ENABLE_WEBRTC)
4294 DCHECK(!web_user_media_client_
);
4295 web_user_media_client_
= new UserMediaClientImpl(
4297 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4298 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4302 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4303 const blink::WebURL
& url
,
4304 WebMediaPlayerClient
* client
) {
4305 #if defined(ENABLE_WEBRTC)
4306 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4308 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4309 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4310 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4311 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4312 new RenderMediaLog(),
4313 CreateRendererFactory());
4316 #endif // defined(ENABLE_WEBRTC)
4319 scoped_ptr
<MediaStreamRendererFactory
>
4320 RenderFrameImpl::CreateRendererFactory() {
4321 #if defined(ENABLE_WEBRTC)
4322 return scoped_ptr
<MediaStreamRendererFactory
>(
4323 new MediaStreamRendererFactory());
4325 return scoped_ptr
<MediaStreamRendererFactory
>(
4326 static_cast<MediaStreamRendererFactory
*>(NULL
));
4330 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4332 bool is_history_navigation
,
4333 const HistoryNavigationParams
& history_params
,
4335 WebURLRequest::CachePolicy
* cache_policy
) {
4336 MaybeHandleDebugURL(url
);
4337 if (!render_view_
->webview())
4341 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4343 // If this is a stale back/forward (due to a recent navigation the browser
4344 // didn't know about), ignore it. Only check if swapped in because if the
4345 // frame is swapped out, it won't commit before asking the browser.
4346 if (!render_view_
->is_swapped_out() && is_history_navigation
&&
4347 render_view_
->history_list_offset_
!=
4348 history_params
.current_history_list_offset
) {
4352 render_view_
->history_list_offset_
=
4353 history_params
.current_history_list_offset
;
4354 render_view_
->history_list_length_
=
4355 history_params
.current_history_list_length
;
4356 if (history_params
.should_clear_history_list
) {
4357 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4358 CHECK_EQ(0, render_view_
->history_list_length_
);
4361 if (!is_swapped_out_
|| frame_
->parent())
4364 // This is a swapped out main frame, so swap the renderer back in.
4365 // We marked the view as hidden when swapping the view out, so be sure to
4366 // reset the visibility state before navigating to the new URL.
4367 render_view_
->webview()->setVisibilityState(
4368 render_view_
->visibilityState(), false);
4370 // If this is an attempt to reload while we are swapped out, we should not
4371 // reload swappedout://, but the previous page, which is stored in
4372 // params.state. Setting is_reload to false will treat this like a back
4373 // navigation to accomplish that.
4375 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4377 // We refresh timezone when a view is swapped in since timezone
4378 // can get out of sync when the system timezone is updated while
4379 // the view is swapped out.
4380 RenderThreadImpl::NotifyTimezoneChange();
4382 render_view_
->SetSwappedOut(false);
4383 is_swapped_out_
= false;
4387 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4388 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4389 switches::kEnableBrowserSideNavigation
));
4391 // TODO(clamy): Execute the beforeunload event.
4393 // Note: At this stage, the goal is to apply all the modifications the
4394 // renderer wants to make to the request, and then send it to the browser, so
4395 // that the actual network request can be started. Ideally, all such
4396 // modifications should take place in willSendRequest, and in the
4397 // implementation of willSendRequest for the various InspectorAgents
4400 // TODO(clamy): Apply devtools override.
4401 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4403 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4405 // TODO(clamy): Same-document navigations should not be sent back to the
4407 // TODO(clamy): Data urls should not be sent back to the browser either.
4408 Send(new FrameHostMsg_DidStartLoading(routing_id_
, true));
4409 Send(new FrameHostMsg_BeginNavigation(
4410 routing_id_
, MakeCommonNavigationParams(request
),
4411 BeginNavigationParams(request
->httpMethod().latin1(),
4412 GetWebURLRequestHeaders(*request
),
4413 GetLoadFlagsForWebURLRequest(*request
),
4414 request
->hasUserGesture()),
4415 GetRequestBodyForWebURLRequest(*request
)));
4418 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4420 // A loadData request with a specified base URL.
4421 std::string mime_type
, charset
, data
;
4422 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4423 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4424 params
.url
: params
.base_url_for_data_url
;
4426 WebData(data
.c_str(), data
.length()),
4427 WebString::fromUTF8(mime_type
),
4428 WebString::fromUTF8(charset
),
4430 params
.history_url_for_data_url
,
4433 CHECK(false) << "Invalid URL passed: "
4434 << params
.url
.possibly_invalid_spec();
4438 GURL
RenderFrameImpl::GetLoadingUrl() const {
4439 WebDataSource
* ds
= frame_
->dataSource();
4440 if (ds
->hasUnreachableURL())
4441 return ds
->unreachableURL();
4443 const WebURLRequest
& request
= ds
->request();
4444 return request
.url();
4447 #if defined(OS_ANDROID)
4449 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4450 const blink::WebURL
& url
,
4451 WebMediaPlayerClient
* client
,
4452 media::MediaPermission
* media_permission
,
4453 blink::WebContentDecryptionModule
* initial_cdm
) {
4454 GpuChannelHost
* gpu_channel_host
=
4455 RenderThreadImpl::current()->EstablishGpuChannelSync(
4456 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4457 if (!gpu_channel_host
) {
4458 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4462 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4463 if (SynchronousCompositorFactory
* factory
=
4464 SynchronousCompositorFactory::GetInstance()) {
4465 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4467 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4468 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4470 if (!context_provider
.get()) {
4471 LOG(ERROR
) << "Failed to get context3d for media player";
4475 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4476 context_provider
, gpu_channel_host
, routing_id_
);
4479 return new WebMediaPlayerAndroid(
4482 weak_factory_
.GetWeakPtr(),
4483 GetMediaPlayerManager(),
4487 stream_texture_factory
,
4488 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4489 new RenderMediaLog());
4492 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4493 if (!media_player_manager_
)
4494 media_player_manager_
= new RendererMediaPlayerManager(this);
4495 return media_player_manager_
;
4498 #endif // defined(OS_ANDROID)
4500 #if defined(ENABLE_BROWSER_CDMS)
4501 RendererCdmManager
* RenderFrameImpl::GetCdmManager() {
4503 cdm_manager_
= new RendererCdmManager(this);
4504 return cdm_manager_
;
4506 #endif // defined(ENABLE_BROWSER_CDMS)
4508 } // namespace content