1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h"
21 #include "cc/base/switches.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/permissions/permission_dispatcher.h"
24 #include "content/child/plugin_messages.h"
25 #include "content/child/quota_dispatcher.h"
26 #include "content/child/request_extra_data.h"
27 #include "content/child/service_worker/service_worker_handle_reference.h"
28 #include "content/child/service_worker/service_worker_network_provider.h"
29 #include "content/child/service_worker/service_worker_provider_context.h"
30 #include "content/child/service_worker/web_service_worker_provider_impl.h"
31 #include "content/child/v8_value_converter_impl.h"
32 #include "content/child/web_url_loader_impl.h"
33 #include "content/child/web_url_request_util.h"
34 #include "content/child/webmessageportchannel_impl.h"
35 #include "content/child/websocket_bridge.h"
36 #include "content/child/weburlresponse_extradata_impl.h"
37 #include "content/common/clipboard_messages.h"
38 #include "content/common/frame_messages.h"
39 #include "content/common/frame_replication_state.h"
40 #include "content/common/input_messages.h"
41 #include "content/common/navigation_params.h"
42 #include "content/common/service_worker/service_worker_types.h"
43 #include "content/common/swapped_out_messages.h"
44 #include "content/common/view_messages.h"
45 #include "content/public/common/bindings_policy.h"
46 #include "content/public/common/content_constants.h"
47 #include "content/public/common/content_switches.h"
48 #include "content/public/common/context_menu_params.h"
49 #include "content/public/common/page_state.h"
50 #include "content/public/common/resource_response.h"
51 #include "content/public/common/url_constants.h"
52 #include "content/public/common/url_utils.h"
53 #include "content/public/renderer/browser_plugin_delegate.h"
54 #include "content/public/renderer/content_renderer_client.h"
55 #include "content/public/renderer/context_menu_client.h"
56 #include "content/public/renderer/document_state.h"
57 #include "content/public/renderer/navigation_state.h"
58 #include "content/public/renderer/render_frame_observer.h"
59 #include "content/public/renderer/renderer_ppapi_host.h"
60 #include "content/renderer/accessibility/renderer_accessibility.h"
61 #include "content/renderer/browser_plugin/browser_plugin.h"
62 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
63 #include "content/renderer/child_frame_compositing_helper.h"
64 #include "content/renderer/context_menu_params_builder.h"
65 #include "content/renderer/devtools/devtools_agent.h"
66 #include "content/renderer/dom_automation_controller.h"
67 #include "content/renderer/dom_utils.h"
68 #include "content/renderer/external_popup_menu.h"
69 #include "content/renderer/geolocation_dispatcher.h"
70 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
71 #include "content/renderer/history_controller.h"
72 #include "content/renderer/history_serialization.h"
73 #include "content/renderer/image_loading_helper.h"
74 #include "content/renderer/ime_event_guard.h"
75 #include "content/renderer/internal_document_state_data.h"
76 #include "content/renderer/manifest/manifest_manager.h"
77 #include "content/renderer/media/audio_renderer_mixer_manager.h"
78 #include "content/renderer/media/crypto/render_cdm_factory.h"
79 #include "content/renderer/media/media_permission_dispatcher.h"
80 #include "content/renderer/media/media_stream_dispatcher.h"
81 #include "content/renderer/media/media_stream_renderer_factory.h"
82 #include "content/renderer/media/midi_dispatcher.h"
83 #include "content/renderer/media/render_media_log.h"
84 #include "content/renderer/media/user_media_client_impl.h"
85 #include "content/renderer/media/webmediaplayer_ms.h"
86 #include "content/renderer/memory_benchmarking_extension.h"
87 #include "content/renderer/mojo/service_registry_js_wrapper.h"
88 #include "content/renderer/navigation_state_impl.h"
89 #include "content/renderer/notification_permission_dispatcher.h"
90 #include "content/renderer/npapi/plugin_channel_host.h"
91 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
92 #include "content/renderer/presentation/presentation_dispatcher.h"
93 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
94 #include "content/renderer/render_frame_proxy.h"
95 #include "content/renderer/render_process.h"
96 #include "content/renderer/render_thread_impl.h"
97 #include "content/renderer/render_view_impl.h"
98 #include "content/renderer/render_widget_fullscreen_pepper.h"
99 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
100 #include "content/renderer/renderer_webcolorchooser_impl.h"
101 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
102 #include "content/renderer/shared_worker_repository.h"
103 #include "content/renderer/skia_benchmarking_extension.h"
104 #include "content/renderer/stats_collection_controller.h"
105 #include "content/renderer/web_ui_extension.h"
106 #include "content/renderer/websharedworker_proxy.h"
107 #include "gin/modules/module_registry.h"
108 #include "media/base/audio_renderer_mixer_input.h"
109 #include "media/base/media_log.h"
110 #include "media/blink/webencryptedmediaclient_impl.h"
111 #include "media/blink/webmediaplayer_impl.h"
112 #include "media/blink/webmediaplayer_params.h"
113 #include "media/renderers/gpu_video_accelerator_factories.h"
114 #include "net/base/data_url.h"
115 #include "net/base/net_errors.h"
116 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
117 #include "net/http/http_util.h"
118 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
119 #include "third_party/WebKit/public/platform/WebString.h"
120 #include "third_party/WebKit/public/platform/WebURL.h"
121 #include "third_party/WebKit/public/platform/WebURLError.h"
122 #include "third_party/WebKit/public/platform/WebURLResponse.h"
123 #include "third_party/WebKit/public/platform/WebVector.h"
124 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
125 #include "third_party/WebKit/public/web/WebDocument.h"
126 #include "third_party/WebKit/public/web/WebFrameWidget.h"
127 #include "third_party/WebKit/public/web/WebGlyphCache.h"
128 #include "third_party/WebKit/public/web/WebKit.h"
129 #include "third_party/WebKit/public/web/WebLocalFrame.h"
130 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
131 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
132 #include "third_party/WebKit/public/web/WebPlugin.h"
133 #include "third_party/WebKit/public/web/WebPluginParams.h"
134 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
135 #include "third_party/WebKit/public/web/WebRange.h"
136 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
137 #include "third_party/WebKit/public/web/WebScriptSource.h"
138 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
139 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
140 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
141 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
142 #include "third_party/WebKit/public/web/WebSettings.h"
143 #include "third_party/WebKit/public/web/WebSurroundingText.h"
144 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
145 #include "third_party/WebKit/public/web/WebView.h"
146 #include "third_party/mojo/src/mojo/edk/js/core.h"
147 #include "third_party/mojo/src/mojo/edk/js/support.h"
149 #if defined(ENABLE_PLUGINS)
150 #include "content/renderer/npapi/webplugin_impl.h"
151 #include "content/renderer/pepper/pepper_browser_connection.h"
152 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
153 #include "content/renderer/pepper/pepper_webplugin_impl.h"
154 #include "content/renderer/pepper/plugin_module.h"
157 #if defined(ENABLE_WEBRTC)
158 #include "content/renderer/media/rtc_peer_connection_handler.h"
161 #if defined(OS_ANDROID)
162 #include <cpu-features.h>
164 #include "content/common/gpu/client/context_provider_command_buffer.h"
165 #include "content/renderer/android/synchronous_compositor_factory.h"
166 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
167 #include "content/renderer/media/android/renderer_media_player_manager.h"
168 #include "content/renderer/media/android/stream_texture_factory_impl.h"
169 #include "content/renderer/media/android/webmediaplayer_android.h"
171 #include "cc/blink/context_provider_web_context.h"
174 #if defined(ENABLE_PEPPER_CDMS)
175 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
176 #elif defined(ENABLE_BROWSER_CDMS)
177 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
180 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
181 #include "content/renderer/media/media_renderer_service_provider.h"
182 #include "media/mojo/services/mojo_renderer_factory.h"
184 #include "media/renderers/default_renderer_factory.h"
187 using blink::WebContextMenuData
;
188 using blink::WebData
;
189 using blink::WebDataSource
;
190 using blink::WebDocument
;
191 using blink::WebDOMEvent
;
192 using blink::WebDOMMessageEvent
;
193 using blink::WebElement
;
194 using blink::WebExternalPopupMenu
;
195 using blink::WebExternalPopupMenuClient
;
196 using blink::WebFrame
;
197 using blink::WebHistoryItem
;
198 using blink::WebHTTPBody
;
199 using blink::WebLocalFrame
;
200 using blink::WebMediaPlayer
;
201 using blink::WebMediaPlayerClient
;
202 using blink::WebNavigationPolicy
;
203 using blink::WebNavigationType
;
204 using blink::WebNode
;
205 using blink::WebPluginParams
;
206 using blink::WebPopupMenuInfo
;
207 using blink::WebRange
;
208 using blink::WebReferrerPolicy
;
209 using blink::WebScriptSource
;
210 using blink::WebSearchableFormData
;
211 using blink::WebSecurityOrigin
;
212 using blink::WebSecurityPolicy
;
213 using blink::WebSerializedScriptValue
;
214 using blink::WebServiceWorkerProvider
;
215 using blink::WebStorageQuotaCallbacks
;
216 using blink::WebString
;
218 using blink::WebURLError
;
219 using blink::WebURLRequest
;
220 using blink::WebURLResponse
;
221 using blink::WebUserGestureIndicator
;
222 using blink::WebVector
;
223 using blink::WebView
;
225 using base::TimeDelta
;
231 const char kDefaultAcceptHeader
[] =
232 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
234 const char kAcceptHeader
[] = "Accept";
236 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
238 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
239 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
240 LAZY_INSTANCE_INITIALIZER
;
242 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
243 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
245 int64
ExtractPostId(HistoryEntry
* entry
) {
249 const WebHistoryItem
& item
= entry
->root();
250 if (item
.isNull() || item
.httpBody().isNull())
253 return item
.httpBody().identifier();
256 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
257 const WebURLResponse
& response
) {
258 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
261 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
262 // Replace any occurrences of swappedout:// with about:blank.
263 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
264 WebVector
<WebURL
> urls
;
265 ds
->redirectChain(urls
);
266 result
->reserve(urls
.size());
267 for (size_t i
= 0; i
< urls
.size(); ++i
) {
268 if (urls
[i
] != GURL(kSwappedOutURL
))
269 result
->push_back(urls
[i
]);
271 result
->push_back(blank_url
);
275 // Returns the original request url. If there is no redirect, the original
276 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
277 // frame was loaded by loadData, the original url will be ds->unreachableURL()
278 GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
279 // WebDataSource has unreachable URL means that the frame is loaded through
280 // blink::WebFrame::loadData(), and the base URL will be in the redirect
281 // chain. However, we never visited the baseURL. So in this case, we should
282 // use the unreachable URL as the original URL.
283 if (ds
->hasUnreachableURL())
284 return ds
->unreachableURL();
286 std::vector
<GURL
> redirects
;
287 GetRedirectChain(ds
, &redirects
);
288 if (!redirects
.empty())
289 return redirects
.at(0);
291 return ds
->originalRequest().url();
294 NOINLINE
void CrashIntentionally() {
295 // NOTE(shess): Crash directly rather than using NOTREACHED() so
296 // that the signature is easier to triage in crash reports.
297 volatile int* zero
= NULL
;
301 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
302 NOINLINE
void MaybeTriggerAsanError(const GURL
& url
) {
303 // NOTE(rogerm): We intentionally perform an invalid heap access here in
304 // order to trigger an Address Sanitizer (ASAN) error report.
305 const char kCrashDomain
[] = "crash";
306 const char kHeapOverflow
[] = "/heap-overflow";
307 const char kHeapUnderflow
[] = "/heap-underflow";
308 const char kUseAfterFree
[] = "/use-after-free";
309 #if defined(SYZYASAN)
310 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
311 const char kCorruptHeap
[] = "/corrupt-heap";
314 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
320 std::string
crash_type(url
.path());
321 if (crash_type
== kHeapOverflow
) {
322 base::debug::AsanHeapOverflow();
323 } else if (crash_type
== kHeapUnderflow
) {
324 base::debug::AsanHeapUnderflow();
325 } else if (crash_type
== kUseAfterFree
) {
326 base::debug::AsanHeapUseAfterFree();
327 #if defined(SYZYASAN)
328 } else if (crash_type
== kCorruptHeapBlock
) {
329 base::debug::AsanCorruptHeapBlock();
330 } else if (crash_type
== kCorruptHeap
) {
331 base::debug::AsanCorruptHeap();
335 #endif // ADDRESS_SANITIZER || SYZYASAN
337 void MaybeHandleDebugURL(const GURL
& url
) {
338 if (!url
.SchemeIs(kChromeUIScheme
))
340 if (url
== GURL(kChromeUICrashURL
)) {
341 CrashIntentionally();
342 } else if (url
== GURL(kChromeUIDumpURL
)) {
343 // This URL will only correctly create a crash dump file if content is
344 // hosted in a process that has correctly called
345 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
346 // of base::debug::DumpWithoutCrashing for more details.
347 base::debug::DumpWithoutCrashing();
348 } else if (url
== GURL(kChromeUIKillURL
)) {
349 base::Process::Current().Terminate(1, false);
350 } else if (url
== GURL(kChromeUIHangURL
)) {
352 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
354 } else if (url
== GURL(kChromeUIShorthangURL
)) {
355 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
358 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
359 MaybeTriggerAsanError(url
);
360 #endif // ADDRESS_SANITIZER || SYZYASAN
363 // Returns false unless this is a top-level navigation.
364 bool IsTopLevelNavigation(WebFrame
* frame
) {
365 return frame
->parent() == NULL
;
368 // Returns false unless this is a top-level navigation that crosses origins.
369 bool IsNonLocalTopLevelNavigation(const GURL
& url
,
371 WebNavigationType type
,
373 if (!IsTopLevelNavigation(frame
))
376 // Navigations initiated within Webkit are not sent out to the external host
377 // in the following cases.
378 // 1. The url scheme is not http/https
379 // 2. The origin of the url and the opener is the same in which case the
380 // opener relationship is maintained.
381 // 3. Reloads/form submits/back forward navigations
382 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
385 if (type
!= blink::WebNavigationTypeReload
&&
386 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
387 // The opener relationship between the new window and the parent allows the
388 // new window to script the parent and vice versa. This is not allowed if
389 // the origins of the two domains are different. This can be treated as a
390 // top level navigation and routed back to the host.
391 blink::WebFrame
* opener
= frame
->opener();
395 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
401 WebURLRequest
CreateURLRequestForNavigation(
402 const CommonNavigationParams
& common_params
,
403 scoped_ptr
<StreamOverrideParameters
> stream_override
,
404 bool is_view_source_mode_enabled
) {
405 WebURLRequest
request(common_params
.url
);
406 if (is_view_source_mode_enabled
)
407 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
409 if (common_params
.referrer
.url
.is_valid()) {
410 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
411 common_params
.referrer
.policy
,
413 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
414 if (!web_referrer
.isEmpty())
415 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
418 RequestExtraData
* extra_data
= new RequestExtraData();
419 extra_data
->set_stream_override(stream_override
.Pass());
420 request
.setExtraData(extra_data
);
422 // Set the ui timestamp for this navigation. Currently the timestamp here is
423 // only non empty when the navigation was triggered by an Android intent. The
424 // timestamp is converted to a double version supported by blink. It will be
425 // passed back to the browser in the DidCommitProvisionalLoad and the
426 // DocumentLoadComplete IPCs.
427 base::TimeDelta ui_timestamp
= common_params
.ui_timestamp
- base::TimeTicks();
428 request
.setUiStartTime(ui_timestamp
.InSecondsF());
429 request
.setInputPerfMetricReportPolicy(
430 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy
>(
431 common_params
.report_type
));
435 void UpdateFrameNavigationTiming(WebFrame
* frame
,
436 base::TimeTicks browser_navigation_start
,
437 base::TimeTicks renderer_navigation_start
) {
438 // The browser provides the navigation_start time to bootstrap the
439 // Navigation Timing information for the browser-initiated navigations. In
440 // case of cross-process navigations, this carries over the time of
441 // finishing the onbeforeunload handler of the previous page.
442 DCHECK(!browser_navigation_start
.is_null());
443 if (frame
->provisionalDataSource()) {
444 // |browser_navigation_start| is likely before this process existed, so we
445 // can't use InterProcessTimeTicksConverter. We need at least to ensure
446 // that the browser-side navigation start we set is not later than the one
447 // on the renderer side.
448 base::TimeTicks navigation_start
= std::min(
449 browser_navigation_start
, renderer_navigation_start
);
450 double navigation_start_seconds
=
451 (navigation_start
- base::TimeTicks()).InSecondsF();
452 frame
->provisionalDataSource()->setNavigationStartTime(
453 navigation_start_seconds
);
454 // TODO(clamy): We need to provide additional timing values for the
455 // Navigation Timing API to work with browser-side navigations.
460 CommonNavigationParams
MakeCommonNavigationParams(
461 blink::WebURLRequest
* request
) {
462 const RequestExtraData kEmptyData
;
463 const RequestExtraData
* extra_data
=
464 static_cast<RequestExtraData
*>(request
->extraData());
466 extra_data
= &kEmptyData
;
468 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
469 request
->referrerPolicy());
471 // Set the ui timestamp for this navigation. Currently the timestamp here is
472 // only non empty when the navigation was triggered by an Android intent, or
473 // by the user clicking on a link. The timestamp is converted from a double
474 // version supported by blink. It will be passed back to the renderer in the
475 // CommitNavigation IPC, and then back to the browser again in the
476 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
477 base::TimeTicks ui_timestamp
=
478 base::TimeTicks() + base::TimeDelta::FromSecondsD(request
->uiStartTime());
479 FrameMsg_UILoadMetricsReportType::Value report_type
=
480 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
481 request
->inputPerfMetricReportPolicy());
482 return CommonNavigationParams(request
->url(), referrer
,
483 extra_data
->transition_type(),
484 FrameMsg_Navigate_Type::NORMAL
, true,
485 ui_timestamp
, report_type
, GURL(), GURL());
488 #if !defined(OS_ANDROID)
489 media::Context3D
GetSharedMainThreadContext3D() {
490 cc::ContextProvider
* provider
=
491 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
493 return media::Context3D();
494 return media::Context3D(provider
->ContextGL(), provider
->GrContext());
498 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type
) {
499 return navigation_type
== FrameMsg_Navigate_Type::RELOAD
||
500 navigation_type
== FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
||
501 navigation_type
== FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
;
504 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl
=
507 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
509 static_cast<int>(content_name) == static_cast<int>(blink_name), \
510 "enum values must match")
512 // Check that blink::WebSandboxFlags is kept in sync with
513 // content::SandboxFlags.
514 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE
,
515 blink::WebSandboxFlags::None
);
516 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION
,
517 blink::WebSandboxFlags::Navigation
);
518 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS
,
519 blink::WebSandboxFlags::Plugins
);
520 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN
,
521 blink::WebSandboxFlags::Origin
);
522 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS
,
523 blink::WebSandboxFlags::Forms
);
524 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS
,
525 blink::WebSandboxFlags::Scripts
);
526 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION
,
527 blink::WebSandboxFlags::TopNavigation
);
528 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS
,
529 blink::WebSandboxFlags::Popups
);
530 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES
,
531 blink::WebSandboxFlags::AutomaticFeatures
);
532 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK
,
533 blink::WebSandboxFlags::PointerLock
);
534 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN
,
535 blink::WebSandboxFlags::DocumentDomain
);
536 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK
,
537 blink::WebSandboxFlags::OrientationLock
);
538 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL
,
539 blink::WebSandboxFlags::All
);
544 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
546 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
548 if (g_create_render_frame_impl
)
549 return g_create_render_frame_impl(render_view
, routing_id
);
551 return new RenderFrameImpl(render_view
, routing_id
);
555 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int32 routing_id
) {
556 RoutingIDFrameMap::iterator iter
=
557 g_routing_id_frame_map
.Get().find(routing_id
);
558 if (iter
!= g_routing_id_frame_map
.Get().end())
564 void RenderFrameImpl::CreateFrame(
566 int parent_routing_id
,
567 int proxy_routing_id
,
568 const FrameReplicationState
& replicated_state
,
569 CompositorDependencies
* compositor_deps
,
570 const FrameMsg_NewFrame_WidgetParams
& widget_params
) {
571 // TODO(nasko): For now, this message is only sent for subframes, as the
572 // top level frame is created when the RenderView is created through the
574 CHECK_NE(MSG_ROUTING_NONE
, parent_routing_id
);
576 blink::WebLocalFrame
* web_frame
;
577 RenderFrameImpl
* render_frame
;
578 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
579 RenderFrameProxy
* parent_proxy
=
580 RenderFrameProxy::FromRoutingID(parent_routing_id
);
581 // If the browser is sending a valid parent routing id, it should already
582 // be created and registered.
584 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
586 // Create the RenderFrame and WebLocalFrame, linking the two.
588 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
589 web_frame
= parent_web_frame
->createLocalChild(
590 WebString::fromUTF8(replicated_state
.name
),
591 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
), render_frame
);
593 RenderFrameProxy
* proxy
=
594 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
596 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
597 web_frame
= blink::WebLocalFrame::create(render_frame
);
598 render_frame
->proxy_routing_id_
= proxy_routing_id
;
599 web_frame
->initializeToReplaceRemoteFrame(
600 proxy
->web_frame(), WebString::fromUTF8(replicated_state
.name
),
601 ContentToWebSandboxFlags(replicated_state
.sandbox_flags
));
603 render_frame
->SetWebFrame(web_frame
);
605 if (widget_params
.routing_id
!= MSG_ROUTING_NONE
) {
606 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
607 switches::kSitePerProcess
));
608 render_frame
->render_widget_
= RenderWidget::CreateForFrame(
609 widget_params
.routing_id
, widget_params
.surface_id
,
610 widget_params
.hidden
, render_frame
->render_view_
->screen_info(),
611 compositor_deps
, web_frame
);
612 // TODO(kenrb): Observing shouldn't be necessary when we sort out
613 // WasShown and WasHidden, separating page-level visibility from
614 // frame-level visibility.
615 render_frame
->render_widget_
->RegisterRenderFrame(render_frame
);
618 render_frame
->Initialize();
622 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
623 return RenderFrameImpl::FromWebFrame(web_frame
);
627 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
628 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
629 if (iter
!= g_frame_map
.Get().end())
635 void RenderFrameImpl::InstallCreateHook(
636 CreateRenderFrameImplFunction create_render_frame_impl
) {
637 CHECK(!g_create_render_frame_impl
);
638 g_create_render_frame_impl
= create_render_frame_impl
;
642 content::SandboxFlags
RenderFrameImpl::WebToContentSandboxFlags(
643 blink::WebSandboxFlags flags
) {
644 return static_cast<content::SandboxFlags
>(flags
);
648 blink::WebSandboxFlags
RenderFrameImpl::ContentToWebSandboxFlags(
649 content::SandboxFlags flags
) {
650 return static_cast<blink::WebSandboxFlags
>(flags
);
653 // RenderFrameImpl ----------------------------------------------------------
654 RenderFrameImpl::RenderFrameImpl(RenderViewImpl
* render_view
, int routing_id
)
656 is_local_root_(false),
657 render_view_(render_view
->AsWeakPtr()),
658 routing_id_(routing_id
),
659 is_swapped_out_(false),
660 render_frame_proxy_(NULL
),
661 is_detaching_(false),
662 proxy_routing_id_(MSG_ROUTING_NONE
),
663 #if defined(ENABLE_PLUGINS)
664 plugin_power_saver_helper_(NULL
),
667 selection_text_offset_(0),
668 selection_range_(gfx::Range::InvalidRange()),
669 handling_select_range_(false),
670 notification_permission_dispatcher_(NULL
),
671 web_user_media_client_(NULL
),
672 media_permission_dispatcher_(NULL
),
673 midi_dispatcher_(NULL
),
674 #if defined(OS_ANDROID)
675 media_player_manager_(NULL
),
677 #if defined(ENABLE_BROWSER_CDMS)
681 #if defined(VIDEO_HOLE)
682 contains_media_player_(false),
684 devtools_agent_(nullptr),
685 geolocation_dispatcher_(NULL
),
686 push_messaging_dispatcher_(NULL
),
687 presentation_dispatcher_(NULL
),
688 screen_orientation_dispatcher_(NULL
),
689 manifest_manager_(NULL
),
690 accessibility_mode_(AccessibilityModeOff
),
691 renderer_accessibility_(NULL
),
692 weak_factory_(this) {
693 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
694 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
695 CHECK(result
.second
) << "Inserting a duplicate item.";
697 RenderThread::Get()->AddRoute(routing_id_
, this);
699 render_view_
->RegisterRenderFrame(this);
701 // Everything below subclasses RenderFrameObserver and is automatically
702 // deleted when the RenderFrame gets deleted.
703 #if defined(OS_ANDROID)
704 new GinJavaBridgeDispatcher(this);
707 #if defined(ENABLE_PLUGINS)
708 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
711 manifest_manager_
= new ManifestManager(this);
714 RenderFrameImpl::~RenderFrameImpl() {
715 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
716 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
718 #if defined(VIDEO_HOLE)
719 if (contains_media_player_
)
720 render_view_
->UnregisterVideoHoleFrame(this);
723 if (render_frame_proxy_
)
724 delete render_frame_proxy_
;
726 render_view_
->UnregisterRenderFrame(this);
727 g_routing_id_frame_map
.Get().erase(routing_id_
);
728 RenderThread::Get()->RemoveRoute(routing_id_
);
731 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
734 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
735 std::make_pair(web_frame
, this));
736 CHECK(result
.second
) << "Inserting a duplicate item.";
741 void RenderFrameImpl::Initialize() {
742 is_local_root_
= !frame_
->parent() || frame_
->parent()->isWebRemoteFrame();
744 #if defined(ENABLE_PLUGINS)
745 new PepperBrowserConnection(this);
747 new SharedWorkerRepository(this);
749 if (!frame_
->parent())
750 new ImageLoadingHelper(this);
752 if (is_local_root_
&& !render_frame_proxy_
) {
753 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
754 // when |this| is deleted.
755 devtools_agent_
= new DevToolsAgent(this);
758 // We delay calling this until we have the WebFrame so that any observer or
759 // embedder can call GetWebFrame on any RenderFrame.
760 GetContentClient()->renderer()->RenderFrameCreated(this);
763 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
764 return render_view_
.get();
767 #if defined(ENABLE_PLUGINS)
768 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
769 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
770 DidCreatePepperPlugin(host
));
771 if (host
->GetPluginName() == kFlashPluginName
) {
772 RenderThread::Get()->RecordAction(
773 base::UserMetricsAction("FrameLoadWithFlash"));
777 void RenderFrameImpl::PepperDidChangeCursor(
778 PepperPluginInstanceImpl
* instance
,
779 const blink::WebCursorInfo
& cursor
) {
780 // Update the cursor appearance immediately if the requesting plugin is the
781 // one which receives the last mouse event. Otherwise, the new cursor won't be
782 // picked up until the plugin gets the next input event. That is bad if, e.g.,
783 // the plugin would like to set an invisible cursor when there isn't any user
784 // input for a while.
785 if (instance
== render_view_
->pepper_last_mouse_event_target())
786 GetRenderWidget()->didChangeCursor(cursor
);
789 void RenderFrameImpl::PepperDidReceiveMouseEvent(
790 PepperPluginInstanceImpl
* instance
) {
791 render_view_
->set_pepper_last_mouse_event_target(instance
);
794 void RenderFrameImpl::PepperTextInputTypeChanged(
795 PepperPluginInstanceImpl
* instance
) {
796 if (instance
!= render_view_
->focused_pepper_plugin())
799 GetRenderWidget()->UpdateTextInputType();
801 FocusedNodeChangedForAccessibility(WebNode());
804 void RenderFrameImpl::PepperCaretPositionChanged(
805 PepperPluginInstanceImpl
* instance
) {
806 if (instance
!= render_view_
->focused_pepper_plugin())
808 GetRenderWidget()->UpdateSelectionBounds();
811 void RenderFrameImpl::PepperCancelComposition(
812 PepperPluginInstanceImpl
* instance
) {
813 if (instance
!= render_view_
->focused_pepper_plugin())
815 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
816 #if defined(OS_MACOSX) || defined(USE_AURA)
817 GetRenderWidget()->UpdateCompositionInfo(true);
821 void RenderFrameImpl::PepperSelectionChanged(
822 PepperPluginInstanceImpl
* instance
) {
823 if (instance
!= render_view_
->focused_pepper_plugin())
825 SyncSelectionIfRequired();
828 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
829 PepperPluginInstanceImpl
* plugin
) {
831 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
832 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
833 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
834 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
835 plugin
, active_url
, GetRenderWidget()->screenInfo());
836 widget
->show(blink::WebNavigationPolicyIgnore
);
840 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
841 if (!render_view_
->focused_pepper_plugin())
843 return render_view_
->focused_pepper_plugin()->
844 IsPluginAcceptingCompositionEvents();
847 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
848 base::ProcessId plugin_pid
) {
849 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
850 // routing_id_ as a result.
851 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
854 void RenderFrameImpl::SimulateImeSetComposition(
855 const base::string16
& text
,
856 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
859 render_view_
->OnImeSetComposition(
860 text
, underlines
, selection_start
, selection_end
);
863 void RenderFrameImpl::SimulateImeConfirmComposition(
864 const base::string16
& text
,
865 const gfx::Range
& replacement_range
) {
866 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
869 void RenderFrameImpl::OnImeSetComposition(
870 const base::string16
& text
,
871 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
874 // When a PPAPI plugin has focus, we bypass WebKit.
875 if (!IsPepperAcceptingCompositionEvents()) {
876 pepper_composition_text_
= text
;
878 // TODO(kinaba) currently all composition events are sent directly to
879 // plugins. Use DOM event mechanism after WebKit is made aware about
880 // plugins that support composition.
881 // The code below mimics the behavior of WebCore::Editor::setComposition.
883 // Empty -> nonempty: composition started.
884 if (pepper_composition_text_
.empty() && !text
.empty()) {
885 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
888 // Nonempty -> empty: composition canceled.
889 if (!pepper_composition_text_
.empty() && text
.empty()) {
890 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
893 pepper_composition_text_
= text
;
894 // Nonempty: composition is ongoing.
895 if (!pepper_composition_text_
.empty()) {
896 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
897 pepper_composition_text_
, underlines
, selection_start
,
903 void RenderFrameImpl::OnImeConfirmComposition(
904 const base::string16
& text
,
905 const gfx::Range
& replacement_range
,
906 bool keep_selection
) {
907 // When a PPAPI plugin has focus, we bypass WebKit.
908 // Here, text.empty() has a special meaning. It means to commit the last
909 // update of composition text (see
910 // RenderWidgetHost::ImeConfirmComposition()).
911 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
914 // last_text is empty only when both text and pepper_composition_text_ is.
916 if (last_text
.empty())
919 if (!IsPepperAcceptingCompositionEvents()) {
920 base::i18n::UTF16CharIterator
iterator(&last_text
);
922 while (iterator
.Advance()) {
923 blink::WebKeyboardEvent char_event
;
924 char_event
.type
= blink::WebInputEvent::Char
;
925 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
926 char_event
.modifiers
= 0;
927 char_event
.windowsKeyCode
= last_text
[i
];
928 char_event
.nativeKeyCode
= last_text
[i
];
930 const int32 char_start
= i
;
931 for (; i
< iterator
.array_pos(); ++i
) {
932 char_event
.text
[i
- char_start
] = last_text
[i
];
933 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
936 if (GetRenderWidget()->webwidget())
937 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
940 // Mimics the order of events sent by WebKit.
941 // See WebCore::Editor::setComposition() for the corresponding code.
942 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
943 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
945 pepper_composition_text_
.clear();
947 #endif // defined(ENABLE_PLUGINS)
949 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
950 if (!web_user_media_client_
)
951 InitializeUserMediaClient();
952 return web_user_media_client_
?
953 web_user_media_client_
->media_stream_dispatcher() : NULL
;
956 bool RenderFrameImpl::Send(IPC::Message
* message
) {
961 if (is_swapped_out_
) {
962 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
968 return RenderThread::Get()->Send(message
);
971 #if defined(OS_MACOSX) || defined(OS_ANDROID)
972 void RenderFrameImpl::DidHideExternalPopupMenu() {
973 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
974 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
975 external_popup_menu_
.reset();
979 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
980 // We may get here while detaching, when the WebFrame has been deleted. Do
981 // not process any messages in this state.
985 // TODO(kenrb): document() should not be null, but as a transitional step
986 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
987 // to this method. This happens for a top-level remote frame, where a
988 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
989 // around and is still able to receive messages.
990 if (!frame_
->document().isNull())
991 GetContentClient()->SetActiveURL(frame_
->document().url());
993 ObserverListBase
<RenderFrameObserver
>::Iterator
it(&observers_
);
994 RenderFrameObserver
* observer
;
995 while ((observer
= it
.GetNext()) != NULL
) {
996 if (observer
->OnMessageReceived(msg
))
1000 bool handled
= true;
1001 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
1002 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
1003 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
1004 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
1005 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
1006 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
1007 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
1008 OnCustomContextMenuAction
)
1009 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
1010 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
1011 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
1012 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
1013 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
1014 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
1015 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
1016 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
1017 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
1018 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
1019 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
1020 OnMoveRangeSelectionExtent
)
1021 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
1022 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
1023 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
1024 OnExtendSelectionAndDelete
)
1025 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
1026 OnSetCompositionFromExistingText
)
1027 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand
,
1028 OnExecuteNoValueEditCommand
)
1029 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
1030 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
1031 OnJavaScriptExecuteRequest
)
1032 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
1033 OnJavaScriptExecuteRequestForTests
)
1034 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest
,
1035 OnVisualStateRequest
)
1036 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
1037 OnSetEditableSelectionOffsets
)
1038 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView
, OnSetupTransitionView
)
1039 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition
, OnBeginExitTransition
)
1040 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition
, OnRevertExitTransition
)
1041 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements
,
1042 OnHideTransitionElements
)
1043 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements
,
1044 OnShowTransitionElements
)
1045 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
1046 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
1047 OnTextSurroundingSelectionRequest
)
1048 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL
,
1049 OnAddStyleSheetByURL
)
1050 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
1051 OnSetAccessibilityMode
)
1052 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree
,
1053 OnSnapshotAccessibilityTree
)
1054 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
1055 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
1056 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags
, OnDidUpdateSandboxFlags
)
1057 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings
,
1058 OnTextTrackSettingsChanged
)
1059 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent
, OnPostMessageEvent
)
1060 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation
, OnFailedNavigation
)
1061 #if defined(OS_ANDROID)
1062 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
1063 #elif defined(OS_MACOSX)
1064 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
1065 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
1067 IPC_END_MESSAGE_MAP()
1072 void RenderFrameImpl::OnNavigate(
1073 const CommonNavigationParams
& common_params
,
1074 const StartNavigationParams
& start_params
,
1075 const RequestNavigationParams
& request_params
) {
1076 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1077 switches::kEnableBrowserSideNavigation
));
1078 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_
,
1079 "url", common_params
.url
.possibly_invalid_spec());
1081 bool is_reload
= IsReload(common_params
.navigation_type
);
1082 bool is_history_navigation
= request_params
.page_state
.IsValid();
1083 WebURLRequest::CachePolicy cache_policy
=
1084 WebURLRequest::UseProtocolCachePolicy
;
1085 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1086 common_params
.url
, is_history_navigation
, request_params
, &is_reload
,
1088 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
1092 GetContentClient()->SetActiveURL(common_params
.url
);
1094 WebFrame
* frame
= frame_
;
1095 if (!request_params
.frame_to_navigate
.empty()) {
1096 // TODO(nasko): Move this lookup to the browser process.
1097 frame
= render_view_
->webview()->findFrameByName(
1098 WebString::fromUTF8(request_params
.frame_to_navigate
));
1099 CHECK(frame
) << "Invalid frame name passed: "
1100 << request_params
.frame_to_navigate
;
1103 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
1104 // We cannot reload if we do not have any history state. This happens, for
1105 // example, when recovering from a crash.
1107 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1110 pending_navigation_params_
.reset(
1111 new NavigationParams(common_params
, start_params
, request_params
));
1113 // If we are reloading, then WebKit will use the history state of the current
1114 // page, so we should just ignore any given history state. Otherwise, if we
1115 // have history state, then we need to navigate to it, which corresponds to a
1116 // back/forward navigation event.
1118 bool reload_original_url
=
1119 (common_params
.navigation_type
==
1120 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1121 bool ignore_cache
= (common_params
.navigation_type
==
1122 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1124 if (reload_original_url
)
1125 frame
->reloadWithOverrideURL(common_params
.url
, true);
1127 frame
->reload(ignore_cache
);
1128 } else if (is_history_navigation
) {
1129 // We must know the page ID of the page we are navigating back to.
1130 DCHECK_NE(request_params
.page_id
, -1);
1131 scoped_ptr
<HistoryEntry
> entry
=
1132 PageStateToHistoryEntry(request_params
.page_state
);
1134 // Ensure we didn't save the swapped out URL in UpdateState, since the
1135 // browser should never be telling us to navigate to swappedout://.
1136 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
1137 scoped_ptr
<NavigationParams
> navigation_params(
1138 new NavigationParams(*pending_navigation_params_
.get()));
1139 render_view_
->history_controller()->GoToEntry(
1140 entry
.Pass(), navigation_params
.Pass(), cache_policy
);
1142 } else if (!common_params
.base_url_for_data_url
.is_empty()) {
1143 LoadDataURL(common_params
, frame
);
1145 // Navigate to the given URL.
1146 WebURLRequest request
= CreateURLRequestForNavigation(
1147 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
1148 frame
->isViewSourceModeEnabled());
1150 if (!start_params
.extra_headers
.empty()) {
1151 for (net::HttpUtil::HeadersIterator
i(start_params
.extra_headers
.begin(),
1152 start_params
.extra_headers
.end(),
1155 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
1156 WebString::fromUTF8(i
.values()));
1160 if (start_params
.is_post
) {
1161 request
.setHTTPMethod(WebString::fromUTF8("POST"));
1164 WebHTTPBody http_body
;
1165 http_body
.initialize();
1166 const char* data
= NULL
;
1167 if (start_params
.browser_initiated_post_data
.size()) {
1168 data
= reinterpret_cast<const char*>(
1169 &start_params
.browser_initiated_post_data
.front());
1171 http_body
.appendData(
1172 WebData(data
, start_params
.browser_initiated_post_data
.size()));
1173 request
.setHTTPBody(http_body
);
1176 // A session history navigation should have been accompanied by state.
1177 CHECK_EQ(request_params
.page_id
, -1);
1179 // Record this before starting the load, we need a lower bound of this time
1180 // to sanitize the navigationStart override set below.
1181 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
1182 frame
->loadRequest(request
);
1184 UpdateFrameNavigationTiming(frame
, request_params
.browser_navigation_start
,
1185 renderer_navigation_start
);
1188 // In case LoadRequest failed before didCreateDataSource was called.
1189 pending_navigation_params_
.reset();
1192 void RenderFrameImpl::NavigateToSwappedOutURL() {
1193 // We use loadRequest instead of loadHTMLString because the former commits
1194 // synchronously. Otherwise a new navigation can interrupt the navigation
1195 // to kSwappedOutURL. If that happens to be to the page we had been
1196 // showing, then WebKit will never send a commit and we'll be left spinning.
1197 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1198 // the navigation to swappedout:// is not announced to the browser side.
1199 is_swapped_out_
= true;
1200 GURL
swappedOutURL(kSwappedOutURL
);
1201 WebURLRequest
request(swappedOutURL
);
1202 frame_
->loadRequest(request
);
1205 void RenderFrameImpl::BindServiceRegistry(
1206 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
1207 mojo::ServiceProviderPtr exposed_services
) {
1208 service_registry_
.Bind(services
.Pass());
1209 service_registry_
.BindRemoteServiceProvider(exposed_services
.Pass());
1212 ManifestManager
* RenderFrameImpl::manifest_manager() {
1213 return manifest_manager_
;
1216 void RenderFrameImpl::SetPendingNavigationParams(
1217 scoped_ptr
<NavigationParams
> navigation_params
) {
1218 pending_navigation_params_
= navigation_params
.Pass();
1221 void RenderFrameImpl::OnBeforeUnload() {
1222 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1224 // TODO(creis): Right now, this is only called on the main frame. Make the
1225 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1227 CHECK(!frame_
->parent());
1229 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1230 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1231 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1232 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1233 before_unload_start_time
,
1234 before_unload_end_time
));
1237 void RenderFrameImpl::OnSwapOut(
1238 int proxy_routing_id
,
1240 const FrameReplicationState
& replicated_frame_state
) {
1241 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1242 RenderFrameProxy
* proxy
= NULL
;
1243 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
1244 switches::kSitePerProcess
);
1245 bool is_main_frame
= !frame_
->parent();
1247 // Only run unload if we're not swapped out yet, but send the ack either way.
1248 if (!is_swapped_out_
) {
1249 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1250 // a different process. This involves running the unload handler and
1251 // clearing the page. We also allow this process to exit if there are no
1252 // other active RenderFrames in it.
1254 // Send an UpdateState message before we get swapped out.
1255 render_view_
->SyncNavigationState();
1257 // If we need a proxy to replace this, create it now so its routing id is
1258 // registered for receiving IPC messages.
1259 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1260 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(this,
1264 // Synchronously run the unload handler before sending the ACK.
1265 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1266 // unload on subframes as well.
1268 frame_
->dispatchUnloadEvent();
1270 // Swap out and stop sending any IPC messages that are not ACKs.
1272 render_view_
->SetSwappedOut(true);
1273 is_swapped_out_
= true;
1275 // Set the proxy here, since OnStop() below could cause an onload event
1276 // handler to execute, which could trigger code such as
1277 // willCheckAndDispatchMessageEvent() that needs the proxy.
1279 set_render_frame_proxy(proxy
);
1281 // Now that we're swapped out and filtering IPC messages, stop loading to
1282 // ensure that no other in-progress navigation continues. We do this here
1283 // to avoid sending a DidStopLoading message to the browser process.
1284 // TODO(creis): Should we be stopping all frames here and using
1285 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1289 // Transfer settings such as initial drawing parameters to the remote frame,
1290 // if one is created, that will replace this frame.
1291 if (!is_main_frame
&& proxy
)
1292 proxy
->web_frame()->initializeFromFrame(frame_
);
1294 // Replace the page with a blank dummy URL. The unload handler will not be
1295 // run a second time, thanks to a check in FrameLoader::stopLoading.
1296 // TODO(creis): Need to add a better way to do this that avoids running the
1297 // beforeunload handler. For now, we just run it a second time silently.
1298 if (!is_site_per_process
|| is_main_frame
)
1299 NavigateToSwappedOutURL();
1301 // Let WebKit know that this view is hidden so it can drop resources and
1302 // stop compositing.
1303 // TODO(creis): Support this for subframes as well.
1304 if (is_main_frame
) {
1305 render_view_
->webview()->setVisibilityState(
1306 blink::WebPageVisibilityStateHidden
, false);
1310 // It is now safe to show modal dialogs again.
1311 // TODO(creis): Deal with modal dialogs from subframes.
1313 render_view_
->suppress_dialogs_until_swap_out_
= false;
1315 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1317 // Now that all of the cleanup is complete and the browser side is notified,
1318 // start using the RenderFrameProxy, if one is created.
1320 if (!is_main_frame
) {
1321 frame_
->swap(proxy
->web_frame());
1324 proxy
->OnDidStartLoading();
1326 if (is_site_per_process
) {
1327 // TODO(nasko): delete the frame here, since we've replaced it with a
1333 // In --site-per-process, initialize the WebRemoteFrame with the replication
1334 // state passed by the process that is now rendering the frame.
1335 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1336 // in that case we leave the LocalFrame as the main frame visible to Blink
1337 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1338 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1339 // When we do an unconditional swap for all frames, we can remove
1340 // !is_main_frame below.
1341 if (is_site_per_process
&& proxy
&& !is_main_frame
)
1342 proxy
->SetReplicatedState(replicated_frame_state
);
1344 // Safe to exit if no one else is using the process.
1346 render_view_
->WasSwappedOut();
1349 void RenderFrameImpl::OnContextMenuClosed(
1350 const CustomContextMenuContext
& custom_context
) {
1351 if (custom_context
.request_id
) {
1352 // External request, should be in our map.
1353 ContextMenuClient
* client
=
1354 pending_context_menus_
.Lookup(custom_context
.request_id
);
1356 client
->OnMenuClosed(custom_context
.request_id
);
1357 pending_context_menus_
.Remove(custom_context
.request_id
);
1360 if (custom_context
.link_followed
.is_valid()) {
1362 DomUtils::ExtractParentAnchorNode(context_menu_node_
),
1363 custom_context
.link_followed
);
1365 // Internal request, forward to WebKit.
1366 context_menu_node_
.reset();
1370 void RenderFrameImpl::OnCustomContextMenuAction(
1371 const CustomContextMenuContext
& custom_context
,
1373 if (custom_context
.request_id
) {
1374 // External context menu request, look in our map.
1375 ContextMenuClient
* client
=
1376 pending_context_menus_
.Lookup(custom_context
.request_id
);
1378 client
->OnMenuAction(custom_context
.request_id
, action
);
1380 // Internal request, forward to WebKit.
1381 render_view_
->webview()->performCustomContextMenuAction(action
);
1385 void RenderFrameImpl::OnUndo() {
1386 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1389 void RenderFrameImpl::OnRedo() {
1390 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1393 void RenderFrameImpl::OnCut() {
1394 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1395 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1398 void RenderFrameImpl::OnCopy() {
1399 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1400 WebNode current_node
= context_menu_node_
.isNull() ?
1401 GetFocusedElement() : context_menu_node_
;
1402 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1405 void RenderFrameImpl::OnPaste() {
1406 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1407 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1410 void RenderFrameImpl::OnPasteAndMatchStyle() {
1411 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1412 frame_
->executeCommand(
1413 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1416 #if defined(OS_MACOSX)
1417 void RenderFrameImpl::OnCopyToFindPboard() {
1418 // Since the find pasteboard supports only plain text, this can be simpler
1419 // than the |OnCopy()| case.
1420 if (frame_
->hasSelection()) {
1421 base::string16 selection
= frame_
->selectionAsText();
1422 RenderThread::Get()->Send(
1423 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1428 void RenderFrameImpl::OnDelete() {
1429 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1432 void RenderFrameImpl::OnSelectAll() {
1433 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1434 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1437 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1438 const gfx::Point
& extent
) {
1439 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1440 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1442 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1443 frame_
->selectRange(base
, extent
);
1446 void RenderFrameImpl::OnUnselect() {
1447 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1448 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1451 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1452 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1453 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1454 GetRenderWidget()->routing_id()));
1456 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1457 frame_
->moveRangeSelectionExtent(point
);
1460 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1461 if (!frame_
->hasSelection())
1462 frame_
->selectWordAroundCaret();
1464 frame_
->replaceSelection(text
);
1467 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1468 if (!frame_
->hasSelection())
1471 frame_
->replaceMisspelledRange(text
);
1474 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1475 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1478 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1479 const base::string16
& jscript
,
1481 bool notify_result
) {
1482 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1483 TRACE_EVENT_SCOPE_THREAD
);
1485 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1486 v8::Handle
<v8::Value
> result
=
1487 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1489 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1492 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1493 const base::string16
& jscript
,
1495 bool notify_result
) {
1496 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1497 TRACE_EVENT_SCOPE_THREAD
);
1499 // A bunch of tests expect to run code in the context of a user gesture, which
1500 // can grant additional privileges (e.g. the ability to create popups).
1501 blink::WebScopedUserGesture gesture
;
1502 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1503 v8::Handle
<v8::Value
> result
=
1504 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1506 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1509 void RenderFrameImpl::HandleJavascriptExecutionResult(
1510 const base::string16
& jscript
,
1513 v8::Handle
<v8::Value
> result
) {
1514 if (notify_result
) {
1515 base::ListValue list
;
1516 if (!result
.IsEmpty()) {
1517 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1518 v8::Context::Scope
context_scope(context
);
1519 V8ValueConverterImpl converter
;
1520 converter
.SetDateAllowed(true);
1521 converter
.SetRegExpAllowed(true);
1522 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
1523 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
1525 list
.Set(0, base::Value::CreateNullValue());
1527 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1531 void RenderFrameImpl::OnVisualStateRequest(uint64 id
) {
1532 GetRenderWidget()->QueueMessage(
1533 new FrameHostMsg_VisualStateResponse(routing_id_
, id
),
1534 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
1537 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1538 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1539 if (!GetRenderWidget()->ShouldHandleImeEvent())
1541 ImeEventGuard
guard(GetRenderWidget());
1542 frame_
->setEditableSelectionOffsets(start
, end
);
1545 void RenderFrameImpl::OnSetCompositionFromExistingText(
1547 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1548 if (!GetRenderWidget()->ShouldHandleImeEvent())
1550 ImeEventGuard
guard(GetRenderWidget());
1551 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1554 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string
& name
) {
1555 frame_
->executeCommand(WebString::fromUTF8(name
), GetFocusedElement());
1558 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1559 if (!GetRenderWidget()->ShouldHandleImeEvent())
1561 ImeEventGuard
guard(GetRenderWidget());
1562 frame_
->extendSelectionAndDelete(before
, after
);
1565 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1566 if (accessibility_mode_
== new_mode
)
1568 accessibility_mode_
= new_mode
;
1569 if (renderer_accessibility_
) {
1570 // Note: this isn't called automatically by the destructor because
1571 // there'd be no point in calling it in frame teardown, only if there's
1572 // an accessibility mode change but the frame is persisting.
1573 renderer_accessibility_
->DisableAccessibility();
1575 delete renderer_accessibility_
;
1576 renderer_accessibility_
= NULL
;
1578 if (accessibility_mode_
== AccessibilityModeOff
)
1581 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1582 renderer_accessibility_
= new RendererAccessibility(this);
1585 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id
) {
1586 ui::AXTreeUpdate response
;
1587 RendererAccessibility::SnapshotAccessibilityTree(this, &response
);
1588 Send(new AccessibilityHostMsg_SnapshotResponse(
1589 routing_id_
, callback_id
, response
));
1592 void RenderFrameImpl::OnDisownOpener() {
1593 // TODO(creis): We should only see this for main frames for now. To support
1594 // disowning the opener on subframes, we will need to move WebContentsImpl's
1595 // opener_ to FrameTreeNode.
1596 CHECK(!frame_
->parent());
1598 if (frame_
->opener())
1599 frame_
->setOpener(NULL
);
1602 void RenderFrameImpl::OnDidUpdateSandboxFlags(SandboxFlags flags
) {
1603 frame_
->setFrameOwnerSandboxFlags(ContentToWebSandboxFlags(flags
));
1606 void RenderFrameImpl::OnTextTrackSettingsChanged(
1607 const FrameMsg_TextTrackSettings_Params
& params
) {
1608 DCHECK(!frame_
->parent());
1609 if (!render_view_
->webview())
1611 render_view_
->webview()->settings()->setTextTrackBackgroundColor(
1612 WebString::fromUTF8(params
.text_track_background_color
));
1613 render_view_
->webview()->settings()->setTextTrackFontFamily(
1614 WebString::fromUTF8(params
.text_track_font_family
));
1615 render_view_
->webview()->settings()->setTextTrackFontStyle(
1616 WebString::fromUTF8(params
.text_track_font_style
));
1617 render_view_
->webview()->settings()->setTextTrackFontVariant(
1618 WebString::fromUTF8(params
.text_track_font_variant
));
1619 render_view_
->webview()->settings()->setTextTrackTextColor(
1620 WebString::fromUTF8(params
.text_track_text_color
));
1621 render_view_
->webview()->settings()->setTextTrackTextShadow(
1622 WebString::fromUTF8(params
.text_track_text_shadow
));
1623 render_view_
->webview()->settings()->setTextTrackTextSize(
1624 WebString::fromUTF8(params
.text_track_text_size
));
1627 void RenderFrameImpl::OnPostMessageEvent(
1628 const FrameMsg_PostMessage_Params
& params
) {
1629 // Find the source frame if it exists.
1630 WebFrame
* source_frame
= NULL
;
1631 if (params
.source_view_routing_id
!= MSG_ROUTING_NONE
) {
1632 // Support a legacy postMessage path for specifying a source RenderView;
1633 // this is currently used when sending messages to Android WebView.
1634 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1635 RenderViewImpl
* source_view
=
1636 RenderViewImpl::FromRoutingID(params
.source_view_routing_id
);
1638 source_frame
= source_view
->webview()->mainFrame();
1639 } else if (params
.source_routing_id
!= MSG_ROUTING_NONE
) {
1640 RenderFrameProxy
* source_proxy
=
1641 RenderFrameProxy::FromRoutingID(params
.source_routing_id
);
1643 // Currently, navigating a top-level frame cross-process does not swap
1644 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1645 // WebRemoteFrame will not have an associated blink::Frame. If this is
1646 // the case for |source_proxy|, use the corresponding (swapped-out)
1647 // WebLocalFrame instead, so that event.source for this message can be
1648 // set and used properly.
1649 if (source_proxy
->IsMainFrameDetachedFromTree())
1650 source_frame
= source_proxy
->render_view()->webview()->mainFrame();
1652 source_frame
= source_proxy
->web_frame();
1656 // If the message contained MessagePorts, create the corresponding endpoints.
1657 blink::WebMessagePortChannelArray channels
=
1658 WebMessagePortChannelImpl::CreatePorts(
1659 params
.message_ports
, params
.new_routing_ids
,
1660 base::MessageLoopProxy::current().get());
1662 WebSerializedScriptValue serialized_script_value
;
1663 if (params
.is_data_raw_string
) {
1664 v8::HandleScope
handle_scope(blink::mainThreadIsolate());
1665 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1666 v8::Context::Scope
context_scope(context
);
1667 V8ValueConverterImpl converter
;
1668 converter
.SetDateAllowed(true);
1669 converter
.SetRegExpAllowed(true);
1670 scoped_ptr
<base::Value
> value(new base::StringValue(params
.data
));
1671 v8::Handle
<v8::Value
> result_value
= converter
.ToV8Value(value
.get(),
1673 serialized_script_value
= WebSerializedScriptValue::serialize(result_value
);
1675 serialized_script_value
= WebSerializedScriptValue::fromString(params
.data
);
1678 // Create an event with the message. The next-to-last parameter to
1679 // initMessageEvent is the last event ID, which is not used with postMessage.
1680 WebDOMEvent event
= frame_
->document().createEvent("MessageEvent");
1681 WebDOMMessageEvent msg_event
= event
.to
<WebDOMMessageEvent
>();
1682 msg_event
.initMessageEvent("message",
1683 // |canBubble| and |cancellable| are always false
1685 serialized_script_value
,
1686 params
.source_origin
, source_frame
, "", channels
);
1688 // We must pass in the target_origin to do the security check on this side,
1689 // since it may have changed since the original postMessage call was made.
1690 WebSecurityOrigin target_origin
;
1691 if (!params
.target_origin
.empty()) {
1693 WebSecurityOrigin::createFromString(WebString(params
.target_origin
));
1695 frame_
->dispatchMessageEventWithOriginCheck(target_origin
, msg_event
);
1698 #if defined(OS_ANDROID)
1699 void RenderFrameImpl::OnSelectPopupMenuItems(
1701 const std::vector
<int>& selected_indices
) {
1702 // It is possible to receive more than one of these calls if the user presses
1703 // a select faster than it takes for the show-select-popup IPC message to make
1704 // it to the browser UI thread. Ignore the extra-messages.
1705 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1706 if (!external_popup_menu_
)
1709 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1710 external_popup_menu_
.reset();
1714 #if defined(OS_MACOSX)
1715 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1716 if (external_popup_menu_
== NULL
)
1718 external_popup_menu_
->DidSelectItem(selected_index
);
1719 external_popup_menu_
.reset();
1723 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1724 frame_
->reload(ignore_cache
);
1727 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1728 blink::WebSurroundingText surroundingText
;
1729 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1731 if (surroundingText
.isNull()) {
1732 // |surroundingText| might not be correctly initialized, for example if
1733 // |frame_->selectionRange().isNull()|, in other words, if there was no
1735 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1736 routing_id_
, base::string16(), 0, 0));
1740 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1742 surroundingText
.textContent(),
1743 surroundingText
.startOffsetInTextContent(),
1744 surroundingText
.endOffsetInTextContent()));
1747 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string
& url
) {
1748 frame_
->addStyleSheetByURL(WebString::fromUTF8(url
));
1751 void RenderFrameImpl::OnSetupTransitionView(const std::string
& markup
) {
1752 frame_
->document().setIsTransitionDocument(true);
1753 frame_
->navigateToSandboxedMarkup(WebData(markup
.data(), markup
.length()));
1756 void RenderFrameImpl::OnBeginExitTransition(const std::string
& css_selector
,
1757 bool exit_to_native_app
) {
1758 frame_
->document().setIsTransitionDocument(true);
1759 frame_
->document().beginExitTransition(WebString::fromUTF8(css_selector
),
1760 exit_to_native_app
);
1763 void RenderFrameImpl::OnRevertExitTransition() {
1764 frame_
->document().setIsTransitionDocument(false);
1765 frame_
->document().revertExitTransition();
1768 void RenderFrameImpl::OnHideTransitionElements(
1769 const std::string
& css_selector
) {
1770 frame_
->document().hideTransitionElements(WebString::fromUTF8(css_selector
));
1773 void RenderFrameImpl::OnShowTransitionElements(
1774 const std::string
& css_selector
) {
1775 frame_
->document().showTransitionElements(WebString::fromUTF8(css_selector
));
1778 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1779 const base::string16
& message
,
1780 const base::string16
& default_value
,
1781 const GURL
& frame_url
,
1782 base::string16
* result
) {
1783 // Don't allow further dialogs if we are waiting to swap out, since the
1784 // PageGroupLoadDeferrer in our stack prevents it.
1785 if (render_view()->suppress_dialogs_until_swap_out_
)
1788 bool success
= false;
1789 base::string16 result_temp
;
1791 result
= &result_temp
;
1793 render_view()->SendAndRunNestedMessageLoop(
1794 new FrameHostMsg_RunJavaScriptMessage(
1795 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1800 void RenderFrameImpl::LoadNavigationErrorPage(
1801 const WebURLRequest
& failed_request
,
1802 const WebURLError
& error
,
1804 std::string error_html
;
1805 GetContentClient()->renderer()->GetNavigationErrorStrings(
1806 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1808 frame_
->loadHTMLString(error_html
,
1809 GURL(kUnreachableWebDataURL
),
1810 error
.unreachableURL
,
1814 void RenderFrameImpl::DidCommitCompositorFrame() {
1815 if (BrowserPluginManager::Get())
1816 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1818 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1821 RenderView
* RenderFrameImpl::GetRenderView() {
1822 return render_view_
.get();
1825 int RenderFrameImpl::GetRoutingID() {
1829 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1834 WebElement
RenderFrameImpl::GetFocusedElement() const {
1835 WebDocument doc
= frame_
->document();
1837 return doc
.focusedElement();
1839 return WebElement();
1842 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1843 return render_view_
->GetWebkitPreferences();
1846 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1847 const ContextMenuParams
& params
) {
1848 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1849 ContextMenuParams
our_params(params
);
1850 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1851 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1852 return our_params
.custom_context
.request_id
;
1855 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1856 DCHECK(pending_context_menus_
.Lookup(request_id
));
1857 pending_context_menus_
.Remove(request_id
);
1860 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1861 return context_menu_node_
;
1864 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1865 blink::WebFrame
* frame
,
1866 const WebPluginInfo
& info
,
1867 const blink::WebPluginParams
& params
,
1868 scoped_ptr
<content::PluginInstanceThrottler
> throttler
) {
1869 DCHECK_EQ(frame_
, frame
);
1870 #if defined(ENABLE_PLUGINS)
1871 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1872 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1873 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1874 this, params
.mimeType
.utf8(), GURL(params
.url
)));
1875 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1876 this, browser_plugin_delegate
.Pass());
1879 bool pepper_plugin_was_registered
= false;
1880 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1881 this, info
, &pepper_plugin_was_registered
));
1882 if (pepper_plugin_was_registered
) {
1883 if (pepper_module
.get()) {
1884 return new PepperWebPluginImpl(
1885 pepper_module
.get(), params
, this,
1887 static_cast<PluginInstanceThrottlerImpl
*>(throttler
.release())));
1890 #if defined(OS_CHROMEOS)
1891 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1894 // TODO(jam): change to take RenderFrame.
1895 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1902 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1903 const blink::WebURLRequest
& request
,
1904 blink::WebNavigationPolicy policy
) {
1905 DCHECK(!frame_
|| frame_
== frame
);
1906 loadURLExternally(frame
, request
, policy
, WebString());
1909 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1910 OnJavaScriptExecuteRequest(javascript
, 0, false);
1913 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1914 return &service_registry_
;
1917 #if defined(ENABLE_PLUGINS)
1918 void RenderFrameImpl::RegisterPeripheralPlugin(
1919 const GURL
& content_origin
,
1920 const base::Closure
& unthrottle_callback
) {
1921 return plugin_power_saver_helper_
->RegisterPeripheralPlugin(
1922 content_origin
, unthrottle_callback
);
1924 #endif // defined(ENABLE_PLUGINS)
1926 bool RenderFrameImpl::IsFTPDirectoryListing() {
1927 WebURLResponseExtraDataImpl
* extra_data
=
1928 GetExtraDataFromResponse(frame_
->dataSource()->response());
1929 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1932 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1933 BrowserPluginManager::Get()->Attach(element_instance_id
);
1936 void RenderFrameImpl::DetachGuest(int element_instance_id
) {
1937 BrowserPluginManager::Get()->Detach(element_instance_id
);
1940 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1942 const gfx::Range
& range
) {
1943 // Use the routing id of Render Widget Host.
1944 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1950 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1951 v8::Isolate
* isolate
,
1952 v8::Local
<v8::Context
> context
) {
1953 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1954 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1957 v8::HandleScope
handle_scope(isolate
);
1958 registry
->AddBuiltinModule(
1959 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1960 registry
->AddBuiltinModule(isolate
,
1961 mojo::js::Support::kModuleName
,
1962 mojo::js::Support::GetModule(isolate
));
1963 registry
->AddBuiltinModule(
1965 ServiceRegistryJsWrapper::kModuleName
,
1966 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1969 // blink::WebFrameClient implementation ----------------------------------------
1971 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1972 blink::WebLocalFrame
* frame
,
1973 const blink::WebPluginParams
& params
) {
1974 DCHECK_EQ(frame_
, frame
);
1975 return GetContentClient()
1977 ->CreatePluginPlaceholder(this, frame
, params
)
1981 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1982 blink::WebLocalFrame
* frame
,
1983 const blink::WebPluginParams
& params
) {
1984 DCHECK_EQ(frame_
, frame
);
1985 blink::WebPlugin
* plugin
= NULL
;
1986 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1987 this, frame
, params
, &plugin
)) {
1991 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1992 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1993 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1994 kBrowserPluginMimeType
, GURL(params
.url
)));
1995 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1996 this, browser_plugin_delegate
.Pass());
1999 #if defined(ENABLE_PLUGINS)
2001 std::string mime_type
;
2003 Send(new FrameHostMsg_GetPluginInfo(
2004 routing_id_
, params
.url
, frame
->top()->document().url(),
2005 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
2009 WebPluginParams params_to_use
= params
;
2010 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
2011 return CreatePlugin(frame
, info
, params_to_use
, nullptr /* throttler */);
2014 #endif // defined(ENABLE_PLUGINS)
2017 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2018 blink::WebLocalFrame
* frame
,
2019 const blink::WebURL
& url
,
2020 blink::WebMediaPlayerClient
* client
) {
2021 return createMediaPlayer(frame
, url
, client
, nullptr);
2024 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
2025 blink::WebLocalFrame
* frame
,
2026 const blink::WebURL
& url
,
2027 blink::WebMediaPlayerClient
* client
,
2028 blink::WebContentDecryptionModule
* initial_cdm
) {
2029 #if defined(VIDEO_HOLE)
2030 if (!contains_media_player_
) {
2031 render_view_
->RegisterVideoHoleFrame(this);
2032 contains_media_player_
= true;
2034 #endif // defined(VIDEO_HOLE)
2036 blink::WebMediaStream
web_stream(
2037 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
2038 if (!web_stream
.isNull())
2039 return CreateWebMediaPlayerForMediaStream(url
, client
);
2041 #if defined(OS_ANDROID)
2042 return CreateAndroidWebMediaPlayer(url
, client
, GetMediaPermission(),
2045 scoped_refptr
<media::MediaLog
> media_log(new RenderMediaLog());
2047 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
2048 media::WebMediaPlayerParams
params(
2049 base::Bind(&ContentRendererClient::DeferMediaLoad
,
2050 base::Unretained(GetContentClient()->renderer()),
2051 static_cast<RenderFrame
*>(this)),
2052 render_thread
->GetAudioRendererMixerManager()->CreateInput(routing_id_
),
2053 media_log
, render_thread
->GetMediaThreadTaskRunner(),
2054 render_thread
->compositor_message_loop_proxy(),
2055 base::Bind(&GetSharedMainThreadContext3D
), GetMediaPermission(),
2058 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
2059 scoped_ptr
<media::RendererFactory
> media_renderer_factory(
2060 new media::MojoRendererFactory(make_scoped_ptr(
2061 new MediaRendererServiceProvider(GetServiceRegistry()))));
2063 scoped_ptr
<media::RendererFactory
> media_renderer_factory
=
2064 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
2067 if (!media_renderer_factory
.get()) {
2068 media_renderer_factory
.reset(new media::DefaultRendererFactory(
2069 media_log
, render_thread
->GetGpuFactories(),
2070 *render_thread
->GetAudioHardwareConfig()));
2072 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
2074 return new media::WebMediaPlayerImpl(
2075 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer_factory
.Pass(),
2076 GetCdmFactory(), params
);
2077 #endif // defined(OS_ANDROID)
2080 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
2081 blink::WebLocalFrame
* frame
,
2082 blink::WebApplicationCacheHostClient
* client
) {
2083 if (!frame
|| !frame
->view())
2085 DCHECK(!frame_
|| frame_
== frame
);
2086 return new RendererWebApplicationCacheHostImpl(
2087 RenderViewImpl::FromWebView(frame
->view()), client
,
2088 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2091 blink::WebWorkerContentSettingsClientProxy
*
2092 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2093 blink::WebLocalFrame
* frame
) {
2094 if (!frame
|| !frame
->view())
2096 DCHECK(!frame_
|| frame_
== frame
);
2097 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2101 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
2102 const WebPopupMenuInfo
& popup_menu_info
,
2103 WebExternalPopupMenuClient
* popup_menu_client
) {
2104 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2105 // An IPC message is sent to the browser to build and display the actual
2106 // popup. The user could have time to click a different select by the time
2107 // the popup is shown. In that case external_popup_menu_ is non NULL.
2108 // By returning NULL in that case, we instruct Blink to cancel that new
2109 // popup. So from the user perspective, only the first one will show, and
2110 // will have to close the first one before another one can be shown.
2111 if (external_popup_menu_
)
2113 external_popup_menu_
.reset(
2114 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
2115 if (render_view_
->screen_metrics_emulator_
) {
2116 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
2117 external_popup_menu_
.get(),
2118 render_view_
->screen_metrics_emulator_
.get());
2120 return external_popup_menu_
.get();
2126 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
2127 DCHECK(!frame_
|| frame_
== frame
);
2128 return &cookie_jar_
;
2131 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
2132 blink::WebLocalFrame
* frame
) {
2133 DCHECK(!frame_
|| frame_
== frame
);
2134 // At this point we should have non-null data source.
2135 DCHECK(frame
->dataSource());
2136 if (!ChildThreadImpl::current())
2137 return NULL
; // May be null in some tests.
2138 ServiceWorkerNetworkProvider
* provider
=
2139 ServiceWorkerNetworkProvider::FromDocumentState(
2140 DocumentState::FromDataSource(frame
->dataSource()));
2141 return new WebServiceWorkerProviderImpl(
2142 ChildThreadImpl::current()->thread_safe_sender(),
2143 provider
? provider
->context() : NULL
);
2146 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
2147 DCHECK(!frame_
|| frame_
== frame
);
2148 // If the request hasn't yet committed, notify the browser process that it is
2149 // no longer safe to show the pending URL of the main frame, since a URL spoof
2150 // is now possible. (If the request has committed, the browser already knows.)
2151 if (!frame
->parent()) {
2152 DocumentState
* document_state
=
2153 DocumentState::FromDataSource(frame
->dataSource());
2154 NavigationStateImpl
* navigation_state
=
2155 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2157 if (!navigation_state
->request_committed()) {
2158 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
2163 blink::WebFrame
* RenderFrameImpl::createChildFrame(
2164 blink::WebLocalFrame
* parent
,
2165 const blink::WebString
& name
,
2166 blink::WebSandboxFlags sandbox_flags
) {
2167 // Synchronously notify the browser of a child frame creation to get the
2168 // routing_id for the RenderFrame.
2169 int child_routing_id
= MSG_ROUTING_NONE
;
2170 Send(new FrameHostMsg_CreateChildFrame(
2171 routing_id_
, base::UTF16ToUTF8(name
),
2172 WebToContentSandboxFlags(sandbox_flags
), &child_routing_id
));
2174 // Allocation of routing id failed, so we can't create a child frame. This can
2175 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2176 // out state or synchronous IPC message above has failed.
2177 if (child_routing_id
== MSG_ROUTING_NONE
) {
2178 NOTREACHED() << "Failed to allocate routing id for child frame.";
2182 // Create the RenderFrame and WebLocalFrame, linking the two.
2183 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
2184 render_view_
.get(), child_routing_id
);
2185 blink::WebLocalFrame
* web_frame
= WebLocalFrame::create(child_render_frame
);
2186 child_render_frame
->SetWebFrame(web_frame
);
2188 // Add the frame to the frame tree and initialize it.
2189 parent
->appendChild(web_frame
);
2190 child_render_frame
->Initialize();
2195 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
2196 DCHECK(!frame_
|| frame_
== frame
);
2197 // We only need to notify the browser if the active, top-level frame clears
2198 // its opener. We can ignore cases where a swapped out frame clears its
2199 // opener after hearing about it from the browser, and the browser does not
2200 // (yet) care about subframe openers.
2201 if (is_swapped_out_
|| frame
->parent())
2204 // Notify WebContents and all its swapped out RenderViews.
2205 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
2208 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
) {
2209 // NOTE: This function is called on the frame that is being detached and not
2210 // the parent frame. This is different from createChildFrame() which is
2211 // called on the parent frame.
2212 CHECK(!is_detaching_
);
2213 DCHECK(!frame_
|| frame_
== frame
);
2215 bool is_subframe
= !!frame
->parent();
2217 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameDetached());
2218 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2219 FrameDetached(frame
));
2221 Send(new FrameHostMsg_Detach(routing_id_
));
2223 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2224 // sent before setting |is_detaching_| to true.
2225 is_detaching_
= true;
2227 // We need to clean up subframes by removing them from the map and deleting
2228 // the RenderFrameImpl. In contrast, the main frame is owned by its
2229 // containing RenderViewHost (so that they have the same lifetime), so only
2230 // removal from the map is needed and no deletion.
2231 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
2232 CHECK(it
!= g_frame_map
.Get().end());
2233 CHECK_EQ(it
->second
, this);
2234 g_frame_map
.Get().erase(it
);
2237 frame
->parent()->removeChild(frame
);
2239 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2240 // object may not be deleted immediately and other methods may try to access
2247 // Object is invalid after this point.
2251 void RenderFrameImpl::frameFocused() {
2252 Send(new FrameHostMsg_FrameFocused(routing_id_
));
2255 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
2256 DCHECK(!frame_
|| frame_
== frame
);
2258 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
2259 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2260 FrameWillClose(frame
));
2263 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
2264 const blink::WebString
& name
) {
2265 DCHECK(!frame_
|| frame_
== frame
);
2267 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2268 // updates may have performance implications for benchmarks like SunSpider.
2269 // For now, send these updates only for --site-per-process, which needs to
2270 // replicate frame names to frame proxies, and when
2271 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2272 // can be optimized further by only sending the update if there are any
2273 // remote frames in the frame tree, or delaying and batching up IPCs if
2274 // updates are happening too frequently.
2275 bool is_site_per_process
= base::CommandLine::ForCurrentProcess()->HasSwitch(
2276 switches::kSitePerProcess
);
2277 if (is_site_per_process
||
2278 render_view_
->renderer_preferences_
.report_frame_name_changes
) {
2279 Send(new FrameHostMsg_DidChangeName(routing_id_
, base::UTF16ToUTF8(name
)));
2283 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame
* child_frame
,
2284 blink::WebSandboxFlags flags
) {
2285 int frame_routing_id
= MSG_ROUTING_NONE
;
2286 if (child_frame
->isWebRemoteFrame()) {
2288 RenderFrameProxy::FromWebFrame(child_frame
)->routing_id();
2291 RenderFrameImpl::FromWebFrame(child_frame
)->GetRoutingID();
2294 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_
, frame_routing_id
,
2295 WebToContentSandboxFlags(flags
)));
2298 void RenderFrameImpl::didMatchCSS(
2299 blink::WebLocalFrame
* frame
,
2300 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2301 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2302 DCHECK(!frame_
|| frame_
== frame
);
2304 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2306 newly_matching_selectors
,
2307 stopped_matching_selectors
));
2310 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2311 const blink::WebString
& source
) {
2312 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2316 void RenderFrameImpl::didAddMessageToConsole(
2317 const blink::WebConsoleMessage
& message
,
2318 const blink::WebString
& source_name
,
2319 unsigned source_line
,
2320 const blink::WebString
& stack_trace
) {
2321 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2322 switch (message
.level
) {
2323 case blink::WebConsoleMessage::LevelDebug
:
2324 log_severity
= logging::LOG_VERBOSE
;
2326 case blink::WebConsoleMessage::LevelLog
:
2327 case blink::WebConsoleMessage::LevelInfo
:
2328 log_severity
= logging::LOG_INFO
;
2330 case blink::WebConsoleMessage::LevelWarning
:
2331 log_severity
= logging::LOG_WARNING
;
2333 case blink::WebConsoleMessage::LevelError
:
2334 log_severity
= logging::LOG_ERROR
;
2337 log_severity
= logging::LOG_VERBOSE
;
2340 if (shouldReportDetailedMessageForSource(source_name
)) {
2342 RenderFrameObserver
, observers_
,
2343 DetailedConsoleMessageAdded(message
.text
,
2347 static_cast<int32
>(log_severity
)));
2350 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2351 static_cast<int32
>(log_severity
),
2353 static_cast<int32
>(source_line
),
2357 void RenderFrameImpl::loadURLExternally(
2358 blink::WebLocalFrame
* frame
,
2359 const blink::WebURLRequest
& request
,
2360 blink::WebNavigationPolicy policy
,
2361 const blink::WebString
& suggested_name
) {
2362 DCHECK(!frame_
|| frame_
== frame
);
2363 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2364 if (policy
== blink::WebNavigationPolicyDownload
) {
2365 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2366 request
.url(), referrer
,
2369 OpenURL(frame
, request
.url(), referrer
, policy
);
2373 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2374 const NavigationPolicyInfo
& info
) {
2375 DCHECK(!frame_
|| frame_
== info
.frame
);
2376 return DecidePolicyForNavigation(this, info
);
2379 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2380 blink::WebFrame
* frame
) {
2381 DCHECK(!frame_
|| frame_
== frame
);
2382 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2385 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2386 const blink::WebFormElement
& form
) {
2387 DCHECK(!frame_
|| frame_
== frame
);
2389 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSendSubmitEvent(form
));
2392 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2393 const blink::WebFormElement
& form
) {
2394 DCHECK(!frame_
|| frame_
== frame
);
2395 DocumentState
* document_state
=
2396 DocumentState::FromDataSource(frame
->provisionalDataSource());
2397 NavigationStateImpl
* navigation_state
=
2398 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2399 InternalDocumentStateData
* internal_data
=
2400 InternalDocumentStateData::FromDocumentState(document_state
);
2402 if (ui::PageTransitionCoreTypeIs(navigation_state
->GetTransitionType(),
2403 ui::PAGE_TRANSITION_LINK
)) {
2404 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2407 // Save these to be processed when the ensuing navigation is committed.
2408 WebSearchableFormData
web_searchable_form_data(form
);
2409 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2410 internal_data
->set_searchable_form_encoding(
2411 web_searchable_form_data
.encoding().utf8());
2413 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WillSubmitForm(form
));
2416 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2417 blink::WebDataSource
* datasource
) {
2418 DCHECK(!frame_
|| frame_
== frame
);
2420 bool content_initiated
= !pending_navigation_params_
.get();
2422 // Make sure any previous redirect URLs end up in our new data source.
2423 if (pending_navigation_params_
.get()) {
2424 for (const auto& i
:
2425 pending_navigation_params_
->request_params
.redirects
) {
2426 datasource
->appendRedirect(i
);
2430 DocumentState
* document_state
= DocumentState::FromDataSource(datasource
);
2431 if (!document_state
) {
2432 document_state
= new DocumentState
;
2433 datasource
->setExtraData(document_state
);
2434 if (!content_initiated
)
2435 PopulateDocumentStateFromPending(document_state
);
2438 // Carry over the user agent override flag, if it exists.
2439 blink::WebView
* webview
= render_view_
->webview();
2440 if (content_initiated
&& webview
&& webview
->mainFrame() &&
2441 webview
->mainFrame()->isWebLocalFrame() &&
2442 webview
->mainFrame()->dataSource()) {
2443 DocumentState
* old_document_state
=
2444 DocumentState::FromDataSource(webview
->mainFrame()->dataSource());
2445 if (old_document_state
) {
2446 InternalDocumentStateData
* internal_data
=
2447 InternalDocumentStateData::FromDocumentState(document_state
);
2448 InternalDocumentStateData
* old_internal_data
=
2449 InternalDocumentStateData::FromDocumentState(old_document_state
);
2450 internal_data
->set_is_overriding_user_agent(
2451 old_internal_data
->is_overriding_user_agent());
2455 // The rest of RenderView assumes that a WebDataSource will always have a
2456 // non-null NavigationState.
2457 if (content_initiated
) {
2458 document_state
->set_navigation_state(
2459 NavigationStateImpl::CreateContentInitiated());
2461 document_state
->set_navigation_state(CreateNavigationStateFromPending());
2462 pending_navigation_params_
.reset();
2465 // DocumentState::referred_by_prefetcher_ is true if we are
2466 // navigating from a page that used prefetching using a link on that
2467 // page. We are early enough in the request process here that we
2468 // can still see the DocumentState of the previous page and set
2469 // this value appropriately.
2470 // TODO(gavinp): catch the important case of navigation in a new
2471 // renderer process.
2473 if (WebFrame
* old_frame
= webview
->mainFrame()) {
2474 const WebURLRequest
& original_request
= datasource
->originalRequest();
2475 const GURL
referrer(
2476 original_request
.httpHeaderField(WebString::fromUTF8("Referer")));
2477 if (!referrer
.is_empty() && old_frame
->isWebLocalFrame() &&
2478 DocumentState::FromDataSource(old_frame
->dataSource())
2479 ->was_prefetcher()) {
2480 for (; old_frame
; old_frame
= old_frame
->traverseNext(false)) {
2481 WebDataSource
* old_frame_datasource
= old_frame
->dataSource();
2482 if (old_frame_datasource
&&
2483 referrer
== GURL(old_frame_datasource
->request().url())) {
2484 document_state
->set_was_referred_by_prefetcher(true);
2492 if (content_initiated
) {
2493 const WebURLRequest
& request
= datasource
->request();
2494 switch (request
.cachePolicy()) {
2495 case WebURLRequest::UseProtocolCachePolicy
: // normal load.
2496 document_state
->set_load_type(DocumentState::LINK_LOAD_NORMAL
);
2498 case WebURLRequest::ReloadIgnoringCacheData
: // reload.
2499 case WebURLRequest::ReloadBypassingCache
: // end-to-end reload.
2500 document_state
->set_load_type(DocumentState::LINK_LOAD_RELOAD
);
2502 case WebURLRequest::ReturnCacheDataElseLoad
: // allow stale data.
2503 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK
);
2505 case WebURLRequest::ReturnCacheDataDontLoad
: // Don't re-post.
2506 document_state
->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY
);
2513 // Create the serviceworker's per-document network observing object if it
2514 // does not exist (When navigation happens within a page, the provider already
2516 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2517 DocumentState::FromDataSource(datasource
))) {
2518 scoped_ptr
<ServiceWorkerNetworkProvider
> network_provider(
2519 new ServiceWorkerNetworkProvider(routing_id_
,
2520 SERVICE_WORKER_PROVIDER_FOR_WINDOW
));
2521 ServiceWorkerNetworkProvider::AttachToDocumentState(
2522 DocumentState::FromDataSource(datasource
),
2523 network_provider
.Pass());
2527 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2528 bool is_transition_navigation
,
2529 double triggering_event_time
) {
2530 DCHECK(!frame_
|| frame_
== frame
);
2531 WebDataSource
* ds
= frame
->provisionalDataSource();
2533 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2534 // callback is invoked.
2538 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2539 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2540 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2542 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2543 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2545 "Heard swappedout:// when not swapped out.";
2547 // Update the request time if WebKit has better knowledge of it.
2548 if (document_state
->request_time().is_null() &&
2549 triggering_event_time
!= 0.0) {
2550 document_state
->set_request_time(Time::FromDoubleT(triggering_event_time
));
2553 // Start time is only set after request time.
2554 document_state
->set_start_load_time(Time::Now());
2556 bool is_top_most
= !frame
->parent();
2558 render_view_
->set_navigation_gesture(
2559 WebUserGestureIndicator::isProcessingUserGesture() ?
2560 NavigationGestureUser
: NavigationGestureAuto
);
2561 } else if (ds
->replacesCurrentHistoryItem()) {
2562 // Subframe navigations that don't add session history items must be
2563 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2564 // handle loading of error pages.
2565 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2566 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2569 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2570 DidStartProvisionalLoad(frame
));
2571 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2573 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2574 routing_id_
, ds
->request().url(), is_transition_navigation
));
2577 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2578 blink::WebLocalFrame
* frame
) {
2579 DCHECK(!frame_
|| frame_
== frame
);
2580 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2583 void RenderFrameImpl::didFailProvisionalLoad(
2584 blink::WebLocalFrame
* frame
,
2585 const blink::WebURLError
& error
,
2586 blink::WebHistoryCommitType commit_type
) {
2587 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2589 DCHECK(!frame_
|| frame_
== frame
);
2590 WebDataSource
* ds
= frame
->provisionalDataSource();
2593 const WebURLRequest
& failed_request
= ds
->request();
2595 // Notify the browser that we failed a provisional load with an error.
2597 // Note: It is important this notification occur before DidStopLoading so the
2598 // SSL manager can react to the provisional load failure before being
2599 // notified the load stopped.
2601 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2602 DidFailProvisionalLoad(frame
, error
));
2603 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2604 DidFailProvisionalLoad(error
));
2606 SendFailedProvisionalLoad(failed_request
, error
, frame
);
2608 if (!ShouldDisplayErrorPageForFailedLoad(error
.reason
, error
.unreachableURL
))
2611 // Make sure we never show errors in view source mode.
2612 frame
->enableViewSourceMode(false);
2614 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2615 NavigationStateImpl
* navigation_state
=
2616 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2618 // If this is a failed back/forward/reload navigation, then we need to do a
2619 // 'replace' load. This is necessary to avoid messing up session history.
2620 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2621 // as session history is concerned.
2622 bool replace
= commit_type
!= blink::WebStandardCommit
;
2624 // If we failed on a browser initiated request, then make sure that our error
2625 // page load is regarded as the same browser initiated request.
2626 if (!navigation_state
->IsContentInitiated()) {
2627 pending_navigation_params_
.reset(new NavigationParams(
2628 navigation_state
->common_params(), navigation_state
->start_params(),
2629 navigation_state
->request_params()));
2630 pending_navigation_params_
->request_params
.request_time
=
2631 document_state
->request_time();
2634 // Load an error page.
2635 LoadNavigationErrorPage(failed_request
, error
, replace
);
2638 void RenderFrameImpl::didCommitProvisionalLoad(
2639 blink::WebLocalFrame
* frame
,
2640 const blink::WebHistoryItem
& item
,
2641 blink::WebHistoryCommitType commit_type
) {
2642 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2644 "url", GetLoadingUrl().possibly_invalid_spec());
2645 DCHECK(!frame_
|| frame_
== frame
);
2646 DocumentState
* document_state
=
2647 DocumentState::FromDataSource(frame
->dataSource());
2648 NavigationStateImpl
* navigation_state
=
2649 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
2651 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2652 RenderFrameProxy
* proxy
=
2653 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2655 proxy
->web_frame()->swap(frame_
);
2656 proxy_routing_id_
= MSG_ROUTING_NONE
;
2659 // When we perform a new navigation, we need to update the last committed
2660 // session history entry with state for the page we are leaving. Do this
2661 // before updating the HistoryController state.
2662 render_view_
->UpdateSessionHistory(frame
);
2664 render_view_
->history_controller()->UpdateForCommit(
2665 this, item
, commit_type
, navigation_state
->WasWithinSamePage());
2667 InternalDocumentStateData
* internal_data
=
2668 InternalDocumentStateData::FromDocumentState(document_state
);
2670 if (document_state
->commit_load_time().is_null())
2671 document_state
->set_commit_load_time(Time::Now());
2673 if (internal_data
->must_reset_scroll_and_scale_state()) {
2674 render_view_
->webview()->resetScrollAndScaleState();
2675 internal_data
->set_must_reset_scroll_and_scale_state(false);
2677 internal_data
->set_use_error_page(false);
2679 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2680 if (is_new_navigation
) {
2681 // We bump our Page ID to correspond with the new session history entry.
2682 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2684 // Don't update history list values for kSwappedOutURL, since
2685 // we don't want to forget the entry that was there, and since we will
2686 // never come back to kSwappedOutURL. Note that we have to call
2687 // UpdateSessionHistory and update page_id_ even in this case, so that
2688 // the current entry gets a state update and so that we don't send a
2689 // state update to the wrong entry when we swap back in.
2691 navigation_state
->start_params().should_replace_current_entry
,
2692 render_view_
->history_list_length_
> 0);
2693 if (GetLoadingUrl() != GURL(kSwappedOutURL
) &&
2694 !navigation_state
->start_params().should_replace_current_entry
) {
2695 // Advance our offset in session history, applying the length limit.
2696 // There is now no forward history.
2697 render_view_
->history_list_offset_
++;
2698 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2699 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2700 render_view_
->history_list_length_
=
2701 render_view_
->history_list_offset_
+ 1;
2704 // Inspect the navigation_state on this frame to see if the navigation
2705 // corresponds to a session history navigation... Note: |frame| may or
2706 // may not be the toplevel frame, but for the case of capturing session
2707 // history, the first committed frame suffices. We keep track of whether
2708 // we've seen this commit before so that only capture session history once
2711 // Note that we need to check if the page ID changed. In the case of a
2712 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2713 // previous URL and the current page ID, which would be wrong.
2714 if (navigation_state
->request_params().page_id
!= -1 &&
2715 navigation_state
->request_params().page_id
!= render_view_
->page_id_
) {
2716 // This is a successful session history navigation!
2717 render_view_
->page_id_
= navigation_state
->request_params().page_id
;
2719 render_view_
->history_list_offset_
=
2720 navigation_state
->request_params().pending_history_list_offset
;
2725 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2726 CHECK(sent
); // http://crbug.com/407376
2728 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2729 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2731 RenderFrameObserver
, observers_
,
2732 DidCommitProvisionalLoad(is_new_navigation
,
2733 navigation_state
->WasWithinSamePage()));
2735 if (!frame
->parent()) { // Only for top frames.
2736 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2737 if (render_thread_impl
) { // Can be NULL in tests.
2738 render_thread_impl
->histogram_customizer()->
2739 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2740 RenderViewImpl::GetRenderViewCount());
2744 // Remember that we've already processed this request, so we don't update
2745 // the session history again. We do this regardless of whether this is
2746 // a session history navigation, because if we attempted a session history
2747 // navigation without valid HistoryItem state, WebCore will think it is a
2749 navigation_state
->set_request_committed(true);
2751 SendDidCommitProvisionalLoad(frame
, commit_type
);
2753 // Check whether we have new encoding name.
2754 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2757 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2758 DCHECK(!frame_
|| frame_
== frame
);
2760 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2761 DidCreateNewDocument(frame
));
2764 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2765 DCHECK(!frame_
|| frame_
== frame
);
2767 int enabled_bindings
= render_view_
->GetEnabledBindings();
2769 if (enabled_bindings
& BINDINGS_POLICY_WEB_UI
)
2770 WebUIExtension::Install(frame
);
2772 if (enabled_bindings
& BINDINGS_POLICY_DOM_AUTOMATION
)
2773 DomAutomationController::Install(this, frame
);
2775 if (enabled_bindings
& BINDINGS_POLICY_STATS_COLLECTION
)
2776 StatsCollectionController::Install(frame
);
2778 const base::CommandLine
& command_line
=
2779 *base::CommandLine::ForCurrentProcess();
2781 if (command_line
.HasSwitch(cc::switches::kEnableGpuBenchmarking
))
2782 GpuBenchmarking::Install(frame
);
2784 if (command_line
.HasSwitch(switches::kEnableMemoryBenchmarking
))
2785 MemoryBenchmarkingExtension::Install(frame
);
2787 if (command_line
.HasSwitch(switches::kEnableSkiaBenchmarking
))
2788 SkiaBenchmarking::Install(frame
);
2790 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2791 DidClearWindowObject(frame
));
2792 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2795 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2796 DCHECK(!frame_
|| frame_
== frame
);
2798 // Notify the browser about non-blank documents loading in the top frame.
2799 GURL url
= frame
->document().url();
2800 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2801 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2802 // frame->tree()->top().
2803 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2804 if (frame
== main_frame
) {
2805 // For now, don't remember plugin zoom values. We don't want to mix them
2806 // with normal web content (i.e. a fixed layout plugin would usually want
2808 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2809 render_view_
->GetRoutingID(),
2810 main_frame
->document().isPluginDocument()));
2814 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2815 DidCreateDocumentElement(frame
));
2818 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2819 const blink::WebString
& title
,
2820 blink::WebTextDirection direction
) {
2821 DCHECK(!frame_
|| frame_
== frame
);
2822 // Ignore all but top level navigations.
2823 if (!frame
->parent()) {
2824 base::string16 title16
= title
;
2825 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2826 routing_id_
, base::UTF16ToUTF8(title16
));
2828 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2829 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2830 shortened_title
, direction
));
2833 // Also check whether we have new encoding name.
2834 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2837 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2838 blink::WebIconURL::Type icon_type
) {
2839 DCHECK(!frame_
|| frame_
== frame
);
2840 // TODO(nasko): Investigate wheather implementation should move here.
2841 render_view_
->didChangeIcon(frame
, icon_type
);
2844 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2845 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2847 DCHECK(!frame_
|| frame_
== frame
);
2848 WebDataSource
* ds
= frame
->dataSource();
2849 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2850 document_state
->set_finish_document_load_time(Time::Now());
2852 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2854 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2855 DidFinishDocumentLoad(frame
));
2856 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2858 // Check whether we have new encoding name.
2859 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2862 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2863 DCHECK(!frame_
|| frame_
== frame
);
2864 if (!frame
->parent()) {
2865 FrameMsg_UILoadMetricsReportType::Value report_type
=
2866 static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
2867 frame
->dataSource()->request().inputPerfMetricReportPolicy());
2868 base::TimeTicks ui_timestamp
= base::TimeTicks() +
2869 base::TimeDelta::FromSecondsD(
2870 frame
->dataSource()->request().uiStartTime());
2872 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2873 routing_id_
, report_type
, ui_timestamp
));
2877 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2878 const blink::WebURLError
& error
,
2879 blink::WebHistoryCommitType commit_type
) {
2880 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2882 DCHECK(!frame_
|| frame_
== frame
);
2883 // TODO(nasko): Move implementation here. No state needed.
2884 WebDataSource
* ds
= frame
->dataSource();
2887 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2888 DidFailLoad(frame
, error
));
2890 const WebURLRequest
& failed_request
= ds
->request();
2891 base::string16 error_description
;
2892 GetContentClient()->renderer()->GetNavigationErrorStrings(
2898 &error_description
);
2899 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2900 failed_request
.url(),
2902 error_description
));
2905 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2906 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2908 DCHECK(!frame_
|| frame_
== frame
);
2909 WebDataSource
* ds
= frame
->dataSource();
2910 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2911 if (document_state
->finish_load_time().is_null()) {
2912 if (!frame
->parent()) {
2913 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2914 TRACE_EVENT_SCOPE_PROCESS
);
2916 document_state
->set_finish_load_time(Time::Now());
2919 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2920 DidFinishLoad(frame
));
2921 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2923 // Don't send this message while the frame is swapped out.
2924 if (is_swapped_out())
2927 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2928 ds
->request().url()));
2931 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2932 const blink::WebHistoryItem
& item
,
2933 blink::WebHistoryCommitType commit_type
) {
2934 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2936 DCHECK(!frame_
|| frame_
== frame
);
2937 // If this was a reference fragment navigation that we initiated, then we
2938 // could end up having a non-null pending navigation params. We just need to
2939 // update the ExtraData on the datasource so that others who read the
2940 // ExtraData will get the new NavigationState. Similarly, if we did not
2941 // initiate this navigation, then we need to take care to reset any pre-
2942 // existing navigation state to a content-initiated navigation state.
2943 // didCreateDataSource conveniently takes care of this for us.
2944 didCreateDataSource(frame
, frame
->dataSource());
2946 DocumentState
* document_state
=
2947 DocumentState::FromDataSource(frame
->dataSource());
2948 static_cast<NavigationStateImpl
*>(document_state
->navigation_state())
2949 ->set_was_within_same_page(true);
2951 didCommitProvisionalLoad(frame
, item
, commit_type
);
2954 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2955 DCHECK(!frame_
|| frame_
== frame
);
2956 // TODO(nasko): Move implementation here. Needed methods:
2957 // * StartNavStateSyncTimerIfNecessary
2958 render_view_
->didUpdateCurrentHistoryItem(frame
);
2961 void RenderFrameImpl::addNavigationTransitionData(
2962 const blink::WebTransitionElementData
& data
) {
2963 FrameHostMsg_AddNavigationTransitionData_Params params
;
2964 params
.render_frame_id
= routing_id_
;
2965 params
.allowed_destination_host_pattern
=
2967 params
.selector
= data
.selector
.utf8();
2968 params
.markup
= data
.markup
.utf8();
2969 params
.elements
.resize(data
.elements
.size());
2970 for (size_t i
= 0; i
< data
.elements
.size(); i
++) {
2971 params
.elements
[i
].id
= data
.elements
[i
].id
.utf8();
2972 params
.elements
[i
].rect
= gfx::Rect(data
.elements
[i
].rect
);
2975 Send(new FrameHostMsg_AddNavigationTransitionData(params
));
2978 void RenderFrameImpl::didChangeThemeColor() {
2979 if (frame_
->parent())
2982 Send(new FrameHostMsg_DidChangeThemeColor(
2983 routing_id_
, frame_
->document().themeColor()));
2986 void RenderFrameImpl::dispatchLoad() {
2987 Send(new FrameHostMsg_DispatchLoad(routing_id_
));
2990 void RenderFrameImpl::requestNotificationPermission(
2991 const blink::WebSecurityOrigin
& origin
,
2992 blink::WebNotificationPermissionCallback
* callback
) {
2993 if (!notification_permission_dispatcher_
) {
2994 notification_permission_dispatcher_
=
2995 new NotificationPermissionDispatcher(this);
2998 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
3001 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
3002 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
3005 if (is_empty_selection
)
3006 selection_text_
.clear();
3008 // UpdateTextInputType should be called before SyncSelectionIfRequired.
3009 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
3010 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3011 // to notify the selection was changed. Focus change should be notified
3012 // before selection change.
3013 GetRenderWidget()->UpdateTextInputType();
3014 SyncSelectionIfRequired();
3015 #if defined(OS_ANDROID)
3016 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
3017 RenderWidget::FROM_NON_IME
);
3021 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
3022 blink::WebColorChooserClient
* client
,
3023 const blink::WebColor
& initial_color
,
3024 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
3025 RendererWebColorChooserImpl
* color_chooser
=
3026 new RendererWebColorChooserImpl(this, client
);
3027 std::vector
<ColorSuggestion
> color_suggestions
;
3028 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
3029 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
3031 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
3032 return color_chooser
;
3035 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
3036 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
3039 frame_
->document().url(),
3043 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
3044 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
3047 frame_
->document().url(),
3051 bool RenderFrameImpl::runModalPromptDialog(
3052 const blink::WebString
& message
,
3053 const blink::WebString
& default_value
,
3054 blink::WebString
* actual_value
) {
3055 base::string16 result
;
3056 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
3059 frame_
->document().url(),
3062 actual_value
->assign(result
);
3066 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3068 const blink::WebString
& message
) {
3069 // If we are swapping out, we have already run the beforeunload handler.
3070 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3071 // at all, to avoid running it twice.
3072 if (is_swapped_out_
)
3075 // Don't allow further dialogs if we are waiting to swap out, since the
3076 // PageGroupLoadDeferrer in our stack prevents it.
3077 if (render_view()->suppress_dialogs_until_swap_out_
)
3080 bool success
= false;
3081 // This is an ignored return value, but is included so we can accept the same
3082 // response as RunJavaScriptMessage.
3083 base::string16 ignored_result
;
3084 render_view()->SendAndRunNestedMessageLoop(
3085 new FrameHostMsg_RunBeforeUnloadConfirm(
3086 routing_id_
, frame_
->document().url(), message
, is_reload
,
3087 &success
, &ignored_result
));
3091 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
3092 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
3093 params
.source_type
= GetRenderWidget()->context_menu_source_type();
3094 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
3095 if (GetRenderWidget()->has_host_context_menu_location()) {
3096 params
.x
= GetRenderWidget()->host_context_menu_location().x();
3097 params
.y
= GetRenderWidget()->host_context_menu_location().y();
3100 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3101 // it. We replace it with an empty GURL so the appropriate items are disabled
3102 // in the context menu.
3103 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3104 // data encoded images. We should have a way to save them.
3105 if (params
.src_url
.spec().size() > GetMaxURLChars())
3106 params
.src_url
= GURL();
3107 context_menu_node_
= data
.node
;
3109 #if defined(OS_ANDROID)
3110 gfx::Rect start_rect
;
3112 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
3113 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
3114 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
3117 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
3120 void RenderFrameImpl::clearContextMenu() {
3121 context_menu_node_
.reset();
3124 void RenderFrameImpl::willSendRequest(
3125 blink::WebLocalFrame
* frame
,
3126 unsigned identifier
,
3127 blink::WebURLRequest
& request
,
3128 const blink::WebURLResponse
& redirect_response
) {
3129 DCHECK(!frame_
|| frame_
== frame
);
3130 // The request my be empty during tests.
3131 if (request
.url().isEmpty())
3134 // Set the first party for cookies url if it has not been set yet (new
3135 // requests). For redirects, it is updated by WebURLLoaderImpl.
3136 if (request
.firstPartyForCookies().isEmpty()) {
3137 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
3138 request
.setFirstPartyForCookies(request
.url());
3140 // TODO(nasko): When the top-level frame is remote, there is no document.
3141 // This is broken and should be fixed to propagate the first party.
3142 WebFrame
* top
= frame
->top();
3143 if (top
->isWebLocalFrame()) {
3144 request
.setFirstPartyForCookies(
3145 frame
->top()->document().firstPartyForCookies());
3150 WebFrame
* top_frame
= frame
->top();
3151 // TODO(nasko): Hack around asking about top-frame data source. This means
3152 // for out-of-process iframes we are treating the current frame as the
3153 // top-level frame, which is wrong.
3154 if (!top_frame
|| top_frame
->isWebRemoteFrame())
3156 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
3157 WebDataSource
* top_data_source
= top_frame
->dataSource();
3158 WebDataSource
* data_source
=
3159 provisional_data_source
? provisional_data_source
: top_data_source
;
3161 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
3162 DCHECK(document_state
);
3163 InternalDocumentStateData
* internal_data
=
3164 InternalDocumentStateData::FromDocumentState(document_state
);
3165 NavigationStateImpl
* navigation_state
=
3166 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3167 ui::PageTransition transition_type
= navigation_state
->GetTransitionType();
3168 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
3169 if (frame_ds
&& frame_ds
->isClientRedirect()) {
3170 transition_type
= ui::PageTransitionFromInt(
3171 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3174 GURL
request_url(request
.url());
3176 if (GetContentClient()->renderer()->WillSendRequest(
3180 request
.firstPartyForCookies(),
3182 request
.setURL(WebURL(new_url
));
3185 if (internal_data
->is_cache_policy_override_set())
3186 request
.setCachePolicy(internal_data
->cache_policy_override());
3188 // The request's extra data may indicate that we should set a custom user
3189 // agent. This needs to be done here, after WebKit is through with setting the
3190 // user agent on its own. Similarly, it may indicate that we should set an
3191 // X-Requested-With header. This must be done here to avoid breaking CORS
3193 // PlzNavigate: there may also be a stream url associated with the request.
3194 WebString custom_user_agent
;
3195 WebString requested_with
;
3196 scoped_ptr
<StreamOverrideParameters
> stream_override
;
3197 if (request
.extraData()) {
3198 RequestExtraData
* old_extra_data
=
3199 static_cast<RequestExtraData
*>(request
.extraData());
3201 custom_user_agent
= old_extra_data
->custom_user_agent();
3202 if (!custom_user_agent
.isNull()) {
3203 if (custom_user_agent
.isEmpty())
3204 request
.clearHTTPHeaderField("User-Agent");
3206 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
3209 requested_with
= old_extra_data
->requested_with();
3210 if (!requested_with
.isNull()) {
3211 if (requested_with
.isEmpty())
3212 request
.clearHTTPHeaderField("X-Requested-With");
3214 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
3216 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
3219 // Add the default accept header for frame request if it has not been set
3221 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3222 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
3223 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
3224 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
3225 WebString::fromUTF8(kDefaultAcceptHeader
));
3228 // Add an empty HTTP origin header for non GET methods if none is currently
3230 request
.addHTTPOriginIfNeeded(WebString());
3232 // Attach |should_replace_current_entry| state to requests so that, should
3233 // this navigation later require a request transfer, all state is preserved
3234 // when it is re-created in the new process.
3235 bool should_replace_current_entry
= false;
3236 if (navigation_state
->IsContentInitiated()) {
3237 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
3239 // If the navigation is browser-initiated, the NavigationState contains the
3240 // correct value instead of the WebDataSource.
3242 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3243 // NavigationState::should_replace_current_entry().
3244 should_replace_current_entry
=
3245 navigation_state
->start_params().should_replace_current_entry
;
3248 int provider_id
= kInvalidServiceWorkerProviderId
;
3249 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
3250 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
3251 // |provisionalDataSource| may be null in some content::ResourceFetcher
3252 // use cases, we don't hook those requests.
3253 if (frame
->provisionalDataSource()) {
3254 ServiceWorkerNetworkProvider
* provider
=
3255 ServiceWorkerNetworkProvider::FromDocumentState(
3256 DocumentState::FromDataSource(frame
->provisionalDataSource()));
3257 provider_id
= provider
->provider_id();
3259 } else if (frame
->dataSource()) {
3260 ServiceWorkerNetworkProvider
* provider
=
3261 ServiceWorkerNetworkProvider::FromDocumentState(
3262 DocumentState::FromDataSource(frame
->dataSource()));
3263 provider_id
= provider
->provider_id();
3266 WebFrame
* parent
= frame
->parent();
3267 int parent_routing_id
= MSG_ROUTING_NONE
;
3269 parent_routing_id
= -1;
3270 } else if (parent
->isWebLocalFrame()) {
3271 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
3273 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
3276 RequestExtraData
* extra_data
= new RequestExtraData();
3277 extra_data
->set_visibility_state(render_view_
->visibilityState());
3278 extra_data
->set_custom_user_agent(custom_user_agent
);
3279 extra_data
->set_requested_with(requested_with
);
3280 extra_data
->set_render_frame_id(routing_id_
);
3281 extra_data
->set_is_main_frame(!parent
);
3282 extra_data
->set_frame_origin(
3283 GURL(frame
->document().securityOrigin().toString()));
3284 extra_data
->set_parent_is_main_frame(parent
&& !parent
->parent());
3285 extra_data
->set_parent_render_frame_id(parent_routing_id
);
3286 extra_data
->set_allow_download(
3287 navigation_state
->common_params().allow_download
);
3288 extra_data
->set_transition_type(transition_type
);
3289 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
3290 extra_data
->set_transferred_request_child_id(
3291 navigation_state
->start_params().transferred_request_child_id
);
3292 extra_data
->set_transferred_request_request_id(
3293 navigation_state
->start_params().transferred_request_request_id
);
3294 extra_data
->set_service_worker_provider_id(provider_id
);
3295 extra_data
->set_stream_override(stream_override
.Pass());
3296 request
.setExtraData(extra_data
);
3298 DocumentState
* top_document_state
=
3299 DocumentState::FromDataSource(top_data_source
);
3300 if (top_document_state
) {
3301 // TODO(gavinp): separate out prefetching and prerender field trials
3302 // if the rel=prerender rel type is sticking around.
3303 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
3304 top_document_state
->set_was_prefetcher(true);
3307 // This is an instance where we embed a copy of the routing id
3308 // into the data portion of the message. This can cause problems if we
3309 // don't register this id on the browser side, since the download manager
3310 // expects to find a RenderViewHost based off the id.
3311 request
.setRequestorID(render_view_
->GetRoutingID());
3312 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3314 if (!navigation_state
->start_params().extra_headers
.empty()) {
3315 for (net::HttpUtil::HeadersIterator
i(
3316 navigation_state
->start_params().extra_headers
.begin(),
3317 navigation_state
->start_params().extra_headers
.end(), "\n");
3319 if (LowerCaseEqualsASCII(i
.name(), "referer")) {
3320 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
3321 blink::WebReferrerPolicyDefault
,
3323 WebString::fromUTF8(i
.values()));
3324 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
3326 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
3327 WebString::fromUTF8(i
.values()));
3332 if (!render_view_
->renderer_preferences_
.enable_referrers
)
3333 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
3336 void RenderFrameImpl::didReceiveResponse(
3337 blink::WebLocalFrame
* frame
,
3338 unsigned identifier
,
3339 const blink::WebURLResponse
& response
) {
3340 DCHECK(!frame_
|| frame_
== frame
);
3341 // Only do this for responses that correspond to a provisional data source
3342 // of the top-most frame. If we have a provisional data source, then we
3343 // can't have any sub-resources yet, so we know that this response must
3344 // correspond to a frame load.
3345 if (!frame
->provisionalDataSource() || frame
->parent())
3348 // If we are in view source mode, then just let the user see the source of
3349 // the server's error page.
3350 if (frame
->isViewSourceModeEnabled())
3353 DocumentState
* document_state
=
3354 DocumentState::FromDataSource(frame
->provisionalDataSource());
3355 int http_status_code
= response
.httpStatusCode();
3357 // Record page load flags.
3358 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3360 document_state
->set_was_fetched_via_spdy(
3361 extra_data
->was_fetched_via_spdy());
3362 document_state
->set_was_npn_negotiated(
3363 extra_data
->was_npn_negotiated());
3364 document_state
->set_npn_negotiated_protocol(
3365 extra_data
->npn_negotiated_protocol());
3366 document_state
->set_was_alternate_protocol_available(
3367 extra_data
->was_alternate_protocol_available());
3368 document_state
->set_connection_info(
3369 extra_data
->connection_info());
3370 document_state
->set_was_fetched_via_proxy(
3371 extra_data
->was_fetched_via_proxy());
3372 document_state
->set_proxy_server(
3373 extra_data
->proxy_server());
3375 InternalDocumentStateData
* internal_data
=
3376 InternalDocumentStateData::FromDocumentState(document_state
);
3377 internal_data
->set_http_status_code(http_status_code
);
3378 // Whether or not the http status code actually corresponds to an error is
3379 // only checked when the page is done loading, if |use_error_page| is
3381 internal_data
->set_use_error_page(true);
3384 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3385 unsigned identifier
) {
3386 DCHECK(!frame_
|| frame_
== frame
);
3387 InternalDocumentStateData
* internal_data
=
3388 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3389 if (!internal_data
->use_error_page())
3392 // Do not show error page when DevTools is attached.
3393 RenderFrameImpl
* localRoot
= this;
3394 while (localRoot
->frame_
&& localRoot
->frame_
->parent() &&
3395 localRoot
->frame_
->parent()->isWebLocalFrame()) {
3396 localRoot
= RenderFrameImpl::FromWebFrame(localRoot
->frame_
->parent());
3399 if (localRoot
->devtools_agent_
&& localRoot
->devtools_agent_
->IsAttached())
3402 // Display error page, if appropriate.
3403 std::string error_domain
= "http";
3404 int http_status_code
= internal_data
->http_status_code();
3405 if (GetContentClient()->renderer()->HasErrorPage(
3406 http_status_code
, &error_domain
)) {
3408 error
.unreachableURL
= frame
->document().url();
3409 error
.domain
= WebString::fromUTF8(error_domain
);
3410 error
.reason
= http_status_code
;
3411 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3415 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3416 blink::WebLocalFrame
* frame
,
3417 const blink::WebURLRequest
& request
,
3418 const blink::WebURLResponse
& response
) {
3419 DCHECK(!frame_
|| frame_
== frame
);
3420 // The recipients of this message have no use for data: URLs: they don't
3421 // affect the page's insecure content list and are not in the disk cache. To
3422 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3423 // filter them out here.
3424 GURL
url(request
.url());
3425 if (url
.SchemeIs(url::kDataScheme
))
3428 // Let the browser know we loaded a resource from the memory cache. This
3429 // message is needed to display the correct SSL indicators.
3430 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3431 render_view_
->GetRoutingID(),
3433 response
.securityInfo(),
3434 request
.httpMethod().utf8(),
3435 response
.mimeType().utf8(),
3436 WebURLRequestToResourceType(request
)));
3439 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3440 DCHECK(!frame_
|| frame_
== frame
);
3441 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3442 render_view_
->GetRoutingID()));
3445 void RenderFrameImpl::didRunInsecureContent(
3446 blink::WebLocalFrame
* frame
,
3447 const blink::WebSecurityOrigin
& origin
,
3448 const blink::WebURL
& target
) {
3449 DCHECK(!frame_
|| frame_
== frame
);
3450 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3451 render_view_
->GetRoutingID(),
3452 origin
.toString().utf8(),
3456 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3457 DCHECK(!frame_
|| frame_
== frame
);
3458 #if defined(ENABLE_PLUGINS)
3459 if (frame
!= render_view_
->webview()->mainFrame())
3461 PluginChannelHost::Broadcast(
3462 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3466 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3467 v8::Handle
<v8::Context
> context
,
3468 int extension_group
,
3470 DCHECK(!frame_
|| frame_
== frame
);
3472 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
3473 DidCreateScriptContext(context
, extension_group
, world_id
));
3476 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3477 v8::Handle
<v8::Context
> context
,
3479 DCHECK(!frame_
|| frame_
== frame
);
3481 FOR_EACH_OBSERVER(RenderFrameObserver
,
3483 WillReleaseScriptContext(context
, world_id
));
3486 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3487 blink::WebLocalFrame
* frame
) {
3488 DCHECK(!frame_
|| frame_
== frame
);
3489 if (frame
->parent())
3492 InternalDocumentStateData
* data
=
3493 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3494 data
->set_did_first_visually_non_empty_layout(true);
3496 #if defined(OS_ANDROID)
3497 GetRenderWidget()->DidChangeBodyBackgroundColor(
3498 render_view_
->webwidget_
->backgroundColor());
3501 GetRenderWidget()->QueueMessage(
3502 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3503 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3506 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3507 DCHECK(!frame_
|| frame_
== frame
);
3508 // TODO(nasko): Move implementation here. Needed methods:
3509 // * StartNavStateSyncTimerIfNecessary
3510 render_view_
->didChangeScrollOffset(frame
);
3512 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeScrollOffset());
3515 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3516 DCHECK(!frame_
|| frame_
== frame
);
3517 if (!frame
->parent()) {
3518 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3519 render_view_
->GetRoutingID()));
3523 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3525 bool final_update
) {
3526 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3528 active_match_ordinal
= 0;
3530 render_view_
->Send(new ViewHostMsg_Find_Reply(
3531 render_view_
->GetRoutingID(), request_id
, count
,
3532 gfx::Rect(), active_match_ordinal
, final_update
));
3535 void RenderFrameImpl::reportFindInPageSelection(
3537 int active_match_ordinal
,
3538 const blink::WebRect
& selection_rect
) {
3539 render_view_
->Send(new ViewHostMsg_Find_Reply(
3540 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3541 active_match_ordinal
, false));
3544 void RenderFrameImpl::requestStorageQuota(
3545 blink::WebLocalFrame
* frame
,
3546 blink::WebStorageQuotaType type
,
3547 unsigned long long requested_size
,
3548 blink::WebStorageQuotaCallbacks callbacks
) {
3549 DCHECK(!frame_
|| frame_
== frame
);
3550 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3551 if (origin
.isUnique()) {
3552 // Unique origins cannot store persistent state.
3553 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3556 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3557 render_view_
->GetRoutingID(),
3558 GURL(origin
.toString()),
3559 static_cast<storage::StorageType
>(type
),
3561 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3564 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3565 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3566 impl
->set_render_frame_id(routing_id_
);
3569 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3570 if (!geolocation_dispatcher_
)
3571 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3572 return geolocation_dispatcher_
;
3575 blink::WebPresentationClient
* RenderFrameImpl::presentationClient() {
3576 if (!presentation_dispatcher_
)
3577 presentation_dispatcher_
= new PresentationDispatcher(this);
3578 return presentation_dispatcher_
;
3581 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3582 if (!push_messaging_dispatcher_
)
3583 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3584 return push_messaging_dispatcher_
;
3587 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3588 blink::WebLocalFrame
* frame
,
3589 blink::WebRTCPeerConnectionHandler
* handler
) {
3590 DCHECK(!frame_
|| frame_
== frame
);
3591 #if defined(ENABLE_WEBRTC)
3592 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3596 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3597 if (!web_user_media_client_
)
3598 InitializeUserMediaClient();
3599 return web_user_media_client_
;
3602 blink::WebEncryptedMediaClient
* RenderFrameImpl::encryptedMediaClient() {
3603 if (!web_encrypted_media_client_
) {
3604 web_encrypted_media_client_
.reset(new media::WebEncryptedMediaClientImpl(
3605 GetCdmFactory(), GetMediaPermission()));
3607 return web_encrypted_media_client_
.get();
3610 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3611 if (!midi_dispatcher_
)
3612 midi_dispatcher_
= new MidiDispatcher(this);
3613 return midi_dispatcher_
;
3616 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3617 blink::WebLocalFrame
* source_frame
,
3618 blink::WebFrame
* target_frame
,
3619 blink::WebSecurityOrigin target_origin
,
3620 blink::WebDOMMessageEvent event
) {
3621 DCHECK(!frame_
|| frame_
== target_frame
);
3623 // Currently, a postMessage that targets a cross-process frame can be plumbed
3624 // either through this function or RenderFrameProxy::postMessageEvent. This
3625 // function is used when the target cross-process frame is a top-level frame
3626 // which has been swapped out. In that case, the corresponding WebLocalFrame
3627 // currently remains in the frame tree even in site-per-process mode (see
3628 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3629 // --site-per-process mode for all other cases.
3631 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3632 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3633 // cross-process postMessages.
3634 if (!is_swapped_out_
)
3637 // It is possible to get here on a swapped-out frame without a
3638 // |render_frame_proxy_|. This happens when:
3639 // - This process only has one active RenderView and is about to go away
3640 // (e.g., due to cross-process navigation).
3641 // - The top frame has a subframe with an unload handler.
3642 // - The subframe sends a postMessage to the top-level frame in its unload
3644 // See https://crbug.com/475651 for details. We return false here, since we
3645 // don't want to deliver the message to the new process in this case.
3646 if (!render_frame_proxy_
)
3649 render_frame_proxy_
->postMessageEvent(
3650 source_frame
, render_frame_proxy_
->web_frame(), target_origin
, event
);
3654 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3655 const blink::WebURL
& url
) {
3656 DCHECK(!frame_
|| frame_
== frame
);
3657 std::string user_agent_override_for_url
=
3658 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3659 if (!user_agent_override_for_url
.empty())
3660 return WebString::fromUTF8(user_agent_override_for_url
);
3662 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3663 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3664 return blink::WebString();
3667 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3668 // associated with it, so the checks below are not valid. Temporarily
3669 // return early and fix properly as part of https://crbug.com/426555.
3670 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3671 return blink::WebString();
3673 // If we're in the middle of committing a load, the data source we need
3674 // will still be provisional.
3675 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3676 WebDataSource
* data_source
= NULL
;
3677 if (main_frame
->provisionalDataSource())
3678 data_source
= main_frame
->provisionalDataSource();
3680 data_source
= main_frame
->dataSource();
3682 InternalDocumentStateData
* internal_data
= data_source
?
3683 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3684 if (internal_data
&& internal_data
->is_overriding_user_agent())
3685 return WebString::fromUTF8(
3686 render_view_
->renderer_preferences_
.user_agent_override
);
3687 return blink::WebString();
3690 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3691 DCHECK(!frame_
|| frame_
== frame
);
3692 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3693 return WebString::fromUTF8("1");
3697 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3698 bool default_value
) {
3699 DCHECK(!frame_
|| frame_
== frame
);
3703 bool blocked
= true;
3704 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3705 render_view_
->GetRoutingID(),
3706 GURL(frame
->top()->document().securityOrigin().toString()),
3707 THREE_D_API_TYPE_WEBGL
,
3712 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3713 int arb_robustness_status_code
) {
3714 DCHECK(!frame_
|| frame_
== frame
);
3715 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3716 GURL(frame
->top()->document().securityOrigin().toString()),
3717 THREE_D_API_TYPE_WEBGL
,
3718 arb_robustness_status_code
));
3721 blink::WebScreenOrientationClient
*
3722 RenderFrameImpl::webScreenOrientationClient() {
3723 if (!screen_orientation_dispatcher_
)
3724 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3725 return screen_orientation_dispatcher_
;
3728 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3729 ServiceWorkerNetworkProvider
* provider
=
3730 ServiceWorkerNetworkProvider::FromDocumentState(
3731 DocumentState::FromDataSource(&data_source
));
3732 return provider
->context()->controller_handle_id() !=
3733 kInvalidServiceWorkerHandleId
;
3736 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3737 ServiceWorkerNetworkProvider
* provider
=
3738 ServiceWorkerNetworkProvider::FromDocumentState(
3739 DocumentState::FromDataSource(&data_source
));
3741 if (provider
->context()->controller())
3742 return provider
->context()->controller()->version_id();
3743 return kInvalidServiceWorkerVersionId
;
3746 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3747 blink::WebAXEvent event
) {
3748 HandleWebAccessibilityEvent(obj
, event
);
3751 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3754 const blink::WebAXObject
& start_object
,
3756 const blink::WebAXObject
& end_object
,
3758 if (renderer_accessibility_
) {
3759 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3760 identifier
, match_index
, start_object
, start_offset
,
3761 end_object
, end_offset
);
3765 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
) {
3766 DCHECK(!frame_
|| frame_
== frame
);
3768 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3771 void RenderFrameImpl::didChangeDefaultPresentation(
3772 blink::WebLocalFrame
* frame
) {
3773 DCHECK(!frame_
|| frame_
== frame
);
3776 RenderFrameObserver
, observers_
, DidChangeDefaultPresentation());
3779 bool RenderFrameImpl::enterFullscreen() {
3780 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, true));
3784 bool RenderFrameImpl::exitFullscreen() {
3785 Send(new FrameHostMsg_ToggleFullscreen(routing_id_
, false));
3789 blink::WebPermissionClient
* RenderFrameImpl::permissionClient() {
3790 if (!permission_client_
)
3791 permission_client_
.reset(new PermissionDispatcher(GetServiceRegistry()));
3793 return permission_client_
.get();
3796 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3797 Send(new FrameHostMsg_MediaPlayingNotification(
3798 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3799 player
->hasAudio(), player
->isRemote()));
3802 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3803 Send(new FrameHostMsg_MediaPausedNotification(
3804 routing_id_
, reinterpret_cast<int64
>(player
)));
3807 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3811 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3812 observers_
.AddObserver(observer
);
3815 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3816 observer
->RenderFrameGone();
3817 observers_
.RemoveObserver(observer
);
3820 void RenderFrameImpl::OnStop() {
3822 frame_
->stopLoading();
3823 if (!frame_
->parent())
3824 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3826 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3829 void RenderFrameImpl::WasHidden() {
3830 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3833 void RenderFrameImpl::WasShown() {
3834 // TODO(kenrb): Need to figure out how to do this better. Should
3835 // VisibilityState remain a page-level concept or move to frames?
3836 // The semantics of 'Show' might have to change here.
3837 if (render_widget_
) {
3838 static_cast<blink::WebFrameWidget
*>(render_widget_
->webwidget())->
3839 setVisibilityState(blink::WebPageVisibilityStateVisible
, false);
3841 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3844 void RenderFrameImpl::WidgetWillClose() {
3845 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WidgetWillClose());
3848 bool RenderFrameImpl::IsHidden() {
3849 return GetRenderWidget()->is_hidden();
3852 // Tell the embedding application that the URL of the active page has changed.
3853 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3854 blink::WebFrame
* frame
,
3855 blink::WebHistoryCommitType commit_type
) {
3856 DCHECK(!frame_
|| frame_
== frame
);
3857 WebDataSource
* ds
= frame
->dataSource();
3860 const WebURLRequest
& request
= ds
->request();
3861 const WebURLResponse
& response
= ds
->response();
3863 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3864 NavigationStateImpl
* navigation_state
=
3865 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
3866 InternalDocumentStateData
* internal_data
=
3867 InternalDocumentStateData::FromDocumentState(document_state
);
3869 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3870 params
.http_status_code
= response
.httpStatusCode();
3871 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3872 params
.is_post
= false;
3873 params
.post_id
= -1;
3874 params
.page_id
= render_view_
->page_id_
;
3875 // We need to track the RenderViewHost routing_id because of downstream
3876 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3877 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3878 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3879 // based on the ID stored in the resource requests. Once those dependencies
3880 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3881 // client to be based on the routing_id of the RenderFrameHost.
3882 params
.render_view_routing_id
= render_view_
->routing_id();
3883 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3884 params
.socket_address
.set_port(response
.remotePort());
3885 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3887 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3888 params
.was_within_same_page
= navigation_state
->WasWithinSamePage();
3889 params
.security_info
= response
.securityInfo();
3891 // Set the URL to be displayed in the browser UI to the user.
3892 params
.url
= GetLoadingUrl();
3893 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3895 // Set the origin of the frame. This will be replicated to the corresponding
3896 // RenderFrameProxies in other processes.
3897 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3898 // to https://crbug.com/439608 and will be replicated as unique origins.
3899 if (!is_swapped_out_
) {
3900 WebString
serialized_origin(frame
->document().securityOrigin().toString());
3901 if (GURL(serialized_origin
).IsStandard())
3902 params
.origin
= url::Origin(serialized_origin
.utf8());
3905 if (frame
->document().baseURL() != params
.url
)
3906 params
.base_url
= frame
->document().baseURL();
3908 GetRedirectChain(ds
, ¶ms
.redirects
);
3909 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3910 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3912 params
.searchable_form_url
= internal_data
->searchable_form_url();
3913 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3915 params
.gesture
= render_view_
->navigation_gesture_
;
3916 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3918 // Make navigation state a part of the DidCommitProvisionalLoad message so
3919 // that committed entry has it at all times.
3920 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3922 params
.page_state
= HistoryEntryToPageState(entry
);
3924 params
.page_state
= PageState::CreateFromURL(request
.url());
3926 if (!frame
->parent()) {
3927 // Top-level navigation.
3929 // Reset the zoom limits in case a plugin had changed them previously. This
3930 // will also call us back which will cause us to send a message to
3931 // update WebContentsImpl.
3932 render_view_
->webview()->zoomLimitsChanged(
3933 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3934 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3936 // Set zoom level, but don't do it for full-page plugin since they don't use
3937 // the same zoom settings.
3938 HostZoomLevels::iterator host_zoom
=
3939 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3940 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3941 // Reset the zoom levels for plugins.
3942 render_view_
->webview()->setZoomLevel(0);
3944 // If the zoom level is not found, then do nothing. In-page navigation
3945 // relies on not changing the zoom level in this case.
3946 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3947 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3950 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3951 // This zoom level was merely recorded transiently for this load. We can
3952 // erase it now. If at some point we reload this page, the browser will
3953 // send us a new, up-to-date zoom level.
3954 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3957 // Update contents MIME type for main frame.
3958 params
.contents_mime_type
= ds
->response().mimeType().utf8();
3960 params
.transition
= navigation_state
->GetTransitionType();
3961 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
3962 // If the main frame does a load, it should not be reported as a subframe
3963 // navigation. This can occur in the following case:
3964 // 1. You're on a site with frames.
3965 // 2. You do a subframe navigation. This is stored with transition type
3967 // 3. You navigate to some non-frame site, say, google.com.
3968 // 4. You navigate back to the page from step 2. Since it was initially
3969 // MANUAL_SUBFRAME, it will be that same transition type here.
3970 // We don't want that, because any navigation that changes the toplevel
3971 // frame should be tracked as a toplevel navigation (this allows us to
3972 // update the URL bar, etc).
3973 params
.transition
= ui::PAGE_TRANSITION_LINK
;
3976 // If the page contained a client redirect (meta refresh, document.loc...),
3977 // set the referrer and transition appropriately.
3978 if (ds
->isClientRedirect()) {
3980 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
3981 params
.transition
= ui::PageTransitionFromInt(
3982 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3984 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
3985 frame
, ds
->request());
3988 base::string16 method
= request
.httpMethod();
3989 if (EqualsASCII(method
, "POST")) {
3990 params
.is_post
= true;
3991 params
.post_id
= ExtractPostId(entry
);
3994 // Send the user agent override back.
3995 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
3997 // Track the URL of the original request. We use the first entry of the
3998 // redirect chain if it exists because the chain may have started in another
4000 params
.original_request_url
= GetOriginalRequestURL(ds
);
4002 params
.history_list_was_cleared
=
4003 navigation_state
->request_params().should_clear_history_list
;
4005 params
.report_type
= static_cast<FrameMsg_UILoadMetricsReportType::Value
>(
4006 frame
->dataSource()->request().inputPerfMetricReportPolicy());
4007 params
.ui_timestamp
= base::TimeTicks() + base::TimeDelta::FromSecondsD(
4008 frame
->dataSource()->request().uiStartTime());
4010 // Save some histogram data so we can compute the average memory used per
4011 // page load of the glyphs.
4012 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4013 blink::WebGlyphCache::pageCount());
4015 // This message needs to be sent before any of allowScripts(),
4016 // allowImages(), allowPlugins() is called for the new page, so that when
4017 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4018 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4019 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4021 // Subframe navigation: the type depends on whether this navigation
4022 // generated a new session history entry. When they do generate a session
4023 // history entry, it means the user initiated the navigation and we should
4025 if (commit_type
== blink::WebStandardCommit
)
4026 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
4028 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
4030 DCHECK(!navigation_state
->request_params().should_clear_history_list
);
4031 params
.history_list_was_cleared
= false;
4032 params
.report_type
= FrameMsg_UILoadMetricsReportType::NO_REPORT
;
4034 // Don't send this message while the subframe is swapped out.
4035 if (!is_swapped_out())
4036 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
4039 // If we end up reusing this WebRequest (for example, due to a #ref click),
4040 // we don't want the transition type to persist. Just clear it.
4041 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
4044 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
4045 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4047 render_view_
->FrameDidStartLoading(frame_
);
4048 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
4051 void RenderFrameImpl::didStopLoading() {
4052 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4054 render_view_
->FrameDidStopLoading(frame_
);
4055 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
4058 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
4059 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
4062 void RenderFrameImpl::HandleWebAccessibilityEvent(
4063 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
4064 if (renderer_accessibility_
)
4065 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
4068 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
4069 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FocusedNodeChanged(node
));
4072 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode
& node
) {
4073 if (renderer_accessibility())
4074 renderer_accessibility()->AccessibilityFocusedNodeChanged(node
);
4078 void RenderFrameImpl::OnCommitNavigation(
4079 const ResourceResponseHead
& response
,
4080 const GURL
& stream_url
,
4081 const CommonNavigationParams
& common_params
,
4082 const RequestNavigationParams
& request_params
) {
4083 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4084 switches::kEnableBrowserSideNavigation
));
4085 bool is_reload
= false;
4086 bool is_history_navigation
= request_params
.page_state
.IsValid();
4087 WebURLRequest::CachePolicy cache_policy
=
4088 WebURLRequest::UseProtocolCachePolicy
;
4089 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4090 common_params
.url
, is_history_navigation
, request_params
, &is_reload
,
4092 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4096 GetContentClient()->SetActiveURL(common_params
.url
);
4098 pending_navigation_params_
.reset(new NavigationParams(
4099 common_params
, StartNavigationParams(), request_params
));
4101 if (!common_params
.base_url_for_data_url
.is_empty() ||
4102 common_params
.url
.SchemeIs(url::kDataScheme
)) {
4103 LoadDataURL(common_params
, frame_
);
4107 // Create a WebURLRequest that blink can use to get access to the body of the
4108 // response through a stream in the browser. Blink will then commit the
4110 // TODO(clamy): Have the navigation commit directly, without going through
4111 // loading a WebURLRequest.
4112 scoped_ptr
<StreamOverrideParameters
> stream_override(
4113 new StreamOverrideParameters());
4114 stream_override
->stream_url
= stream_url
;
4115 stream_override
->response
= response
;
4116 WebURLRequest request
=
4117 CreateURLRequestForNavigation(common_params
,
4118 stream_override
.Pass(),
4119 frame_
->isViewSourceModeEnabled());
4121 // Make sure that blink loader will not try to use browser side navigation for
4122 // this request (since it already went to the browser).
4123 request
.setCheckForBrowserSideNavigation(false);
4125 // Record this before starting the load. A lower bound of this time is needed
4126 // to sanitize the navigationStart override set below.
4127 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
4128 frame_
->loadRequest(request
);
4129 UpdateFrameNavigationTiming(frame_
, request_params
.browser_navigation_start
,
4130 renderer_navigation_start
);
4133 void RenderFrameImpl::OnFailedNavigation(
4134 const CommonNavigationParams
& common_params
,
4135 const RequestNavigationParams
& request_params
,
4136 bool has_stale_copy_in_cache
,
4138 bool is_reload
= IsReload(common_params
.navigation_type
);
4139 bool is_history_navigation
= request_params
.page_state
.IsValid();
4140 WebURLRequest::CachePolicy cache_policy
=
4141 WebURLRequest::UseProtocolCachePolicy
;
4142 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4143 common_params
.url
, is_history_navigation
, request_params
, &is_reload
,
4145 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4149 GetContentClient()->SetActiveURL(common_params
.url
);
4151 pending_navigation_params_
.reset(new NavigationParams(
4152 common_params
, StartNavigationParams(), request_params
));
4154 // Inform the browser of the start of the provisional load. This is needed so
4155 // that the load is properly tracked by the WebNavigation API.
4156 // TODO(clamy): Properly set is_transition_navigation.
4157 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4158 routing_id_
, common_params
.url
, false));
4160 // Send the provisional load failure.
4161 blink::WebURLError error
=
4162 CreateWebURLError(common_params
.url
, has_stale_copy_in_cache
, error_code
);
4163 WebURLRequest failed_request
= CreateURLRequestForNavigation(
4164 common_params
, scoped_ptr
<StreamOverrideParameters
>(),
4165 frame_
->isViewSourceModeEnabled());
4166 SendFailedProvisionalLoad(failed_request
, error
, frame_
);
4168 if (!ShouldDisplayErrorPageForFailedLoad(error_code
, common_params
.url
)) {
4169 Send(new FrameHostMsg_DidDropNavigation(routing_id_
));
4173 // Make sure errors are not shown in view source mode.
4174 frame_
->enableViewSourceMode(false);
4176 // Replace the current history entry in reloads, history navigations and loads
4177 // of the same url. This corresponds to Blink's notion of a standard
4179 // TODO(clamy): see if initial commits in subframes should be handled
4181 bool replace
= is_reload
|| is_history_navigation
||
4182 common_params
.url
== GetLoadingUrl();
4183 LoadNavigationErrorPage(failed_request
, error
, replace
);
4186 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
4187 RenderFrame
* render_frame
,
4188 const NavigationPolicyInfo
& info
) {
4190 // The handlenavigation API is deprecated and will be removed once
4191 // crbug.com/325351 is resolved.
4192 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
4193 GetContentClient()->renderer()->HandleNavigation(
4195 static_cast<DocumentState
*>(info
.extraData
),
4196 render_view_
->opener_id_
,
4199 info
.navigationType
,
4202 return blink::WebNavigationPolicyIgnore
;
4206 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
4208 const base::CommandLine
& command_line
=
4209 *base::CommandLine::ForCurrentProcess();
4211 bool is_subframe
= !!info
.frame
->parent();
4213 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe
) {
4214 // There's no reason to ignore navigations on subframes, since the swap out
4215 // logic no longer applies.
4217 if (is_swapped_out_
) {
4218 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
4219 // Targeted links may try to navigate a swapped out frame. Allow the
4220 // browser process to navigate the tab instead. Note that it is also
4221 // possible for non-targeted navigations (from this view) to arrive
4222 // here just after we are swapped out. It's ok to send them to the
4223 // browser, as long as they're for the top level frame.
4224 // TODO(creis): Ensure this supports targeted form submissions when
4225 // fixing http://crbug.com/101395.
4226 if (info
.frame
->parent() == NULL
) {
4227 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
4228 info
.defaultPolicy
);
4229 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4232 // We should otherwise ignore in-process iframe navigations, if they
4233 // arrive just after we are swapped out.
4234 return blink::WebNavigationPolicyIgnore
;
4237 // Allow kSwappedOutURL to complete.
4238 return info
.defaultPolicy
;
4242 // Webkit is asking whether to navigate to a new URL.
4243 // This is fine normally, except if we're showing UI from one security
4244 // context and they're trying to navigate to a different context.
4245 const GURL
& url
= info
.urlRequest
.url();
4247 // A content initiated navigation may have originated from a link-click,
4248 // script, drag-n-drop operation, etc.
4249 DocumentState
* document_state
= static_cast<DocumentState
*>(info
.extraData
);
4250 bool is_content_initiated
=
4251 document_state
->navigation_state()->IsContentInitiated();
4254 // If --enable-strict-site-isolation is enabled, send all top-level
4255 // navigations to the browser to let it swap processes when crossing site
4256 // boundaries. This is currently expected to break some script calls and
4257 // navigations, such as form submissions.
4258 bool force_swap_due_to_flag
=
4259 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
);
4260 if (force_swap_due_to_flag
&&
4261 !info
.frame
->parent() && (is_content_initiated
|| info
.isRedirect
)) {
4262 WebString origin_str
= info
.frame
->document().securityOrigin().toString();
4263 GURL
frame_url(origin_str
.utf8().data());
4264 // TODO(cevans): revisit whether this site check is still necessary once
4265 // crbug.com/101395 is fixed.
4266 bool same_domain_or_host
=
4267 net::registry_controlled_domains::SameDomainOrHost(
4270 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
4271 // Only keep same-site (domain + scheme) and data URLs in the same process.
4273 (same_domain_or_host
&& frame_url
.scheme() == url
.scheme()) ||
4274 url
.SchemeIs(url::kDataScheme
);
4275 if (!is_same_site
) {
4276 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4277 return blink::WebNavigationPolicyIgnore
;
4281 // If the browser is interested, then give it a chance to look at the request.
4282 if (is_content_initiated
) {
4284 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
4285 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
4286 EqualsASCII(info
.urlRequest
.httpMethod(), "POST");
4287 bool browser_handles_request
=
4288 render_view_
->renderer_preferences_
4289 .browser_handles_non_local_top_level_requests
4290 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
4292 if (!browser_handles_request
) {
4293 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
4294 render_view_
->renderer_preferences_
4295 .browser_handles_all_top_level_requests
;
4298 if (browser_handles_request
) {
4299 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
4300 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4304 // Use the frame's original request's URL rather than the document's URL for
4305 // subsequent checks. For a popup, the document's URL may become the opener
4306 // window's URL if the opener has called document.write().
4307 // See http://crbug.com/93517.
4308 GURL
old_url(info
.frame
->dataSource()->request().url());
4310 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4311 // an extension or app origin, leaving a WebUI page, etc). We only care about
4312 // top-level navigations (not iframes). But we sometimes navigate to
4313 // about:blank to clear a tab, and we want to still allow that.
4315 // Note: this is known to break POST submissions when crossing process
4316 // boundaries until http://crbug.com/101395 is fixed. This is better for
4317 // security than loading a WebUI, extension or app page in the wrong process.
4318 // POST requests don't work because this mechanism does not preserve form
4319 // POST data. We will need to send the request's httpBody data up to the
4320 // browser process, and issue a special POST navigation in WebKit (via
4321 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4322 // for examples of how to send the httpBody data.
4323 if (!info
.frame
->parent() && is_content_initiated
&&
4324 !url
.SchemeIs(url::kAboutScheme
)) {
4325 bool send_referrer
= false;
4327 // All navigations to or from WebUI URLs or within WebUI-enabled
4328 // RenderProcesses must be handled by the browser process so that the
4329 // correct bindings and data sources can be registered.
4330 // Similarly, navigations to view-source URLs or within ViewSource mode
4331 // must be handled by the browser process (except for reloads - those are
4332 // safe to leave within the renderer).
4333 // Lastly, access to file:// URLs from non-file:// URL pages must be
4334 // handled by the browser so that ordinary renderer processes don't get
4335 // blessed with file permissions.
4336 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
4337 bool is_initial_navigation
= render_view_
->page_id_
== -1;
4338 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
4339 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
4340 url
.SchemeIs(kViewSourceScheme
) ||
4341 (info
.frame
->isViewSourceModeEnabled() &&
4342 info
.navigationType
!= blink::WebNavigationTypeReload
);
4344 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
4345 // Fork non-file to file opens. Check the opener URL if this is the
4346 // initial navigation in a newly opened window.
4347 GURL
source_url(old_url
);
4348 if (is_initial_navigation
&& source_url
.is_empty() &&
4349 info
.frame
->opener())
4350 source_url
= info
.frame
->opener()->top()->document().url();
4351 DCHECK(!source_url
.is_empty());
4352 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
4356 // Give the embedder a chance.
4357 should_fork
= GetContentClient()->renderer()->ShouldFork(
4358 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
4359 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
4363 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
4364 info
.defaultPolicy
);
4365 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
4369 // Detect when a page is "forking" a new tab that can be safely rendered in
4370 // its own process. This is done by sites like Gmail that try to open links
4371 // in new windows without script connections back to the original page. We
4372 // treat such cases as browser navigations (in which we will create a new
4373 // renderer for a cross-site navigation), rather than WebKit navigations.
4375 // We use the following heuristic to decide whether to fork a new page in its
4377 // The parent page must open a new tab to about:blank, set the new tab's
4378 // window.opener to null, and then redirect the tab to a cross-site URL using
4381 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4384 // Must start from a tab showing about:blank, which is later redirected.
4385 old_url
== GURL(url::kAboutBlankURL
) &&
4386 // Must be the first real navigation of the tab.
4387 render_view_
->historyBackListCount() < 1 &&
4388 render_view_
->historyForwardListCount() < 1 &&
4389 // The parent page must have set the child's window.opener to null before
4390 // redirecting to the desired URL.
4391 info
.frame
->opener() == NULL
&&
4392 // Must be a top-level frame.
4393 info
.frame
->parent() == NULL
&&
4394 // Must not have issued the request from this page.
4395 is_content_initiated
&&
4396 // Must be targeted at the current tab.
4397 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
4398 // Must be a JavaScript navigation, which appears as "other".
4399 info
.navigationType
== blink::WebNavigationTypeOther
;
4402 // Open the URL via the browser, not via WebKit.
4403 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
4404 return blink::WebNavigationPolicyIgnore
;
4407 // PlzNavigate: send the request to the browser if needed.
4408 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4409 switches::kEnableBrowserSideNavigation
) &&
4410 info
.urlRequest
.checkForBrowserSideNavigation()) {
4411 BeginNavigation(&info
.urlRequest
);
4412 return blink::WebNavigationPolicyIgnore
;
4415 return info
.defaultPolicy
;
4418 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
4420 const Referrer
& referrer
,
4421 WebNavigationPolicy policy
) {
4422 DCHECK_EQ(frame_
, frame
);
4424 FrameHostMsg_OpenURL_Params params
;
4426 params
.referrer
= referrer
;
4427 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
4428 WebDataSource
* ds
= frame
->provisionalDataSource();
4430 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
4431 NavigationStateImpl
* navigation_state
=
4432 static_cast<NavigationStateImpl
*>(document_state
->navigation_state());
4433 if (navigation_state
->IsContentInitiated()) {
4434 params
.should_replace_current_entry
=
4435 ds
->replacesCurrentHistoryItem() &&
4436 render_view_
->history_list_length_
;
4438 // This is necessary to preserve the should_replace_current_entry value on
4439 // cross-process redirects, in the event it was set by a previous process.
4441 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4442 // NavigationState::should_replace_current_entry().
4443 params
.should_replace_current_entry
=
4444 navigation_state
->start_params().should_replace_current_entry
;
4447 params
.should_replace_current_entry
= false;
4449 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
4450 if (GetContentClient()->renderer()->AllowPopup())
4451 params
.user_gesture
= true;
4453 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
4454 policy
== blink::WebNavigationPolicyNewForegroundTab
||
4455 policy
== blink::WebNavigationPolicyNewWindow
||
4456 policy
== blink::WebNavigationPolicyNewPopup
) {
4457 WebUserGestureIndicator::consumeUserGesture();
4460 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
4463 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
4464 const std::string
& encoding_name
) {
4465 // Only update main frame's encoding_name.
4466 if (!frame
->parent())
4467 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
4470 void RenderFrameImpl::SyncSelectionIfRequired() {
4471 base::string16 text
;
4474 #if defined(ENABLE_PLUGINS)
4475 if (render_view_
->focused_pepper_plugin_
) {
4476 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4477 offset
= 0; // Pepper API does not support offset reporting.
4478 // TODO(kinaba): cut as needed.
4482 size_t location
, length
;
4483 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4484 &location
, &length
)) {
4488 range
= gfx::Range(location
, location
+ length
);
4490 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4491 blink::WebTextInputTypeNone
) {
4492 // If current focused element is editable, we will send 100 more chars
4493 // before and after selection. It is for input method surrounding text
4495 if (location
> kExtraCharsBeforeAndAfterSelection
)
4496 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4499 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4500 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4501 if (!webrange
.isNull())
4502 text
= webrange
.toPlainText();
4505 text
= frame_
->selectionAsText();
4506 // http://crbug.com/101435
4507 // In some case, frame->selectionAsText() returned text's length is not
4508 // equal to the length returned from webwidget()->caretOrSelectionRange().
4509 // So we have to set the range according to text.length().
4510 range
.set_end(range
.start() + text
.length());
4514 // Sometimes we get repeated didChangeSelection calls from webkit when
4515 // the selection hasn't actually changed. We don't want to report these
4516 // because it will cause us to continually claim the X clipboard.
4517 if (selection_text_offset_
!= offset
||
4518 selection_range_
!= range
||
4519 selection_text_
!= text
) {
4520 selection_text_
= text
;
4521 selection_text_offset_
= offset
;
4522 selection_range_
= range
;
4523 SetSelectedText(text
, offset
, range
);
4525 GetRenderWidget()->UpdateSelectionBounds();
4528 void RenderFrameImpl::InitializeUserMediaClient() {
4529 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4532 #if defined(OS_ANDROID)
4533 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4534 switches::kDisableWebRTC
))
4538 #if defined(ENABLE_WEBRTC)
4539 DCHECK(!web_user_media_client_
);
4540 web_user_media_client_
= new UserMediaClientImpl(
4542 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4543 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4547 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4548 const blink::WebURL
& url
,
4549 WebMediaPlayerClient
* client
) {
4550 #if defined(ENABLE_WEBRTC)
4551 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4553 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4554 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4555 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4556 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4557 new RenderMediaLog(),
4558 CreateRendererFactory());
4561 #endif // defined(ENABLE_WEBRTC)
4564 scoped_ptr
<MediaStreamRendererFactory
>
4565 RenderFrameImpl::CreateRendererFactory() {
4566 #if defined(ENABLE_WEBRTC)
4567 return scoped_ptr
<MediaStreamRendererFactory
>(
4568 new MediaStreamRendererFactory());
4570 return scoped_ptr
<MediaStreamRendererFactory
>(
4571 static_cast<MediaStreamRendererFactory
*>(NULL
));
4575 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4577 bool is_history_navigation
,
4578 const RequestNavigationParams
& request_params
,
4580 WebURLRequest::CachePolicy
* cache_policy
) {
4581 MaybeHandleDebugURL(url
);
4582 if (!render_view_
->webview())
4586 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4588 // If this is a stale back/forward (due to a recent navigation the browser
4589 // didn't know about), ignore it. Only check if swapped in because if the
4590 // frame is swapped out, it won't commit before asking the browser.
4591 if (!render_view_
->is_swapped_out() && is_history_navigation
&&
4592 render_view_
->history_list_offset_
!=
4593 request_params
.current_history_list_offset
) {
4597 render_view_
->history_list_offset_
=
4598 request_params
.current_history_list_offset
;
4599 render_view_
->history_list_length_
=
4600 request_params
.current_history_list_length
;
4601 if (request_params
.should_clear_history_list
) {
4602 CHECK_EQ(-1, render_view_
->history_list_offset_
);
4603 CHECK_EQ(0, render_view_
->history_list_length_
);
4606 if (!is_swapped_out_
|| frame_
->parent())
4609 // This is a swapped out main frame, so swap the renderer back in.
4610 // We marked the view as hidden when swapping the view out, so be sure to
4611 // reset the visibility state before navigating to the new URL.
4612 render_view_
->webview()->setVisibilityState(
4613 render_view_
->visibilityState(), false);
4615 // If this is an attempt to reload while we are swapped out, we should not
4616 // reload swappedout://, but the previous page, which is stored in
4617 // params.state. Setting is_reload to false will treat this like a back
4618 // navigation to accomplish that.
4620 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4622 // We refresh timezone when a view is swapped in since timezone
4623 // can get out of sync when the system timezone is updated while
4624 // the view is swapped out.
4625 RenderThreadImpl::NotifyTimezoneChange();
4627 render_view_
->SetSwappedOut(false);
4628 is_swapped_out_
= false;
4632 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4633 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4634 switches::kEnableBrowserSideNavigation
));
4636 // TODO(clamy): Execute the beforeunload event.
4638 // Note: At this stage, the goal is to apply all the modifications the
4639 // renderer wants to make to the request, and then send it to the browser, so
4640 // that the actual network request can be started. Ideally, all such
4641 // modifications should take place in willSendRequest, and in the
4642 // implementation of willSendRequest for the various InspectorAgents
4645 // TODO(clamy): Apply devtools override.
4646 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4648 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4650 // TODO(clamy): Same-document navigations should not be sent back to the
4652 // TODO(clamy): Data urls should not be sent back to the browser either.
4653 Send(new FrameHostMsg_DidStartLoading(routing_id_
, true));
4654 Send(new FrameHostMsg_BeginNavigation(
4655 routing_id_
, MakeCommonNavigationParams(request
),
4656 BeginNavigationParams(request
->httpMethod().latin1(),
4657 GetWebURLRequestHeaders(*request
),
4658 GetLoadFlagsForWebURLRequest(*request
),
4659 request
->hasUserGesture()),
4660 GetRequestBodyForWebURLRequest(*request
)));
4663 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams
& params
,
4665 // A loadData request with a specified base URL.
4666 std::string mime_type
, charset
, data
;
4667 if (net::DataURL::Parse(params
.url
, &mime_type
, &charset
, &data
)) {
4668 const GURL base_url
= params
.base_url_for_data_url
.is_empty() ?
4669 params
.url
: params
.base_url_for_data_url
;
4671 WebData(data
.c_str(), data
.length()),
4672 WebString::fromUTF8(mime_type
),
4673 WebString::fromUTF8(charset
),
4675 params
.history_url_for_data_url
,
4678 CHECK(false) << "Invalid URL passed: "
4679 << params
.url
.possibly_invalid_spec();
4683 void RenderFrameImpl::SendFailedProvisionalLoad(
4684 const blink::WebURLRequest
& request
,
4685 const blink::WebURLError
& error
,
4686 blink::WebLocalFrame
* frame
) {
4687 bool show_repost_interstitial
= (error
.reason
== net::ERR_CACHE_MISS
&&
4688 EqualsASCII(request
.httpMethod(), "POST"));
4690 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
4691 params
.error_code
= error
.reason
;
4692 GetContentClient()->renderer()->GetNavigationErrorStrings(
4693 render_view_
.get(), frame
, request
, error
, NULL
,
4694 ¶ms
.error_description
);
4695 params
.url
= error
.unreachableURL
;
4696 params
.showing_repost_interstitial
= show_repost_interstitial
;
4697 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_
, params
));
4700 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4702 const GURL
& unreachable_url
) {
4703 // Don't display an error page if this is simply a cancelled load. Aside
4704 // from being dumb, Blink doesn't expect it and it will cause a crash.
4705 if (error_code
== net::ERR_ABORTED
)
4708 // Don't display "client blocked" error page if browser has asked us not to.
4709 if (error_code
== net::ERR_BLOCKED_BY_CLIENT
&&
4710 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
4714 // Allow the embedder to suppress an error page.
4715 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4716 this, unreachable_url
)) {
4720 if (RenderThreadImpl::current() &&
4721 RenderThreadImpl::current()->layout_test_mode()) {
4728 GURL
RenderFrameImpl::GetLoadingUrl() const {
4729 WebDataSource
* ds
= frame_
->dataSource();
4730 if (ds
->hasUnreachableURL())
4731 return ds
->unreachableURL();
4733 const WebURLRequest
& request
= ds
->request();
4734 return request
.url();
4737 void RenderFrameImpl::PopulateDocumentStateFromPending(
4738 DocumentState
* document_state
) {
4739 document_state
->set_request_time(
4740 pending_navigation_params_
->request_params
.request_time
);
4742 InternalDocumentStateData
* internal_data
=
4743 InternalDocumentStateData::FromDocumentState(document_state
);
4745 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4746 url::kJavaScriptScheme
) &&
4747 pending_navigation_params_
->common_params
.navigation_type
==
4748 FrameMsg_Navigate_Type::RESTORE
) {
4749 // We're doing a load of a page that was restored from the last session. By
4750 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4751 // can result in stale data for pages that are set to expire. We explicitly
4752 // override that by setting the policy here so that as necessary we load
4753 // from the network.
4755 // TODO(davidben): Remove this in favor of passing a cache policy to the
4756 // loadHistoryItem call in OnNavigate. That requires not overloading
4757 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4758 // policy based on load type, etc".
4759 internal_data
->set_cache_policy_override(
4760 WebURLRequest::UseProtocolCachePolicy
);
4763 if (IsReload(pending_navigation_params_
->common_params
.navigation_type
))
4764 document_state
->set_load_type(DocumentState::RELOAD
);
4765 else if (pending_navigation_params_
->request_params
.page_state
.IsValid())
4766 document_state
->set_load_type(DocumentState::HISTORY_LOAD
);
4768 document_state
->set_load_type(DocumentState::NORMAL_LOAD
);
4770 internal_data
->set_is_overriding_user_agent(
4771 pending_navigation_params_
->request_params
.is_overriding_user_agent
);
4772 internal_data
->set_must_reset_scroll_and_scale_state(
4773 pending_navigation_params_
->common_params
.navigation_type
==
4774 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
4775 document_state
->set_can_load_local_resources(
4776 pending_navigation_params_
->request_params
.can_load_local_resources
);
4779 NavigationState
* RenderFrameImpl::CreateNavigationStateFromPending() {
4780 // A navigation resulting from loading a javascript URL should not be treated
4781 // as a browser initiated event. Instead, we want it to look as if the page
4782 // initiated any load resulting from JS execution.
4783 if (!pending_navigation_params_
->common_params
.url
.SchemeIs(
4784 url::kJavaScriptScheme
)) {
4785 return NavigationStateImpl::CreateBrowserInitiated(
4786 pending_navigation_params_
->common_params
,
4787 pending_navigation_params_
->start_params
,
4788 pending_navigation_params_
->request_params
);
4790 return NavigationStateImpl::CreateContentInitiated();
4793 #if defined(OS_ANDROID)
4795 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4796 const blink::WebURL
& url
,
4797 WebMediaPlayerClient
* client
,
4798 media::MediaPermission
* media_permission
,
4799 blink::WebContentDecryptionModule
* initial_cdm
) {
4800 GpuChannelHost
* gpu_channel_host
=
4801 RenderThreadImpl::current()->EstablishGpuChannelSync(
4802 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4803 if (!gpu_channel_host
) {
4804 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4808 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4809 if (SynchronousCompositorFactory
* factory
=
4810 SynchronousCompositorFactory::GetInstance()) {
4811 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4813 scoped_refptr
<cc_blink::ContextProviderWebContext
> context_provider
=
4814 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4816 if (!context_provider
.get()) {
4817 LOG(ERROR
) << "Failed to get context3d for media player";
4821 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4822 context_provider
, gpu_channel_host
, routing_id_
);
4825 return new WebMediaPlayerAndroid(
4826 frame_
, client
, weak_factory_
.GetWeakPtr(), GetMediaPlayerManager(),
4827 GetCdmFactory(), media_permission
, initial_cdm
, stream_texture_factory
,
4828 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4829 new RenderMediaLog());
4832 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4833 if (!media_player_manager_
)
4834 media_player_manager_
= new RendererMediaPlayerManager(this);
4835 return media_player_manager_
;
4838 #endif // defined(OS_ANDROID)
4840 media::MediaPermission
* RenderFrameImpl::GetMediaPermission() {
4841 if (!media_permission_dispatcher_
)
4842 media_permission_dispatcher_
= new MediaPermissionDispatcher(this);
4843 return media_permission_dispatcher_
;
4846 media::CdmFactory
* RenderFrameImpl::GetCdmFactory() {
4847 #if defined(ENABLE_BROWSER_CDMS)
4849 cdm_manager_
= new RendererCdmManager(this);
4850 #endif // defined(ENABLE_BROWSER_CDMS)
4852 if (!cdm_factory_
) {
4854 cdm_factory_
= new RenderCdmFactory(
4855 #if defined(ENABLE_PEPPER_CDMS)
4856 base::Bind(&PepperCdmWrapperImpl::Create
, frame_
),
4857 #elif defined(ENABLE_BROWSER_CDMS)
4863 return cdm_factory_
;
4866 } // namespace content