1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h"
21 #include "cc/base/switches.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/permissions/permission_manager.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/navigation_state_impl.h"
88 #include "content/renderer/notification_permission_dispatcher.h"
89 #include "content/renderer/npapi/plugin_channel_host.h"
90 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
91 #include "content/renderer/presentation/presentation_dispatcher.h"
92 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
93 #include "content/renderer/render_frame_proxy.h"
94 #include "content/renderer/render_process.h"
95 #include "content/renderer/render_thread_impl.h"
96 #include "content/renderer/render_view_impl.h"
97 #include "content/renderer/render_widget_fullscreen_pepper.h"
98 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
99 #include "content/renderer/renderer_webcolorchooser_impl.h"
100 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
101 #include "content/renderer/shared_worker_repository.h"
102 #include "content/renderer/skia_benchmarking_extension.h"
103 #include "content/renderer/stats_collection_controller.h"
104 #include "content/renderer/web_ui_extension.h"
105 #include "content/renderer/websharedworker_proxy.h"
106 #include "gin/modules/module_registry.h"
107 #include "media/base/audio_renderer_mixer_input.h"
108 #include "media/base/media_log.h"
109 #include "media/blink/webencryptedmediaclient_impl.h"
110 #include "media/blink/webmediaplayer_impl.h"
111 #include "media/blink/webmediaplayer_params.h"
112 #include "media/renderers/gpu_video_accelerator_factories.h"
113 #include "net/base/data_url.h"
114 #include "net/base/net_errors.h"
115 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
116 #include "net/http/http_util.h"
117 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
118 #include "third_party/WebKit/public/platform/WebString.h"
119 #include "third_party/WebKit/public/platform/WebURL.h"
120 #include "third_party/WebKit/public/platform/WebURLError.h"
121 #include "third_party/WebKit/public/platform/WebURLResponse.h"
122 #include "third_party/WebKit/public/platform/WebVector.h"
123 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
124 #include "third_party/WebKit/public/web/WebDocument.h"
125 #include "third_party/WebKit/public/web/WebFrameWidget.h"
126 #include "third_party/WebKit/public/web/WebGlyphCache.h"
127 #include "third_party/WebKit/public/web/WebLocalFrame.h"
128 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
129 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
130 #include "third_party/WebKit/public/web/WebPlugin.h"
131 #include "third_party/WebKit/public/web/WebPluginParams.h"
132 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
133 #include "third_party/WebKit/public/web/WebRange.h"
134 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
135 #include "third_party/WebKit/public/web/WebScriptSource.h"
136 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
137 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
138 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
139 #include "third_party/WebKit/public/web/WebSurroundingText.h"
140 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
141 #include "third_party/WebKit/public/web/WebView.h"
142 #include "third_party/mojo/src/mojo/edk/js/core.h"
143 #include "third_party/mojo/src/mojo/edk/js/support.h"
145 #if defined(ENABLE_PLUGINS)
146 #include "content/renderer/npapi/webplugin_impl.h"
147 #include "content/renderer/pepper/pepper_browser_connection.h"
148 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
149 #include "content/renderer/pepper/pepper_webplugin_impl.h"
150 #include "content/renderer/pepper/plugin_module.h"
153 #if defined(ENABLE_WEBRTC)
154 #include "content/renderer/media/rtc_peer_connection_handler.h"
157 #if defined(OS_ANDROID)
158 #include <cpu-features.h>
160 #include "content/common/gpu/client/context_provider_command_buffer.h"
161 #include "content/renderer/android/synchronous_compositor_factory.h"
162 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
163 #include "content/renderer/media/android/renderer_media_player_manager.h"
164 #include "content/renderer/media/android/stream_texture_factory_impl.h"
165 #include "content/renderer/media/android/webmediaplayer_android.h"
167 #include "cc/blink/context_provider_web_context.h"
170 #if defined(ENABLE_PEPPER_CDMS)
171 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
172 #elif defined(ENABLE_BROWSER_CDMS)
173 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
176 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
177 #include "content/renderer/media/media_renderer_service_provider.h"
178 #include "media/mojo/services/mojo_renderer_factory.h"
180 #include "media/renderers/default_renderer_factory.h"
183 using blink::WebContextMenuData
;
184 using blink::WebData
;
185 using blink::WebDataSource
;
186 using blink::WebDocument
;
187 using blink::WebElement
;
188 using blink::WebExternalPopupMenu
;
189 using blink::WebExternalPopupMenuClient
;
190 using blink::WebFrame
;
191 using blink::WebHistoryItem
;
192 using blink::WebHTTPBody
;
193 using blink::WebLocalFrame
;
194 using blink::WebMediaPlayer
;
195 using blink::WebMediaPlayerClient
;
196 using blink::WebNavigationPolicy
;
197 using blink::WebNavigationType
;
198 using blink::WebNode
;
199 using blink::WebPluginParams
;
200 using blink::WebPopupMenuInfo
;
201 using blink::WebRange
;
202 using blink::WebReferrerPolicy
;
203 using blink::WebScriptSource
;
204 using blink::WebSearchableFormData
;
205 using blink::WebSecurityOrigin
;
206 using blink::WebSecurityPolicy
;
207 using blink::WebServiceWorkerProvider
;
208 using blink::WebStorageQuotaCallbacks
;
209 using blink::WebString
;
211 using blink::WebURLError
;
212 using blink::WebURLRequest
;
213 using blink::WebURLResponse
;
214 using blink::WebUserGestureIndicator
;
215 using blink::WebVector
;
216 using blink::WebView
;
218 using base::TimeDelta
;
224 const char kDefaultAcceptHeader
[] =
225 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
227 const char kAcceptHeader
[] = "Accept";
229 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
231 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
232 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
233 LAZY_INSTANCE_INITIALIZER
;
235 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
236 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
238 int64
ExtractPostId(HistoryEntry
* entry
) {
242 const WebHistoryItem
& item
= entry
->root();
243 if (item
.isNull() || item
.httpBody().isNull())
246 return item
.httpBody().identifier();
249 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
250 const WebURLResponse
& response
) {
251 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
254 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
255 // Replace any occurrences of swappedout:// with about:blank.
256 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
257 WebVector
<WebURL
> urls
;
258 ds
->redirectChain(urls
);
259 result
->reserve(urls
.size());
260 for (size_t i
= 0; i
< urls
.size(); ++i
) {
261 if (urls
[i
] != GURL(kSwappedOutURL
))
262 result
->push_back(urls
[i
]);
264 result
->push_back(blank_url
);
268 // Returns the original request url. If there is no redirect, the original
269 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
270 // frame was loaded by loadData, the original url will be ds->unreachableURL()
271 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
272 // WebDataSource has unreachable URL means that the frame is loaded through
273 // blink::WebFrame::loadData(), and the base URL will be in the redirect
274 // chain. However, we never visited the baseURL. So in this case, we should
275 // use the unreachable URL as the original URL.
276 if (ds
->hasUnreachableURL())
277 return ds
->unreachableURL();
279 std::vector
<GURL
> redirects
;
280 GetRedirectChain(ds
, &redirects
);
281 if (!redirects
.empty())
282 return redirects
.at(0);
284 return ds
->originalRequest().url();
287 NOINLINE
void CrashIntentionally() {
288 // NOTE(shess): Crash directly rather than using NOTREACHED() so
289 // that the signature is easier to triage in crash reports.
290 volatile int* zero
= NULL
;
294 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
295 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
296 // NOTE(rogerm): We intentionally perform an invalid heap access here in
297 // order to trigger an Address Sanitizer (ASAN) error report.
298 const char kCrashDomain
[] = "crash";
299 const char kHeapOverflow
[] = "/heap-overflow";
300 const char kHeapUnderflow
[] = "/heap-underflow";
301 const char kUseAfterFree
[] = "/use-after-free";
302 #if defined(SYZYASAN)
303 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
304 const char kCorruptHeap
[] = "/corrupt-heap";
307 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
313 std::string
crash_type(url
.path());
314 if (crash_type
== kHeapOverflow
) {
315 base::debug::AsanHeapOverflow();
316 } else if (crash_type
== kHeapUnderflow
) {
317 base::debug::AsanHeapUnderflow();
318 } else if (crash_type
== kUseAfterFree
) {
319 base::debug::AsanHeapUseAfterFree();
320 #if defined(SYZYASAN)
321 } else if (crash_type
== kCorruptHeapBlock
) {
322 base::debug::AsanCorruptHeapBlock();
323 } else if (crash_type
== kCorruptHeap
) {
324 base::debug::AsanCorruptHeap();
328 #endif // ADDRESS_SANITIZER || SYZYASAN
330 void MaybeHandleDebugURL(const GURL
& url
) {
331 if (!url
.SchemeIs(kChromeUIScheme
))
333 if (url
== GURL(kChromeUICrashURL
)) {
334 CrashIntentionally();
335 } else if (url
== GURL(kChromeUIDumpURL
)) {
336 // This URL will only correctly create a crash dump file if content is
337 // hosted in a process that has correctly called
338 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
339 // of base::debug::DumpWithoutCrashing for more details.
340 base::debug::DumpWithoutCrashing();
341 } else if (url
== GURL(kChromeUIKillURL
)) {
342 base::Process::Current().Terminate(1, false);
343 } else if (url
== GURL(kChromeUIHangURL
)) {
345 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
347 } else if (url
== GURL(kChromeUIShorthangURL
)) {
348 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
351 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
352 MaybeTriggerAsanError(url
);
353 #endif // ADDRESS_SANITIZER || SYZYASAN
356 // Returns false unless this is a top-level navigation.
357 bool IsTopLevelNavigation(WebFrame
* frame
) {
358 return frame
->parent() == NULL
;
361 // Returns false unless this is a top-level navigation that crosses origins.
362 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
364 WebNavigationType type
,
366 if (!IsTopLevelNavigation(frame
))
369 // Navigations initiated within Webkit are not sent out to the external host
370 // in the following cases.
371 // 1. The url scheme is not http/https
372 // 2. The origin of the url and the opener is the same in which case the
373 // opener relationship is maintained.
374 // 3. Reloads/form submits/back forward navigations
375 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
378 if (type
!= blink::WebNavigationTypeReload
&&
379 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
380 // The opener relationship between the new window and the parent allows the
381 // new window to script the parent and vice versa. This is not allowed if
382 // the origins of the two domains are different. This can be treated as a
383 // top level navigation and routed back to the host.
384 blink::WebFrame
* opener
= frame
->opener();
388 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
394 WebURLRequest
CreateURLRequestForNavigation(
395 const CommonNavigationParams
& common_params
,
396 scoped_ptr
<StreamOverrideParameters
> stream_override
,
397 bool is_view_source_mode_enabled
) {
398 WebURLRequest
request(common_params
.url
);
399 if (is_view_source_mode_enabled
)
400 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
402 if (common_params
.referrer
.url
.is_valid()) {
403 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
404 common_params
.referrer
.policy
,
406 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
407 if (!web_referrer
.isEmpty())
408 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
411 RequestExtraData
* extra_data
= new RequestExtraData();
412 extra_data
->set_stream_override(stream_override
.Pass());
413 request
.setExtraData(extra_data
);
415 // Set the ui timestamp for this navigation. Currently the timestamp here is
416 // only non empty when the navigation was triggered by an Android intent. The
417 // timestamp is converted to a double version supported by blink. It will be
418 // passed back to the browser in the DidCommitProvisionalLoad and the
419 // DocumentLoadComplete IPCs.
420 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
421 request
.setUiStartTime(ui_timestamp
.InSecondsF());
422 request
.setInputPerfMetricReportPolicy(
423 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
424 common_params
.report_type
));
428 void UpdateFrameNavigationTiming(WebFrame
* frame
,
429 base::TimeTicks browser_navigation_start
,
430 base::TimeTicks renderer_navigation_start
) {
431 // The browser provides the navigation_start time to bootstrap the
432 // Navigation Timing information for the browser-initiated navigations. In
433 // case of cross-process navigations, this carries over the time of
434 // finishing the onbeforeunload handler of the previous page.
435 DCHECK(!browser_navigation_start
.is_null());
436 if (frame
->provisionalDataSource()) {
437 // |browser_navigation_start| is likely before this process existed, so we
438 // can't use InterProcessTimeTicksConverter. We need at least to ensure
439 // that the browser-side navigation start we set is not later than the one
440 // on the renderer side.
441 base::TimeTicks navigation_start
= std::min(
442 browser_navigation_start
, renderer_navigation_start
);
443 double navigation_start_seconds
=
444 (navigation_start
- base::TimeTicks()).InSecondsF();
445 frame
->provisionalDataSource()->setNavigationStartTime(
446 navigation_start_seconds
);
447 // TODO(clamy): We need to provide additional timing values for the
448 // Navigation Timing API to work with browser-side navigations.
453 CommonNavigationParams
MakeCommonNavigationParams(
454 blink::WebURLRequest
* request
) {
455 const RequestExtraData kEmptyData
;
456 const RequestExtraData
* extra_data
=
457 static_cast<RequestExtraData
*>(request
->extraData());
459 extra_data
= &kEmptyData
;
461 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
462 request
->referrerPolicy());
464 // Set the ui timestamp for this navigation. Currently the timestamp here is
465 // only non empty when the navigation was triggered by an Android intent, or
466 // by the user clicking on a link. The timestamp is converted from a double
467 // version supported by blink. It will be passed back to the renderer in the
468 // CommitNavigation IPC, and then back to the browser again in the
469 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
470 base::TimeTicks ui_timestamp
=
471 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
472 FrameMsg_UILoadMetricsReportType::Value report_type
=
473 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
474 request
->inputPerfMetricReportPolicy());
475 return CommonNavigationParams(request
->url(), referrer
,
476 extra_data
->transition_type(),
477 FrameMsg_Navigate_Type::NORMAL
, true,
478 ui_timestamp
, report_type
, GURL(), GURL());
481 #if !defined(OS_ANDROID)
482 media::Context3D
GetSharedMainThreadContext3D() {
483 cc::ContextProvider
* provider
=
484 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
486 return media::Context3D();
487 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
491 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
494 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
496 static_cast<int>(content_name) == static_cast<int>(blink_name), \
497 "enum values must match")
499 // Check that blink::WebSandboxFlags is kept in sync with
500 // content::SandboxFlags.
501 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE
,
502 blink::WebSandboxFlags::None
);
503 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION
,
504 blink::WebSandboxFlags::Navigation
);
505 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS
,
506 blink::WebSandboxFlags::Plugins
);
507 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN
,
508 blink::WebSandboxFlags::Origin
);
509 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS
,
510 blink::WebSandboxFlags::Forms
);
511 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS
,
512 blink::WebSandboxFlags::Scripts
);
513 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION
,
514 blink::WebSandboxFlags::TopNavigation
);
515 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS
,
516 blink::WebSandboxFlags::Popups
);
517 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES
,
518 blink::WebSandboxFlags::AutomaticFeatures
);
519 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK
,
520 blink::WebSandboxFlags::PointerLock
);
521 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN
,
522 blink::WebSandboxFlags::DocumentDomain
);
523 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK
,
524 blink::WebSandboxFlags::OrientationLock
);
525 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL
,
526 blink::WebSandboxFlags::All
);
531 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
533 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
535 if (g_create_render_frame_impl
)
536 return g_create_render_frame_impl(render_view
, routing_id
);
538 return new RenderFrameImpl(render_view
, routing_id
);
542 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int32 routing_id
) {
543 RoutingIDFrameMap::iterator iter
=
544 g_routing_id_frame_map
.Get().find(routing_id
);
545 if (iter
!= g_routing_id_frame_map
.Get().end())
551 void RenderFrameImpl::CreateFrame(
553 int parent_routing_id
,
554 int proxy_routing_id
,
555 const FrameReplicationState
& replicated_state
,
556 CompositorDependencies
* compositor_deps
,
557 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
558 // TODO(nasko): For now, this message is only sent for subframes, as the
559 // top level frame is created when the RenderView is created through the
561 CHECK_NE(MSG_ROUTING_NONE
, parent_routing_id
);
563 blink::WebLocalFrame
* web_frame
;
564 RenderFrameImpl
* render_frame
;
565 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
566 RenderFrameProxy
* parent_proxy
=
567 RenderFrameProxy::FromRoutingID(parent_routing_id
);
568 // If the browser is sending a valid parent routing id, it should already
569 // be created and registered.
571 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
573 // Create the RenderFrame and WebLocalFrame, linking the two.
575 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
576 web_frame
= parent_web_frame
->createLocalChild(
577 WebString::fromUTF8(replicated_state
.name
),
578 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
), render_frame
);
580 RenderFrameProxy
* proxy
=
581 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
583 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
584 web_frame
= blink::WebLocalFrame::create(render_frame
);
585 render_frame
->proxy_routing_id_
= proxy_routing_id
;
586 web_frame
->initializeToReplaceRemoteFrame(
587 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
588 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
));
590 render_frame
->SetWebFrame(web_frame
);
592 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
593 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
594 switches::kSitePerProcess
));
595 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
596 widget_params
.routing_id
, widget_params
.surface_id
,
597 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
598 compositor_deps
, web_frame
);
599 // TODO(kenrb): Observing shouldn't be necessary when we sort out
600 // WasShown and WasHidden, separating page-level visibility from
601 // frame-level visibility.
602 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
605 render_frame
->Initialize();
609 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
610 return RenderFrameImpl::FromWebFrame(web_frame
);
614 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
615 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
616 if (iter
!= g_frame_map
.Get().end())
622 void RenderFrameImpl::InstallCreateHook(
623 CreateRenderFrameImplFunction create_render_frame_impl
) {
624 CHECK(!g_create_render_frame_impl
);
625 g_create_render_frame_impl
= create_render_frame_impl
;
629 content::SandboxFlags
RenderFrameImpl::WebToContentSandboxFlags(
630 blink::WebSandboxFlags flags
) {
631 return static_cast<content::SandboxFlags
>(flags
);
635 blink::WebSandboxFlags
RenderFrameImpl::ContentToWebSandboxFlags(
636 content::SandboxFlags flags
) {
637 return static_cast<blink::WebSandboxFlags
>(flags
);
640 // RenderFrameImpl ----------------------------------------------------------
641 RenderFrameImpl::RenderFrameImpl(RenderViewImpl
* render_view
, int routing_id
)
643 render_view_(render_view
->AsWeakPtr()),
644 routing_id_(routing_id
),
645 is_swapped_out_(false),
646 render_frame_proxy_(NULL
),
647 is_detaching_(false),
648 proxy_routing_id_(MSG_ROUTING_NONE
),
649 #if defined(ENABLE_PLUGINS)
650 plugin_power_saver_helper_(NULL
),
653 selection_text_offset_(0),
654 selection_range_(gfx::Range::InvalidRange()),
655 handling_select_range_(false),
656 notification_permission_dispatcher_(NULL
),
657 web_user_media_client_(NULL
),
658 media_permission_dispatcher_(NULL
),
659 midi_dispatcher_(NULL
),
660 #if defined(OS_ANDROID)
661 media_player_manager_(NULL
),
663 #if defined(ENABLE_BROWSER_CDMS)
666 #if defined(VIDEO_HOLE)
667 contains_media_player_(false),
669 geolocation_dispatcher_(NULL
),
670 push_messaging_dispatcher_(NULL
),
671 presentation_dispatcher_(NULL
),
672 screen_orientation_dispatcher_(NULL
),
673 manifest_manager_(NULL
),
674 accessibility_mode_(AccessibilityModeOff
),
675 renderer_accessibility_(NULL
),
676 weak_factory_(this) {
677 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
678 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
679 CHECK(result
.second
) << "Inserting a duplicate item.";
681 RenderThread::Get()->AddRoute(routing_id_
, this);
683 render_view_
->RegisterRenderFrame(this);
685 // Everything below subclasses RenderFrameObserver and is automatically
686 // deleted when the RenderFrame gets deleted.
687 #if defined(OS_ANDROID)
688 new GinJavaBridgeDispatcher(this);
691 #if defined(ENABLE_PLUGINS)
692 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
695 manifest_manager_
= new ManifestManager(this);
698 RenderFrameImpl::~RenderFrameImpl() {
699 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
700 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
702 #if defined(VIDEO_HOLE)
703 if (contains_media_player_
)
704 render_view_
->UnregisterVideoHoleFrame(this);
707 if (render_frame_proxy_
)
708 delete render_frame_proxy_
;
710 render_view_
->UnregisterRenderFrame(this);
711 g_routing_id_frame_map
.Get().erase(routing_id_
);
712 RenderThread::Get()->RemoveRoute(routing_id_
);
715 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
718 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
719 std::make_pair(web_frame
, this));
720 CHECK(result
.second
) << "Inserting a duplicate item.";
725 void RenderFrameImpl::Initialize() {
726 #if defined(ENABLE_PLUGINS)
727 new PepperBrowserConnection(this);
729 new SharedWorkerRepository(this);
731 if (!frame_
->parent())
732 new ImageLoadingHelper(this);
734 // We delay calling this until we have the WebFrame so that any observer or
735 // embedder can call GetWebFrame on any RenderFrame.
736 GetContentClient()->renderer()->RenderFrameCreated(this);
739 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
740 return render_view_
.get();
743 #if defined(ENABLE_PLUGINS)
744 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
745 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
746 DidCreatePepperPlugin(host
));
747 if (host
->GetPluginName() == kFlashPluginName
) {
748 RenderThread::Get()->RecordAction(
749 base::UserMetricsAction("FrameLoadWithFlash"));
753 void RenderFrameImpl::PepperDidChangeCursor(
754 PepperPluginInstanceImpl
* instance
,
755 const blink::WebCursorInfo
& cursor
) {
756 // Update the cursor appearance immediately if the requesting plugin is the
757 // one which receives the last mouse event. Otherwise, the new cursor won't be
758 // picked up until the plugin gets the next input event. That is bad if, e.g.,
759 // the plugin would like to set an invisible cursor when there isn't any user
760 // input for a while.
761 if (instance
== render_view_
->pepper_last_mouse_event_target())
762 GetRenderWidget()->didChangeCursor(cursor
);
765 void RenderFrameImpl::PepperDidReceiveMouseEvent(
766 PepperPluginInstanceImpl
* instance
) {
767 render_view_
->set_pepper_last_mouse_event_target(instance
);
770 void RenderFrameImpl::PepperTextInputTypeChanged(
771 PepperPluginInstanceImpl
* instance
) {
772 if (instance
!= render_view_
->focused_pepper_plugin())
775 GetRenderWidget()->UpdateTextInputType();
777 FocusedNodeChangedForAccessibility(WebNode());
780 void RenderFrameImpl::PepperCaretPositionChanged(
781 PepperPluginInstanceImpl
* instance
) {
782 if (instance
!= render_view_
->focused_pepper_plugin())
784 GetRenderWidget()->UpdateSelectionBounds();
787 void RenderFrameImpl::PepperCancelComposition(
788 PepperPluginInstanceImpl
* instance
) {
789 if (instance
!= render_view_
->focused_pepper_plugin())
791 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
792 #if defined(OS_MACOSX) || defined(USE_AURA)
793 GetRenderWidget()->UpdateCompositionInfo(true);
797 void RenderFrameImpl::PepperSelectionChanged(
798 PepperPluginInstanceImpl
* instance
) {
799 if (instance
!= render_view_
->focused_pepper_plugin())
801 SyncSelectionIfRequired();
804 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
805 PepperPluginInstanceImpl
* plugin
) {
807 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
808 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
809 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
810 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
811 plugin
, active_url
, GetRenderWidget()->screenInfo());
812 widget
->show(blink::WebNavigationPolicyIgnore
);
816 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
817 if (!render_view_
->focused_pepper_plugin())
819 return render_view_
->focused_pepper_plugin()->
820 IsPluginAcceptingCompositionEvents();
823 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
824 base::ProcessId plugin_pid
) {
825 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
826 // routing_id_ as a result.
827 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
830 void RenderFrameImpl::SimulateImeSetComposition(
831 const base::string16
& text
,
832 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
835 render_view_
->OnImeSetComposition(
836 text
, underlines
, selection_start
, selection_end
);
839 void RenderFrameImpl::SimulateImeConfirmComposition(
840 const base::string16
& text
,
841 const gfx::Range
& replacement_range
) {
842 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
845 void RenderFrameImpl::OnImeSetComposition(
846 const base::string16
& text
,
847 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
850 // When a PPAPI plugin has focus, we bypass WebKit.
851 if (!IsPepperAcceptingCompositionEvents()) {
852 pepper_composition_text_
= text
;
854 // TODO(kinaba) currently all composition events are sent directly to
855 // plugins. Use DOM event mechanism after WebKit is made aware about
856 // plugins that support composition.
857 // The code below mimics the behavior of WebCore::Editor::setComposition.
859 // Empty -> nonempty: composition started.
860 if (pepper_composition_text_
.empty() && !text
.empty()) {
861 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
864 // Nonempty -> empty: composition canceled.
865 if (!pepper_composition_text_
.empty() && text
.empty()) {
866 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
869 pepper_composition_text_
= text
;
870 // Nonempty: composition is ongoing.
871 if (!pepper_composition_text_
.empty()) {
872 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
873 pepper_composition_text_
, underlines
, selection_start
,
879 void RenderFrameImpl::OnImeConfirmComposition(
880 const base::string16
& text
,
881 const gfx::Range
& replacement_range
,
882 bool keep_selection
) {
883 // When a PPAPI plugin has focus, we bypass WebKit.
884 // Here, text.empty() has a special meaning. It means to commit the last
885 // update of composition text (see
886 // RenderWidgetHost::ImeConfirmComposition()).
887 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
890 // last_text is empty only when both text and pepper_composition_text_ is.
892 if (last_text
.empty())
895 if (!IsPepperAcceptingCompositionEvents()) {
896 base::i18n::UTF16CharIterator
iterator(&last_text
);
898 while (iterator
.Advance()) {
899 blink::WebKeyboardEvent char_event
;
900 char_event
.type
= blink::WebInputEvent::Char
;
901 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
902 char_event
.modifiers
= 0;
903 char_event
.windowsKeyCode
= last_text
[i
];
904 char_event
.nativeKeyCode
= last_text
[i
];
906 const int32 char_start
= i
;
907 for (; i
< iterator
.array_pos(); ++i
) {
908 char_event
.text
[i
- char_start
] = last_text
[i
];
909 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
912 if (GetRenderWidget()->webwidget())
913 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
916 // Mimics the order of events sent by WebKit.
917 // See WebCore::Editor::setComposition() for the corresponding code.
918 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
919 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
921 pepper_composition_text_
.clear();
923 #endif // defined(ENABLE_PLUGINS)
925 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
926 if (!web_user_media_client_
)
927 InitializeUserMediaClient();
928 return web_user_media_client_
?
929 web_user_media_client_
->media_stream_dispatcher() : NULL
;
932 bool RenderFrameImpl::Send(IPC::Message
* message
) {
937 if (is_swapped_out_
) {
938 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
944 return RenderThread::Get()->Send(message
);
947 #if defined(OS_MACOSX) || defined(OS_ANDROID)
948 void RenderFrameImpl::DidHideExternalPopupMenu() {
949 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
950 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
951 external_popup_menu_
.reset();
955 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
956 // We may get here while detaching, when the WebFrame has been deleted. Do
957 // not process any messages in this state.
961 // TODO(kenrb): document() should not be null, but as a transitional step
962 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
963 // to this method. This happens for a top-level remote frame, where a
964 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
965 // around and is still able to receive messages.
966 if (!frame_
->document().isNull())
967 GetContentClient()->SetActiveURL(frame_
->document().url());
969 ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
970 RenderFrameObserver
* observer
;
971 while ((observer
= it
.GetNext()) != NULL
) {
972 if (observer
->OnMessageReceived(msg
))
977 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
978 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
979 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
980 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
981 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
982 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
983 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
984 OnCustomContextMenuAction
)
985 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
986 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
987 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
988 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
989 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
990 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
991 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
992 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
993 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
994 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
995 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
996 OnMoveRangeSelectionExtent
)
997 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
998 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
999 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1000 OnExtendSelectionAndDelete
)
1001 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1002 OnSetCompositionFromExistingText
)
1003 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1004 OnExecuteNoValueEditCommand
)
1005 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1006 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1007 OnJavaScriptExecuteRequest
)
1008 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1009 OnJavaScriptExecuteRequestForTests
)
1010 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1011 OnVisualStateRequest
)
1012 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1013 OnSetEditableSelectionOffsets
)
1014 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView
, OnSetupTransitionView
)
1015 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition
, OnBeginExitTransition
)
1016 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition
, OnRevertExitTransition
)
1017 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements
,
1018 OnHideTransitionElements
)
1019 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements
,
1020 OnShowTransitionElements
)
1021 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1022 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1023 OnTextSurroundingSelectionRequest
)
1024 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL
,
1025 OnAddStyleSheetByURL
)
1026 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1027 OnSetAccessibilityMode
)
1028 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1029 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1030 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1031 #if defined(OS_ANDROID)
1032 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1033 #elif defined(OS_MACOSX)
1034 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1035 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1037 IPC_END_MESSAGE_MAP()
1042 void RenderFrameImpl::OnNavigate(
1043 const CommonNavigationParams
& common_params
,
1044 const StartNavigationParams
& start_params
,
1045 const CommitNavigationParams
& commit_params
,
1046 const HistoryNavigationParams
& history_params
) {
1047 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1048 "url", common_params
.url
.possibly_invalid_spec());
1050 bool is_reload
= RenderViewImpl::IsReload(common_params
.navigation_type
);
1051 bool is_history_navigation
= history_params
.page_state
.IsValid();
1052 WebURLRequest::CachePolicy cache_policy
=
1053 WebURLRequest::UseProtocolCachePolicy
;
1054 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1055 common_params
.url
, is_history_navigation
, history_params
, &is_reload
,
1057 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
1061 GetContentClient()->SetActiveURL(common_params
.url
);
1063 WebFrame
* frame
= frame_
;
1064 if (!commit_params
.frame_to_navigate
.empty()) {
1065 // TODO(nasko): Move this lookup to the browser process.
1066 frame
= render_view_
->webview()->findFrameByName(
1067 WebString::fromUTF8(commit_params
.frame_to_navigate
));
1068 CHECK(frame
) << "Invalid frame name passed: "
1069 << commit_params
.frame_to_navigate
;
1072 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
1073 // We cannot reload if we do not have any history state. This happens, for
1074 // example, when recovering from a crash.
1076 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1079 render_view_
->pending_navigation_params_
.reset(new NavigationParams(
1080 common_params
, start_params
, commit_params
, history_params
));
1082 // If we are reloading, then WebKit will use the history state of the current
1083 // page, so we should just ignore any given history state. Otherwise, if we
1084 // have history state, then we need to navigate to it, which corresponds to a
1085 // back/forward navigation event.
1087 bool reload_original_url
=
1088 (common_params
.navigation_type
==
1089 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1090 bool ignore_cache
= (common_params
.navigation_type
==
1091 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1093 if (reload_original_url
)
1094 frame
->reloadWithOverrideURL(common_params
.url
, true);
1096 frame
->reload(ignore_cache
);
1097 } else if (is_history_navigation
) {
1098 // We must know the page ID of the page we are navigating back to.
1099 DCHECK_NE(history_params
.page_id
, -1);
1100 scoped_ptr
<HistoryEntry
> entry
=
1101 PageStateToHistoryEntry(history_params
.page_state
);
1103 // Ensure we didn't save the swapped out URL in UpdateState, since the
1104 // browser should never be telling us to navigate to swappedout://.
1105 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
1106 render_view_
->history_controller()->GoToEntry(entry
.Pass(), cache_policy
);
1108 } else if (!common_params
.base_url_for_data_url
.is_empty()) {
1109 LoadDataURL(common_params
, frame
);
1111 // Navigate to the given URL.
1112 WebURLRequest request
= CreateURLRequestForNavigation(
1113 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
1114 frame
->isViewSourceModeEnabled());
1116 if (!start_params
.extra_headers
.empty()) {
1117 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
1118 start_params
.extra_headers
.end(),
1121 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
1122 WebString::fromUTF8(i
.values()));
1126 if (start_params
.is_post
) {
1127 request
.setHTTPMethod(WebString::fromUTF8("POST"));
1130 WebHTTPBody http_body
;
1131 http_body
.initialize();
1132 const char* data
= NULL
;
1133 if (start_params
.browser_initiated_post_data
.size()) {
1134 data
= reinterpret_cast<const char*>(
1135 &start_params
.browser_initiated_post_data
.front());
1137 http_body
.appendData(
1138 WebData(data
, start_params
.browser_initiated_post_data
.size()));
1139 request
.setHTTPBody(http_body
);
1142 // A session history navigation should have been accompanied by state.
1143 CHECK_EQ(history_params
.page_id
, -1);
1145 // Record this before starting the load, we need a lower bound of this time
1146 // to sanitize the navigationStart override set below.
1147 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
1148 frame
->loadRequest(request
);
1150 UpdateFrameNavigationTiming(frame
, commit_params
.browser_navigation_start
,
1151 renderer_navigation_start
);
1154 // In case LoadRequest failed before DidCreateDataSource was called.
1155 render_view_
->pending_navigation_params_
.reset();
1158 void RenderFrameImpl::NavigateToSwappedOutURL() {
1159 // We use loadRequest instead of loadHTMLString because the former commits
1160 // synchronously. Otherwise a new navigation can interrupt the navigation
1161 // to kSwappedOutURL. If that happens to be to the page we had been
1162 // showing, then WebKit will never send a commit and we'll be left spinning.
1163 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1164 // the navigation to swappedout:// is not announced to the browser side.
1165 is_swapped_out_
= true;
1166 GURL
swappedOutURL(kSwappedOutURL
);
1167 WebURLRequest
request(swappedOutURL
);
1168 frame_
->loadRequest(request
);
1171 void RenderFrameImpl::BindServiceRegistry(
1172 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1173 mojo::ServiceProviderPtr exposed_services
) {
1174 service_registry_
.Bind(services
.Pass());
1175 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1178 ManifestManager
* RenderFrameImpl::manifest_manager() {
1179 return manifest_manager_
;
1182 void RenderFrameImpl::OnBeforeUnload() {
1183 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1185 // TODO(creis): Right now, this is only called on the main frame. Make the
1186 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1188 CHECK(!frame_
->parent());
1190 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1191 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1192 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1193 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1194 before_unload_start_time
,
1195 before_unload_end_time
));
1198 void RenderFrameImpl::OnSwapOut(
1199 int proxy_routing_id
,
1201 const FrameReplicationState
& replicated_frame_state
) {
1202 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1203 RenderFrameProxy
* proxy
= NULL
;
1204 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1205 switches::kSitePerProcess
);
1206 bool is_main_frame
= !frame_
->parent();
1208 // Only run unload if we're not swapped out yet, but send the ack either way.
1209 if (!is_swapped_out_
) {
1210 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1211 // a different process. This involves running the unload handler and
1212 // clearing the page. We also allow this process to exit if there are no
1213 // other active RenderFrames in it.
1215 // Send an UpdateState message before we get swapped out.
1216 render_view_
->SyncNavigationState();
1218 // If we need a proxy to replace this, create it now so its routing id is
1219 // registered for receiving IPC messages.
1220 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1221 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(this,
1225 // Synchronously run the unload handler before sending the ACK.
1226 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1227 // unload on subframes as well.
1229 frame_
->dispatchUnloadEvent();
1231 // Swap out and stop sending any IPC messages that are not ACKs.
1233 render_view_
->SetSwappedOut(true);
1234 is_swapped_out_
= true;
1236 // Now that we're swapped out and filtering IPC messages, stop loading to
1237 // ensure that no other in-progress navigation continues. We do this here
1238 // to avoid sending a DidStopLoading message to the browser process.
1239 // TODO(creis): Should we be stopping all frames here and using
1240 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1244 // Transfer settings such as initial drawing parameters to the remote frame,
1245 // if one is created, that will replace this frame.
1246 if (!is_main_frame
&& proxy
)
1247 proxy
->web_frame()->initializeFromFrame(frame_
);
1249 // Replace the page with a blank dummy URL. The unload handler will not be
1250 // run a second time, thanks to a check in FrameLoader::stopLoading.
1251 // TODO(creis): Need to add a better way to do this that avoids running the
1252 // beforeunload handler. For now, we just run it a second time silently.
1253 if (!is_site_per_process
|| is_main_frame
)
1254 NavigateToSwappedOutURL();
1256 // Let WebKit know that this view is hidden so it can drop resources and
1257 // stop compositing.
1258 // TODO(creis): Support this for subframes as well.
1259 if (is_main_frame
) {
1260 render_view_
->webview()->setVisibilityState(
1261 blink::WebPageVisibilityStateHidden
, false);
1265 // It is now safe to show modal dialogs again.
1266 // TODO(creis): Deal with modal dialogs from subframes.
1268 render_view_
->suppress_dialogs_until_swap_out_
= false;
1270 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1272 // Now that all of the cleanup is complete and the browser side is notified,
1273 // start using the RenderFrameProxy, if one is created.
1275 if (!is_main_frame
) {
1276 frame_
->swap(proxy
->web_frame());
1279 proxy
->OnDidStartLoading();
1281 if (is_site_per_process
) {
1282 // TODO(nasko): delete the frame here, since we've replaced it with a
1286 set_render_frame_proxy(proxy
);
1290 // In --site-per-process, initialize the WebRemoteFrame with the replication
1291 // state passed by the process that is now rendering the frame.
1292 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1293 // in that case we leave the LocalFrame as the main frame visible to Blink
1294 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1295 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1296 // When we do an unconditional swap for all frames, we can remove
1297 // !is_main_frame below.
1298 if (is_site_per_process
&& proxy
&& !is_main_frame
)
1299 proxy
->SetReplicatedState(replicated_frame_state
);
1301 // Safe to exit if no one else is using the process.
1303 render_view_
->WasSwappedOut();
1306 void RenderFrameImpl::OnContextMenuClosed(
1307 const CustomContextMenuContext
& custom_context
) {
1308 if (custom_context
.request_id
) {
1309 // External request, should be in our map.
1310 ContextMenuClient
* client
=
1311 pending_context_menus_
.Lookup(custom_context
.request_id
);
1313 client
->OnMenuClosed(custom_context
.request_id
);
1314 pending_context_menus_
.Remove(custom_context
.request_id
);
1317 if (custom_context
.link_followed
.is_valid()) {
1319 DomUtils::ExtractParentAnchorNode(context_menu_node_
),
1320 custom_context
.link_followed
);
1322 // Internal request, forward to WebKit.
1323 context_menu_node_
.reset();
1327 void RenderFrameImpl::OnCustomContextMenuAction(
1328 const CustomContextMenuContext
& custom_context
,
1330 if (custom_context
.request_id
) {
1331 // External context menu request, look in our map.
1332 ContextMenuClient
* client
=
1333 pending_context_menus_
.Lookup(custom_context
.request_id
);
1335 client
->OnMenuAction(custom_context
.request_id
, action
);
1337 // Internal request, forward to WebKit.
1338 render_view_
->webview()->performCustomContextMenuAction(action
);
1342 void RenderFrameImpl::OnUndo() {
1343 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1346 void RenderFrameImpl::OnRedo() {
1347 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1350 void RenderFrameImpl::OnCut() {
1351 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1352 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1355 void RenderFrameImpl::OnCopy() {
1356 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1357 WebNode current_node
= context_menu_node_
.isNull() ?
1358 GetFocusedElement() : context_menu_node_
;
1359 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1362 void RenderFrameImpl::OnPaste() {
1363 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1364 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1367 void RenderFrameImpl::OnPasteAndMatchStyle() {
1368 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1369 frame_
->executeCommand(
1370 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1373 #if defined(OS_MACOSX)
1374 void RenderFrameImpl::OnCopyToFindPboard() {
1375 // Since the find pasteboard supports only plain text, this can be simpler
1376 // than the |OnCopy()| case.
1377 if (frame_
->hasSelection()) {
1378 base::string16 selection
= frame_
->selectionAsText();
1379 RenderThread::Get()->Send(
1380 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1385 void RenderFrameImpl::OnDelete() {
1386 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1389 void RenderFrameImpl::OnSelectAll() {
1390 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1391 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1394 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1395 const gfx::Point
& extent
) {
1396 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1397 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1399 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1400 frame_
->selectRange(base
, extent
);
1403 void RenderFrameImpl::OnUnselect() {
1404 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1405 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1408 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1409 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1410 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1411 GetRenderWidget()->routing_id()));
1413 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1414 frame_
->moveRangeSelectionExtent(point
);
1417 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1418 if (!frame_
->hasSelection())
1419 frame_
->selectWordAroundCaret();
1421 frame_
->replaceSelection(text
);
1424 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1425 if (!frame_
->hasSelection())
1428 frame_
->replaceMisspelledRange(text
);
1431 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1432 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1435 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1436 const base::string16
& jscript
,
1438 bool notify_result
) {
1439 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1440 TRACE_EVENT_SCOPE_THREAD
);
1442 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1443 v8::Handle
<v8::Value
> result
=
1444 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1446 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1449 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1450 const base::string16
& jscript
,
1452 bool notify_result
) {
1453 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1454 TRACE_EVENT_SCOPE_THREAD
);
1456 // A bunch of tests expect to run code in the context of a user gesture, which
1457 // can grant additional privileges (e.g. the ability to create popups).
1458 blink::WebScopedUserGesture gesture
;
1459 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1460 v8::Handle
<v8::Value
> result
=
1461 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1463 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1466 void RenderFrameImpl::HandleJavascriptExecutionResult(
1467 const base::string16
& jscript
,
1470 v8::Handle
<v8::Value
> result
) {
1471 if (notify_result
) {
1472 base::ListValue list
;
1473 if (!result
.IsEmpty()) {
1474 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1475 v8::Context::Scope
context_scope(context
);
1476 V8ValueConverterImpl converter
;
1477 converter
.SetDateAllowed(true);
1478 converter
.SetRegExpAllowed(true);
1479 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
1480 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
1482 list
.Set(0, base::Value::CreateNullValue());
1484 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1488 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1489 GetRenderWidget()->QueueMessage(
1490 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1491 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1494 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1495 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1496 if (!GetRenderWidget()->ShouldHandleImeEvent())
1498 ImeEventGuard
guard(GetRenderWidget());
1499 frame_
->setEditableSelectionOffsets(start
, end
);
1502 void RenderFrameImpl::OnSetCompositionFromExistingText(
1504 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1505 if (!GetRenderWidget()->ShouldHandleImeEvent())
1507 ImeEventGuard
guard(GetRenderWidget());
1508 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1511 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1512 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1515 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1516 if (!GetRenderWidget()->ShouldHandleImeEvent())
1518 ImeEventGuard
guard(GetRenderWidget());
1519 frame_
->extendSelectionAndDelete(before
, after
);
1522 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1523 if (accessibility_mode_
== new_mode
)
1525 accessibility_mode_
= new_mode
;
1526 if (renderer_accessibility_
) {
1527 // Note: this isn't called automatically by the destructor because
1528 // there'd be no point in calling it in frame teardown, only if there's
1529 // an accessibility mode change but the frame is persisting.
1530 renderer_accessibility_
->DisableAccessibility();
1532 delete renderer_accessibility_
;
1533 renderer_accessibility_
= NULL
;
1535 if (accessibility_mode_
== AccessibilityModeOff
)
1538 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1539 renderer_accessibility_
= new RendererAccessibility(this);
1542 void RenderFrameImpl::OnDisownOpener() {
1543 // TODO(creis): We should only see this for main frames for now. To support
1544 // disowning the opener on subframes, we will need to move WebContentsImpl's
1545 // opener_ to FrameTreeNode.
1546 CHECK(!frame_
->parent());
1548 if (frame_
->opener())
1549 frame_
->setOpener(NULL
);
1552 void RenderFrameImpl::OnDidUpdateSandboxFlags(SandboxFlags flags
) {
1553 frame_
->setFrameOwnerSandboxFlags(ContentToWebSandboxFlags(flags
));
1556 #if defined(OS_ANDROID)
1557 void RenderFrameImpl::OnSelectPopupMenuItems(
1559 const std::vector
<int>& selected_indices
) {
1560 // It is possible to receive more than one of these calls if the user presses
1561 // a select faster than it takes for the show-select-popup IPC message to make
1562 // it to the browser UI thread. Ignore the extra-messages.
1563 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1564 if (!external_popup_menu_
)
1567 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1568 external_popup_menu_
.reset();
1572 #if defined(OS_MACOSX)
1573 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1574 if (external_popup_menu_
== NULL
)
1576 external_popup_menu_
->DidSelectItem(selected_index
);
1577 external_popup_menu_
.reset();
1581 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1582 frame_
->reload(ignore_cache
);
1585 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1586 blink::WebSurroundingText surroundingText
;
1587 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1589 if (surroundingText
.isNull()) {
1590 // |surroundingText| might not be correctly initialized, for example if
1591 // |frame_->selectionRange().isNull()|, in other words, if there was no
1593 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1594 routing_id_
, base::string16(), 0, 0));
1598 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1600 surroundingText
.textContent(),
1601 surroundingText
.startOffsetInTextContent(),
1602 surroundingText
.endOffsetInTextContent()));
1605 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string
& url
) {
1606 frame_
->addStyleSheetByURL(WebString::fromUTF8(url
));
1609 void RenderFrameImpl::OnSetupTransitionView(const std::string
& markup
) {
1610 frame_
->document().setIsTransitionDocument(true);
1611 frame_
->navigateToSandboxedMarkup(WebData(markup
.data(), markup
.length()));
1614 void RenderFrameImpl::OnBeginExitTransition(const std::string
& css_selector
,
1615 bool exit_to_native_app
) {
1616 frame_
->document().setIsTransitionDocument(true);
1617 frame_
->document().beginExitTransition(WebString::fromUTF8(css_selector
),
1618 exit_to_native_app
);
1621 void RenderFrameImpl::OnRevertExitTransition() {
1622 frame_
->document().setIsTransitionDocument(false);
1623 frame_
->document().revertExitTransition();
1626 void RenderFrameImpl::OnHideTransitionElements(
1627 const std::string
& css_selector
) {
1628 frame_
->document().hideTransitionElements(WebString::fromUTF8(css_selector
));
1631 void RenderFrameImpl::OnShowTransitionElements(
1632 const std::string
& css_selector
) {
1633 frame_
->document().showTransitionElements(WebString::fromUTF8(css_selector
));
1636 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1637 const base::string16
& message
,
1638 const base::string16
& default_value
,
1639 const GURL
& frame_url
,
1640 base::string16
* result
) {
1641 // Don't allow further dialogs if we are waiting to swap out, since the
1642 // PageGroupLoadDeferrer in our stack prevents it.
1643 if (render_view()->suppress_dialogs_until_swap_out_
)
1646 bool success
= false;
1647 base::string16 result_temp
;
1649 result
= &result_temp
;
1651 render_view()->SendAndRunNestedMessageLoop(
1652 new FrameHostMsg_RunJavaScriptMessage(
1653 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1658 void RenderFrameImpl::LoadNavigationErrorPage(
1659 const WebURLRequest
& failed_request
,
1660 const WebURLError
& error
,
1662 std::string error_html
;
1663 GetContentClient()->renderer()->GetNavigationErrorStrings(
1664 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1666 frame_
->loadHTMLString(error_html
,
1667 GURL(kUnreachableWebDataURL
),
1668 error
.unreachableURL
,
1672 void RenderFrameImpl::DidCommitCompositorFrame() {
1673 if (BrowserPluginManager::Get())
1674 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1676 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1679 RenderView
* RenderFrameImpl::GetRenderView() {
1680 return render_view_
.get();
1683 int RenderFrameImpl::GetRoutingID() {
1687 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1692 WebElement
RenderFrameImpl::GetFocusedElement() const {
1693 WebDocument doc
= frame_
->document();
1695 return doc
.focusedElement();
1697 return WebElement();
1700 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1701 return render_view_
->GetWebkitPreferences();
1704 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1705 const ContextMenuParams
& params
) {
1706 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1707 ContextMenuParams
our_params(params
);
1708 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1709 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1710 return our_params
.custom_context
.request_id
;
1713 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1714 DCHECK(pending_context_menus_
.Lookup(request_id
));
1715 pending_context_menus_
.Remove(request_id
);
1718 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1719 return context_menu_node_
;
1722 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1723 blink::WebFrame
* frame
,
1724 const WebPluginInfo
& info
,
1725 const blink::WebPluginParams
& params
,
1726 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1727 DCHECK_EQ(frame_
, frame
);
1728 #if defined(ENABLE_PLUGINS)
1729 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1730 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1731 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1732 this, params
.mimeType
.utf8(), GURL(params
.url
)));
1733 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1734 this, browser_plugin_delegate
.Pass());
1737 bool pepper_plugin_was_registered
= false;
1738 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1739 this, info
, &pepper_plugin_was_registered
));
1740 if (pepper_plugin_was_registered
) {
1741 if (pepper_module
.get()) {
1742 return new PepperWebPluginImpl(
1743 pepper_module
.get(), params
, this,
1745 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1748 #if defined(OS_CHROMEOS)
1749 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1752 // TODO(jam): change to take RenderFrame.
1753 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1760 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1761 const blink::WebURLRequest
& request
,
1762 blink::WebNavigationPolicy policy
) {
1763 DCHECK(!frame_
|| frame_
== frame
);
1764 loadURLExternally(frame
, request
, policy
, WebString());
1767 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1768 OnJavaScriptExecuteRequest(javascript
, 0, false);
1771 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1772 return &service_registry_
;
1775 #if defined(ENABLE_PLUGINS)
1776 void RenderFrameImpl::RegisterPeripheralPlugin(
1777 const GURL
& content_origin
,
1778 const base::Closure
& unthrottle_callback
) {
1779 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1780 content_origin
, unthrottle_callback
);
1782 #endif // defined(ENABLE_PLUGINS)
1784 bool RenderFrameImpl::IsFTPDirectoryListing() {
1785 WebURLResponseExtraDataImpl
* extra_data
=
1786 GetExtraDataFromResponse(frame_
->dataSource()->response());
1787 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1790 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1791 BrowserPluginManager::Get()->Attach(element_instance_id
);
1794 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1795 BrowserPluginManager::Get()->Detach(element_instance_id
);
1798 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1800 const gfx::Range
& range
) {
1801 // Use the routing id of Render Widget Host.
1802 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1808 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1809 v8::Isolate
* isolate
,
1810 v8::Handle
<v8::Context
> context
) {
1811 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1812 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1815 v8::HandleScope
handle_scope(isolate
);
1816 registry
->AddBuiltinModule(
1817 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1818 registry
->AddBuiltinModule(isolate
,
1819 mojo::js::Support::kModuleName
,
1820 mojo::js::Support::GetModule(isolate
));
1821 registry
->AddBuiltinModule(
1823 ServiceRegistryJsWrapper::kModuleName
,
1824 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1827 // blink::WebFrameClient implementation ----------------------------------------
1829 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1830 blink::WebLocalFrame
* frame
,
1831 const blink::WebPluginParams
& params
) {
1832 DCHECK_EQ(frame_
, frame
);
1833 return GetContentClient()
1835 ->CreatePluginPlaceholder(this, frame
, params
)
1839 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1840 blink::WebLocalFrame
* frame
,
1841 const blink::WebPluginParams
& params
) {
1842 DCHECK_EQ(frame_
, frame
);
1843 blink::WebPlugin
* plugin
= NULL
;
1844 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1845 this, frame
, params
, &plugin
)) {
1849 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1850 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1851 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1852 kBrowserPluginMimeType
, GURL(params
.url
)));
1853 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1854 this, browser_plugin_delegate
.Pass());
1857 #if defined(ENABLE_PLUGINS)
1859 std::string mime_type
;
1861 Send(new FrameHostMsg_GetPluginInfo(
1862 routing_id_
, params
.url
, frame
->top()->document().url(),
1863 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
1867 WebPluginParams params_to_use
= params
;
1868 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
1869 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
1872 #endif // defined(ENABLE_PLUGINS)
1875 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1876 blink::WebLocalFrame
* frame
,
1877 const blink::WebURL
& url
,
1878 blink::WebMediaPlayerClient
* client
) {
1879 return createMediaPlayer(frame
, url
, client
, nullptr);
1882 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1883 blink::WebLocalFrame
* frame
,
1884 const blink::WebURL
& url
,
1885 blink::WebMediaPlayerClient
* client
,
1886 blink::WebContentDecryptionModule
* initial_cdm
) {
1887 #if defined(VIDEO_HOLE)
1888 if (!contains_media_player_
) {
1889 render_view_
->RegisterVideoHoleFrame(this);
1890 contains_media_player_
= true;
1892 #endif // defined(VIDEO_HOLE)
1894 blink::WebMediaStream
web_stream(
1895 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
1896 if (!web_stream
.isNull())
1897 return CreateWebMediaPlayerForMediaStream(url
, client
);
1899 if (!media_permission_dispatcher_
)
1900 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
1902 #if defined(OS_ANDROID)
1903 return CreateAndroidWebMediaPlayer(url
, client
, media_permission_dispatcher_
,
1906 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
1909 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
1910 media::WebMediaPlayerParams
params(
1911 base::Bind(&ContentRendererClient::DeferMediaLoad
,
1912 base::Unretained(GetContentClient()->renderer()),
1913 static_cast<RenderFrame
*>(this)),
1914 render_thread
->GetAudioRendererMixerManager()->CreateInput(
1915 render_view_
->routing_id_
, routing_id_
),
1916 media_log
, render_thread
->GetMediaThreadTaskRunner(),
1917 render_thread
->compositor_message_loop_proxy(),
1918 base::Bind(&GetSharedMainThreadContext3D
), media_permission_dispatcher_
,
1921 #if defined(ENABLE_PEPPER_CDMS)
1922 scoped_ptr
<media::CdmFactory
> cdm_factory(
1923 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create
, frame
)));
1924 #elif defined(ENABLE_BROWSER_CDMS)
1925 scoped_ptr
<media::CdmFactory
> cdm_factory(
1926 new RenderCdmFactory(GetCdmManager()));
1928 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
1931 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1932 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
1933 new media::MojoRendererFactory(make_scoped_ptr(
1934 new MediaRendererServiceProvider(GetServiceRegistry()))));
1936 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
1937 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
1940 if (!media_renderer_factory
.get()) {
1941 media_renderer_factory
.reset(new media::DefaultRendererFactory(
1942 media_log
, render_thread
->GetGpuFactories(),
1943 *render_thread
->GetAudioHardwareConfig()));
1945 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
1947 return new media::WebMediaPlayerImpl(
1948 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer_factory
.Pass(),
1949 cdm_factory
.Pass(), params
);
1950 #endif // defined(OS_ANDROID)
1953 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
1954 blink::WebLocalFrame
* frame
,
1955 blink::WebApplicationCacheHostClient
* client
) {
1956 if (!frame
|| !frame
->view())
1958 DCHECK(!frame_
|| frame_
== frame
);
1959 return new RendererWebApplicationCacheHostImpl(
1960 RenderViewImpl::FromWebView(frame
->view()), client
,
1961 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1964 blink::WebWorkerContentSettingsClientProxy
*
1965 RenderFrameImpl::createWorkerContentSettingsClientProxy(
1966 blink::WebLocalFrame
* frame
) {
1967 if (!frame
|| !frame
->view())
1969 DCHECK(!frame_
|| frame_
== frame
);
1970 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
1974 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
1975 const WebPopupMenuInfo
& popup_menu_info
,
1976 WebExternalPopupMenuClient
* popup_menu_client
) {
1977 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1978 // An IPC message is sent to the browser to build and display the actual
1979 // popup. The user could have time to click a different select by the time
1980 // the popup is shown. In that case external_popup_menu_ is non NULL.
1981 // By returning NULL in that case, we instruct Blink to cancel that new
1982 // popup. So from the user perspective, only the first one will show, and
1983 // will have to close the first one before another one can be shown.
1984 if (external_popup_menu_
)
1986 external_popup_menu_
.reset(
1987 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
1988 if (render_view_
->screen_metrics_emulator_
) {
1989 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
1990 external_popup_menu_
.get(),
1991 render_view_
->screen_metrics_emulator_
.get());
1993 return external_popup_menu_
.get();
1999 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2000 DCHECK(!frame_
|| frame_
== frame
);
2001 return &cookie_jar_
;
2004 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2005 blink::WebLocalFrame
* frame
) {
2006 DCHECK(!frame_
|| frame_
== frame
);
2007 // At this point we should have non-null data source.
2008 DCHECK(frame
->dataSource());
2009 if (!ChildThreadImpl::current())
2010 return NULL
; // May be null in some tests.
2011 ServiceWorkerNetworkProvider
* provider
=
2012 ServiceWorkerNetworkProvider::FromDocumentState(
2013 DocumentState::FromDataSource(frame
->dataSource()));
2014 return new WebServiceWorkerProviderImpl(
2015 ChildThreadImpl::current()->thread_safe_sender(),
2016 provider
? provider
->context() : NULL
);
2019 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2020 DCHECK(!frame_
|| frame_
== frame
);
2021 // If the request hasn't yet committed, notify the browser process that it is
2022 // no longer safe to show the pending URL of the main frame, since a URL spoof
2023 // is now possible. (If the request has committed, the browser already knows.)
2024 if (!frame
->parent()) {
2025 DocumentState
* document_state
=
2026 DocumentState::FromDataSource(frame
->dataSource());
2027 NavigationStateImpl
* navigation_state
=
2028 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2030 if (!navigation_state
->request_committed()) {
2031 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2036 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2037 blink::WebLocalFrame
* parent
,
2038 const blink::WebString
& name
,
2039 blink::WebSandboxFlags sandbox_flags
) {
2040 // Synchronously notify the browser of a child frame creation to get the
2041 // routing_id for the RenderFrame.
2042 int child_routing_id
= MSG_ROUTING_NONE
;
2043 Send(new FrameHostMsg_CreateChildFrame(
2044 routing_id_
, base::UTF16ToUTF8(name
),
2045 WebToContentSandboxFlags(sandbox_flags
), &child_routing_id
));
2047 // Allocation of routing id failed, so we can't create a child frame. This can
2048 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2049 // out state or synchronous IPC message above has failed.
2050 if (child_routing_id
== MSG_ROUTING_NONE
) {
2051 NOTREACHED() << "Failed to allocate routing id for child frame.";
2055 // Create the RenderFrame and WebLocalFrame, linking the two.
2056 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2057 render_view_
.get(), child_routing_id
);
2058 blink::WebLocalFrame
* web_frame
= WebLocalFrame::create(child_render_frame
);
2059 child_render_frame
->SetWebFrame(web_frame
);
2061 // Add the frame to the frame tree and initialize it.
2062 parent
->appendChild(web_frame
);
2063 child_render_frame
->Initialize();
2068 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2069 DCHECK(!frame_
|| frame_
== frame
);
2070 // We only need to notify the browser if the active, top-level frame clears
2071 // its opener. We can ignore cases where a swapped out frame clears its
2072 // opener after hearing about it from the browser, and the browser does not
2073 // (yet) care about subframe openers.
2074 if (is_swapped_out_
|| frame
->parent())
2077 // Notify WebContents and all its swapped out RenderViews.
2078 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2081 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
) {
2082 // NOTE: This function is called on the frame that is being detached and not
2083 // the parent frame. This is different from createChildFrame() which is
2084 // called on the parent frame.
2085 CHECK(!is_detaching_
);
2086 DCHECK(!frame_
|| frame_
== frame
);
2088 bool is_subframe
= !!frame
->parent();
2090 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2091 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2092 FrameDetached(frame
));
2094 Send(new FrameHostMsg_Detach(routing_id_
));
2096 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2097 // sent before setting |is_detaching_| to true.
2098 is_detaching_
= true;
2100 // We need to clean up subframes by removing them from the map and deleting
2101 // the RenderFrameImpl. In contrast, the main frame is owned by its
2102 // containing RenderViewHost (so that they have the same lifetime), so only
2103 // removal from the map is needed and no deletion.
2104 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2105 CHECK(it
!= g_frame_map
.Get().end());
2106 CHECK_EQ(it
->second
, this);
2107 g_frame_map
.Get().erase(it
);
2110 frame
->parent()->removeChild(frame
);
2112 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2113 // object may not be deleted immediately and other methods may try to access
2120 // Object is invalid after this point.
2124 void RenderFrameImpl::frameFocused() {
2125 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2128 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2129 DCHECK(!frame_
|| frame_
== frame
);
2131 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2132 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2133 FrameWillClose(frame
));
2136 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2137 const blink::WebString
& name
) {
2138 DCHECK(!frame_
|| frame_
== frame
);
2140 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2141 // updates may have performance implications for benchmarks like SunSpider.
2142 // For now, send these updates only for --site-per-process, which needs to
2143 // replicate frame names to frame proxies, and when
2144 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2145 // can be optimized further by only sending the update if there are any
2146 // remote frames in the frame tree, or delaying and batching up IPCs if
2147 // updates are happening too frequently.
2148 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
2149 switches::kSitePerProcess
);
2150 if (is_site_per_process
||
2151 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2152 Send(new FrameHostMsg_DidChangeName(routing_id_
, base::UTF16ToUTF8(name
)));
2156 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2157 blink::WebSandboxFlags flags
) {
2158 int frame_routing_id
= MSG_ROUTING_NONE
;
2159 if (child_frame
->isWebRemoteFrame()) {
2161 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2164 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2167 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2168 WebToContentSandboxFlags(flags
)));
2171 void RenderFrameImpl::didMatchCSS(
2172 blink::WebLocalFrame
* frame
,
2173 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2174 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2175 DCHECK(!frame_
|| frame_
== frame
);
2177 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2179 newly_matching_selectors
,
2180 stopped_matching_selectors
));
2183 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2184 const blink::WebString
& source
) {
2185 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2189 void RenderFrameImpl::didAddMessageToConsole(
2190 const blink::WebConsoleMessage
& message
,
2191 const blink::WebString
& source_name
,
2192 unsigned source_line
,
2193 const blink::WebString
& stack_trace
) {
2194 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2195 switch (message
.level
) {
2196 case blink::WebConsoleMessage::LevelDebug
:
2197 log_severity
= logging::LOG_VERBOSE
;
2199 case blink::WebConsoleMessage::LevelLog
:
2200 case blink::WebConsoleMessage::LevelInfo
:
2201 log_severity
= logging::LOG_INFO
;
2203 case blink::WebConsoleMessage::LevelWarning
:
2204 log_severity
= logging::LOG_WARNING
;
2206 case blink::WebConsoleMessage::LevelError
:
2207 log_severity
= logging::LOG_ERROR
;
2213 if (shouldReportDetailedMessageForSource(source_name
)) {
2215 RenderFrameObserver
, observers_
,
2216 DetailedConsoleMessageAdded(message
.text
,
2220 static_cast<int32
>(log_severity
)));
2223 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2224 static_cast<int32
>(log_severity
),
2226 static_cast<int32
>(source_line
),
2230 void RenderFrameImpl::loadURLExternally(
2231 blink::WebLocalFrame
* frame
,
2232 const blink::WebURLRequest
& request
,
2233 blink::WebNavigationPolicy policy
,
2234 const blink::WebString
& suggested_name
) {
2235 DCHECK(!frame_
|| frame_
== frame
);
2236 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2237 if (policy
== blink::WebNavigationPolicyDownload
) {
2238 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2239 request
.url(), referrer
,
2242 OpenURL(frame
, request
.url(), referrer
, policy
);
2246 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2247 const NavigationPolicyInfo
& info
) {
2248 DCHECK(!frame_
|| frame_
== info
.frame
);
2249 return DecidePolicyForNavigation(this, info
);
2252 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2253 blink::WebFrame
* frame
) {
2254 DCHECK(!frame_
|| frame_
== frame
);
2255 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2258 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2259 const blink::WebFormElement
& form
) {
2260 DCHECK(!frame_
|| frame_
== frame
);
2262 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2265 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2266 const blink::WebFormElement
& form
) {
2267 DCHECK(!frame_
|| frame_
== frame
);
2268 DocumentState
* document_state
=
2269 DocumentState::FromDataSource(frame
->provisionalDataSource());
2270 NavigationStateImpl
* navigation_state
=
2271 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2272 InternalDocumentStateData
* internal_data
=
2273 InternalDocumentStateData::FromDocumentState(document_state
);
2275 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2276 ui::PAGE_TRANSITION_LINK
)) {
2277 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2280 // Save these to be processed when the ensuing navigation is committed.
2281 WebSearchableFormData
web_searchable_form_data(form
);
2282 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2283 internal_data
->set_searchable_form_encoding(
2284 web_searchable_form_data
.encoding().utf8());
2286 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2289 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2290 blink::WebDataSource
* datasource
) {
2291 DCHECK(!frame_
|| frame_
== frame
);
2293 // TODO(nasko): Move implementation here. Needed state:
2294 // * pending_navigation_params_
2297 // * PopulateDocumentStateFromPending
2298 // * CreateNavigationStateFromPending
2299 render_view_
->didCreateDataSource(frame
, datasource
);
2301 // Create the serviceworker's per-document network observing object if it
2302 // does not exist (When navigation happens within a page, the provider already
2304 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2305 DocumentState::FromDataSource(datasource
))) {
2306 scoped_ptr
<ServiceWorkerNetworkProvider
>
2307 network_provider(new ServiceWorkerNetworkProvider(
2308 routing_id_
, SERVICE_WORKER_PROVIDER_FOR_CONTROLLEE
));
2309 ServiceWorkerNetworkProvider::AttachToDocumentState(
2310 DocumentState::FromDataSource(datasource
),
2311 network_provider
.Pass());
2315 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2316 bool is_transition_navigation
,
2317 double triggering_event_time
) {
2318 DCHECK(!frame_
|| frame_
== frame
);
2319 WebDataSource
* ds
= frame
->provisionalDataSource();
2321 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2322 // callback is invoked.
2326 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2327 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2328 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2330 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2331 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2333 "Heard swappedout:// when not swapped out.";
2335 // Update the request time if WebKit has better knowledge of it.
2336 if (document_state
->request_time().is_null() &&
2337 triggering_event_time
!= 0.0) {
2338 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2341 // Start time is only set after request time.
2342 document_state
->set_start_load_time(Time::Now());
2344 bool is_top_most
= !frame
->parent();
2346 render_view_
->set_navigation_gesture(
2347 WebUserGestureIndicator::isProcessingUserGesture() ?
2348 NavigationGestureUser
: NavigationGestureAuto
);
2349 } else if (ds
->replacesCurrentHistoryItem()) {
2350 // Subframe navigations that don't add session history items must be
2351 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2352 // handle loading of error pages.
2353 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2354 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2357 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2358 DidStartProvisionalLoad(frame
));
2359 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2361 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2362 routing_id_
, ds
->request().url(), is_transition_navigation
));
2365 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2366 blink::WebLocalFrame
* frame
) {
2367 DCHECK(!frame_
|| frame_
== frame
);
2368 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2371 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame
* frame
,
2372 const blink::WebURLError
& error
) {
2373 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2375 DCHECK(!frame_
|| frame_
== frame
);
2376 WebDataSource
* ds
= frame
->provisionalDataSource();
2379 const WebURLRequest
& failed_request
= ds
->request();
2381 // Notify the browser that we failed a provisional load with an error.
2383 // Note: It is important this notification occur before DidStopLoading so the
2384 // SSL manager can react to the provisional load failure before being
2385 // notified the load stopped.
2387 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2388 DidFailProvisionalLoad(frame
, error
));
2389 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2390 DidFailProvisionalLoad(error
));
2392 bool show_repost_interstitial
=
2393 (error
.reason
== net::ERR_CACHE_MISS
&&
2394 EqualsASCII(failed_request
.httpMethod(), "POST"));
2396 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
2397 params
.error_code
= error
.reason
;
2398 GetContentClient()->renderer()->GetNavigationErrorStrings(
2404 ¶ms
.error_description
);
2405 params
.url
= error
.unreachableURL
;
2406 params
.showing_repost_interstitial
= show_repost_interstitial
;
2407 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2408 routing_id_
, params
));
2410 // Don't display an error page if this is simply a cancelled load. Aside
2411 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2412 if (error
.reason
== net::ERR_ABORTED
)
2415 // Don't display "client blocked" error page if browser has asked us not to.
2416 if (error
.reason
== net::ERR_BLOCKED_BY_CLIENT
&&
2417 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
2421 // Allow the embedder to suppress an error page.
2422 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2423 error
.unreachableURL
)) {
2427 if (RenderThreadImpl::current() &&
2428 RenderThreadImpl::current()->layout_test_mode()) {
2432 // Make sure we never show errors in view source mode.
2433 frame
->enableViewSourceMode(false);
2435 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2436 NavigationStateImpl
* navigation_state
=
2437 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2439 // If this is a failed back/forward/reload navigation, then we need to do a
2440 // 'replace' load. This is necessary to avoid messing up session history.
2441 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2442 // as session history is concerned.
2444 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2447 // TODO(davidben): This should also take the failed navigation's replacement
2448 // state into account, if a location.replace() failed.
2450 navigation_state
->history_params().page_id
!= -1 ||
2451 ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2452 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2454 // If we failed on a browser initiated request, then make sure that our error
2455 // page load is regarded as the same browser initiated request.
2456 if (!navigation_state
->IsContentInitiated()) {
2457 render_view_
->pending_navigation_params_
.reset(new NavigationParams(
2458 navigation_state
->common_params(), navigation_state
->start_params(),
2459 CommitNavigationParams(false, base::TimeTicks(), std::vector
<GURL
>(),
2460 false, std::string(),
2461 document_state
->request_time()),
2462 navigation_state
->history_params()));
2465 // Load an error page.
2466 LoadNavigationErrorPage(failed_request
, error
, replace
);
2469 void RenderFrameImpl::didCommitProvisionalLoad(
2470 blink::WebLocalFrame
* frame
,
2471 const blink::WebHistoryItem
& item
,
2472 blink::WebHistoryCommitType commit_type
) {
2473 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2475 "url", GetLoadingUrl().possibly_invalid_spec());
2476 DCHECK(!frame_
|| frame_
== frame
);
2477 DocumentState
* document_state
=
2478 DocumentState::FromDataSource(frame
->dataSource());
2479 NavigationStateImpl
* navigation_state
=
2480 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2482 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2483 RenderFrameProxy
* proxy
=
2484 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2486 proxy
->web_frame()->swap(frame_
);
2487 proxy_routing_id_
= MSG_ROUTING_NONE
;
2490 // When we perform a new navigation, we need to update the last committed
2491 // session history entry with state for the page we are leaving. Do this
2492 // before updating the HistoryController state.
2493 render_view_
->UpdateSessionHistory(frame
);
2495 render_view_
->history_controller()->UpdateForCommit(
2496 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2498 InternalDocumentStateData
* internal_data
=
2499 InternalDocumentStateData::FromDocumentState(document_state
);
2501 if (document_state
->commit_load_time().is_null())
2502 document_state
->set_commit_load_time(Time::Now());
2504 if (internal_data
->must_reset_scroll_and_scale_state()) {
2505 render_view_
->webview()->resetScrollAndScaleState();
2506 internal_data
->set_must_reset_scroll_and_scale_state(false);
2508 internal_data
->set_use_error_page(false);
2510 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2511 if (is_new_navigation
) {
2512 // We bump our Page ID to correspond with the new session history entry.
2513 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2515 // Don't update history list values for kSwappedOutURL, since
2516 // we don't want to forget the entry that was there, and since we will
2517 // never come back to kSwappedOutURL. Note that we have to call
2518 // UpdateSessionHistory and update page_id_ even in this case, so that
2519 // the current entry gets a state update and so that we don't send a
2520 // state update to the wrong entry when we swap back in.
2522 navigation_state
->start_params().should_replace_current_entry
,
2523 render_view_
->history_list_length_
> 0);
2524 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2525 !navigation_state
->start_params().should_replace_current_entry
) {
2526 // Advance our offset in session history, applying the length limit.
2527 // There is now no forward history.
2528 render_view_
->history_list_offset_
++;
2529 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2530 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2531 render_view_
->history_list_length_
=
2532 render_view_
->history_list_offset_
+ 1;
2535 // Inspect the navigation_state on this frame to see if the navigation
2536 // corresponds to a session history navigation... Note: |frame| may or
2537 // may not be the toplevel frame, but for the case of capturing session
2538 // history, the first committed frame suffices. We keep track of whether
2539 // we've seen this commit before so that only capture session history once
2542 // Note that we need to check if the page ID changed. In the case of a
2543 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2544 // previous URL and the current page ID, which would be wrong.
2545 if (navigation_state
->history_params().page_id
!= -1 &&
2546 navigation_state
->history_params().page_id
!= render_view_
->page_id_
&&
2547 !navigation_state
->request_committed()) {
2548 // This is a successful session history navigation!
2549 render_view_
->page_id_
= navigation_state
->history_params().page_id
;
2551 render_view_
->history_list_offset_
=
2552 navigation_state
->history_params().pending_history_list_offset
;
2557 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2558 CHECK(sent
); // http://crbug.com/407376
2560 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2561 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2563 RenderFrameObserver
, observers_
,
2564 DidCommitProvisionalLoad(is_new_navigation
,
2565 navigation_state
->WasWithinSamePage()));
2567 if (!frame
->parent()) { // Only for top frames.
2568 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2569 if (render_thread_impl
) { // Can be NULL in tests.
2570 render_thread_impl
->histogram_customizer()->
2571 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2572 RenderViewImpl::GetRenderViewCount());
2576 // Remember that we've already processed this request, so we don't update
2577 // the session history again. We do this regardless of whether this is
2578 // a session history navigation, because if we attempted a session history
2579 // navigation without valid HistoryItem state, WebCore will think it is a
2581 navigation_state
->set_request_committed(true);
2583 SendDidCommitProvisionalLoad(frame
, commit_type
);
2585 // Check whether we have new encoding name.
2586 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2589 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2590 DCHECK(!frame_
|| frame_
== frame
);
2592 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2593 DidCreateNewDocument(frame
));
2596 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2597 DCHECK(!frame_
|| frame_
== frame
);
2599 int enabled_bindings
= render_view_
->GetEnabledBindings();
2601 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2602 WebUIExtension::Install(frame
);
2604 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2605 DomAutomationController::Install(this, frame
);
2607 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2608 StatsCollectionController::Install(frame
);
2610 const base::CommandLine
& command_line
=
2611 *base::CommandLine::ForCurrentProcess();
2613 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2614 GpuBenchmarking::Install(frame
);
2616 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2617 MemoryBenchmarkingExtension::Install(frame
);
2619 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2620 SkiaBenchmarking::Install(frame
);
2622 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2623 DidClearWindowObject(frame
));
2624 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2627 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2628 DCHECK(!frame_
|| frame_
== frame
);
2630 // Notify the browser about non-blank documents loading in the top frame.
2631 GURL url
= frame
->document().url();
2632 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2633 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2634 // frame->tree()->top().
2635 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2636 if (frame
== main_frame
) {
2637 // For now, don't remember plugin zoom values. We don't want to mix them
2638 // with normal web content (i.e. a fixed layout plugin would usually want
2640 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2641 render_view_
->GetRoutingID(),
2642 main_frame
->document().isPluginDocument()));
2646 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2647 DidCreateDocumentElement(frame
));
2650 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2651 const blink::WebString
& title
,
2652 blink::WebTextDirection direction
) {
2653 DCHECK(!frame_
|| frame_
== frame
);
2654 // Ignore all but top level navigations.
2655 if (!frame
->parent()) {
2656 base::string16 title16
= title
;
2657 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2658 routing_id_
, base::UTF16ToUTF8(title16
));
2660 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2661 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2662 shortened_title
, direction
));
2665 // Also check whether we have new encoding name.
2666 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2669 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2670 blink::WebIconURL::Type icon_type
) {
2671 DCHECK(!frame_
|| frame_
== frame
);
2672 // TODO(nasko): Investigate wheather implementation should move here.
2673 render_view_
->didChangeIcon(frame
, icon_type
);
2676 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2677 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2679 DCHECK(!frame_
|| frame_
== frame
);
2680 WebDataSource
* ds
= frame
->dataSource();
2681 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2682 document_state
->set_finish_document_load_time(Time::Now());
2684 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2686 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2687 DidFinishDocumentLoad(frame
));
2688 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2690 // Check whether we have new encoding name.
2691 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2694 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2695 DCHECK(!frame_
|| frame_
== frame
);
2696 if (!frame
->parent()) {
2697 FrameMsg_UILoadMetricsReportType::Value report_type
=
2698 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2699 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2700 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2701 base::TimeDelta::FromSecondsD(
2702 frame
->dataSource()->request().uiStartTime());
2704 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2705 routing_id_
, report_type
, ui_timestamp
));
2709 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2710 const blink::WebURLError
& error
) {
2711 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2713 DCHECK(!frame_
|| frame_
== frame
);
2714 // TODO(nasko): Move implementation here. No state needed.
2715 WebDataSource
* ds
= frame
->dataSource();
2718 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2719 DidFailLoad(frame
, error
));
2721 const WebURLRequest
& failed_request
= ds
->request();
2722 base::string16 error_description
;
2723 GetContentClient()->renderer()->GetNavigationErrorStrings(
2729 &error_description
);
2730 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2731 failed_request
.url(),
2733 error_description
));
2736 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2737 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2739 DCHECK(!frame_
|| frame_
== frame
);
2740 WebDataSource
* ds
= frame
->dataSource();
2741 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2742 if (document_state
->finish_load_time().is_null()) {
2743 if (!frame
->parent()) {
2744 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2745 TRACE_EVENT_SCOPE_PROCESS
);
2747 document_state
->set_finish_load_time(Time::Now());
2750 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2751 DidFinishLoad(frame
));
2752 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2754 // Don't send this message while the frame is swapped out.
2755 if (is_swapped_out())
2758 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2759 ds
->request().url()));
2762 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2763 const blink::WebHistoryItem
& item
,
2764 blink::WebHistoryCommitType commit_type
) {
2765 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2767 DCHECK(!frame_
|| frame_
== frame
);
2768 // If this was a reference fragment navigation that we initiated, then we
2769 // could end up having a non-null pending navigation params. We just need to
2770 // update the ExtraData on the datasource so that others who read the
2771 // ExtraData will get the new NavigationState. Similarly, if we did not
2772 // initiate this navigation, then we need to take care to reset any pre-
2773 // existing navigation state to a content-initiated navigation state.
2774 // DidCreateDataSource conveniently takes care of this for us.
2775 didCreateDataSource(frame
, frame
->dataSource());
2777 DocumentState
* document_state
=
2778 DocumentState::FromDataSource(frame
->dataSource());
2779 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2780 ->set_was_within_same_page(true);
2782 didCommitProvisionalLoad(frame
, item
, commit_type
);
2785 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2786 DCHECK(!frame_
|| frame_
== frame
);
2787 // TODO(nasko): Move implementation here. Needed methods:
2788 // * StartNavStateSyncTimerIfNecessary
2789 render_view_
->didUpdateCurrentHistoryItem(frame
);
2792 void RenderFrameImpl::addNavigationTransitionData(
2793 const blink::WebTransitionElementData
& data
) {
2794 FrameHostMsg_AddNavigationTransitionData_Params params
;
2795 params
.render_frame_id
= routing_id_
;
2796 params
.allowed_destination_host_pattern
=
2798 params
.selector
= data
.selector
.utf8();
2799 params
.markup
= data
.markup
.utf8();
2800 params
.elements
.resize(data
.elements
.size());
2801 for (size_t i
= 0; i
< data
.elements
.size(); i
++) {
2802 params
.elements
[i
].id
= data
.elements
[i
].id
.utf8();
2803 params
.elements
[i
].rect
= gfx::Rect(data
.elements
[i
].rect
);
2806 Send(new FrameHostMsg_AddNavigationTransitionData(params
));
2809 void RenderFrameImpl::didChangeThemeColor() {
2810 if (frame_
->parent())
2813 Send(new FrameHostMsg_DidChangeThemeColor(
2814 routing_id_
, frame_
->document().themeColor()));
2817 void RenderFrameImpl::dispatchLoad() {
2818 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
2821 void RenderFrameImpl::requestNotificationPermission(
2822 const blink::WebSecurityOrigin
& origin
,
2823 blink::WebNotificationPermissionCallback
* callback
) {
2824 if (!notification_permission_dispatcher_
) {
2825 notification_permission_dispatcher_
=
2826 new NotificationPermissionDispatcher(this);
2829 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
2832 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
2833 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
2836 if (is_empty_selection
)
2837 selection_text_
.clear();
2839 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2840 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2841 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2842 // to notify the selection was changed. Focus change should be notified
2843 // before selection change.
2844 GetRenderWidget()->UpdateTextInputType();
2845 SyncSelectionIfRequired();
2846 #if defined(OS_ANDROID)
2847 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
2848 RenderWidget::FROM_NON_IME
);
2852 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
2853 blink::WebColorChooserClient
* client
,
2854 const blink::WebColor
& initial_color
,
2855 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
2856 RendererWebColorChooserImpl
* color_chooser
=
2857 new RendererWebColorChooserImpl(this, client
);
2858 std::vector
<ColorSuggestion
> color_suggestions
;
2859 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
2860 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
2862 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
2863 return color_chooser
;
2866 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
2867 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
2870 frame_
->document().url(),
2874 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
2875 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
2878 frame_
->document().url(),
2882 bool RenderFrameImpl::runModalPromptDialog(
2883 const blink::WebString
& message
,
2884 const blink::WebString
& default_value
,
2885 blink::WebString
* actual_value
) {
2886 base::string16 result
;
2887 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
2890 frame_
->document().url(),
2893 actual_value
->assign(result
);
2897 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2899 const blink::WebString
& message
) {
2900 // If we are swapping out, we have already run the beforeunload handler.
2901 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2902 // at all, to avoid running it twice.
2903 if (is_swapped_out_
)
2906 // Don't allow further dialogs if we are waiting to swap out, since the
2907 // PageGroupLoadDeferrer in our stack prevents it.
2908 if (render_view()->suppress_dialogs_until_swap_out_
)
2911 bool success
= false;
2912 // This is an ignored return value, but is included so we can accept the same
2913 // response as RunJavaScriptMessage.
2914 base::string16 ignored_result
;
2915 render_view()->SendAndRunNestedMessageLoop(
2916 new FrameHostMsg_RunBeforeUnloadConfirm(
2917 routing_id_
, frame_
->document().url(), message
, is_reload
,
2918 &success
, &ignored_result
));
2922 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
2923 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
2924 params
.source_type
= GetRenderWidget()->context_menu_source_type();
2925 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
2926 if (GetRenderWidget()->has_host_context_menu_location()) {
2927 params
.x
= GetRenderWidget()->host_context_menu_location().x();
2928 params
.y
= GetRenderWidget()->host_context_menu_location().y();
2931 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2932 // it. We replace it with an empty GURL so the appropriate items are disabled
2933 // in the context menu.
2934 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2935 // data encoded images. We should have a way to save them.
2936 if (params
.src_url
.spec().size() > GetMaxURLChars())
2937 params
.src_url
= GURL();
2938 context_menu_node_
= data
.node
;
2940 #if defined(OS_ANDROID)
2941 gfx::Rect start_rect
;
2943 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
2944 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
2945 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
2948 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
2951 void RenderFrameImpl::clearContextMenu() {
2952 context_menu_node_
.reset();
2955 void RenderFrameImpl::willSendRequest(
2956 blink::WebLocalFrame
* frame
,
2957 unsigned identifier
,
2958 blink::WebURLRequest
& request
,
2959 const blink::WebURLResponse
& redirect_response
) {
2960 DCHECK(!frame_
|| frame_
== frame
);
2961 // The request my be empty during tests.
2962 if (request
.url().isEmpty())
2965 // Set the first party for cookies url if it has not been set yet (new
2966 // requests). For redirects, it is updated by WebURLLoaderImpl.
2967 if (request
.firstPartyForCookies().isEmpty()) {
2968 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
2969 request
.setFirstPartyForCookies(request
.url());
2971 // TODO(nasko): When the top-level frame is remote, there is no document.
2972 // This is broken and should be fixed to propagate the first party.
2973 WebFrame
* top
= frame
->top();
2974 if (top
->isWebLocalFrame()) {
2975 request
.setFirstPartyForCookies(
2976 frame
->top()->document().firstPartyForCookies());
2981 WebFrame
* top_frame
= frame
->top();
2982 // TODO(nasko): Hack around asking about top-frame data source. This means
2983 // for out-of-process iframes we are treating the current frame as the
2984 // top-level frame, which is wrong.
2985 if (!top_frame
|| top_frame
->isWebRemoteFrame())
2987 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
2988 WebDataSource
* top_data_source
= top_frame
->dataSource();
2989 WebDataSource
* data_source
=
2990 provisional_data_source
? provisional_data_source
: top_data_source
;
2992 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
2993 DCHECK(document_state
);
2994 InternalDocumentStateData
* internal_data
=
2995 InternalDocumentStateData::FromDocumentState(document_state
);
2996 NavigationStateImpl
* navigation_state
=
2997 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2998 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
2999 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
3000 if (frame_ds
&& frame_ds
->isClientRedirect()) {
3001 transition_type
= ui::PageTransitionFromInt(
3002 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3005 GURL
request_url(request
.url());
3007 if (GetContentClient()->renderer()->WillSendRequest(
3011 request
.firstPartyForCookies(),
3013 request
.setURL(WebURL(new_url
));
3016 if (internal_data
->is_cache_policy_override_set())
3017 request
.setCachePolicy(internal_data
->cache_policy_override());
3019 // The request's extra data may indicate that we should set a custom user
3020 // agent. This needs to be done here, after WebKit is through with setting the
3021 // user agent on its own. Similarly, it may indicate that we should set an
3022 // X-Requested-With header. This must be done here to avoid breaking CORS
3024 // PlzNavigate: there may also be a stream url associated with the request.
3025 WebString custom_user_agent
;
3026 WebString requested_with
;
3027 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3028 if (request
.extraData()) {
3029 RequestExtraData
* old_extra_data
=
3030 static_cast<RequestExtraData
*>(request
.extraData());
3032 custom_user_agent
= old_extra_data
->custom_user_agent();
3033 if (!custom_user_agent
.isNull()) {
3034 if (custom_user_agent
.isEmpty())
3035 request
.clearHTTPHeaderField("User-Agent");
3037 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3040 requested_with
= old_extra_data
->requested_with();
3041 if (!requested_with
.isNull()) {
3042 if (requested_with
.isEmpty())
3043 request
.clearHTTPHeaderField("X-Requested-With");
3045 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3047 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3050 // Add the default accept header for frame request if it has not been set
3052 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3053 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3054 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3055 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3056 WebString::fromUTF8(kDefaultAcceptHeader
));
3059 // Add an empty HTTP origin header for non GET methods if none is currently
3061 request
.addHTTPOriginIfNeeded(WebString());
3063 // Attach |should_replace_current_entry| state to requests so that, should
3064 // this navigation later require a request transfer, all state is preserved
3065 // when it is re-created in the new process.
3066 bool should_replace_current_entry
= false;
3067 if (navigation_state
->IsContentInitiated()) {
3068 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3070 // If the navigation is browser-initiated, the NavigationState contains the
3071 // correct value instead of the WebDataSource.
3073 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3074 // NavigationState::should_replace_current_entry().
3075 should_replace_current_entry
=
3076 navigation_state
->start_params().should_replace_current_entry
;
3079 int provider_id
= kInvalidServiceWorkerProviderId
;
3080 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3081 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3082 // |provisionalDataSource| may be null in some content::ResourceFetcher
3083 // use cases, we don't hook those requests.
3084 if (frame
->provisionalDataSource()) {
3085 ServiceWorkerNetworkProvider
* provider
=
3086 ServiceWorkerNetworkProvider::FromDocumentState(
3087 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3088 provider_id
= provider
->provider_id();
3090 } else if (frame
->dataSource()) {
3091 ServiceWorkerNetworkProvider
* provider
=
3092 ServiceWorkerNetworkProvider::FromDocumentState(
3093 DocumentState::FromDataSource(frame
->dataSource()));
3094 provider_id
= provider
->provider_id();
3097 WebFrame
* parent
= frame
->parent();
3098 int parent_routing_id
= MSG_ROUTING_NONE
;
3100 parent_routing_id
= -1;
3101 } else if (parent
->isWebLocalFrame()) {
3102 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3104 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3107 RequestExtraData
* extra_data
= new RequestExtraData();
3108 extra_data
->set_visibility_state(render_view_
->visibilityState());
3109 extra_data
->set_custom_user_agent(custom_user_agent
);
3110 extra_data
->set_requested_with(requested_with
);
3111 extra_data
->set_render_frame_id(routing_id_
);
3112 extra_data
->set_is_main_frame(!parent
);
3113 extra_data
->set_frame_origin(
3114 GURL(frame
->document().securityOrigin().toString()));
3115 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3116 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3117 extra_data
->set_allow_download(
3118 navigation_state
->common_params().allow_download
);
3119 extra_data
->set_transition_type(transition_type
);
3120 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3121 extra_data
->set_transferred_request_child_id(
3122 navigation_state
->start_params().transferred_request_child_id
);
3123 extra_data
->set_transferred_request_request_id(
3124 navigation_state
->start_params().transferred_request_request_id
);
3125 extra_data
->set_service_worker_provider_id(provider_id
);
3126 extra_data
->set_stream_override(stream_override
.Pass());
3127 request
.setExtraData(extra_data
);
3129 DocumentState
* top_document_state
=
3130 DocumentState::FromDataSource(top_data_source
);
3131 if (top_document_state
) {
3132 // TODO(gavinp): separate out prefetching and prerender field trials
3133 // if the rel=prerender rel type is sticking around.
3134 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3135 top_document_state
->set_was_prefetcher(true);
3138 // This is an instance where we embed a copy of the routing id
3139 // into the data portion of the message. This can cause problems if we
3140 // don't register this id on the browser side, since the download manager
3141 // expects to find a RenderViewHost based off the id.
3142 request
.setRequestorID(render_view_
->GetRoutingID());
3143 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3145 if (!navigation_state
->start_params().extra_headers
.empty()) {
3146 for (net::HttpUtil::HeadersIterator
i(
3147 navigation_state
->start_params().extra_headers
.begin(),
3148 navigation_state
->start_params().extra_headers
.end(), "\n");
3150 if (LowerCaseEqualsASCII(i
.name(), "referer")) {
3151 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3152 blink::WebReferrerPolicyDefault
,
3154 WebString::fromUTF8(i
.values()));
3155 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3157 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3158 WebString::fromUTF8(i
.values()));
3163 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3164 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3167 void RenderFrameImpl::didReceiveResponse(
3168 blink::WebLocalFrame
* frame
,
3169 unsigned identifier
,
3170 const blink::WebURLResponse
& response
) {
3171 DCHECK(!frame_
|| frame_
== frame
);
3172 // Only do this for responses that correspond to a provisional data source
3173 // of the top-most frame. If we have a provisional data source, then we
3174 // can't have any sub-resources yet, so we know that this response must
3175 // correspond to a frame load.
3176 if (!frame
->provisionalDataSource() || frame
->parent())
3179 // If we are in view source mode, then just let the user see the source of
3180 // the server's error page.
3181 if (frame
->isViewSourceModeEnabled())
3184 DocumentState
* document_state
=
3185 DocumentState::FromDataSource(frame
->provisionalDataSource());
3186 int http_status_code
= response
.httpStatusCode();
3188 // Record page load flags.
3189 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3191 document_state
->set_was_fetched_via_spdy(
3192 extra_data
->was_fetched_via_spdy());
3193 document_state
->set_was_npn_negotiated(
3194 extra_data
->was_npn_negotiated());
3195 document_state
->set_npn_negotiated_protocol(
3196 extra_data
->npn_negotiated_protocol());
3197 document_state
->set_was_alternate_protocol_available(
3198 extra_data
->was_alternate_protocol_available());
3199 document_state
->set_connection_info(
3200 extra_data
->connection_info());
3201 document_state
->set_was_fetched_via_proxy(
3202 extra_data
->was_fetched_via_proxy());
3203 document_state
->set_proxy_server(
3204 extra_data
->proxy_server());
3206 InternalDocumentStateData
* internal_data
=
3207 InternalDocumentStateData::FromDocumentState(document_state
);
3208 internal_data
->set_http_status_code(http_status_code
);
3209 // Whether or not the http status code actually corresponds to an error is
3210 // only checked when the page is done loading, if |use_error_page| is
3212 internal_data
->set_use_error_page(true);
3215 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3216 unsigned identifier
) {
3217 DCHECK(!frame_
|| frame_
== frame
);
3218 InternalDocumentStateData
* internal_data
=
3219 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3220 if (!internal_data
->use_error_page())
3223 // Do not show error page when DevTools is attached.
3224 if (render_view_
->devtools_agent_
&&
3225 render_view_
->devtools_agent_
->IsAttached()) {
3229 // Display error page, if appropriate.
3230 std::string error_domain
= "http";
3231 int http_status_code
= internal_data
->http_status_code();
3232 if (GetContentClient()->renderer()->HasErrorPage(
3233 http_status_code
, &error_domain
)) {
3235 error
.unreachableURL
= frame
->document().url();
3236 error
.domain
= WebString::fromUTF8(error_domain
);
3237 error
.reason
= http_status_code
;
3238 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3242 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3243 blink::WebLocalFrame
* frame
,
3244 const blink::WebURLRequest
& request
,
3245 const blink::WebURLResponse
& response
) {
3246 DCHECK(!frame_
|| frame_
== frame
);
3247 // The recipients of this message have no use for data: URLs: they don't
3248 // affect the page's insecure content list and are not in the disk cache. To
3249 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3250 // filter them out here.
3251 GURL
url(request
.url());
3252 if (url
.SchemeIs(url::kDataScheme
))
3255 // Let the browser know we loaded a resource from the memory cache. This
3256 // message is needed to display the correct SSL indicators.
3257 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3258 render_view_
->GetRoutingID(),
3260 response
.securityInfo(),
3261 request
.httpMethod().utf8(),
3262 response
.mimeType().utf8(),
3263 WebURLRequestToResourceType(request
)));
3266 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3267 DCHECK(!frame_
|| frame_
== frame
);
3268 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3269 render_view_
->GetRoutingID()));
3272 void RenderFrameImpl::didRunInsecureContent(
3273 blink::WebLocalFrame
* frame
,
3274 const blink::WebSecurityOrigin
& origin
,
3275 const blink::WebURL
& target
) {
3276 DCHECK(!frame_
|| frame_
== frame
);
3277 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3278 render_view_
->GetRoutingID(),
3279 origin
.toString().utf8(),
3283 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3284 DCHECK(!frame_
|| frame_
== frame
);
3285 #if defined(ENABLE_PLUGINS)
3286 if (frame
!= render_view_
->webview()->mainFrame())
3288 PluginChannelHost::Broadcast(
3289 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3293 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3294 v8::Handle
<v8::Context
> context
,
3295 int extension_group
,
3297 DCHECK(!frame_
|| frame_
== frame
);
3298 GetContentClient()->renderer()->DidCreateScriptContext(
3299 frame
, context
, extension_group
, world_id
);
3302 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3303 v8::Handle
<v8::Context
> context
,
3305 DCHECK(!frame_
|| frame_
== frame
);
3307 FOR_EACH_OBSERVER(RenderFrameObserver
,
3309 WillReleaseScriptContext(context
, world_id
));
3312 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3313 blink::WebLocalFrame
* frame
) {
3314 DCHECK(!frame_
|| frame_
== frame
);
3315 if (frame
->parent())
3318 InternalDocumentStateData
* data
=
3319 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3320 data
->set_did_first_visually_non_empty_layout(true);
3322 #if defined(OS_ANDROID)
3323 GetRenderWidget()->DidChangeBodyBackgroundColor(
3324 render_view_
->webwidget_
->backgroundColor());
3327 GetRenderWidget()->QueueMessage(
3328 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3329 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3332 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3333 DCHECK(!frame_
|| frame_
== frame
);
3334 // TODO(nasko): Move implementation here. Needed methods:
3335 // * StartNavStateSyncTimerIfNecessary
3336 render_view_
->didChangeScrollOffset(frame
);
3338 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3341 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3342 DCHECK(!frame_
|| frame_
== frame
);
3343 if (!frame
->parent()) {
3344 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3345 render_view_
->GetRoutingID()));
3349 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3351 bool final_update
) {
3352 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3354 active_match_ordinal
= 0;
3356 render_view_
->Send(new ViewHostMsg_Find_Reply(
3357 render_view_
->GetRoutingID(), request_id
, count
,
3358 gfx::Rect(), active_match_ordinal
, final_update
));
3361 void RenderFrameImpl::reportFindInPageSelection(
3363 int active_match_ordinal
,
3364 const blink::WebRect
& selection_rect
) {
3365 render_view_
->Send(new ViewHostMsg_Find_Reply(
3366 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3367 active_match_ordinal
, false));
3370 void RenderFrameImpl::requestStorageQuota(
3371 blink::WebLocalFrame
* frame
,
3372 blink::WebStorageQuotaType type
,
3373 unsigned long long requested_size
,
3374 blink::WebStorageQuotaCallbacks callbacks
) {
3375 DCHECK(!frame_
|| frame_
== frame
);
3376 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3377 if (origin
.isUnique()) {
3378 // Unique origins cannot store persistent state.
3379 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3382 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3383 render_view_
->GetRoutingID(),
3384 GURL(origin
.toString()),
3385 static_cast<storage::StorageType
>(type
),
3387 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3390 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3391 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3392 impl
->set_render_frame_id(routing_id_
);
3395 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3396 if (!geolocation_dispatcher_
)
3397 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3398 return geolocation_dispatcher_
;
3401 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3402 if (!presentation_dispatcher_
)
3403 presentation_dispatcher_
= new PresentationDispatcher(this);
3404 return presentation_dispatcher_
;
3407 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3408 if (!push_messaging_dispatcher_
)
3409 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3410 return push_messaging_dispatcher_
;
3413 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3414 blink::WebLocalFrame
* frame
,
3415 blink::WebRTCPeerConnectionHandler
* handler
) {
3416 DCHECK(!frame_
|| frame_
== frame
);
3417 #if defined(ENABLE_WEBRTC)
3418 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3422 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3423 if (!web_user_media_client_
)
3424 InitializeUserMediaClient();
3425 return web_user_media_client_
;
3428 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3429 if (!web_encrypted_media_client_
) {
3430 #if defined(ENABLE_PEPPER_CDMS)
3431 scoped_ptr
<media::CdmFactory
> cdm_factory(
3432 new RenderCdmFactory(base::Bind(PepperCdmWrapperImpl::Create
, frame_
)));
3433 #elif defined(ENABLE_BROWSER_CDMS)
3434 scoped_ptr
<media::CdmFactory
> cdm_factory(
3435 new RenderCdmFactory(GetCdmManager()));
3437 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
3440 if (!media_permission_dispatcher_
)
3441 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
3443 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3444 cdm_factory
.Pass(), media_permission_dispatcher_
));
3446 return web_encrypted_media_client_
.get();
3449 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3450 if (!midi_dispatcher_
)
3451 midi_dispatcher_
= new MidiDispatcher(this);
3452 return midi_dispatcher_
;
3455 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3456 blink::WebLocalFrame
* source_frame
,
3457 blink::WebFrame
* target_frame
,
3458 blink::WebSecurityOrigin target_origin
,
3459 blink::WebDOMMessageEvent event
) {
3460 DCHECK(!frame_
|| frame_
== target_frame
);
3462 if (!is_swapped_out_
)
3465 ViewMsg_PostMessage_Params params
;
3466 params
.is_data_raw_string
= false;
3467 params
.data
= event
.data().toString();
3468 params
.source_origin
= event
.origin();
3469 if (!target_origin
.isNull())
3470 params
.target_origin
= target_origin
.toString();
3472 params
.message_ports
=
3473 WebMessagePortChannelImpl::ExtractMessagePortIDs(event
.releaseChannels());
3475 // Include the routing ID for the source frame (if one exists), which the
3476 // browser process will translate into the routing ID for the equivalent
3477 // frame in the target process.
3478 params
.source_routing_id
= MSG_ROUTING_NONE
;
3480 RenderViewImpl
* source_view
=
3481 RenderViewImpl::FromWebView(source_frame
->view());
3483 params
.source_routing_id
= source_view
->routing_id();
3486 Send(new ViewHostMsg_RouteMessageEvent(render_view_
->routing_id_
, params
));
3490 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3491 const blink::WebURL
& url
) {
3492 DCHECK(!frame_
|| frame_
== frame
);
3493 std::string user_agent_override_for_url
=
3494 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3495 if (!user_agent_override_for_url
.empty())
3496 return WebString::fromUTF8(user_agent_override_for_url
);
3498 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3499 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3500 return blink::WebString();
3503 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3504 // associated with it, so the checks below are not valid. Temporarily
3505 // return early and fix properly as part of https://crbug.com/426555.
3506 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3507 return blink::WebString();
3509 // If we're in the middle of committing a load, the data source we need
3510 // will still be provisional.
3511 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3512 WebDataSource
* data_source
= NULL
;
3513 if (main_frame
->provisionalDataSource())
3514 data_source
= main_frame
->provisionalDataSource();
3516 data_source
= main_frame
->dataSource();
3518 InternalDocumentStateData
* internal_data
= data_source
?
3519 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3520 if (internal_data
&& internal_data
->is_overriding_user_agent())
3521 return WebString::fromUTF8(
3522 render_view_
->renderer_preferences_
.user_agent_override
);
3523 return blink::WebString();
3526 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3527 DCHECK(!frame_
|| frame_
== frame
);
3528 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3529 return WebString::fromUTF8("1");
3533 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3534 bool default_value
) {
3535 DCHECK(!frame_
|| frame_
== frame
);
3539 bool blocked
= true;
3540 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3541 render_view_
->GetRoutingID(),
3542 GURL(frame
->top()->document().securityOrigin().toString()),
3543 THREE_D_API_TYPE_WEBGL
,
3548 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3549 int arb_robustness_status_code
) {
3550 DCHECK(!frame_
|| frame_
== frame
);
3551 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3552 GURL(frame
->top()->document().securityOrigin().toString()),
3553 THREE_D_API_TYPE_WEBGL
,
3554 arb_robustness_status_code
));
3557 blink::WebScreenOrientationClient
*
3558 RenderFrameImpl::webScreenOrientationClient() {
3559 if (!screen_orientation_dispatcher_
)
3560 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3561 return screen_orientation_dispatcher_
;
3564 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3565 ServiceWorkerNetworkProvider
* provider
=
3566 ServiceWorkerNetworkProvider::FromDocumentState(
3567 DocumentState::FromDataSource(&data_source
));
3568 return provider
->context()->controller_handle_id() !=
3569 kInvalidServiceWorkerHandleId
;
3572 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3573 ServiceWorkerNetworkProvider
* provider
=
3574 ServiceWorkerNetworkProvider::FromDocumentState(
3575 DocumentState::FromDataSource(&data_source
));
3577 if (provider
->context()->controller())
3578 return provider
->context()->controller()->version_id();
3579 return kInvalidServiceWorkerVersionId
;
3582 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3583 blink::WebAXEvent event
) {
3584 HandleWebAccessibilityEvent(obj
, event
);
3587 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3590 const blink::WebAXObject
& start_object
,
3592 const blink::WebAXObject
& end_object
,
3594 if (renderer_accessibility_
) {
3595 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3596 identifier
, match_index
, start_object
, start_offset
,
3597 end_object
, end_offset
);
3601 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3602 DCHECK(!frame_
|| frame_
== frame
);
3604 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3607 void RenderFrameImpl::didChangeDefaultPresentation(
3608 blink::WebLocalFrame
* frame
) {
3609 DCHECK(!frame_
|| frame_
== frame
);
3612 RenderFrameObserver
, observers_
, DidChangeDefaultPresentation());
3615 bool RenderFrameImpl::enterFullscreen() {
3616 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3620 bool RenderFrameImpl::exitFullscreen() {
3621 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3625 void RenderFrameImpl::suddenTerminationDisablerChanged(
3627 blink::WebFrameClient::SuddenTerminationDisablerType type
) {
3629 case blink::WebFrameClient::BeforeUnloadHandler
:
3630 Send(new FrameHostMsg_BeforeUnloadHandlersPresent(
3631 routing_id_
, present
));
3633 case blink::WebFrameClient::UnloadHandler
:
3634 Send(new FrameHostMsg_UnloadHandlersPresent(
3635 routing_id_
, present
));
3642 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3643 if (!permission_client_
)
3644 permission_client_
.reset(new PermissionManager(GetServiceRegistry()));
3646 return permission_client_
.get();
3649 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3650 Send(new FrameHostMsg_MediaPlayingNotification(
3651 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3652 player
->hasAudio(), player
->isRemote()));
3655 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3656 Send(new FrameHostMsg_MediaPausedNotification(
3657 routing_id_
, reinterpret_cast<int64
>(player
)));
3660 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3664 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3665 observers_
.AddObserver(observer
);
3668 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3669 observer
->RenderFrameGone();
3670 observers_
.RemoveObserver(observer
);
3673 void RenderFrameImpl::OnStop() {
3675 frame_
->stopLoading();
3676 if (!frame_
->parent())
3677 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3679 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3682 void RenderFrameImpl::WasHidden() {
3683 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3686 void RenderFrameImpl::WasShown() {
3687 // TODO(kenrb): Need to figure out how to do this better. Should
3688 // VisibilityState remain a page-level concept or move to frames?
3689 // The semantics of 'Show' might have to change here.
3690 if (render_widget_
) {
3691 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3692 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3694 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3697 bool RenderFrameImpl::IsHidden() {
3698 return GetRenderWidget()->is_hidden();
3701 // Tell the embedding application that the URL of the active page has changed.
3702 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3703 blink::WebFrame
* frame
,
3704 blink::WebHistoryCommitType commit_type
) {
3705 DCHECK(!frame_
|| frame_
== frame
);
3706 WebDataSource
* ds
= frame
->dataSource();
3709 const WebURLRequest
& request
= ds
->request();
3710 const WebURLResponse
& response
= ds
->response();
3712 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3713 NavigationStateImpl
* navigation_state
=
3714 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3715 InternalDocumentStateData
* internal_data
=
3716 InternalDocumentStateData::FromDocumentState(document_state
);
3718 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3719 params
.http_status_code
= response
.httpStatusCode();
3720 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3721 params
.is_post
= false;
3722 params
.post_id
= -1;
3723 params
.page_id
= render_view_
->page_id_
;
3724 // We need to track the RenderViewHost routing_id because of downstream
3725 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3726 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3727 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3728 // based on the ID stored in the resource requests. Once those dependencies
3729 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3730 // client to be based on the routing_id of the RenderFrameHost.
3731 params
.render_view_routing_id
= render_view_
->routing_id();
3732 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3733 params
.socket_address
.set_port(response
.remotePort());
3734 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3736 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3737 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3738 params
.security_info
= response
.securityInfo();
3740 // Set the URL to be displayed in the browser UI to the user.
3741 params
.url
= GetLoadingUrl();
3742 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3744 // Set the origin of the frame. This will be replicated to the corresponding
3745 // RenderFrameProxies in other processes.
3746 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3747 // to https://crbug.com/439608 and will be replicated as unique origins.
3748 if (!is_swapped_out_
) {
3749 WebString
serialized_origin(frame
->document().securityOrigin().toString());
3750 if (GURL(serialized_origin
).IsStandard())
3751 params
.origin
= url::Origin(serialized_origin
.utf8());
3754 if (frame
->document().baseURL() != params
.url
)
3755 params
.base_url
= frame
->document().baseURL();
3757 GetRedirectChain(ds
, ¶ms
.redirects
);
3758 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3759 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3761 params
.searchable_form_url
= internal_data
->searchable_form_url();
3762 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3764 params
.gesture
= render_view_
->navigation_gesture_
;
3765 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3767 // Make navigation state a part of the DidCommitProvisionalLoad message so
3768 // that committed entry has it at all times.
3769 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3771 params
.page_state
= HistoryEntryToPageState(entry
);
3773 params
.page_state
= PageState::CreateFromURL(request
.url());
3775 if (!frame
->parent()) {
3776 // Top-level navigation.
3778 // Reset the zoom limits in case a plugin had changed them previously. This
3779 // will also call us back which will cause us to send a message to
3780 // update WebContentsImpl.
3781 render_view_
->webview()->zoomLimitsChanged(
3782 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3783 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3785 // Set zoom level, but don't do it for full-page plugin since they don't use
3786 // the same zoom settings.
3787 HostZoomLevels::iterator host_zoom
=
3788 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3789 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3790 // Reset the zoom levels for plugins.
3791 render_view_
->webview()->setZoomLevel(0);
3793 // If the zoom level is not found, then do nothing. In-page navigation
3794 // relies on not changing the zoom level in this case.
3795 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3796 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3799 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3800 // This zoom level was merely recorded transiently for this load. We can
3801 // erase it now. If at some point we reload this page, the browser will
3802 // send us a new, up-to-date zoom level.
3803 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3806 // Update contents MIME type for main frame.
3807 params
.contents_mime_type
= ds
->response().mimeType().utf8();
3809 params
.transition
= navigation_state
->GetTransitionType();
3810 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
3811 // If the main frame does a load, it should not be reported as a subframe
3812 // navigation. This can occur in the following case:
3813 // 1. You're on a site with frames.
3814 // 2. You do a subframe navigation. This is stored with transition type
3816 // 3. You navigate to some non-frame site, say, google.com.
3817 // 4. You navigate back to the page from step 2. Since it was initially
3818 // MANUAL_SUBFRAME, it will be that same transition type here.
3819 // We don't want that, because any navigation that changes the toplevel
3820 // frame should be tracked as a toplevel navigation (this allows us to
3821 // update the URL bar, etc).
3822 params
.transition
= ui::PAGE_TRANSITION_LINK
;
3825 // If the page contained a client redirect (meta refresh, document.loc...),
3826 // set the referrer and transition appropriately.
3827 if (ds
->isClientRedirect()) {
3829 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
3830 params
.transition
= ui::PageTransitionFromInt(
3831 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3833 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
3834 frame
, ds
->request());
3837 base::string16 method
= request
.httpMethod();
3838 if (EqualsASCII(method
, "POST")) {
3839 params
.is_post
= true;
3840 params
.post_id
= ExtractPostId(entry
);
3843 // Send the user agent override back.
3844 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
3846 // Track the URL of the original request. We use the first entry of the
3847 // redirect chain if it exists because the chain may have started in another
3849 params
.original_request_url
= GetOriginalRequestURL(ds
);
3851 params
.history_list_was_cleared
=
3852 navigation_state
->history_params().should_clear_history_list
;
3854 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
3855 frame
->dataSource()->request().inputPerfMetricReportPolicy());
3856 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
3857 frame
->dataSource()->request().uiStartTime());
3859 // Save some histogram data so we can compute the average memory used per
3860 // page load of the glyphs.
3861 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3862 blink::WebGlyphCache::pageCount());
3864 // This message needs to be sent before any of allowScripts(),
3865 // allowImages(), allowPlugins() is called for the new page, so that when
3866 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3867 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3868 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3870 // Subframe navigation: the type depends on whether this navigation
3871 // generated a new session history entry. When they do generate a session
3872 // history entry, it means the user initiated the navigation and we should
3874 if (commit_type
== blink::WebStandardCommit
)
3875 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
3877 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
3879 DCHECK(!navigation_state
->history_params().should_clear_history_list
);
3880 params
.history_list_was_cleared
= false;
3881 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
3883 // Don't send this message while the subframe is swapped out.
3884 if (!is_swapped_out())
3885 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3888 // If we end up reusing this WebRequest (for example, due to a #ref click),
3889 // we don't want the transition type to persist. Just clear it.
3890 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
3893 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
3894 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3896 render_view_
->FrameDidStartLoading(frame_
);
3897 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
3900 void RenderFrameImpl::didStopLoading() {
3901 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3903 render_view_
->FrameDidStopLoading(frame_
);
3904 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
3907 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
3908 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
3911 void RenderFrameImpl::HandleWebAccessibilityEvent(
3912 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
3913 if (renderer_accessibility_
)
3914 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
3917 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
3918 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
3921 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
3922 if (renderer_accessibility())
3923 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
3927 void RenderFrameImpl::OnCommitNavigation(
3928 const ResourceResponseHead
& response
,
3929 const GURL
& stream_url
,
3930 const CommonNavigationParams
& common_params
,
3931 const CommitNavigationParams
& commit_params
,
3932 const HistoryNavigationParams
& history_params
) {
3933 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3934 switches::kEnableBrowserSideNavigation
));
3935 bool is_reload
= false;
3936 bool is_history_navigation
= history_params
.page_state
.IsValid();
3937 WebURLRequest::CachePolicy cache_policy
=
3938 WebURLRequest::UseProtocolCachePolicy
;
3939 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3940 common_params
.url
, is_history_navigation
, history_params
, &is_reload
,
3945 GetContentClient()->SetActiveURL(common_params
.url
);
3947 render_view_
->pending_navigation_params_
.reset(new NavigationParams(
3948 common_params
, StartNavigationParams(), commit_params
, history_params
));
3950 if (!common_params
.base_url_for_data_url
.is_empty() ||
3951 common_params
.url
.SchemeIs(url::kDataScheme
)) {
3952 LoadDataURL(common_params
, frame_
);
3956 // Create a WebURLRequest that blink can use to get access to the body of the
3957 // response through a stream in the browser. Blink will then commit the
3959 // TODO(clamy): Have the navigation commit directly, without going through
3960 // loading a WebURLRequest.
3961 scoped_ptr
<StreamOverrideParameters
> stream_override(
3962 new StreamOverrideParameters());
3963 stream_override
->stream_url
= stream_url
;
3964 stream_override
->response
= response
;
3965 WebURLRequest request
=
3966 CreateURLRequestForNavigation(common_params
,
3967 stream_override
.Pass(),
3968 frame_
->isViewSourceModeEnabled());
3970 // Make sure that blink loader will not try to use browser side navigation for
3971 // this request (since it already went to the browser).
3972 request
.setCheckForBrowserSideNavigation(false);
3974 // Record this before starting the load. A lower bound of this time is needed
3975 // to sanitize the navigationStart override set below.
3976 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
3977 frame_
->loadRequest(request
);
3978 UpdateFrameNavigationTiming(
3979 frame_
, commit_params
.browser_navigation_start
,
3980 renderer_navigation_start
);
3983 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
3984 RenderFrame
* render_frame
,
3985 const NavigationPolicyInfo
& info
) {
3987 // The handlenavigation API is deprecated and will be removed once
3988 // crbug.com/325351 is resolved.
3989 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
3990 GetContentClient()->renderer()->HandleNavigation(
3992 static_cast<DocumentState
*>(info
.extraData
),
3993 render_view_
->opener_id_
,
3996 info
.navigationType
,
3999 return blink::WebNavigationPolicyIgnore
;
4003 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4005 const base::CommandLine
& command_line
=
4006 *base::CommandLine::ForCurrentProcess();
4008 bool is_subframe
= !!info
.frame
->parent();
4010 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe
) {
4011 // There's no reason to ignore navigations on subframes, since the swap out
4012 // logic no longer applies.
4014 if (is_swapped_out_
) {
4015 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4016 // Targeted links may try to navigate a swapped out frame. Allow the
4017 // browser process to navigate the tab instead. Note that it is also
4018 // possible for non-targeted navigations (from this view) to arrive
4019 // here just after we are swapped out. It's ok to send them to the
4020 // browser, as long as they're for the top level frame.
4021 // TODO(creis): Ensure this supports targeted form submissions when
4022 // fixing http://crbug.com/101395.
4023 if (info
.frame
->parent() == NULL
) {
4024 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4025 info
.defaultPolicy
);
4026 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4029 // We should otherwise ignore in-process iframe navigations, if they
4030 // arrive just after we are swapped out.
4031 return blink::WebNavigationPolicyIgnore
;
4034 // Allow kSwappedOutURL to complete.
4035 return info
.defaultPolicy
;
4039 // Webkit is asking whether to navigate to a new URL.
4040 // This is fine normally, except if we're showing UI from one security
4041 // context and they're trying to navigate to a different context.
4042 const GURL
& url
= info
.urlRequest
.url();
4044 // A content initiated navigation may have originated from a link-click,
4045 // script, drag-n-drop operation, etc.
4046 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4047 bool is_content_initiated
=
4048 document_state
->navigation_state()->IsContentInitiated();
4051 // If --enable-strict-site-isolation is enabled, send all top-level
4052 // navigations to the browser to let it swap processes when crossing site
4053 // boundaries. This is currently expected to break some script calls and
4054 // navigations, such as form submissions.
4055 bool force_swap_due_to_flag
=
4056 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
);
4057 if (force_swap_due_to_flag
&&
4058 !info
.frame
->parent() && (is_content_initiated
|| info
.isRedirect
)) {
4059 WebString origin_str
= info
.frame
->document().securityOrigin().toString();
4060 GURL
frame_url(origin_str
.utf8().data());
4061 // TODO(cevans): revisit whether this site check is still necessary once
4062 // crbug.com/101395 is fixed.
4063 bool same_domain_or_host
=
4064 net::registry_controlled_domains::SameDomainOrHost(
4067 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
4068 // Only keep same-site (domain + scheme) and data URLs in the same process.
4070 (same_domain_or_host
&& frame_url
.scheme() == url
.scheme()) ||
4071 url
.SchemeIs(url::kDataScheme
);
4072 if (!is_same_site
) {
4073 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4074 return blink::WebNavigationPolicyIgnore
;
4078 // If the browser is interested, then give it a chance to look at the request.
4079 if (is_content_initiated
) {
4081 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4082 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4083 EqualsASCII(info
.urlRequest
.httpMethod(), "POST");
4084 bool browser_handles_request
=
4085 render_view_
->renderer_preferences_
4086 .browser_handles_non_local_top_level_requests
4087 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4089 if (!browser_handles_request
) {
4090 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4091 render_view_
->renderer_preferences_
4092 .browser_handles_all_top_level_requests
;
4095 if (browser_handles_request
) {
4096 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4097 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4101 // Use the frame's original request's URL rather than the document's URL for
4102 // subsequent checks. For a popup, the document's URL may become the opener
4103 // window's URL if the opener has called document.write().
4104 // See http://crbug.com/93517.
4105 GURL
old_url(info
.frame
->dataSource()->request().url());
4107 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4108 // an extension or app origin, leaving a WebUI page, etc). We only care about
4109 // top-level navigations (not iframes). But we sometimes navigate to
4110 // about:blank to clear a tab, and we want to still allow that.
4112 // Note: this is known to break POST submissions when crossing process
4113 // boundaries until http://crbug.com/101395 is fixed. This is better for
4114 // security than loading a WebUI, extension or app page in the wrong process.
4115 // POST requests don't work because this mechanism does not preserve form
4116 // POST data. We will need to send the request's httpBody data up to the
4117 // browser process, and issue a special POST navigation in WebKit (via
4118 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4119 // for examples of how to send the httpBody data.
4120 if (!info
.frame
->parent() && is_content_initiated
&&
4121 !url
.SchemeIs(url::kAboutScheme
)) {
4122 bool send_referrer
= false;
4124 // All navigations to or from WebUI URLs or within WebUI-enabled
4125 // RenderProcesses must be handled by the browser process so that the
4126 // correct bindings and data sources can be registered.
4127 // Similarly, navigations to view-source URLs or within ViewSource mode
4128 // must be handled by the browser process (except for reloads - those are
4129 // safe to leave within the renderer).
4130 // Lastly, access to file:// URLs from non-file:// URL pages must be
4131 // handled by the browser so that ordinary renderer processes don't get
4132 // blessed with file permissions.
4133 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4134 bool is_initial_navigation
= render_view_
->page_id_
== -1;
4135 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4136 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4137 url
.SchemeIs(kViewSourceScheme
) ||
4138 (info
.frame
->isViewSourceModeEnabled() &&
4139 info
.navigationType
!= blink::WebNavigationTypeReload
);
4141 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4142 // Fork non-file to file opens. Check the opener URL if this is the
4143 // initial navigation in a newly opened window.
4144 GURL
source_url(old_url
);
4145 if (is_initial_navigation
&& source_url
.is_empty() &&
4146 info
.frame
->opener())
4147 source_url
= info
.frame
->opener()->top()->document().url();
4148 DCHECK(!source_url
.is_empty());
4149 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4153 // Give the embedder a chance.
4154 should_fork
= GetContentClient()->renderer()->ShouldFork(
4155 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4156 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4160 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4161 info
.defaultPolicy
);
4162 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4166 // Detect when a page is "forking" a new tab that can be safely rendered in
4167 // its own process. This is done by sites like Gmail that try to open links
4168 // in new windows without script connections back to the original page. We
4169 // treat such cases as browser navigations (in which we will create a new
4170 // renderer for a cross-site navigation), rather than WebKit navigations.
4172 // We use the following heuristic to decide whether to fork a new page in its
4174 // The parent page must open a new tab to about:blank, set the new tab's
4175 // window.opener to null, and then redirect the tab to a cross-site URL using
4178 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4181 // Must start from a tab showing about:blank, which is later redirected.
4182 old_url
== GURL(url::kAboutBlankURL
) &&
4183 // Must be the first real navigation of the tab.
4184 render_view_
->historyBackListCount() < 1 &&
4185 render_view_
->historyForwardListCount() < 1 &&
4186 // The parent page must have set the child's window.opener to null before
4187 // redirecting to the desired URL.
4188 info
.frame
->opener() == NULL
&&
4189 // Must be a top-level frame.
4190 info
.frame
->parent() == NULL
&&
4191 // Must not have issued the request from this page.
4192 is_content_initiated
&&
4193 // Must be targeted at the current tab.
4194 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4195 // Must be a JavaScript navigation, which appears as "other".
4196 info
.navigationType
== blink::WebNavigationTypeOther
;
4199 // Open the URL via the browser, not via WebKit.
4200 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4201 return blink::WebNavigationPolicyIgnore
;
4204 // PlzNavigate: send the request to the browser if needed.
4205 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4206 switches::kEnableBrowserSideNavigation
) &&
4207 info
.urlRequest
.checkForBrowserSideNavigation()) {
4208 BeginNavigation(&info
.urlRequest
);
4209 return blink::WebNavigationPolicyIgnore
;
4212 return info
.defaultPolicy
;
4215 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4217 const Referrer
& referrer
,
4218 WebNavigationPolicy policy
) {
4219 DCHECK_EQ(frame_
, frame
);
4221 FrameHostMsg_OpenURL_Params params
;
4223 params
.referrer
= referrer
;
4224 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4225 WebDataSource
* ds
= frame
->provisionalDataSource();
4227 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4228 NavigationStateImpl
* navigation_state
=
4229 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4230 if (navigation_state
->IsContentInitiated()) {
4231 params
.should_replace_current_entry
=
4232 ds
->replacesCurrentHistoryItem() &&
4233 render_view_
->history_list_length_
;
4235 // This is necessary to preserve the should_replace_current_entry value on
4236 // cross-process redirects, in the event it was set by a previous process.
4238 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4239 // NavigationState::should_replace_current_entry().
4240 params
.should_replace_current_entry
=
4241 navigation_state
->start_params().should_replace_current_entry
;
4244 params
.should_replace_current_entry
= false;
4246 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4247 if (GetContentClient()->renderer()->AllowPopup())
4248 params
.user_gesture
= true;
4250 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4251 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4252 policy
== blink::WebNavigationPolicyNewWindow
||
4253 policy
== blink::WebNavigationPolicyNewPopup
) {
4254 WebUserGestureIndicator::consumeUserGesture();
4257 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4260 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4261 const std::string
& encoding_name
) {
4262 // Only update main frame's encoding_name.
4263 if (!frame
->parent())
4264 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4267 void RenderFrameImpl::SyncSelectionIfRequired() {
4268 base::string16 text
;
4271 #if defined(ENABLE_PLUGINS)
4272 if (render_view_
->focused_pepper_plugin_
) {
4273 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4274 offset
= 0; // Pepper API does not support offset reporting.
4275 // TODO(kinaba): cut as needed.
4279 size_t location
, length
;
4280 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4281 &location
, &length
)) {
4285 range
= gfx::Range(location
, location
+ length
);
4287 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4288 blink::WebTextInputTypeNone
) {
4289 // If current focused element is editable, we will send 100 more chars
4290 // before and after selection. It is for input method surrounding text
4292 if (location
> kExtraCharsBeforeAndAfterSelection
)
4293 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4296 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4297 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4298 if (!webrange
.isNull())
4299 text
= webrange
.toPlainText();
4302 text
= frame_
->selectionAsText();
4303 // http://crbug.com/101435
4304 // In some case, frame->selectionAsText() returned text's length is not
4305 // equal to the length returned from webwidget()->caretOrSelectionRange().
4306 // So we have to set the range according to text.length().
4307 range
.set_end(range
.start() + text
.length());
4311 // Sometimes we get repeated didChangeSelection calls from webkit when
4312 // the selection hasn't actually changed. We don't want to report these
4313 // because it will cause us to continually claim the X clipboard.
4314 if (selection_text_offset_
!= offset
||
4315 selection_range_
!= range
||
4316 selection_text_
!= text
) {
4317 selection_text_
= text
;
4318 selection_text_offset_
= offset
;
4319 selection_range_
= range
;
4320 SetSelectedText(text
, offset
, range
);
4322 GetRenderWidget()->UpdateSelectionBounds();
4325 void RenderFrameImpl::InitializeUserMediaClient() {
4326 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4329 #if defined(OS_ANDROID)
4330 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4331 switches::kDisableWebRTC
))
4335 #if defined(ENABLE_WEBRTC)
4336 DCHECK(!web_user_media_client_
);
4337 web_user_media_client_
= new UserMediaClientImpl(
4339 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4340 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4344 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4345 const blink::WebURL
& url
,
4346 WebMediaPlayerClient
* client
) {
4347 #if defined(ENABLE_WEBRTC)
4348 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4350 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4351 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4352 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4353 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4354 new RenderMediaLog(),
4355 CreateRendererFactory());
4358 #endif // defined(ENABLE_WEBRTC)
4361 scoped_ptr
<MediaStreamRendererFactory
>
4362 RenderFrameImpl::CreateRendererFactory() {
4363 #if defined(ENABLE_WEBRTC)
4364 return scoped_ptr
<MediaStreamRendererFactory
>(
4365 new MediaStreamRendererFactory());
4367 return scoped_ptr
<MediaStreamRendererFactory
>(
4368 static_cast<MediaStreamRendererFactory
*>(NULL
));
4372 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4374 bool is_history_navigation
,
4375 const HistoryNavigationParams
& history_params
,
4377 WebURLRequest::CachePolicy
* cache_policy
) {
4378 MaybeHandleDebugURL(url
);
4379 if (!render_view_
->webview())
4383 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4385 // If this is a stale back/forward (due to a recent navigation the browser
4386 // didn't know about), ignore it. Only check if swapped in because if the
4387 // frame is swapped out, it won't commit before asking the browser.
4388 if (!render_view_
->is_swapped_out() && is_history_navigation
&&
4389 render_view_
->history_list_offset_
!=
4390 history_params
.current_history_list_offset
) {
4394 render_view_
->history_list_offset_
=
4395 history_params
.current_history_list_offset
;
4396 render_view_
->history_list_length_
=
4397 history_params
.current_history_list_length
;
4398 if (history_params
.should_clear_history_list
) {
4399 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4400 CHECK_EQ(0, render_view_
->history_list_length_
);
4403 if (!is_swapped_out_
|| frame_
->parent())
4406 // This is a swapped out main frame, so swap the renderer back in.
4407 // We marked the view as hidden when swapping the view out, so be sure to
4408 // reset the visibility state before navigating to the new URL.
4409 render_view_
->webview()->setVisibilityState(
4410 render_view_
->visibilityState(), false);
4412 // If this is an attempt to reload while we are swapped out, we should not
4413 // reload swappedout://, but the previous page, which is stored in
4414 // params.state. Setting is_reload to false will treat this like a back
4415 // navigation to accomplish that.
4417 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4419 // We refresh timezone when a view is swapped in since timezone
4420 // can get out of sync when the system timezone is updated while
4421 // the view is swapped out.
4422 RenderThreadImpl::NotifyTimezoneChange();
4424 render_view_
->SetSwappedOut(false);
4425 is_swapped_out_
= false;
4429 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4430 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4431 switches::kEnableBrowserSideNavigation
));
4433 // TODO(clamy): Execute the beforeunload event.
4435 // Note: At this stage, the goal is to apply all the modifications the
4436 // renderer wants to make to the request, and then send it to the browser, so
4437 // that the actual network request can be started. Ideally, all such
4438 // modifications should take place in willSendRequest, and in the
4439 // implementation of willSendRequest for the various InspectorAgents
4442 // TODO(clamy): Apply devtools override.
4443 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4445 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4447 // TODO(clamy): Same-document navigations should not be sent back to the
4449 // TODO(clamy): Data urls should not be sent back to the browser either.
4450 Send(new FrameHostMsg_DidStartLoading(routing_id_
, true));
4451 Send(new FrameHostMsg_BeginNavigation(
4452 routing_id_
, MakeCommonNavigationParams(request
),
4453 BeginNavigationParams(request
->httpMethod().latin1(),
4454 GetWebURLRequestHeaders(*request
),
4455 GetLoadFlagsForWebURLRequest(*request
),
4456 request
->hasUserGesture()),
4457 GetRequestBodyForWebURLRequest(*request
)));
4460 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4462 // A loadData request with a specified base URL.
4463 std::string mime_type
, charset
, data
;
4464 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4465 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4466 params
.url
: params
.base_url_for_data_url
;
4468 WebData(data
.c_str(), data
.length()),
4469 WebString::fromUTF8(mime_type
),
4470 WebString::fromUTF8(charset
),
4472 params
.history_url_for_data_url
,
4475 CHECK(false) << "Invalid URL passed: "
4476 << params
.url
.possibly_invalid_spec();
4480 GURL
RenderFrameImpl::GetLoadingUrl() const {
4481 WebDataSource
* ds
= frame_
->dataSource();
4482 if (ds
->hasUnreachableURL())
4483 return ds
->unreachableURL();
4485 const WebURLRequest
& request
= ds
->request();
4486 return request
.url();
4489 #if defined(OS_ANDROID)
4491 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4492 const blink::WebURL
& url
,
4493 WebMediaPlayerClient
* client
,
4494 media::MediaPermission
* media_permission
,
4495 blink::WebContentDecryptionModule
* initial_cdm
) {
4496 GpuChannelHost
* gpu_channel_host
=
4497 RenderThreadImpl::current()->EstablishGpuChannelSync(
4498 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4499 if (!gpu_channel_host
) {
4500 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4504 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4505 if (SynchronousCompositorFactory
* factory
=
4506 SynchronousCompositorFactory::GetInstance()) {
4507 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4509 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4510 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4512 if (!context_provider
.get()) {
4513 LOG(ERROR
) << "Failed to get context3d for media player";
4517 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4518 context_provider
, gpu_channel_host
, routing_id_
);
4521 return new WebMediaPlayerAndroid(
4524 weak_factory_
.GetWeakPtr(),
4525 GetMediaPlayerManager(),
4529 stream_texture_factory
,
4530 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4531 new RenderMediaLog());
4534 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4535 if (!media_player_manager_
)
4536 media_player_manager_
= new RendererMediaPlayerManager(this);
4537 return media_player_manager_
;
4540 #endif // defined(OS_ANDROID)
4542 #if defined(ENABLE_BROWSER_CDMS)
4543 RendererCdmManager
* RenderFrameImpl::GetCdmManager() {
4545 cdm_manager_
= new RendererCdmManager(this);
4546 return cdm_manager_
;
4548 #endif // defined(ENABLE_BROWSER_CDMS)
4550 } // namespace content