1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/render_frame_impl.h"
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/kill.h"
18 #include "base/process/process.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/plugin_messages.h"
24 #include "content/child/quota_dispatcher.h"
25 #include "content/child/request_extra_data.h"
26 #include "content/child/service_worker/service_worker_handle_reference.h"
27 #include "content/child/service_worker/service_worker_network_provider.h"
28 #include "content/child/service_worker/service_worker_provider_context.h"
29 #include "content/child/service_worker/web_service_worker_provider_impl.h"
30 #include "content/child/web_url_loader_impl.h"
31 #include "content/child/web_url_request_util.h"
32 #include "content/child/webmessageportchannel_impl.h"
33 #include "content/child/websocket_bridge.h"
34 #include "content/child/weburlresponse_extradata_impl.h"
35 #include "content/common/clipboard_messages.h"
36 #include "content/common/frame_messages.h"
37 #include "content/common/input_messages.h"
38 #include "content/common/service_worker/service_worker_types.h"
39 #include "content/common/swapped_out_messages.h"
40 #include "content/common/view_messages.h"
41 #include "content/public/common/bindings_policy.h"
42 #include "content/public/common/content_constants.h"
43 #include "content/public/common/content_switches.h"
44 #include "content/public/common/context_menu_params.h"
45 #include "content/public/common/page_state.h"
46 #include "content/public/common/resource_response.h"
47 #include "content/public/common/url_constants.h"
48 #include "content/public/common/url_utils.h"
49 #include "content/public/renderer/browser_plugin_delegate.h"
50 #include "content/public/renderer/content_renderer_client.h"
51 #include "content/public/renderer/context_menu_client.h"
52 #include "content/public/renderer/document_state.h"
53 #include "content/public/renderer/navigation_state.h"
54 #include "content/public/renderer/render_frame_observer.h"
55 #include "content/public/renderer/renderer_ppapi_host.h"
56 #include "content/renderer/accessibility/renderer_accessibility.h"
57 #include "content/renderer/browser_plugin/browser_plugin.h"
58 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
59 #include "content/renderer/child_frame_compositing_helper.h"
60 #include "content/renderer/context_menu_params_builder.h"
61 #include "content/renderer/devtools/devtools_agent.h"
62 #include "content/renderer/dom_automation_controller.h"
63 #include "content/renderer/dom_utils.h"
64 #include "content/renderer/external_popup_menu.h"
65 #include "content/renderer/geolocation_dispatcher.h"
66 #include "content/renderer/history_controller.h"
67 #include "content/renderer/history_serialization.h"
68 #include "content/renderer/image_loading_helper.h"
69 #include "content/renderer/ime_event_guard.h"
70 #include "content/renderer/internal_document_state_data.h"
71 #include "content/renderer/manifest/manifest_manager.h"
72 #include "content/renderer/media/audio_renderer_mixer_manager.h"
73 #include "content/renderer/media/crypto/render_cdm_factory.h"
74 #include "content/renderer/media/media_stream_dispatcher.h"
75 #include "content/renderer/media/media_stream_renderer_factory.h"
76 #include "content/renderer/media/midi_dispatcher.h"
77 #include "content/renderer/media/render_media_log.h"
78 #include "content/renderer/media/user_media_client_impl.h"
79 #include "content/renderer/media/webmediaplayer_ms.h"
80 #include "content/renderer/mojo/service_registry_js_wrapper.h"
81 #include "content/renderer/notification_permission_dispatcher.h"
82 #include "content/renderer/npapi/plugin_channel_host.h"
83 #include "content/renderer/push_messaging_dispatcher.h"
84 #include "content/renderer/render_frame_proxy.h"
85 #include "content/renderer/render_process.h"
86 #include "content/renderer/render_thread_impl.h"
87 #include "content/renderer/render_view_impl.h"
88 #include "content/renderer/render_widget_fullscreen_pepper.h"
89 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
90 #include "content/renderer/renderer_webcolorchooser_impl.h"
91 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
92 #include "content/renderer/shared_worker_repository.h"
93 #include "content/renderer/v8_value_converter_impl.h"
94 #include "content/renderer/websharedworker_proxy.h"
95 #include "gin/modules/module_registry.h"
96 #include "media/base/audio_renderer_mixer_input.h"
97 #include "media/base/renderer.h"
98 #include "media/blink/encrypted_media_player_support.h"
99 #include "media/blink/webcontentdecryptionmodule_impl.h"
100 #include "media/blink/webmediaplayer_impl.h"
101 #include "media/blink/webmediaplayer_params.h"
102 #include "media/filters/gpu_video_accelerator_factories.h"
103 #include "mojo/edk/js/core.h"
104 #include "mojo/edk/js/support.h"
105 #include "net/base/data_url.h"
106 #include "net/base/net_errors.h"
107 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
108 #include "net/http/http_util.h"
109 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
110 #include "third_party/WebKit/public/platform/WebString.h"
111 #include "third_party/WebKit/public/platform/WebURL.h"
112 #include "third_party/WebKit/public/platform/WebURLError.h"
113 #include "third_party/WebKit/public/platform/WebURLResponse.h"
114 #include "third_party/WebKit/public/platform/WebVector.h"
115 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
116 #include "third_party/WebKit/public/web/WebDocument.h"
117 #include "third_party/WebKit/public/web/WebGlyphCache.h"
118 #include "third_party/WebKit/public/web/WebLocalFrame.h"
119 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
120 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
121 #include "third_party/WebKit/public/web/WebPlugin.h"
122 #include "third_party/WebKit/public/web/WebPluginParams.h"
123 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
124 #include "third_party/WebKit/public/web/WebRange.h"
125 #include "third_party/WebKit/public/web/WebScriptSource.h"
126 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
127 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
128 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
129 #include "third_party/WebKit/public/web/WebSurroundingText.h"
130 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
131 #include "third_party/WebKit/public/web/WebView.h"
133 #if defined(ENABLE_PLUGINS)
134 #include "content/renderer/npapi/webplugin_impl.h"
135 #include "content/renderer/pepper/pepper_browser_connection.h"
136 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
137 #include "content/renderer/pepper/pepper_webplugin_impl.h"
138 #include "content/renderer/pepper/plugin_module.h"
139 #include "content/renderer/pepper/plugin_power_saver_helper.h"
142 #if defined(ENABLE_WEBRTC)
143 #include "content/renderer/media/rtc_peer_connection_handler.h"
146 #if defined(OS_ANDROID)
147 #include <cpu-features.h>
149 #include "content/common/gpu/client/context_provider_command_buffer.h"
150 #include "content/renderer/android/synchronous_compositor_factory.h"
151 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
152 #include "content/renderer/media/android/renderer_media_player_manager.h"
153 #include "content/renderer/media/android/stream_texture_factory_impl.h"
154 #include "content/renderer/media/android/webmediaplayer_android.h"
157 #if defined(ENABLE_PEPPER_CDMS)
158 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
159 #elif defined(ENABLE_BROWSER_CDMS)
160 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
163 using blink::WebContextMenuData
;
164 using blink::WebData
;
165 using blink::WebDataSource
;
166 using blink::WebDocument
;
167 using blink::WebElement
;
168 using blink::WebExternalPopupMenu
;
169 using blink::WebExternalPopupMenuClient
;
170 using blink::WebFrame
;
171 using blink::WebHistoryItem
;
172 using blink::WebHTTPBody
;
173 using blink::WebLocalFrame
;
174 using blink::WebMediaPlayer
;
175 using blink::WebMediaPlayerClient
;
176 using blink::WebNavigationPolicy
;
177 using blink::WebNavigationType
;
178 using blink::WebNode
;
179 using blink::WebPluginParams
;
180 using blink::WebPopupMenuInfo
;
181 using blink::WebRange
;
182 using blink::WebReferrerPolicy
;
183 using blink::WebScriptSource
;
184 using blink::WebSearchableFormData
;
185 using blink::WebSecurityOrigin
;
186 using blink::WebSecurityPolicy
;
187 using blink::WebServiceWorkerProvider
;
188 using blink::WebStorageQuotaCallbacks
;
189 using blink::WebString
;
191 using blink::WebURLError
;
192 using blink::WebURLRequest
;
193 using blink::WebURLResponse
;
194 using blink::WebUserGestureIndicator
;
195 using blink::WebVector
;
196 using blink::WebView
;
198 using base::TimeDelta
;
204 const char kDefaultAcceptHeader
[] =
205 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
207 const char kAcceptHeader
[] = "Accept";
209 const size_t kExtraCharsBeforeAndAfterSelection
= 100;
211 typedef std::map
<int, RenderFrameImpl
*> RoutingIDFrameMap
;
212 static base::LazyInstance
<RoutingIDFrameMap
> g_routing_id_frame_map
=
213 LAZY_INSTANCE_INITIALIZER
;
215 typedef std::map
<blink::WebFrame
*, RenderFrameImpl
*> FrameMap
;
216 base::LazyInstance
<FrameMap
> g_frame_map
= LAZY_INSTANCE_INITIALIZER
;
218 int64
ExtractPostId(const WebHistoryItem
& item
) {
222 if (item
.httpBody().isNull())
225 return item
.httpBody().identifier();
228 WebURLResponseExtraDataImpl
* GetExtraDataFromResponse(
229 const WebURLResponse
& response
) {
230 return static_cast<WebURLResponseExtraDataImpl
*>(response
.extraData());
233 void GetRedirectChain(WebDataSource
* ds
, std::vector
<GURL
>* result
) {
234 // Replace any occurrences of swappedout:// with about:blank.
235 const WebURL
& blank_url
= GURL(url::kAboutBlankURL
);
236 WebVector
<WebURL
> urls
;
237 ds
->redirectChain(urls
);
238 result
->reserve(urls
.size());
239 for (size_t i
= 0; i
< urls
.size(); ++i
) {
240 if (urls
[i
] != GURL(kSwappedOutURL
))
241 result
->push_back(urls
[i
]);
243 result
->push_back(blank_url
);
247 // Returns the original request url. If there is no redirect, the original
248 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
249 // frame was loaded by loadData, the original url will be ds->unreachableURL()
250 static GURL
GetOriginalRequestURL(WebDataSource
* ds
) {
251 // WebDataSource has unreachable URL means that the frame is loaded through
252 // blink::WebFrame::loadData(), and the base URL will be in the redirect
253 // chain. However, we never visited the baseURL. So in this case, we should
254 // use the unreachable URL as the original URL.
255 if (ds
->hasUnreachableURL())
256 return ds
->unreachableURL();
258 std::vector
<GURL
> redirects
;
259 GetRedirectChain(ds
, &redirects
);
260 if (!redirects
.empty())
261 return redirects
.at(0);
263 return ds
->originalRequest().url();
266 NOINLINE
static void CrashIntentionally() {
267 // NOTE(shess): Crash directly rather than using NOTREACHED() so
268 // that the signature is easier to triage in crash reports.
269 volatile int* zero
= NULL
;
273 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
274 NOINLINE
static void MaybeTriggerAsanError(const GURL
& url
) {
275 // NOTE(rogerm): We intentionally perform an invalid heap access here in
276 // order to trigger an Address Sanitizer (ASAN) error report.
277 const char kCrashDomain
[] = "crash";
278 const char kHeapOverflow
[] = "/heap-overflow";
279 const char kHeapUnderflow
[] = "/heap-underflow";
280 const char kUseAfterFree
[] = "/use-after-free";
281 #if defined(SYZYASAN)
282 const char kCorruptHeapBlock
[] = "/corrupt-heap-block";
283 const char kCorruptHeap
[] = "/corrupt-heap";
286 if (!url
.DomainIs(kCrashDomain
, sizeof(kCrashDomain
) - 1))
292 std::string
crash_type(url
.path());
293 if (crash_type
== kHeapOverflow
) {
294 base::debug::AsanHeapOverflow();
295 } else if (crash_type
== kHeapUnderflow
) {
296 base::debug::AsanHeapUnderflow();
297 } else if (crash_type
== kUseAfterFree
) {
298 base::debug::AsanHeapUseAfterFree();
299 #if defined(SYZYASAN)
300 } else if (crash_type
== kCorruptHeapBlock
) {
301 base::debug::AsanCorruptHeapBlock();
302 } else if (crash_type
== kCorruptHeap
) {
303 base::debug::AsanCorruptHeap();
307 #endif // ADDRESS_SANITIZER || SYZYASAN
309 static void MaybeHandleDebugURL(const GURL
& url
) {
310 if (!url
.SchemeIs(kChromeUIScheme
))
312 if (url
== GURL(kChromeUICrashURL
)) {
313 CrashIntentionally();
314 } else if (url
== GURL(kChromeUIDumpURL
)) {
315 // This URL will only correctly create a crash dump file if content is
316 // hosted in a process that has correctly called
317 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
318 // of base::debug::DumpWithoutCrashing for more details.
319 base::debug::DumpWithoutCrashing();
320 } else if (url
== GURL(kChromeUIKillURL
)) {
321 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
322 } else if (url
== GURL(kChromeUIHangURL
)) {
324 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
326 } else if (url
== GURL(kChromeUIShorthangURL
)) {
327 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
330 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
331 MaybeTriggerAsanError(url
);
332 #endif // ADDRESS_SANITIZER || SYZYASAN
335 // Returns false unless this is a top-level navigation.
336 static bool IsTopLevelNavigation(WebFrame
* frame
) {
337 return frame
->parent() == NULL
;
340 // Returns false unless this is a top-level navigation that crosses origins.
341 static bool IsNonLocalTopLevelNavigation(const GURL
& url
,
343 WebNavigationType type
,
345 if (!IsTopLevelNavigation(frame
))
348 // Navigations initiated within Webkit are not sent out to the external host
349 // in the following cases.
350 // 1. The url scheme is not http/https
351 // 2. The origin of the url and the opener is the same in which case the
352 // opener relationship is maintained.
353 // 3. Reloads/form submits/back forward navigations
354 if (!url
.SchemeIs(url::kHttpScheme
) && !url
.SchemeIs(url::kHttpsScheme
))
357 if (type
!= blink::WebNavigationTypeReload
&&
358 type
!= blink::WebNavigationTypeBackForward
&& !is_form_post
) {
359 // The opener relationship between the new window and the parent allows the
360 // new window to script the parent and vice versa. This is not allowed if
361 // the origins of the two domains are different. This can be treated as a
362 // top level navigation and routed back to the host.
363 blink::WebFrame
* opener
= frame
->opener();
367 if (url
.GetOrigin() != GURL(opener
->document().url()).GetOrigin())
373 WebURLRequest
CreateURLRequestForNavigation(
374 const CommonNavigationParams
& common_params
,
375 const RequestNavigationParams
& request_params
,
376 scoped_ptr
<StreamOverrideParameters
> stream_override
,
377 bool is_view_source_mode_enabled
) {
378 WebURLRequest
request(common_params
.url
);
379 if (is_view_source_mode_enabled
)
380 request
.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad
);
382 if (common_params
.referrer
.url
.is_valid()) {
383 WebString web_referrer
= WebSecurityPolicy::generateReferrerHeader(
384 common_params
.referrer
.policy
,
386 WebString::fromUTF8(common_params
.referrer
.url
.spec()));
387 if (!web_referrer
.isEmpty())
388 request
.setHTTPReferrer(web_referrer
, common_params
.referrer
.policy
);
391 if (!request_params
.extra_headers
.empty()) {
392 for (net::HttpUtil::HeadersIterator
i(request_params
.extra_headers
.begin(),
393 request_params
.extra_headers
.end(),
396 request
.addHTTPHeaderField(WebString::fromUTF8(i
.name()),
397 WebString::fromUTF8(i
.values()));
401 if (request_params
.is_post
) {
402 request
.setHTTPMethod(WebString::fromUTF8("POST"));
405 WebHTTPBody http_body
;
406 http_body
.initialize();
407 const char* data
= NULL
;
408 if (request_params
.browser_initiated_post_data
.size()) {
409 data
= reinterpret_cast<const char*>(
410 &request_params
.browser_initiated_post_data
.front());
412 http_body
.appendData(
413 WebData(data
, request_params
.browser_initiated_post_data
.size()));
414 request
.setHTTPBody(http_body
);
417 RequestExtraData
* extra_data
= new RequestExtraData();
418 extra_data
->set_stream_override(stream_override
.Pass());
419 request
.setExtraData(extra_data
);
423 void UpdateFrameNavigationTiming(WebFrame
* frame
,
424 base::TimeTicks browser_navigation_start
,
425 base::TimeTicks renderer_navigation_start
) {
426 // The browser provides the navigation_start time to bootstrap the
427 // Navigation Timing information for the browser-initiated navigations. In
428 // case of cross-process navigations, this carries over the time of
429 // finishing the onbeforeunload handler of the previous page.
430 DCHECK(!browser_navigation_start
.is_null());
431 if (frame
->provisionalDataSource()) {
432 // |browser_navigation_start| is likely before this process existed, so we
433 // can't use InterProcessTimeTicksConverter. We need at least to ensure
434 // that the browser-side navigation start we set is not later than the one
435 // on the renderer side.
436 base::TimeTicks navigation_start
= std::min(
437 browser_navigation_start
, renderer_navigation_start
);
438 double navigation_start_seconds
=
439 (navigation_start
- base::TimeTicks()).InSecondsF();
440 frame
->provisionalDataSource()->setNavigationStartTime(
441 navigation_start_seconds
);
442 // TODO(clamy): We need to provide additional timing values for the
443 // Navigation Timing API to work with browser-side navigations.
448 FrameHostMsg_BeginNavigation_Params
MakeBeginNavigationParams(
449 blink::WebURLRequest
* request
) {
450 FrameHostMsg_BeginNavigation_Params params
;
451 params
.method
= request
->httpMethod().latin1();
452 params
.headers
= GetWebURLRequestHeaders(*request
);
453 params
.load_flags
= GetLoadFlagsForWebURLRequest(*request
);
454 // TODO(clamy): fill the http body.
455 params
.has_user_gesture
= request
->hasUserGesture();
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
;
467 CommonNavigationParams params
;
468 params
.url
= request
->url();
469 params
.referrer
= Referrer(
470 GURL(request
->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
471 request
->referrerPolicy());
472 params
.transition
= extra_data
->transition_type();
478 static RenderFrameImpl
* (*g_create_render_frame_impl
)(RenderViewImpl
*, int32
) =
482 RenderFrameImpl
* RenderFrameImpl::Create(RenderViewImpl
* render_view
,
484 DCHECK(routing_id
!= MSG_ROUTING_NONE
);
486 if (g_create_render_frame_impl
)
487 return g_create_render_frame_impl(render_view
, routing_id
);
489 return new RenderFrameImpl(render_view
, routing_id
);
493 RenderFrameImpl
* RenderFrameImpl::FromRoutingID(int32 routing_id
) {
494 RoutingIDFrameMap::iterator iter
=
495 g_routing_id_frame_map
.Get().find(routing_id
);
496 if (iter
!= g_routing_id_frame_map
.Get().end())
502 void RenderFrameImpl::CreateFrame(int routing_id
,
503 int parent_routing_id
,
504 int proxy_routing_id
) {
505 // TODO(nasko): For now, this message is only sent for subframes, as the
506 // top level frame is created when the RenderView is created through the
508 CHECK_NE(MSG_ROUTING_NONE
, parent_routing_id
);
510 blink::WebLocalFrame
* web_frame
;
511 RenderFrameImpl
* render_frame
;
512 if (proxy_routing_id
== MSG_ROUTING_NONE
) {
513 RenderFrameProxy
* parent_proxy
=
514 RenderFrameProxy::FromRoutingID(parent_routing_id
);
515 // If the browser is sending a valid parent routing id, it should already
516 // be created and registered.
518 blink::WebRemoteFrame
* parent_web_frame
= parent_proxy
->web_frame();
520 // Create the RenderFrame and WebLocalFrame, linking the two.
522 RenderFrameImpl::Create(parent_proxy
->render_view(), routing_id
);
523 web_frame
= parent_web_frame
->createLocalChild("", render_frame
);
525 RenderFrameProxy
* proxy
=
526 RenderFrameProxy::FromRoutingID(proxy_routing_id
);
528 render_frame
= RenderFrameImpl::Create(proxy
->render_view(), routing_id
);
529 web_frame
= blink::WebLocalFrame::create(render_frame
);
530 render_frame
->proxy_routing_id_
= proxy_routing_id
;
531 web_frame
->initializeToReplaceRemoteFrame(proxy
->web_frame());
533 render_frame
->SetWebFrame(web_frame
);
534 render_frame
->Initialize();
538 RenderFrame
* RenderFrame::FromWebFrame(blink::WebFrame
* web_frame
) {
539 return RenderFrameImpl::FromWebFrame(web_frame
);
543 RenderFrameImpl
* RenderFrameImpl::FromWebFrame(blink::WebFrame
* web_frame
) {
544 FrameMap::iterator iter
= g_frame_map
.Get().find(web_frame
);
545 if (iter
!= g_frame_map
.Get().end())
551 void RenderFrameImpl::InstallCreateHook(
552 RenderFrameImpl
* (*create_render_frame_impl
)(RenderViewImpl
*, int32
)) {
553 CHECK(!g_create_render_frame_impl
);
554 g_create_render_frame_impl
= create_render_frame_impl
;
557 // RenderFrameImpl ----------------------------------------------------------
558 RenderFrameImpl::RenderFrameImpl(RenderViewImpl
* render_view
, int routing_id
)
560 render_view_(render_view
->AsWeakPtr()),
561 routing_id_(routing_id
),
562 is_swapped_out_(false),
563 render_frame_proxy_(NULL
),
564 is_detaching_(false),
565 proxy_routing_id_(MSG_ROUTING_NONE
),
566 #if defined(ENABLE_PLUGINS)
567 plugin_power_saver_helper_(NULL
),
570 selection_text_offset_(0),
571 selection_range_(gfx::Range::InvalidRange()),
572 handling_select_range_(false),
573 notification_permission_dispatcher_(NULL
),
574 web_user_media_client_(NULL
),
575 midi_dispatcher_(NULL
),
576 #if defined(OS_ANDROID)
577 media_player_manager_(NULL
),
579 #if defined(ENABLE_BROWSER_CDMS)
582 #if defined(VIDEO_HOLE)
583 contains_media_player_(false),
585 geolocation_dispatcher_(NULL
),
586 push_messaging_dispatcher_(NULL
),
587 screen_orientation_dispatcher_(NULL
),
588 manifest_manager_(NULL
),
589 accessibility_mode_(AccessibilityModeOff
),
590 renderer_accessibility_(NULL
),
591 weak_factory_(this) {
592 std::pair
<RoutingIDFrameMap::iterator
, bool> result
=
593 g_routing_id_frame_map
.Get().insert(std::make_pair(routing_id_
, this));
594 CHECK(result
.second
) << "Inserting a duplicate item.";
596 RenderThread::Get()->AddRoute(routing_id_
, this);
598 render_view_
->RegisterRenderFrame(this);
600 // Everything below subclasses RenderFrameObserver and is automatically
601 // deleted when the RenderFrame gets deleted.
602 #if defined(OS_ANDROID)
603 new GinJavaBridgeDispatcher(this);
606 #if defined(ENABLE_PLUGINS)
607 plugin_power_saver_helper_
= new PluginPowerSaverHelper(this);
610 manifest_manager_
= new ManifestManager(this);
613 RenderFrameImpl::~RenderFrameImpl() {
614 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, RenderFrameGone());
615 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnDestruct());
617 #if defined(VIDEO_HOLE)
618 if (contains_media_player_
)
619 render_view_
->UnregisterVideoHoleFrame(this);
622 if (render_frame_proxy_
)
623 delete render_frame_proxy_
;
625 render_view_
->UnregisterRenderFrame(this);
626 g_routing_id_frame_map
.Get().erase(routing_id_
);
627 RenderThread::Get()->RemoveRoute(routing_id_
);
630 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame
* web_frame
) {
633 std::pair
<FrameMap::iterator
, bool> result
= g_frame_map
.Get().insert(
634 std::make_pair(web_frame
, this));
635 CHECK(result
.second
) << "Inserting a duplicate item.";
640 void RenderFrameImpl::Initialize() {
641 #if defined(ENABLE_PLUGINS)
642 new PepperBrowserConnection(this);
644 new SharedWorkerRepository(this);
646 if (!frame_
->parent())
647 new ImageLoadingHelper(this);
649 // We delay calling this until we have the WebFrame so that any observer or
650 // embedder can call GetWebFrame on any RenderFrame.
651 GetContentClient()->renderer()->RenderFrameCreated(this);
654 RenderWidget
* RenderFrameImpl::GetRenderWidget() {
655 return render_view_
.get();
658 #if defined(ENABLE_PLUGINS)
659 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost
* host
) {
660 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
661 DidCreatePepperPlugin(host
));
662 if (host
->GetPluginName() == kFlashPluginName
) {
663 RenderThread::Get()->RecordAction(
664 base::UserMetricsAction("FrameLoadWithFlash"));
668 void RenderFrameImpl::PepperDidChangeCursor(
669 PepperPluginInstanceImpl
* instance
,
670 const blink::WebCursorInfo
& cursor
) {
671 // Update the cursor appearance immediately if the requesting plugin is the
672 // one which receives the last mouse event. Otherwise, the new cursor won't be
673 // picked up until the plugin gets the next input event. That is bad if, e.g.,
674 // the plugin would like to set an invisible cursor when there isn't any user
675 // input for a while.
676 if (instance
== render_view_
->pepper_last_mouse_event_target())
677 GetRenderWidget()->didChangeCursor(cursor
);
680 void RenderFrameImpl::PepperDidReceiveMouseEvent(
681 PepperPluginInstanceImpl
* instance
) {
682 render_view_
->set_pepper_last_mouse_event_target(instance
);
685 void RenderFrameImpl::PepperTextInputTypeChanged(
686 PepperPluginInstanceImpl
* instance
) {
687 if (instance
!= render_view_
->focused_pepper_plugin())
690 GetRenderWidget()->UpdateTextInputType();
691 if (renderer_accessibility())
692 renderer_accessibility()->FocusedNodeChanged(WebNode());
695 void RenderFrameImpl::PepperCaretPositionChanged(
696 PepperPluginInstanceImpl
* instance
) {
697 if (instance
!= render_view_
->focused_pepper_plugin())
699 GetRenderWidget()->UpdateSelectionBounds();
702 void RenderFrameImpl::PepperCancelComposition(
703 PepperPluginInstanceImpl
* instance
) {
704 if (instance
!= render_view_
->focused_pepper_plugin())
706 Send(new InputHostMsg_ImeCancelComposition(render_view_
->GetRoutingID()));;
707 #if defined(OS_MACOSX) || defined(USE_AURA)
708 GetRenderWidget()->UpdateCompositionInfo(true);
712 void RenderFrameImpl::PepperSelectionChanged(
713 PepperPluginInstanceImpl
* instance
) {
714 if (instance
!= render_view_
->focused_pepper_plugin())
716 SyncSelectionIfRequired();
719 RenderWidgetFullscreenPepper
* RenderFrameImpl::CreatePepperFullscreenContainer(
720 PepperPluginInstanceImpl
* plugin
) {
722 if (render_view_
->webview() && render_view_
->webview()->mainFrame())
723 active_url
= GURL(render_view_
->webview()->mainFrame()->document().url());
724 RenderWidgetFullscreenPepper
* widget
= RenderWidgetFullscreenPepper::Create(
725 GetRenderWidget()->routing_id(), plugin
, active_url
,
726 GetRenderWidget()->screenInfo());
727 widget
->show(blink::WebNavigationPolicyIgnore
);
731 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
732 if (!render_view_
->focused_pepper_plugin())
734 return render_view_
->focused_pepper_plugin()->
735 IsPluginAcceptingCompositionEvents();
738 void RenderFrameImpl::PluginCrashed(const base::FilePath
& plugin_path
,
739 base::ProcessId plugin_pid
) {
740 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
741 // routing_id_ as a result.
742 Send(new FrameHostMsg_PluginCrashed(routing_id_
, plugin_path
, plugin_pid
));
745 void RenderFrameImpl::SimulateImeSetComposition(
746 const base::string16
& text
,
747 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
750 render_view_
->OnImeSetComposition(
751 text
, underlines
, selection_start
, selection_end
);
754 void RenderFrameImpl::SimulateImeConfirmComposition(
755 const base::string16
& text
,
756 const gfx::Range
& replacement_range
) {
757 render_view_
->OnImeConfirmComposition(text
, replacement_range
, false);
760 void RenderFrameImpl::OnImeSetComposition(
761 const base::string16
& text
,
762 const std::vector
<blink::WebCompositionUnderline
>& underlines
,
765 // When a PPAPI plugin has focus, we bypass WebKit.
766 if (!IsPepperAcceptingCompositionEvents()) {
767 pepper_composition_text_
= text
;
769 // TODO(kinaba) currently all composition events are sent directly to
770 // plugins. Use DOM event mechanism after WebKit is made aware about
771 // plugins that support composition.
772 // The code below mimics the behavior of WebCore::Editor::setComposition.
774 // Empty -> nonempty: composition started.
775 if (pepper_composition_text_
.empty() && !text
.empty()) {
776 render_view_
->focused_pepper_plugin()->HandleCompositionStart(
779 // Nonempty -> empty: composition canceled.
780 if (!pepper_composition_text_
.empty() && text
.empty()) {
781 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(
784 pepper_composition_text_
= text
;
785 // Nonempty: composition is ongoing.
786 if (!pepper_composition_text_
.empty()) {
787 render_view_
->focused_pepper_plugin()->HandleCompositionUpdate(
788 pepper_composition_text_
, underlines
, selection_start
,
794 void RenderFrameImpl::OnImeConfirmComposition(
795 const base::string16
& text
,
796 const gfx::Range
& replacement_range
,
797 bool keep_selection
) {
798 // When a PPAPI plugin has focus, we bypass WebKit.
799 // Here, text.empty() has a special meaning. It means to commit the last
800 // update of composition text (see
801 // RenderWidgetHost::ImeConfirmComposition()).
802 const base::string16
& last_text
= text
.empty() ? pepper_composition_text_
805 // last_text is empty only when both text and pepper_composition_text_ is.
807 if (last_text
.empty())
810 if (!IsPepperAcceptingCompositionEvents()) {
811 base::i18n::UTF16CharIterator
iterator(&last_text
);
813 while (iterator
.Advance()) {
814 blink::WebKeyboardEvent char_event
;
815 char_event
.type
= blink::WebInputEvent::Char
;
816 char_event
.timeStampSeconds
= base::Time::Now().ToDoubleT();
817 char_event
.modifiers
= 0;
818 char_event
.windowsKeyCode
= last_text
[i
];
819 char_event
.nativeKeyCode
= last_text
[i
];
821 const int32 char_start
= i
;
822 for (; i
< iterator
.array_pos(); ++i
) {
823 char_event
.text
[i
- char_start
] = last_text
[i
];
824 char_event
.unmodifiedText
[i
- char_start
] = last_text
[i
];
827 if (GetRenderWidget()->webwidget())
828 GetRenderWidget()->webwidget()->handleInputEvent(char_event
);
831 // Mimics the order of events sent by WebKit.
832 // See WebCore::Editor::setComposition() for the corresponding code.
833 render_view_
->focused_pepper_plugin()->HandleCompositionEnd(last_text
);
834 render_view_
->focused_pepper_plugin()->HandleTextInput(last_text
);
836 pepper_composition_text_
.clear();
839 PluginPowerSaverHelper
* RenderFrameImpl::plugin_power_saver_helper() {
840 DCHECK(plugin_power_saver_helper_
);
841 return plugin_power_saver_helper_
;
843 #endif // defined(ENABLE_PLUGINS)
845 MediaStreamDispatcher
* RenderFrameImpl::GetMediaStreamDispatcher() {
846 if (!web_user_media_client_
)
847 InitializeUserMediaClient();
848 return web_user_media_client_
?
849 web_user_media_client_
->media_stream_dispatcher() : NULL
;
852 bool RenderFrameImpl::Send(IPC::Message
* message
) {
857 if (is_swapped_out_
) {
858 if (!SwappedOutMessages::CanSendWhileSwappedOut(message
)) {
864 return RenderThread::Get()->Send(message
);
867 #if defined(OS_MACOSX) || defined(OS_ANDROID)
868 void RenderFrameImpl::DidHideExternalPopupMenu() {
869 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
870 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
871 external_popup_menu_
.reset();
875 bool RenderFrameImpl::OnMessageReceived(const IPC::Message
& msg
) {
876 // TODO(kenrb): document() should not be null, but as a transitional step
877 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
878 // to this method. This happens for a top-level remote frame, where a
879 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
880 // around and is still able to receive messages.
881 if (!frame_
->document().isNull())
882 GetContentClient()->SetActiveURL(frame_
->document().url());
884 ObserverListBase
<RenderFrameObserver
>::Iterator
it(observers_
);
885 RenderFrameObserver
* observer
;
886 while ((observer
= it
.GetNext()) != NULL
) {
887 if (observer
->OnMessageReceived(msg
))
892 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl
, msg
)
893 IPC_MESSAGE_HANDLER(FrameMsg_Navigate
, OnNavigate
)
894 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload
, OnBeforeUnload
)
895 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut
, OnSwapOut
)
896 IPC_MESSAGE_HANDLER(FrameMsg_Stop
, OnStop
)
897 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed
, OnContextMenuClosed
)
898 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction
,
899 OnCustomContextMenuAction
)
900 IPC_MESSAGE_HANDLER(InputMsg_Undo
, OnUndo
)
901 IPC_MESSAGE_HANDLER(InputMsg_Redo
, OnRedo
)
902 IPC_MESSAGE_HANDLER(InputMsg_Cut
, OnCut
)
903 IPC_MESSAGE_HANDLER(InputMsg_Copy
, OnCopy
)
904 IPC_MESSAGE_HANDLER(InputMsg_Paste
, OnPaste
)
905 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle
, OnPasteAndMatchStyle
)
906 IPC_MESSAGE_HANDLER(InputMsg_Delete
, OnDelete
)
907 IPC_MESSAGE_HANDLER(InputMsg_SelectAll
, OnSelectAll
)
908 IPC_MESSAGE_HANDLER(InputMsg_SelectRange
, OnSelectRange
)
909 IPC_MESSAGE_HANDLER(InputMsg_Unselect
, OnUnselect
)
910 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent
,
911 OnMoveRangeSelectionExtent
)
912 IPC_MESSAGE_HANDLER(InputMsg_Replace
, OnReplace
)
913 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling
, OnReplaceMisspelling
)
914 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete
,
915 OnExtendSelectionAndDelete
)
916 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText
,
917 OnSetCompositionFromExistingText
)
918 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest
, OnCSSInsertRequest
)
919 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest
,
920 OnJavaScriptExecuteRequest
)
921 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests
,
922 OnJavaScriptExecuteRequestForTests
)
923 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets
,
924 OnSetEditableSelectionOffsets
)
925 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView
, OnSetupTransitionView
)
926 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition
, OnBeginExitTransition
)
927 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements
,
928 OnHideTransitionElements
)
929 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements
,
930 OnShowTransitionElements
)
931 IPC_MESSAGE_HANDLER(FrameMsg_Reload
, OnReload
)
932 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest
,
933 OnTextSurroundingSelectionRequest
)
934 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL
,
935 OnAddStyleSheetByURL
)
936 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode
,
937 OnSetAccessibilityMode
)
938 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener
, OnDisownOpener
)
939 IPC_MESSAGE_HANDLER(FrameMsg_RequestNavigation
, OnRequestNavigation
)
940 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation
, OnCommitNavigation
)
941 #if defined(OS_ANDROID)
942 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems
, OnSelectPopupMenuItems
)
943 #elif defined(OS_MACOSX)
944 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem
, OnSelectPopupMenuItem
)
945 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard
, OnCopyToFindPboard
)
947 IPC_END_MESSAGE_MAP()
952 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params
& params
) {
953 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
955 "url", params
.common_params
.url
.possibly_invalid_spec());
957 RenderViewImpl::IsReload(params
.common_params
.navigation_type
);
958 WebURLRequest::CachePolicy cache_policy
=
959 WebURLRequest::UseProtocolCachePolicy
;
960 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
961 params
.common_params
.url
, params
.common_params
.navigation_type
,
962 params
.commit_params
.page_state
, true, params
.pending_history_list_offset
,
963 params
.page_id
, &is_reload
, &cache_policy
)) {
967 int pending_history_list_offset
= params
.pending_history_list_offset
;
968 int current_history_list_offset
= params
.current_history_list_offset
;
969 int current_history_list_length
= params
.current_history_list_length
;
970 if (params
.should_clear_history_list
) {
971 CHECK_EQ(pending_history_list_offset
, -1);
972 CHECK_EQ(current_history_list_offset
, -1);
973 CHECK_EQ(current_history_list_length
, 0);
975 render_view_
->history_list_offset_
= current_history_list_offset
;
976 render_view_
->history_list_length_
= current_history_list_length
;
977 if (render_view_
->history_list_length_
>= 0) {
978 render_view_
->history_page_ids_
.resize(
979 render_view_
->history_list_length_
, -1);
981 if (pending_history_list_offset
>= 0 &&
982 pending_history_list_offset
< render_view_
->history_list_length_
) {
983 render_view_
->history_page_ids_
[pending_history_list_offset
] =
987 GetContentClient()->SetActiveURL(params
.common_params
.url
);
989 WebFrame
* frame
= frame_
;
990 if (!params
.frame_to_navigate
.empty()) {
991 // TODO(nasko): Move this lookup to the browser process.
992 frame
= render_view_
->webview()->findFrameByName(
993 WebString::fromUTF8(params
.frame_to_navigate
));
994 CHECK(frame
) << "Invalid frame name passed: " << params
.frame_to_navigate
;
997 if (is_reload
&& !render_view_
->history_controller()->GetCurrentEntry()) {
998 // We cannot reload if we do not have any history state. This happens, for
999 // example, when recovering from a crash.
1001 cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
1004 render_view_
->pending_navigation_params_
.reset(
1005 new FrameMsg_Navigate_Params(params
));
1007 // If we are reloading, then WebKit will use the history state of the current
1008 // page, so we should just ignore any given history state. Otherwise, if we
1009 // have history state, then we need to navigate to it, which corresponds to a
1010 // back/forward navigation event.
1012 bool reload_original_url
=
1013 (params
.common_params
.navigation_type
==
1014 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL
);
1015 bool ignore_cache
= (params
.common_params
.navigation_type
==
1016 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE
);
1018 if (reload_original_url
)
1019 frame
->reloadWithOverrideURL(params
.common_params
.url
, true);
1021 frame
->reload(ignore_cache
);
1022 } else if (params
.commit_params
.page_state
.IsValid()) {
1023 // We must know the page ID of the page we are navigating back to.
1024 DCHECK_NE(params
.page_id
, -1);
1025 scoped_ptr
<HistoryEntry
> entry
=
1026 PageStateToHistoryEntry(params
.commit_params
.page_state
);
1028 // Ensure we didn't save the swapped out URL in UpdateState, since the
1029 // browser should never be telling us to navigate to swappedout://.
1030 CHECK(entry
->root().urlString() != WebString::fromUTF8(kSwappedOutURL
));
1031 render_view_
->history_controller()->GoToEntry(entry
.Pass(), cache_policy
);
1033 } else if (!params
.base_url_for_data_url
.is_empty()) {
1034 // A loadData request with a specified base URL.
1035 std::string mime_type
, charset
, data
;
1036 if (net::DataURL::Parse(
1037 params
.common_params
.url
, &mime_type
, &charset
, &data
)) {
1039 WebData(data
.c_str(), data
.length()),
1040 WebString::fromUTF8(mime_type
),
1041 WebString::fromUTF8(charset
),
1042 params
.base_url_for_data_url
,
1043 params
.history_url_for_data_url
,
1046 CHECK(false) << "Invalid URL passed: "
1047 << params
.common_params
.url
.possibly_invalid_spec();
1050 // Navigate to the given URL.
1051 WebURLRequest request
=
1052 CreateURLRequestForNavigation(params
.common_params
,
1053 params
.request_params
,
1054 scoped_ptr
<StreamOverrideParameters
>(),
1055 frame
->isViewSourceModeEnabled());
1057 // A session history navigation should have been accompanied by state.
1058 CHECK_EQ(params
.page_id
, -1);
1060 // Record this before starting the load, we need a lower bound of this time
1061 // to sanitize the navigationStart override set below.
1062 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
1063 frame
->loadRequest(request
);
1065 UpdateFrameNavigationTiming(
1066 frame
, params
.commit_params
.browser_navigation_start
,
1067 renderer_navigation_start
);
1070 // In case LoadRequest failed before DidCreateDataSource was called.
1071 render_view_
->pending_navigation_params_
.reset();
1074 void RenderFrameImpl::NavigateToSwappedOutURL() {
1075 // We use loadRequest instead of loadHTMLString because the former commits
1076 // synchronously. Otherwise a new navigation can interrupt the navigation
1077 // to kSwappedOutURL. If that happens to be to the page we had been
1078 // showing, then WebKit will never send a commit and we'll be left spinning.
1079 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1080 // the navigation to swappedout:// is not announced to the browser side.
1081 is_swapped_out_
= true;
1082 GURL
swappedOutURL(kSwappedOutURL
);
1083 WebURLRequest
request(swappedOutURL
);
1084 frame_
->loadRequest(request
);
1087 void RenderFrameImpl::BindServiceRegistry(
1088 mojo::ScopedMessagePipeHandle service_provider_handle
) {
1089 service_registry_
.BindRemoteServiceProvider(service_provider_handle
.Pass());
1092 ManifestManager
* RenderFrameImpl::manifest_manager() {
1093 return manifest_manager_
;
1096 void RenderFrameImpl::OnBeforeUnload() {
1097 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1099 // TODO(creis): Right now, this is only called on the main frame. Make the
1100 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1102 CHECK(!frame_
->parent());
1104 base::TimeTicks before_unload_start_time
= base::TimeTicks::Now();
1105 bool proceed
= frame_
->dispatchBeforeUnloadEvent();
1106 base::TimeTicks before_unload_end_time
= base::TimeTicks::Now();
1107 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_
, proceed
,
1108 before_unload_start_time
,
1109 before_unload_end_time
));
1112 void RenderFrameImpl::OnSwapOut(int proxy_routing_id
) {
1113 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_
);
1114 RenderFrameProxy
* proxy
= NULL
;
1115 bool is_site_per_process
=
1116 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess
);
1117 bool is_main_frame
= !frame_
->parent();
1119 // Only run unload if we're not swapped out yet, but send the ack either way.
1120 if (!is_swapped_out_
) {
1121 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1122 // a different process. This involves running the unload handler and
1123 // clearing the page. We also allow this process to exit if there are no
1124 // other active RenderFrames in it.
1126 // Send an UpdateState message before we get swapped out.
1127 render_view_
->SyncNavigationState();
1129 // If we need a proxy to replace this, create it now so its routing id is
1130 // registered for receiving IPC messages.
1131 if (proxy_routing_id
!= MSG_ROUTING_NONE
) {
1132 proxy
= RenderFrameProxy::CreateProxyToReplaceFrame(this,
1136 // Synchronously run the unload handler before sending the ACK.
1137 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1138 // unload on subframes as well.
1140 frame_
->dispatchUnloadEvent();
1142 // Swap out and stop sending any IPC messages that are not ACKs.
1144 render_view_
->SetSwappedOut(true);
1145 is_swapped_out_
= true;
1147 // Now that we're swapped out and filtering IPC messages, stop loading to
1148 // ensure that no other in-progress navigation continues. We do this here
1149 // to avoid sending a DidStopLoading message to the browser process.
1150 // TODO(creis): Should we be stopping all frames here and using
1151 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1155 // Transfer settings such as initial drawing parameters to the remote frame,
1156 // if one is created, that will replace this frame.
1157 if (!is_main_frame
&& proxy
)
1158 proxy
->web_frame()->initializeFromFrame(frame_
);
1160 // Replace the page with a blank dummy URL. The unload handler will not be
1161 // run a second time, thanks to a check in FrameLoader::stopLoading.
1162 // TODO(creis): Need to add a better way to do this that avoids running the
1163 // beforeunload handler. For now, we just run it a second time silently.
1164 if (!is_site_per_process
|| is_main_frame
)
1165 NavigateToSwappedOutURL();
1167 // Let WebKit know that this view is hidden so it can drop resources and
1168 // stop compositing.
1169 // TODO(creis): Support this for subframes as well.
1170 if (is_main_frame
) {
1171 render_view_
->webview()->setVisibilityState(
1172 blink::WebPageVisibilityStateHidden
, false);
1176 // It is now safe to show modal dialogs again.
1177 // TODO(creis): Deal with modal dialogs from subframes.
1179 render_view_
->suppress_dialogs_until_swap_out_
= false;
1181 Send(new FrameHostMsg_SwapOut_ACK(routing_id_
));
1183 // Now that all of the cleanup is complete and the browser side is notified,
1184 // start using the RenderFrameProxy, if one is created.
1186 if (!is_main_frame
) {
1187 frame_
->swap(proxy
->web_frame());
1188 if (is_site_per_process
) {
1189 // TODO(nasko): delete the frame here, since we've replaced it with a
1193 set_render_frame_proxy(proxy
);
1197 // Safe to exit if no one else is using the process.
1199 render_view_
->WasSwappedOut();
1202 void RenderFrameImpl::OnContextMenuClosed(
1203 const CustomContextMenuContext
& custom_context
) {
1204 if (custom_context
.request_id
) {
1205 // External request, should be in our map.
1206 ContextMenuClient
* client
=
1207 pending_context_menus_
.Lookup(custom_context
.request_id
);
1209 client
->OnMenuClosed(custom_context
.request_id
);
1210 pending_context_menus_
.Remove(custom_context
.request_id
);
1213 if (custom_context
.link_followed
.is_valid()) {
1215 DomUtils::ExtractParentAnchorNode(context_menu_node_
),
1216 custom_context
.link_followed
);
1218 // Internal request, forward to WebKit.
1219 context_menu_node_
.reset();
1223 void RenderFrameImpl::OnCustomContextMenuAction(
1224 const CustomContextMenuContext
& custom_context
,
1226 if (custom_context
.request_id
) {
1227 // External context menu request, look in our map.
1228 ContextMenuClient
* client
=
1229 pending_context_menus_
.Lookup(custom_context
.request_id
);
1231 client
->OnMenuAction(custom_context
.request_id
, action
);
1233 // Internal request, forward to WebKit.
1234 render_view_
->webview()->performCustomContextMenuAction(action
);
1238 void RenderFrameImpl::OnUndo() {
1239 frame_
->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1242 void RenderFrameImpl::OnRedo() {
1243 frame_
->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1246 void RenderFrameImpl::OnCut() {
1247 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1248 frame_
->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1251 void RenderFrameImpl::OnCopy() {
1252 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1253 WebNode current_node
= context_menu_node_
.isNull() ?
1254 GetFocusedElement() : context_menu_node_
;
1255 frame_
->executeCommand(WebString::fromUTF8("Copy"), current_node
);
1258 void RenderFrameImpl::OnPaste() {
1259 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1260 frame_
->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1263 void RenderFrameImpl::OnPasteAndMatchStyle() {
1264 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1265 frame_
->executeCommand(
1266 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1269 #if defined(OS_MACOSX)
1270 void RenderFrameImpl::OnCopyToFindPboard() {
1271 // Since the find pasteboard supports only plain text, this can be simpler
1272 // than the |OnCopy()| case.
1273 if (frame_
->hasSelection()) {
1274 base::string16 selection
= frame_
->selectionAsText();
1275 RenderThread::Get()->Send(
1276 new ClipboardHostMsg_FindPboardWriteStringAsync(selection
));
1281 void RenderFrameImpl::OnDelete() {
1282 frame_
->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1285 void RenderFrameImpl::OnSelectAll() {
1286 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1287 frame_
->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1290 void RenderFrameImpl::OnSelectRange(const gfx::Point
& base
,
1291 const gfx::Point
& extent
) {
1292 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1293 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1295 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1296 frame_
->selectRange(base
, extent
);
1299 void RenderFrameImpl::OnUnselect() {
1300 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1301 frame_
->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1304 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point
& point
) {
1305 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1306 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1307 GetRenderWidget()->routing_id()));
1309 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1310 frame_
->moveRangeSelectionExtent(point
);
1313 void RenderFrameImpl::OnReplace(const base::string16
& text
) {
1314 if (!frame_
->hasSelection())
1315 frame_
->selectWordAroundCaret();
1317 frame_
->replaceSelection(text
);
1320 void RenderFrameImpl::OnReplaceMisspelling(const base::string16
& text
) {
1321 if (!frame_
->hasSelection())
1324 frame_
->replaceMisspelledRange(text
);
1327 void RenderFrameImpl::OnCSSInsertRequest(const std::string
& css
) {
1328 frame_
->document().insertStyleSheet(WebString::fromUTF8(css
));
1331 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1332 const base::string16
& jscript
,
1334 bool notify_result
) {
1335 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1336 TRACE_EVENT_SCOPE_THREAD
);
1338 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1339 v8::Handle
<v8::Value
> result
=
1340 frame_
->executeScriptAndReturnValue(WebScriptSource(jscript
));
1342 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1345 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1346 const base::string16
& jscript
,
1348 bool notify_result
) {
1349 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1350 TRACE_EVENT_SCOPE_THREAD
);
1352 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
1353 v8::Handle
<v8::Value
> result
=
1354 frame_
->executeScriptAndReturnValueForTests(WebScriptSource(jscript
));
1356 HandleJavascriptExecutionResult(jscript
, id
, notify_result
, result
);
1359 void RenderFrameImpl::HandleJavascriptExecutionResult(
1360 const base::string16
& jscript
,
1363 v8::Handle
<v8::Value
> result
) {
1364 if (notify_result
) {
1365 base::ListValue list
;
1366 if (!result
.IsEmpty()) {
1367 v8::Local
<v8::Context
> context
= frame_
->mainWorldScriptContext();
1368 v8::Context::Scope
context_scope(context
);
1369 V8ValueConverterImpl converter
;
1370 converter
.SetDateAllowed(true);
1371 converter
.SetRegExpAllowed(true);
1372 base::Value
* result_value
= converter
.FromV8Value(result
, context
);
1373 list
.Set(0, result_value
? result_value
: base::Value::CreateNullValue());
1375 list
.Set(0, base::Value::CreateNullValue());
1377 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_
, id
, list
));
1381 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start
, int end
) {
1382 base::AutoReset
<bool> handling_select_range(&handling_select_range_
, true);
1383 if (!GetRenderWidget()->ShouldHandleImeEvent())
1385 ImeEventGuard
guard(GetRenderWidget());
1386 frame_
->setEditableSelectionOffsets(start
, end
);
1389 void RenderFrameImpl::OnSetCompositionFromExistingText(
1391 const std::vector
<blink::WebCompositionUnderline
>& underlines
) {
1392 if (!GetRenderWidget()->ShouldHandleImeEvent())
1394 ImeEventGuard
guard(GetRenderWidget());
1395 frame_
->setCompositionFromExistingText(start
, end
, underlines
);
1398 void RenderFrameImpl::OnExtendSelectionAndDelete(int before
, int after
) {
1399 if (!GetRenderWidget()->ShouldHandleImeEvent())
1401 ImeEventGuard
guard(GetRenderWidget());
1402 frame_
->extendSelectionAndDelete(before
, after
);
1405 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode
) {
1406 if (accessibility_mode_
== new_mode
)
1408 accessibility_mode_
= new_mode
;
1409 if (renderer_accessibility_
) {
1410 // Note: this isn't called automatically by the destructor because
1411 // there'd be no point in calling it in frame teardown, only if there's
1412 // an accessibility mode change but the frame is persisting.
1413 renderer_accessibility_
->DisableAccessibility();
1415 delete renderer_accessibility_
;
1416 renderer_accessibility_
= NULL
;
1418 if (accessibility_mode_
== AccessibilityModeOff
)
1421 if (accessibility_mode_
& AccessibilityModeFlagFullTree
)
1422 renderer_accessibility_
= new RendererAccessibility(this);
1425 void RenderFrameImpl::OnDisownOpener() {
1426 // TODO(creis): We should only see this for main frames for now. To support
1427 // disowning the opener on subframes, we will need to move WebContentsImpl's
1428 // opener_ to FrameTreeNode.
1429 CHECK(!frame_
->parent());
1431 if (frame_
->opener())
1432 frame_
->setOpener(NULL
);
1435 #if defined(OS_ANDROID)
1436 void RenderFrameImpl::OnSelectPopupMenuItems(
1438 const std::vector
<int>& selected_indices
) {
1439 // It is possible to receive more than one of these calls if the user presses
1440 // a select faster than it takes for the show-select-popup IPC message to make
1441 // it to the browser UI thread. Ignore the extra-messages.
1442 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1443 if (!external_popup_menu_
)
1446 external_popup_menu_
->DidSelectItems(canceled
, selected_indices
);
1447 external_popup_menu_
.reset();
1451 #if defined(OS_MACOSX)
1452 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index
) {
1453 if (external_popup_menu_
== NULL
)
1455 external_popup_menu_
->DidSelectItem(selected_index
);
1456 external_popup_menu_
.reset();
1460 void RenderFrameImpl::OnReload(bool ignore_cache
) {
1461 frame_
->reload(ignore_cache
);
1464 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length
) {
1465 blink::WebSurroundingText surroundingText
;
1466 surroundingText
.initialize(frame_
->selectionRange(), max_length
);
1468 if (surroundingText
.isNull()) {
1469 // |surroundingText| might not be correctly initialized, for example if
1470 // |frame_->selectionRange().isNull()|, in other words, if there was no
1472 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1473 routing_id_
, base::string16(), 0, 0));
1477 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1479 surroundingText
.textContent(),
1480 surroundingText
.startOffsetInTextContent(),
1481 surroundingText
.endOffsetInTextContent()));
1484 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string
& url
) {
1485 frame_
->addStyleSheetByURL(WebString::fromUTF8(url
));
1488 void RenderFrameImpl::OnSetupTransitionView(const std::string
& markup
) {
1489 frame_
->document().setIsTransitionDocument();
1490 frame_
->navigateToSandboxedMarkup(WebData(markup
.data(), markup
.length()));
1493 void RenderFrameImpl::OnBeginExitTransition(const std::string
& css_selector
,
1494 bool exit_to_native_app
) {
1495 frame_
->document().setIsTransitionDocument();
1496 frame_
->document().beginExitTransition(WebString::fromUTF8(css_selector
),
1497 exit_to_native_app
);
1500 void RenderFrameImpl::OnHideTransitionElements(
1501 const std::string
& css_selector
) {
1502 frame_
->document().setIsTransitionDocument();
1503 frame_
->document().hideTransitionElements(WebString::fromUTF8(css_selector
));
1506 void RenderFrameImpl::OnShowTransitionElements(
1507 const std::string
& css_selector
) {
1508 frame_
->document().setIsTransitionDocument();
1509 frame_
->document().showTransitionElements(WebString::fromUTF8(css_selector
));
1512 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type
,
1513 const base::string16
& message
,
1514 const base::string16
& default_value
,
1515 const GURL
& frame_url
,
1516 base::string16
* result
) {
1517 // Don't allow further dialogs if we are waiting to swap out, since the
1518 // PageGroupLoadDeferrer in our stack prevents it.
1519 if (render_view()->suppress_dialogs_until_swap_out_
)
1522 bool success
= false;
1523 base::string16 result_temp
;
1525 result
= &result_temp
;
1527 render_view()->SendAndRunNestedMessageLoop(
1528 new FrameHostMsg_RunJavaScriptMessage(
1529 routing_id_
, message
, default_value
, frame_url
, type
, &success
,
1534 void RenderFrameImpl::LoadNavigationErrorPage(
1535 const WebURLRequest
& failed_request
,
1536 const WebURLError
& error
,
1538 std::string error_html
;
1539 GetContentClient()->renderer()->GetNavigationErrorStrings(
1540 render_view(), frame_
, failed_request
, error
, &error_html
, NULL
);
1542 frame_
->loadHTMLString(error_html
,
1543 GURL(kUnreachableWebDataURL
),
1544 error
.unreachableURL
,
1548 void RenderFrameImpl::DidCommitCompositorFrame() {
1550 RenderFrameObserver
, observers_
, DidCommitCompositorFrame());
1553 RenderView
* RenderFrameImpl::GetRenderView() {
1554 return render_view_
.get();
1557 int RenderFrameImpl::GetRoutingID() {
1561 blink::WebLocalFrame
* RenderFrameImpl::GetWebFrame() {
1566 WebPreferences
& RenderFrameImpl::GetWebkitPreferences() {
1567 return render_view_
->GetWebkitPreferences();
1570 int RenderFrameImpl::ShowContextMenu(ContextMenuClient
* client
,
1571 const ContextMenuParams
& params
) {
1572 DCHECK(client
); // A null client means "internal" when we issue callbacks.
1573 ContextMenuParams
our_params(params
);
1574 our_params
.custom_context
.request_id
= pending_context_menus_
.Add(client
);
1575 Send(new FrameHostMsg_ContextMenu(routing_id_
, our_params
));
1576 return our_params
.custom_context
.request_id
;
1579 void RenderFrameImpl::CancelContextMenu(int request_id
) {
1580 DCHECK(pending_context_menus_
.Lookup(request_id
));
1581 pending_context_menus_
.Remove(request_id
);
1584 blink::WebNode
RenderFrameImpl::GetContextMenuNode() const {
1585 return context_menu_node_
;
1588 blink::WebPlugin
* RenderFrameImpl::CreatePlugin(
1589 blink::WebFrame
* frame
,
1590 const WebPluginInfo
& info
,
1591 const blink::WebPluginParams
& params
,
1592 CreatePluginGesture gesture
) {
1593 DCHECK_EQ(frame_
, frame
);
1594 #if defined(ENABLE_PLUGINS)
1595 if (gesture
== CREATE_PLUGIN_GESTURE_HAS_USER_GESTURE
) {
1596 plugin_power_saver_helper_
->WhitelistContentOrigin(
1597 GURL(params
.url
).GetOrigin());
1600 bool pepper_plugin_was_registered
= false;
1601 scoped_refptr
<PluginModule
> pepper_module(PluginModule::Create(
1602 this, info
, &pepper_plugin_was_registered
));
1603 if (pepper_plugin_was_registered
) {
1604 if (pepper_module
.get()) {
1605 return new PepperWebPluginImpl(pepper_module
.get(), params
, this);
1608 #if defined(OS_CHROMEOS)
1609 LOG(WARNING
) << "Pepper module/plugin creation failed.";
1612 // TODO(jam): change to take RenderFrame.
1613 return new WebPluginImpl(frame
, params
, info
.path
, render_view_
, this);
1620 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame
* frame
,
1621 const blink::WebURLRequest
& request
,
1622 blink::WebNavigationPolicy policy
) {
1623 DCHECK(!frame_
|| frame_
== frame
);
1624 loadURLExternally(frame
, request
, policy
, WebString());
1627 void RenderFrameImpl::ExecuteJavaScript(const base::string16
& javascript
) {
1628 OnJavaScriptExecuteRequest(javascript
, 0, false);
1631 ServiceRegistry
* RenderFrameImpl::GetServiceRegistry() {
1632 return &service_registry_
;
1635 bool RenderFrameImpl::IsFTPDirectoryListing() {
1636 WebURLResponseExtraDataImpl
* extra_data
=
1637 GetExtraDataFromResponse(frame_
->dataSource()->response());
1638 return extra_data
? extra_data
->is_ftp_directory_listing() : false;
1641 void RenderFrameImpl::AttachGuest(int element_instance_id
) {
1642 render_view_
->GetBrowserPluginManager()->Attach(element_instance_id
);
1645 void RenderFrameImpl::SetSelectedText(const base::string16
& selection_text
,
1647 const gfx::Range
& range
) {
1648 // Use the routing id of Render Widget Host.
1649 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1655 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1656 v8::Isolate
* isolate
,
1657 v8::Handle
<v8::Context
> context
) {
1658 gin::ModuleRegistry
* registry
= gin::ModuleRegistry::From(context
);
1659 if (registry
->available_modules().count(mojo::js::Core::kModuleName
))
1662 v8::HandleScope
handle_scope(isolate
);
1663 registry
->AddBuiltinModule(
1664 isolate
, mojo::js::Core::kModuleName
, mojo::js::Core::GetModule(isolate
));
1665 registry
->AddBuiltinModule(isolate
,
1666 mojo::js::Support::kModuleName
,
1667 mojo::js::Support::GetModule(isolate
));
1668 registry
->AddBuiltinModule(
1670 ServiceRegistryJsWrapper::kModuleName
,
1671 ServiceRegistryJsWrapper::Create(isolate
, &service_registry_
).ToV8());
1674 // blink::WebFrameClient implementation ----------------------------------------
1676 blink::WebPluginPlaceholder
* RenderFrameImpl::createPluginPlaceholder(
1677 blink::WebLocalFrame
* frame
,
1678 const blink::WebPluginParams
& params
) {
1679 DCHECK_EQ(frame_
, frame
);
1680 return GetContentClient()
1682 ->CreatePluginPlaceholder(this, frame
, params
)
1686 blink::WebPlugin
* RenderFrameImpl::createPlugin(
1687 blink::WebLocalFrame
* frame
,
1688 const blink::WebPluginParams
& params
) {
1689 DCHECK_EQ(frame_
, frame
);
1690 blink::WebPlugin
* plugin
= NULL
;
1691 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1692 this, frame
, params
, &plugin
)) {
1696 if (base::UTF16ToUTF8(params
.mimeType
) == kBrowserPluginMimeType
) {
1697 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1698 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1699 kBrowserPluginMimeType
, GURL(params
.url
)));
1700 return render_view_
->GetBrowserPluginManager()->CreateBrowserPlugin(
1701 render_view_
.get(), frame
, browser_plugin_delegate
.Pass());
1704 #if defined(ENABLE_PLUGINS)
1706 std::string mime_type
;
1708 Send(new FrameHostMsg_GetPluginInfo(
1709 routing_id_
, params
.url
, frame
->top()->document().url(),
1710 params
.mimeType
.utf8(), &found
, &info
, &mime_type
));
1714 if (info
.type
== WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN
) {
1715 scoped_ptr
<BrowserPluginDelegate
> browser_plugin_delegate(
1716 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1717 this, mime_type
, GURL(params
.url
)));
1718 return render_view_
->GetBrowserPluginManager()->CreateBrowserPlugin(
1719 render_view_
.get(), frame
, browser_plugin_delegate
.Pass());
1723 WebPluginParams params_to_use
= params
;
1724 params_to_use
.mimeType
= WebString::fromUTF8(mime_type
);
1725 return CreatePlugin(frame
, info
, params_to_use
,
1726 CREATE_PLUGIN_GESTURE_NO_USER_GESTURE
);
1729 #endif // defined(ENABLE_PLUGINS)
1732 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1733 blink::WebLocalFrame
* frame
,
1734 const blink::WebURL
& url
,
1735 blink::WebMediaPlayerClient
* client
) {
1736 return createMediaPlayer(frame
, url
, client
, NULL
);
1739 blink::WebMediaPlayer
* RenderFrameImpl::createMediaPlayer(
1740 blink::WebLocalFrame
* frame
,
1741 const blink::WebURL
& url
,
1742 blink::WebMediaPlayerClient
* client
,
1743 blink::WebContentDecryptionModule
* initial_cdm
) {
1744 #if defined(VIDEO_HOLE)
1745 if (!contains_media_player_
) {
1746 render_view_
->RegisterVideoHoleFrame(this);
1747 contains_media_player_
= true;
1749 #endif // defined(VIDEO_HOLE)
1751 blink::WebMediaStream
web_stream(
1752 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url
));
1753 if (!web_stream
.isNull())
1754 return CreateWebMediaPlayerForMediaStream(url
, client
);
1756 #if defined(OS_ANDROID)
1757 return CreateAndroidWebMediaPlayer(url
, client
, initial_cdm
);
1759 RenderThreadImpl
* render_thread
= RenderThreadImpl::current();
1760 media::WebMediaPlayerParams
params(
1761 base::Bind(&ContentRendererClient::DeferMediaLoad
,
1762 base::Unretained(GetContentClient()->renderer()),
1763 static_cast<RenderFrame
*>(this)),
1764 render_thread
->GetAudioRendererMixerManager()->CreateInput(
1765 render_view_
->routing_id_
, routing_id_
),
1766 *render_thread
->GetAudioHardwareConfig(),
1767 new RenderMediaLog(),
1768 render_thread
->GetGpuFactories(),
1769 render_thread
->GetMediaThreadTaskRunner(),
1770 render_thread
->compositor_message_loop_proxy(),
1773 #if defined(ENABLE_PEPPER_CDMS)
1774 scoped_ptr
<media::CdmFactory
> cdm_factory(
1775 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create
, frame
)));
1777 scoped_ptr
<media::CdmFactory
> cdm_factory(new RenderCdmFactory());
1780 scoped_ptr
<media::Renderer
> media_renderer
=
1781 GetContentClient()->renderer()->CreateMediaRenderer(
1782 this, render_thread
->GetMediaThreadTaskRunner());
1784 return new media::WebMediaPlayerImpl(
1785 frame
, client
, weak_factory_
.GetWeakPtr(), media_renderer
.Pass(),
1786 cdm_factory
.Pass(), params
);
1787 #endif // defined(OS_ANDROID)
1790 blink::WebContentDecryptionModule
*
1791 RenderFrameImpl::createContentDecryptionModule(
1792 blink::WebLocalFrame
* frame
,
1793 const blink::WebSecurityOrigin
& security_origin
,
1794 const blink::WebString
& key_system
) {
1795 DCHECK(!frame_
|| frame_
== frame
);
1797 #if defined(ENABLE_PEPPER_CDMS)
1798 RenderCdmFactory
cdm_factory(
1799 base::Bind(&PepperCdmWrapperImpl::Create
, frame
));
1800 #elif defined(ENABLE_BROWSER_CDMS)
1801 RenderCdmFactory
cdm_factory(GetCdmManager());
1803 RenderCdmFactory cdm_factory
;
1806 return media::WebContentDecryptionModuleImpl::Create(
1807 &cdm_factory
, security_origin
, key_system
);
1810 blink::WebApplicationCacheHost
* RenderFrameImpl::createApplicationCacheHost(
1811 blink::WebLocalFrame
* frame
,
1812 blink::WebApplicationCacheHostClient
* client
) {
1813 if (!frame
|| !frame
->view())
1815 DCHECK(!frame_
|| frame_
== frame
);
1816 return new RendererWebApplicationCacheHostImpl(
1817 RenderViewImpl::FromWebView(frame
->view()), client
,
1818 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1821 blink::WebWorkerPermissionClientProxy
*
1822 RenderFrameImpl::createWorkerPermissionClientProxy(
1823 blink::WebLocalFrame
* frame
) {
1824 if (!frame
|| !frame
->view())
1826 DCHECK(!frame_
|| frame_
== frame
);
1827 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1831 WebExternalPopupMenu
* RenderFrameImpl::createExternalPopupMenu(
1832 const WebPopupMenuInfo
& popup_menu_info
,
1833 WebExternalPopupMenuClient
* popup_menu_client
) {
1834 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1835 // An IPC message is sent to the browser to build and display the actual
1836 // popup. The user could have time to click a different select by the time
1837 // the popup is shown. In that case external_popup_menu_ is non NULL.
1838 // By returning NULL in that case, we instruct Blink to cancel that new
1839 // popup. So from the user perspective, only the first one will show, and
1840 // will have to close the first one before another one can be shown.
1841 if (external_popup_menu_
)
1843 external_popup_menu_
.reset(
1844 new ExternalPopupMenu(this, popup_menu_info
, popup_menu_client
));
1845 if (render_view_
->screen_metrics_emulator_
) {
1846 render_view_
->SetExternalPopupOriginAdjustmentsForEmulation(
1847 external_popup_menu_
.get(),
1848 render_view_
->screen_metrics_emulator_
.get());
1850 return external_popup_menu_
.get();
1856 blink::WebCookieJar
* RenderFrameImpl::cookieJar(blink::WebLocalFrame
* frame
) {
1857 DCHECK(!frame_
|| frame_
== frame
);
1858 return &cookie_jar_
;
1861 blink::WebServiceWorkerProvider
* RenderFrameImpl::createServiceWorkerProvider(
1862 blink::WebLocalFrame
* frame
) {
1863 DCHECK(!frame_
|| frame_
== frame
);
1864 // At this point we should have non-null data source.
1865 DCHECK(frame
->dataSource());
1866 if (!ChildThread::current())
1867 return NULL
; // May be null in some tests.
1868 ServiceWorkerNetworkProvider
* provider
=
1869 ServiceWorkerNetworkProvider::FromDocumentState(
1870 DocumentState::FromDataSource(frame
->dataSource()));
1871 return new WebServiceWorkerProviderImpl(
1872 ChildThread::current()->thread_safe_sender(),
1873 provider
? provider
->context() : NULL
);
1876 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame
* frame
) {
1877 DCHECK(!frame_
|| frame_
== frame
);
1878 // Notify the browser process that it is no longer safe to show the pending
1879 // URL of the main frame, since a URL spoof is now possible.
1880 if (!frame
->parent() && render_view_
->page_id_
== -1)
1881 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_
));
1884 blink::WebFrame
* RenderFrameImpl::createChildFrame(
1885 blink::WebLocalFrame
* parent
,
1886 const blink::WebString
& name
) {
1887 // Synchronously notify the browser of a child frame creation to get the
1888 // routing_id for the RenderFrame.
1889 int child_routing_id
= MSG_ROUTING_NONE
;
1890 Send(new FrameHostMsg_CreateChildFrame(routing_id_
,
1891 base::UTF16ToUTF8(name
),
1892 &child_routing_id
));
1893 // Allocation of routing id failed, so we can't create a child frame. This can
1894 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
1896 if (child_routing_id
== MSG_ROUTING_NONE
) {
1897 #if !defined(OS_LINUX)
1898 // DumpWithoutCrashing() crashes on Linux in renderer processes when
1899 // breakpad and sandboxing are enabled: crbug.com/349600
1900 base::debug::Alias(parent
);
1901 base::debug::Alias(&routing_id_
);
1902 bool render_view_is_swapped_out
= GetRenderWidget()->is_swapped_out();
1903 base::debug::Alias(&render_view_is_swapped_out
);
1904 bool render_view_is_closing
= GetRenderWidget()->closing();
1905 base::debug::Alias(&render_view_is_closing
);
1906 base::debug::Alias(&is_swapped_out_
);
1907 base::debug::DumpWithoutCrashing();
1912 // Create the RenderFrame and WebLocalFrame, linking the two.
1913 RenderFrameImpl
* child_render_frame
= RenderFrameImpl::Create(
1914 render_view_
.get(), child_routing_id
);
1915 blink::WebLocalFrame
* web_frame
= WebLocalFrame::create(child_render_frame
);
1916 child_render_frame
->SetWebFrame(web_frame
);
1918 // Add the frame to the frame tree and initialize it.
1919 parent
->appendChild(web_frame
);
1920 child_render_frame
->Initialize();
1925 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame
* frame
) {
1926 DCHECK(!frame_
|| frame_
== frame
);
1927 // We only need to notify the browser if the active, top-level frame clears
1928 // its opener. We can ignore cases where a swapped out frame clears its
1929 // opener after hearing about it from the browser, and the browser does not
1930 // (yet) care about subframe openers.
1931 if (is_swapped_out_
|| frame
->parent())
1934 // Notify WebContents and all its swapped out RenderViews.
1935 Send(new FrameHostMsg_DidDisownOpener(routing_id_
));
1938 void RenderFrameImpl::frameDetached(blink::WebFrame
* frame
) {
1939 // NOTE: This function is called on the frame that is being detached and not
1940 // the parent frame. This is different from createChildFrame() which is
1941 // called on the parent frame.
1942 CHECK(!is_detaching_
);
1943 DCHECK(!frame_
|| frame_
== frame
);
1945 bool is_subframe
= !!frame
->parent();
1947 Send(new FrameHostMsg_Detach(routing_id_
));
1949 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
1950 // sent before setting |is_detaching_| to true. In contrast, Observers
1951 // should only be notified afterwards so they cannot call back into here and
1952 // have IPCs fired off.
1953 is_detaching_
= true;
1955 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
1956 FrameDetached(frame
));
1958 // We need to clean up subframes by removing them from the map and deleting
1959 // the RenderFrameImpl. In contrast, the main frame is owned by its
1960 // containing RenderViewHost (so that they have the same lifetime), so only
1961 // removal from the map is needed and no deletion.
1962 FrameMap::iterator it
= g_frame_map
.Get().find(frame
);
1963 CHECK(it
!= g_frame_map
.Get().end());
1964 CHECK_EQ(it
->second
, this);
1965 g_frame_map
.Get().erase(it
);
1968 frame
->parent()->removeChild(frame
);
1970 // |frame| is invalid after here.
1975 // Object is invalid after this point.
1979 void RenderFrameImpl::frameFocused() {
1980 Send(new FrameHostMsg_FrameFocused(routing_id_
));
1983 void RenderFrameImpl::willClose(blink::WebFrame
* frame
) {
1984 DCHECK(!frame_
|| frame_
== frame
);
1986 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, FrameWillClose());
1987 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
1988 FrameWillClose(frame
));
1991 void RenderFrameImpl::didChangeName(blink::WebLocalFrame
* frame
,
1992 const blink::WebString
& name
) {
1993 DCHECK(!frame_
|| frame_
== frame
);
1994 if (!render_view_
->renderer_preferences_
.report_frame_name_changes
)
1997 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeName(name
));
2000 void RenderFrameImpl::didMatchCSS(
2001 blink::WebLocalFrame
* frame
,
2002 const blink::WebVector
<blink::WebString
>& newly_matching_selectors
,
2003 const blink::WebVector
<blink::WebString
>& stopped_matching_selectors
) {
2004 DCHECK(!frame_
|| frame_
== frame
);
2006 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2008 newly_matching_selectors
,
2009 stopped_matching_selectors
));
2012 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2013 const blink::WebString
& source
) {
2014 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2018 void RenderFrameImpl::didAddMessageToConsole(
2019 const blink::WebConsoleMessage
& message
,
2020 const blink::WebString
& source_name
,
2021 unsigned source_line
,
2022 const blink::WebString
& stack_trace
) {
2023 logging::LogSeverity log_severity
= logging::LOG_VERBOSE
;
2024 switch (message
.level
) {
2025 case blink::WebConsoleMessage::LevelDebug
:
2026 log_severity
= logging::LOG_VERBOSE
;
2028 case blink::WebConsoleMessage::LevelLog
:
2029 case blink::WebConsoleMessage::LevelInfo
:
2030 log_severity
= logging::LOG_INFO
;
2032 case blink::WebConsoleMessage::LevelWarning
:
2033 log_severity
= logging::LOG_WARNING
;
2035 case blink::WebConsoleMessage::LevelError
:
2036 log_severity
= logging::LOG_ERROR
;
2042 if (shouldReportDetailedMessageForSource(source_name
)) {
2044 RenderFrameObserver
, observers_
,
2045 DetailedConsoleMessageAdded(message
.text
,
2049 static_cast<int32
>(log_severity
)));
2052 Send(new FrameHostMsg_AddMessageToConsole(routing_id_
,
2053 static_cast<int32
>(log_severity
),
2055 static_cast<int32
>(source_line
),
2059 void RenderFrameImpl::loadURLExternally(
2060 blink::WebLocalFrame
* frame
,
2061 const blink::WebURLRequest
& request
,
2062 blink::WebNavigationPolicy policy
,
2063 const blink::WebString
& suggested_name
) {
2064 DCHECK(!frame_
|| frame_
== frame
);
2065 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(frame
, request
));
2066 if (policy
== blink::WebNavigationPolicyDownload
) {
2067 render_view_
->Send(new ViewHostMsg_DownloadUrl(render_view_
->GetRoutingID(),
2068 request
.url(), referrer
,
2071 OpenURL(frame
, request
.url(), referrer
, policy
);
2075 blink::WebNavigationPolicy
RenderFrameImpl::decidePolicyForNavigation(
2076 const NavigationPolicyInfo
& info
) {
2077 DCHECK(!frame_
|| frame_
== info
.frame
);
2078 return DecidePolicyForNavigation(this, info
);
2081 blink::WebHistoryItem
RenderFrameImpl::historyItemForNewChildFrame(
2082 blink::WebFrame
* frame
) {
2083 DCHECK(!frame_
|| frame_
== frame
);
2084 return render_view_
->history_controller()->GetItemForNewChildFrame(this);
2087 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame
* frame
,
2088 const blink::WebFormElement
& form
) {
2089 DCHECK(!frame_
|| frame_
== frame
);
2091 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2092 WillSendSubmitEvent(frame
, form
));
2095 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame
* frame
,
2096 const blink::WebFormElement
& form
) {
2097 DCHECK(!frame_
|| frame_
== frame
);
2098 DocumentState
* document_state
=
2099 DocumentState::FromDataSource(frame
->provisionalDataSource());
2100 NavigationState
* navigation_state
= document_state
->navigation_state();
2101 InternalDocumentStateData
* internal_data
=
2102 InternalDocumentStateData::FromDocumentState(document_state
);
2104 if (ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2105 ui::PAGE_TRANSITION_LINK
)) {
2106 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT
);
2109 // Save these to be processed when the ensuing navigation is committed.
2110 WebSearchableFormData
web_searchable_form_data(form
);
2111 internal_data
->set_searchable_form_url(web_searchable_form_data
.url());
2112 internal_data
->set_searchable_form_encoding(
2113 web_searchable_form_data
.encoding().utf8());
2115 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2116 WillSubmitForm(frame
, form
));
2119 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame
* frame
,
2120 blink::WebDataSource
* datasource
) {
2121 DCHECK(!frame_
|| frame_
== frame
);
2123 // TODO(nasko): Move implementation here. Needed state:
2124 // * pending_navigation_params_
2127 // * PopulateDocumentStateFromPending
2128 // * CreateNavigationStateFromPending
2129 render_view_
->didCreateDataSource(frame
, datasource
);
2131 // Create the serviceworker's per-document network observing object if it
2132 // does not exist (When navigation happens within a page, the provider already
2134 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2135 DocumentState::FromDataSource(datasource
))) {
2136 scoped_ptr
<ServiceWorkerNetworkProvider
>
2137 network_provider(new ServiceWorkerNetworkProvider());
2138 ServiceWorkerNetworkProvider::AttachToDocumentState(
2139 DocumentState::FromDataSource(datasource
),
2140 network_provider
.Pass());
2144 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame
* frame
,
2145 bool is_transition_navigation
) {
2146 DCHECK(!frame_
|| frame_
== frame
);
2147 WebDataSource
* ds
= frame
->provisionalDataSource();
2149 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2150 // callback is invoked.
2154 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2155 "id", routing_id_
, "url", ds
->request().url().string().utf8());
2156 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2158 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2159 CHECK((ds
->request().url() != GURL(kSwappedOutURL
)) ||
2161 "Heard swappedout:// when not swapped out.";
2163 // Update the request time if WebKit has better knowledge of it.
2164 if (document_state
->request_time().is_null()) {
2165 double event_time
= ds
->triggeringEventTime();
2166 if (event_time
!= 0.0)
2167 document_state
->set_request_time(Time::FromDoubleT(event_time
));
2170 // Start time is only set after request time.
2171 document_state
->set_start_load_time(Time::Now());
2173 bool is_top_most
= !frame
->parent();
2175 render_view_
->set_navigation_gesture(
2176 WebUserGestureIndicator::isProcessingUserGesture() ?
2177 NavigationGestureUser
: NavigationGestureAuto
);
2178 } else if (ds
->replacesCurrentHistoryItem()) {
2179 // Subframe navigations that don't add session history items must be
2180 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2181 // handle loading of error pages.
2182 document_state
->navigation_state()->set_transition_type(
2183 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2186 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2187 DidStartProvisionalLoad(frame
));
2188 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidStartProvisionalLoad());
2190 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2191 routing_id_
, ds
->request().url(), is_transition_navigation
));
2194 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2195 blink::WebLocalFrame
* frame
) {
2196 DCHECK(!frame_
|| frame_
== frame
);
2197 render_view_
->history_controller()->RemoveChildrenForRedirect(this);
2200 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame
* frame
,
2201 const blink::WebURLError
& error
) {
2202 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2204 DCHECK(!frame_
|| frame_
== frame
);
2205 WebDataSource
* ds
= frame
->provisionalDataSource();
2208 const WebURLRequest
& failed_request
= ds
->request();
2210 // Notify the browser that we failed a provisional load with an error.
2212 // Note: It is important this notification occur before DidStopLoading so the
2213 // SSL manager can react to the provisional load failure before being
2214 // notified the load stopped.
2216 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2217 DidFailProvisionalLoad(frame
, error
));
2218 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2219 DidFailProvisionalLoad(error
));
2221 bool show_repost_interstitial
=
2222 (error
.reason
== net::ERR_CACHE_MISS
&&
2223 EqualsASCII(failed_request
.httpMethod(), "POST"));
2225 FrameHostMsg_DidFailProvisionalLoadWithError_Params params
;
2226 params
.error_code
= error
.reason
;
2227 GetContentClient()->renderer()->GetNavigationErrorStrings(
2233 ¶ms
.error_description
);
2234 params
.url
= error
.unreachableURL
;
2235 params
.showing_repost_interstitial
= show_repost_interstitial
;
2236 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2237 routing_id_
, params
));
2239 // Don't display an error page if this is simply a cancelled load. Aside
2240 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2241 if (error
.reason
== net::ERR_ABORTED
)
2244 // Don't display "client blocked" error page if browser has asked us not to.
2245 if (error
.reason
== net::ERR_BLOCKED_BY_CLIENT
&&
2246 render_view_
->renderer_preferences_
.disable_client_blocked_error_page
) {
2250 // Allow the embedder to suppress an error page.
2251 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2252 error
.unreachableURL
)) {
2256 if (RenderThreadImpl::current() &&
2257 RenderThreadImpl::current()->layout_test_mode()) {
2261 // Make sure we never show errors in view source mode.
2262 frame
->enableViewSourceMode(false);
2264 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2265 NavigationState
* navigation_state
= document_state
->navigation_state();
2267 // If this is a failed back/forward/reload navigation, then we need to do a
2268 // 'replace' load. This is necessary to avoid messing up session history.
2269 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2270 // as session history is concerned.
2272 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2275 // TODO(davidben): This should also take the failed navigation's replacement
2276 // state into account, if a location.replace() failed.
2278 navigation_state
->pending_page_id() != -1 ||
2279 ui::PageTransitionCoreTypeIs(navigation_state
->transition_type(),
2280 ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
2282 // If we failed on a browser initiated request, then make sure that our error
2283 // page load is regarded as the same browser initiated request.
2284 if (!navigation_state
->is_content_initiated()) {
2285 render_view_
->pending_navigation_params_
.reset(
2286 new FrameMsg_Navigate_Params
);
2287 render_view_
->pending_navigation_params_
->page_id
=
2288 navigation_state
->pending_page_id();
2289 render_view_
->pending_navigation_params_
->pending_history_list_offset
=
2290 navigation_state
->pending_history_list_offset();
2291 render_view_
->pending_navigation_params_
->should_clear_history_list
=
2292 navigation_state
->history_list_was_cleared();
2293 render_view_
->pending_navigation_params_
->common_params
.transition
=
2294 navigation_state
->transition_type();
2295 render_view_
->pending_navigation_params_
->request_time
=
2296 document_state
->request_time();
2297 render_view_
->pending_navigation_params_
->should_replace_current_entry
=
2301 // Load an error page.
2302 LoadNavigationErrorPage(failed_request
, error
, replace
);
2305 void RenderFrameImpl::didCommitProvisionalLoad(
2306 blink::WebLocalFrame
* frame
,
2307 const blink::WebHistoryItem
& item
,
2308 blink::WebHistoryCommitType commit_type
) {
2309 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2311 "url", GetLoadingUrl().possibly_invalid_spec());
2312 DCHECK(!frame_
|| frame_
== frame
);
2313 DocumentState
* document_state
=
2314 DocumentState::FromDataSource(frame
->dataSource());
2315 NavigationState
* navigation_state
= document_state
->navigation_state();
2317 if (proxy_routing_id_
!= MSG_ROUTING_NONE
) {
2318 RenderFrameProxy
* proxy
=
2319 RenderFrameProxy::FromRoutingID(proxy_routing_id_
);
2321 proxy
->web_frame()->swap(frame_
);
2322 proxy_routing_id_
= MSG_ROUTING_NONE
;
2325 // When we perform a new navigation, we need to update the last committed
2326 // session history entry with state for the page we are leaving. Do this
2327 // before updating the HistoryController state.
2328 render_view_
->UpdateSessionHistory(frame
);
2330 render_view_
->history_controller()->UpdateForCommit(this, item
, commit_type
,
2331 navigation_state
->was_within_same_page());
2333 InternalDocumentStateData
* internal_data
=
2334 InternalDocumentStateData::FromDocumentState(document_state
);
2336 if (document_state
->commit_load_time().is_null())
2337 document_state
->set_commit_load_time(Time::Now());
2339 if (internal_data
->must_reset_scroll_and_scale_state()) {
2340 render_view_
->webview()->resetScrollAndScaleState();
2341 internal_data
->set_must_reset_scroll_and_scale_state(false);
2343 internal_data
->set_use_error_page(false);
2345 bool is_new_navigation
= commit_type
== blink::WebStandardCommit
;
2346 if (is_new_navigation
) {
2347 // We bump our Page ID to correspond with the new session history entry.
2348 render_view_
->page_id_
= render_view_
->next_page_id_
++;
2350 // Don't update history_page_ids_ (etc) for kSwappedOutURL, since
2351 // we don't want to forget the entry that was there, and since we will
2352 // never come back to kSwappedOutURL. Note that we have to call
2353 // UpdateSessionHistory and update page_id_ even in this case, so that
2354 // the current entry gets a state update and so that we don't send a
2355 // state update to the wrong entry when we swap back in.
2356 if (GetLoadingUrl() != GURL(kSwappedOutURL
)) {
2357 // Advance our offset in session history, applying the length limit.
2358 // There is now no forward history.
2359 render_view_
->history_list_offset_
++;
2360 if (render_view_
->history_list_offset_
>= kMaxSessionHistoryEntries
)
2361 render_view_
->history_list_offset_
= kMaxSessionHistoryEntries
- 1;
2362 render_view_
->history_list_length_
=
2363 render_view_
->history_list_offset_
+ 1;
2364 render_view_
->history_page_ids_
.resize(
2365 render_view_
->history_list_length_
, -1);
2366 render_view_
->history_page_ids_
[render_view_
->history_list_offset_
] =
2367 render_view_
->page_id_
;
2370 // Inspect the navigation_state on this frame to see if the navigation
2371 // corresponds to a session history navigation... Note: |frame| may or
2372 // may not be the toplevel frame, but for the case of capturing session
2373 // history, the first committed frame suffices. We keep track of whether
2374 // we've seen this commit before so that only capture session history once
2377 // Note that we need to check if the page ID changed. In the case of a
2378 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2379 // previous URL and the current page ID, which would be wrong.
2380 if (navigation_state
->pending_page_id() != -1 &&
2381 navigation_state
->pending_page_id() != render_view_
->page_id_
&&
2382 !navigation_state
->request_committed()) {
2383 // This is a successful session history navigation!
2384 render_view_
->page_id_
= navigation_state
->pending_page_id();
2386 render_view_
->history_list_offset_
=
2387 navigation_state
->pending_history_list_offset();
2389 // If the history list is valid, our list of page IDs should be correct.
2390 DCHECK(render_view_
->history_list_length_
<= 0 ||
2391 render_view_
->history_list_offset_
< 0 ||
2392 render_view_
->history_list_offset_
>=
2393 render_view_
->history_list_length_
||
2394 render_view_
->history_page_ids_
[render_view_
->history_list_offset_
]
2395 == render_view_
->page_id_
);
2400 new FrameHostMsg_DidAssignPageId(routing_id_
, render_view_
->page_id_
));
2401 CHECK(sent
); // http://crbug.com/407376
2403 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
,
2404 DidCommitProvisionalLoad(frame
, is_new_navigation
));
2405 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
,
2406 DidCommitProvisionalLoad(is_new_navigation
));
2408 if (!frame
->parent()) { // Only for top frames.
2409 RenderThreadImpl
* render_thread_impl
= RenderThreadImpl::current();
2410 if (render_thread_impl
) { // Can be NULL in tests.
2411 render_thread_impl
->histogram_customizer()->
2412 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2413 RenderViewImpl::GetRenderViewCount());
2417 // Remember that we've already processed this request, so we don't update
2418 // the session history again. We do this regardless of whether this is
2419 // a session history navigation, because if we attempted a session history
2420 // navigation without valid HistoryItem state, WebCore will think it is a
2422 navigation_state
->set_request_committed(true);
2424 SendDidCommitProvisionalLoad(frame
);
2426 // Check whether we have new encoding name.
2427 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2430 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame
* frame
) {
2431 DCHECK(!frame_
|| frame_
== frame
);
2433 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2434 DidCreateNewDocument(frame
));
2437 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame
* frame
) {
2438 DCHECK(!frame_
|| frame_
== frame
);
2439 // TODO(nasko): Move implementation here. Needed state:
2440 // * enabled_bindings_
2441 // * dom_automation_controller_
2442 // * stats_collection_controller_
2444 render_view_
->didClearWindowObject(frame
);
2446 if (render_view_
->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION
)
2447 DomAutomationController::Install(this, frame
);
2449 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidClearWindowObject());
2452 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame
* frame
) {
2453 DCHECK(!frame_
|| frame_
== frame
);
2455 // Notify the browser about non-blank documents loading in the top frame.
2456 GURL url
= frame
->document().url();
2457 if (url
.is_valid() && url
.spec() != url::kAboutBlankURL
) {
2458 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2459 // frame->tree()->top().
2460 blink::WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
2461 if (frame
== main_frame
) {
2462 // For now, don't remember plugin zoom values. We don't want to mix them
2463 // with normal web content (i.e. a fixed layout plugin would usually want
2465 render_view_
->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2466 render_view_
->GetRoutingID(),
2467 main_frame
->document().isPluginDocument()));
2471 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2472 DidCreateDocumentElement(frame
));
2475 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame
* frame
,
2476 const blink::WebString
& title
,
2477 blink::WebTextDirection direction
) {
2478 DCHECK(!frame_
|| frame_
== frame
);
2479 // Ignore all but top level navigations.
2480 if (!frame
->parent()) {
2481 base::string16 title16
= title
;
2482 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2483 routing_id_
, base::UTF16ToUTF8(title16
));
2485 base::string16 shortened_title
= title16
.substr(0, kMaxTitleChars
);
2486 Send(new FrameHostMsg_UpdateTitle(routing_id_
,
2487 shortened_title
, direction
));
2490 // Also check whether we have new encoding name.
2491 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2494 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame
* frame
,
2495 blink::WebIconURL::Type icon_type
) {
2496 DCHECK(!frame_
|| frame_
== frame
);
2497 // TODO(nasko): Investigate wheather implementation should move here.
2498 render_view_
->didChangeIcon(frame
, icon_type
);
2501 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame
* frame
) {
2502 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2504 DCHECK(!frame_
|| frame_
== frame
);
2505 WebDataSource
* ds
= frame
->dataSource();
2506 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2507 document_state
->set_finish_document_load_time(Time::Now());
2509 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_
));
2511 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2512 DidFinishDocumentLoad(frame
));
2513 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishDocumentLoad());
2515 // Check whether we have new encoding name.
2516 UpdateEncoding(frame
, frame
->view()->pageEncoding().utf8());
2519 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame
* frame
) {
2520 DCHECK(!frame_
|| frame_
== frame
);
2521 if (!frame
->parent())
2522 Send(new FrameHostMsg_DocumentOnLoadCompleted(routing_id_
));
2525 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame
* frame
,
2526 const blink::WebURLError
& error
) {
2527 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2529 DCHECK(!frame_
|| frame_
== frame
);
2530 // TODO(nasko): Move implementation here. No state needed.
2531 WebDataSource
* ds
= frame
->dataSource();
2534 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2535 DidFailLoad(frame
, error
));
2537 const WebURLRequest
& failed_request
= ds
->request();
2538 base::string16 error_description
;
2539 GetContentClient()->renderer()->GetNavigationErrorStrings(
2545 &error_description
);
2546 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_
,
2547 failed_request
.url(),
2549 error_description
));
2552 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame
* frame
) {
2553 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2555 DCHECK(!frame_
|| frame_
== frame
);
2556 WebDataSource
* ds
= frame
->dataSource();
2557 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
2558 if (document_state
->finish_load_time().is_null()) {
2559 if (!frame
->parent()) {
2560 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2561 TRACE_EVENT_SCOPE_PROCESS
);
2563 document_state
->set_finish_load_time(Time::Now());
2566 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers(),
2567 DidFinishLoad(frame
));
2568 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidFinishLoad());
2570 // Don't send this message while the frame is swapped out.
2571 if (is_swapped_out())
2574 Send(new FrameHostMsg_DidFinishLoad(routing_id_
,
2575 ds
->request().url()));
2578 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame
* frame
,
2579 const blink::WebHistoryItem
& item
,
2580 blink::WebHistoryCommitType commit_type
) {
2581 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2583 DCHECK(!frame_
|| frame_
== frame
);
2584 // If this was a reference fragment navigation that we initiated, then we
2585 // could end up having a non-null pending navigation params. We just need to
2586 // update the ExtraData on the datasource so that others who read the
2587 // ExtraData will get the new NavigationState. Similarly, if we did not
2588 // initiate this navigation, then we need to take care to reset any pre-
2589 // existing navigation state to a content-initiated navigation state.
2590 // DidCreateDataSource conveniently takes care of this for us.
2591 didCreateDataSource(frame
, frame
->dataSource());
2593 DocumentState
* document_state
=
2594 DocumentState::FromDataSource(frame
->dataSource());
2595 NavigationState
* new_state
= document_state
->navigation_state();
2596 new_state
->set_was_within_same_page(true);
2598 didCommitProvisionalLoad(frame
, item
, commit_type
);
2601 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame
* frame
) {
2602 DCHECK(!frame_
|| frame_
== frame
);
2603 // TODO(nasko): Move implementation here. Needed methods:
2604 // * StartNavStateSyncTimerIfNecessary
2605 render_view_
->didUpdateCurrentHistoryItem(frame
);
2608 void RenderFrameImpl::addNavigationTransitionData(
2609 const blink::WebTransitionElementData
& data
) {
2610 FrameHostMsg_AddNavigationTransitionData_Params params
;
2611 params
.render_frame_id
= routing_id_
;
2612 params
.allowed_destination_host_pattern
=
2614 params
.selector
= data
.selector
.utf8();
2615 params
.markup
= data
.markup
.utf8();
2616 params
.elements
.resize(data
.elements
.size());
2617 for (size_t i
= 0; i
< data
.elements
.size(); i
++) {
2618 params
.elements
[i
].id
= data
.elements
[i
].id
.utf8();
2619 params
.elements
[i
].rect
= gfx::Rect(data
.elements
[i
].rect
);
2622 Send(new FrameHostMsg_AddNavigationTransitionData(params
));
2625 void RenderFrameImpl::didChangeThemeColor() {
2626 if (frame_
->parent())
2629 Send(new FrameHostMsg_DidChangeThemeColor(
2630 routing_id_
, frame_
->document().themeColor()));
2633 void RenderFrameImpl::requestNotificationPermission(
2634 const blink::WebSecurityOrigin
& origin
,
2635 blink::WebNotificationPermissionCallback
* callback
) {
2636 if (!notification_permission_dispatcher_
) {
2637 notification_permission_dispatcher_
=
2638 new NotificationPermissionDispatcher(this);
2641 notification_permission_dispatcher_
->RequestPermission(origin
, callback
);
2644 void RenderFrameImpl::didChangeSelection(bool is_empty_selection
) {
2645 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_
)
2648 if (is_empty_selection
)
2649 selection_text_
.clear();
2651 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2652 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2653 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2654 // to notify the selection was changed. Focus change should be notified
2655 // before selection change.
2656 GetRenderWidget()->UpdateTextInputType();
2657 SyncSelectionIfRequired();
2658 #if defined(OS_ANDROID)
2659 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME
,
2660 RenderWidget::FROM_NON_IME
);
2664 blink::WebColorChooser
* RenderFrameImpl::createColorChooser(
2665 blink::WebColorChooserClient
* client
,
2666 const blink::WebColor
& initial_color
,
2667 const blink::WebVector
<blink::WebColorSuggestion
>& suggestions
) {
2668 RendererWebColorChooserImpl
* color_chooser
=
2669 new RendererWebColorChooserImpl(this, client
);
2670 std::vector
<ColorSuggestion
> color_suggestions
;
2671 for (size_t i
= 0; i
< suggestions
.size(); i
++) {
2672 color_suggestions
.push_back(ColorSuggestion(suggestions
[i
]));
2674 color_chooser
->Open(static_cast<SkColor
>(initial_color
), color_suggestions
);
2675 return color_chooser
;
2678 void RenderFrameImpl::runModalAlertDialog(const blink::WebString
& message
) {
2679 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT
,
2682 frame_
->document().url(),
2686 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString
& message
) {
2687 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM
,
2690 frame_
->document().url(),
2694 bool RenderFrameImpl::runModalPromptDialog(
2695 const blink::WebString
& message
,
2696 const blink::WebString
& default_value
,
2697 blink::WebString
* actual_value
) {
2698 base::string16 result
;
2699 bool ok
= RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT
,
2702 frame_
->document().url(),
2705 actual_value
->assign(result
);
2709 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2711 const blink::WebString
& message
) {
2712 // If we are swapping out, we have already run the beforeunload handler.
2713 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2714 // at all, to avoid running it twice.
2715 if (is_swapped_out_
)
2718 // Don't allow further dialogs if we are waiting to swap out, since the
2719 // PageGroupLoadDeferrer in our stack prevents it.
2720 if (render_view()->suppress_dialogs_until_swap_out_
)
2723 bool success
= false;
2724 // This is an ignored return value, but is included so we can accept the same
2725 // response as RunJavaScriptMessage.
2726 base::string16 ignored_result
;
2727 render_view()->SendAndRunNestedMessageLoop(
2728 new FrameHostMsg_RunBeforeUnloadConfirm(
2729 routing_id_
, frame_
->document().url(), message
, is_reload
,
2730 &success
, &ignored_result
));
2734 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData
& data
) {
2735 ContextMenuParams params
= ContextMenuParamsBuilder::Build(data
);
2736 params
.source_type
= GetRenderWidget()->context_menu_source_type();
2737 GetRenderWidget()->OnShowHostContextMenu(¶ms
);
2738 if (GetRenderWidget()->has_host_context_menu_location()) {
2739 params
.x
= GetRenderWidget()->host_context_menu_location().x();
2740 params
.y
= GetRenderWidget()->host_context_menu_location().y();
2743 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2744 // it. We replace it with an empty GURL so the appropriate items are disabled
2745 // in the context menu.
2746 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2747 // data encoded images. We should have a way to save them.
2748 if (params
.src_url
.spec().size() > GetMaxURLChars())
2749 params
.src_url
= GURL();
2750 context_menu_node_
= data
.node
;
2752 #if defined(OS_ANDROID)
2753 gfx::Rect start_rect
;
2755 GetRenderWidget()->GetSelectionBounds(&start_rect
, &end_rect
);
2756 params
.selection_start
= gfx::Point(start_rect
.x(), start_rect
.bottom());
2757 params
.selection_end
= gfx::Point(end_rect
.right(), end_rect
.bottom());
2760 Send(new FrameHostMsg_ContextMenu(routing_id_
, params
));
2763 void RenderFrameImpl::clearContextMenu() {
2764 context_menu_node_
.reset();
2767 void RenderFrameImpl::willSendRequest(
2768 blink::WebLocalFrame
* frame
,
2769 unsigned identifier
,
2770 blink::WebURLRequest
& request
,
2771 const blink::WebURLResponse
& redirect_response
) {
2772 DCHECK(!frame_
|| frame_
== frame
);
2773 // The request my be empty during tests.
2774 if (request
.url().isEmpty())
2777 // Set the first party for cookies url if it has not been set yet (new
2778 // requests). For redirects, it is updated by WebURLLoaderImpl.
2779 if (request
.firstPartyForCookies().isEmpty()) {
2780 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
) {
2781 request
.setFirstPartyForCookies(request
.url());
2783 // TODO(nasko): When the top-level frame is remote, there is no document.
2784 // This is broken and should be fixed to propagate the first party.
2785 WebFrame
* top
= frame
->top();
2786 if (top
->isWebLocalFrame()) {
2787 request
.setFirstPartyForCookies(
2788 frame
->top()->document().firstPartyForCookies());
2793 WebFrame
* top_frame
= frame
->top();
2794 // TODO(nasko): Hack around asking about top-frame data source. This means
2795 // for out-of-process iframes we are treating the current frame as the
2796 // top-level frame, which is wrong.
2797 if (!top_frame
|| top_frame
->isWebRemoteFrame())
2799 WebDataSource
* provisional_data_source
= top_frame
->provisionalDataSource();
2800 WebDataSource
* top_data_source
= top_frame
->dataSource();
2801 WebDataSource
* data_source
=
2802 provisional_data_source
? provisional_data_source
: top_data_source
;
2804 DocumentState
* document_state
= DocumentState::FromDataSource(data_source
);
2805 DCHECK(document_state
);
2806 InternalDocumentStateData
* internal_data
=
2807 InternalDocumentStateData::FromDocumentState(document_state
);
2808 NavigationState
* navigation_state
= document_state
->navigation_state();
2809 ui::PageTransition transition_type
= navigation_state
->transition_type();
2810 WebDataSource
* frame_ds
= frame
->provisionalDataSource();
2811 if (frame_ds
&& frame_ds
->isClientRedirect()) {
2812 transition_type
= ui::PageTransitionFromInt(
2813 transition_type
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
2816 GURL
request_url(request
.url());
2818 if (GetContentClient()->renderer()->WillSendRequest(
2822 request
.firstPartyForCookies(),
2824 request
.setURL(WebURL(new_url
));
2827 if (internal_data
->is_cache_policy_override_set())
2828 request
.setCachePolicy(internal_data
->cache_policy_override());
2830 // The request's extra data may indicate that we should set a custom user
2831 // agent. This needs to be done here, after WebKit is through with setting the
2832 // user agent on its own. Similarly, it may indicate that we should set an
2833 // X-Requested-With header. This must be done here to avoid breaking CORS
2835 // PlzNavigate: there may also be a stream url associated with the request.
2836 WebString custom_user_agent
;
2837 WebString requested_with
;
2838 scoped_ptr
<StreamOverrideParameters
> stream_override
;
2839 if (request
.extraData()) {
2840 RequestExtraData
* old_extra_data
=
2841 static_cast<RequestExtraData
*>(request
.extraData());
2843 custom_user_agent
= old_extra_data
->custom_user_agent();
2844 if (!custom_user_agent
.isNull()) {
2845 if (custom_user_agent
.isEmpty())
2846 request
.clearHTTPHeaderField("User-Agent");
2848 request
.setHTTPHeaderField("User-Agent", custom_user_agent
);
2851 requested_with
= old_extra_data
->requested_with();
2852 if (!requested_with
.isNull()) {
2853 if (requested_with
.isEmpty())
2854 request
.clearHTTPHeaderField("X-Requested-With");
2856 request
.setHTTPHeaderField("X-Requested-With", requested_with
);
2858 stream_override
= old_extra_data
->TakeStreamOverrideOwnership();
2861 // Add the default accept header for frame request if it has not been set
2863 if ((request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
2864 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) &&
2865 request
.httpHeaderField(WebString::fromUTF8(kAcceptHeader
)).isEmpty()) {
2866 request
.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader
),
2867 WebString::fromUTF8(kDefaultAcceptHeader
));
2870 // Add an empty HTTP origin header for non GET methods if none is currently
2872 request
.addHTTPOriginIfNeeded(WebString());
2874 // Attach |should_replace_current_entry| state to requests so that, should
2875 // this navigation later require a request transfer, all state is preserved
2876 // when it is re-created in the new process.
2877 bool should_replace_current_entry
= false;
2878 if (navigation_state
->is_content_initiated()) {
2879 should_replace_current_entry
= data_source
->replacesCurrentHistoryItem();
2881 // If the navigation is browser-initiated, the NavigationState contains the
2882 // correct value instead of the WebDataSource.
2884 // TODO(davidben): Avoid this awkward duplication of state. See comment on
2885 // NavigationState::should_replace_current_entry().
2886 should_replace_current_entry
=
2887 navigation_state
->should_replace_current_entry();
2890 int provider_id
= kInvalidServiceWorkerProviderId
;
2891 if (request
.frameType() == blink::WebURLRequest::FrameTypeTopLevel
||
2892 request
.frameType() == blink::WebURLRequest::FrameTypeNested
) {
2893 // |provisionalDataSource| may be null in some content::ResourceFetcher
2894 // use cases, we don't hook those requests.
2895 if (frame
->provisionalDataSource()) {
2896 ServiceWorkerNetworkProvider
* provider
=
2897 ServiceWorkerNetworkProvider::FromDocumentState(
2898 DocumentState::FromDataSource(frame
->provisionalDataSource()));
2899 provider_id
= provider
->provider_id();
2901 } else if (frame
->dataSource()) {
2902 ServiceWorkerNetworkProvider
* provider
=
2903 ServiceWorkerNetworkProvider::FromDocumentState(
2904 DocumentState::FromDataSource(frame
->dataSource()));
2905 provider_id
= provider
->provider_id();
2908 WebFrame
* parent
= frame
->parent();
2909 int parent_routing_id
= MSG_ROUTING_NONE
;
2911 parent_routing_id
= -1;
2912 } else if (parent
->isWebLocalFrame()) {
2913 parent_routing_id
= FromWebFrame(parent
)->GetRoutingID();
2915 parent_routing_id
= RenderFrameProxy::FromWebFrame(parent
)->routing_id();
2918 RequestExtraData
* extra_data
= new RequestExtraData();
2919 extra_data
->set_visibility_state(render_view_
->visibilityState());
2920 extra_data
->set_custom_user_agent(custom_user_agent
);
2921 extra_data
->set_requested_with(requested_with
);
2922 extra_data
->set_render_frame_id(routing_id_
);
2923 extra_data
->set_is_main_frame(frame
== top_frame
);
2924 extra_data
->set_frame_origin(
2925 GURL(frame
->document().securityOrigin().toString()));
2926 extra_data
->set_parent_is_main_frame(frame
->parent() == top_frame
);
2927 extra_data
->set_parent_render_frame_id(parent_routing_id
);
2928 extra_data
->set_allow_download(navigation_state
->allow_download());
2929 extra_data
->set_transition_type(transition_type
);
2930 extra_data
->set_should_replace_current_entry(should_replace_current_entry
);
2931 extra_data
->set_transferred_request_child_id(
2932 navigation_state
->transferred_request_child_id());
2933 extra_data
->set_transferred_request_request_id(
2934 navigation_state
->transferred_request_request_id());
2935 extra_data
->set_service_worker_provider_id(provider_id
);
2936 extra_data
->set_stream_override(stream_override
.Pass());
2937 request
.setExtraData(extra_data
);
2939 DocumentState
* top_document_state
=
2940 DocumentState::FromDataSource(top_data_source
);
2941 if (top_document_state
) {
2942 // TODO(gavinp): separate out prefetching and prerender field trials
2943 // if the rel=prerender rel type is sticking around.
2944 if (request
.requestContext() == WebURLRequest::RequestContextPrefetch
)
2945 top_document_state
->set_was_prefetcher(true);
2948 // This is an instance where we embed a copy of the routing id
2949 // into the data portion of the message. This can cause problems if we
2950 // don't register this id on the browser side, since the download manager
2951 // expects to find a RenderViewHost based off the id.
2952 request
.setRequestorID(render_view_
->GetRoutingID());
2953 request
.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
2955 if (!navigation_state
->extra_headers().empty()) {
2956 for (net::HttpUtil::HeadersIterator
i(
2957 navigation_state
->extra_headers().begin(),
2958 navigation_state
->extra_headers().end(), "\n");
2960 if (LowerCaseEqualsASCII(i
.name(), "referer")) {
2961 WebString referrer
= WebSecurityPolicy::generateReferrerHeader(
2962 blink::WebReferrerPolicyDefault
,
2964 WebString::fromUTF8(i
.values()));
2965 request
.setHTTPReferrer(referrer
, blink::WebReferrerPolicyDefault
);
2967 request
.setHTTPHeaderField(WebString::fromUTF8(i
.name()),
2968 WebString::fromUTF8(i
.values()));
2973 if (!render_view_
->renderer_preferences_
.enable_referrers
)
2974 request
.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault
);
2977 void RenderFrameImpl::didReceiveResponse(
2978 blink::WebLocalFrame
* frame
,
2979 unsigned identifier
,
2980 const blink::WebURLResponse
& response
) {
2981 DCHECK(!frame_
|| frame_
== frame
);
2982 // Only do this for responses that correspond to a provisional data source
2983 // of the top-most frame. If we have a provisional data source, then we
2984 // can't have any sub-resources yet, so we know that this response must
2985 // correspond to a frame load.
2986 if (!frame
->provisionalDataSource() || frame
->parent())
2989 // If we are in view source mode, then just let the user see the source of
2990 // the server's error page.
2991 if (frame
->isViewSourceModeEnabled())
2994 DocumentState
* document_state
=
2995 DocumentState::FromDataSource(frame
->provisionalDataSource());
2996 int http_status_code
= response
.httpStatusCode();
2998 // Record page load flags.
2999 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3001 document_state
->set_was_fetched_via_spdy(
3002 extra_data
->was_fetched_via_spdy());
3003 document_state
->set_was_npn_negotiated(
3004 extra_data
->was_npn_negotiated());
3005 document_state
->set_npn_negotiated_protocol(
3006 extra_data
->npn_negotiated_protocol());
3007 document_state
->set_was_alternate_protocol_available(
3008 extra_data
->was_alternate_protocol_available());
3009 document_state
->set_connection_info(
3010 extra_data
->connection_info());
3011 document_state
->set_was_fetched_via_proxy(
3012 extra_data
->was_fetched_via_proxy());
3013 document_state
->set_proxy_server(
3014 extra_data
->proxy_server());
3016 InternalDocumentStateData
* internal_data
=
3017 InternalDocumentStateData::FromDocumentState(document_state
);
3018 internal_data
->set_http_status_code(http_status_code
);
3019 // Whether or not the http status code actually corresponds to an error is
3020 // only checked when the page is done loading, if |use_error_page| is
3022 internal_data
->set_use_error_page(true);
3025 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame
* frame
,
3026 unsigned identifier
) {
3027 DCHECK(!frame_
|| frame_
== frame
);
3028 InternalDocumentStateData
* internal_data
=
3029 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3030 if (!internal_data
->use_error_page())
3033 // Do not show error page when DevTools is attached.
3034 if (render_view_
->devtools_agent_
->IsAttached())
3037 // Display error page, if appropriate.
3038 std::string error_domain
= "http";
3039 int http_status_code
= internal_data
->http_status_code();
3040 if (GetContentClient()->renderer()->HasErrorPage(
3041 http_status_code
, &error_domain
)) {
3043 error
.unreachableURL
= frame
->document().url();
3044 error
.domain
= WebString::fromUTF8(error_domain
);
3045 error
.reason
= http_status_code
;
3046 LoadNavigationErrorPage(frame
->dataSource()->request(), error
, true);
3050 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3051 blink::WebLocalFrame
* frame
,
3052 const blink::WebURLRequest
& request
,
3053 const blink::WebURLResponse
& response
) {
3054 DCHECK(!frame_
|| frame_
== frame
);
3055 // The recipients of this message have no use for data: URLs: they don't
3056 // affect the page's insecure content list and are not in the disk cache. To
3057 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3058 // filter them out here.
3059 GURL
url(request
.url());
3060 if (url
.SchemeIs(url::kDataScheme
))
3063 // Let the browser know we loaded a resource from the memory cache. This
3064 // message is needed to display the correct SSL indicators.
3065 render_view_
->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3066 render_view_
->GetRoutingID(),
3068 response
.securityInfo(),
3069 request
.httpMethod().utf8(),
3070 response
.mimeType().utf8(),
3071 WebURLRequestToResourceType(request
)));
3074 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame
* frame
) {
3075 DCHECK(!frame_
|| frame_
== frame
);
3076 render_view_
->Send(new ViewHostMsg_DidDisplayInsecureContent(
3077 render_view_
->GetRoutingID()));
3080 void RenderFrameImpl::didRunInsecureContent(
3081 blink::WebLocalFrame
* frame
,
3082 const blink::WebSecurityOrigin
& origin
,
3083 const blink::WebURL
& target
) {
3084 DCHECK(!frame_
|| frame_
== frame
);
3085 render_view_
->Send(new ViewHostMsg_DidRunInsecureContent(
3086 render_view_
->GetRoutingID(),
3087 origin
.toString().utf8(),
3091 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame
* frame
) {
3092 DCHECK(!frame_
|| frame_
== frame
);
3093 #if defined(ENABLE_PLUGINS)
3094 if (frame
!= render_view_
->webview()->mainFrame())
3096 PluginChannelHost::Broadcast(
3097 new PluginHostMsg_DidAbortLoading(render_view_
->GetRoutingID()));
3101 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame
* frame
,
3102 v8::Handle
<v8::Context
> context
,
3103 int extension_group
,
3105 DCHECK(!frame_
|| frame_
== frame
);
3106 GetContentClient()->renderer()->DidCreateScriptContext(
3107 frame
, context
, extension_group
, world_id
);
3110 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame
* frame
,
3111 v8::Handle
<v8::Context
> context
,
3113 DCHECK(!frame_
|| frame_
== frame
);
3115 FOR_EACH_OBSERVER(RenderFrameObserver
,
3117 WillReleaseScriptContext(context
, world_id
));
3120 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3121 blink::WebLocalFrame
* frame
) {
3122 DCHECK(!frame_
|| frame_
== frame
);
3123 if (frame
->parent())
3126 InternalDocumentStateData
* data
=
3127 InternalDocumentStateData::FromDataSource(frame
->dataSource());
3128 data
->set_did_first_visually_non_empty_layout(true);
3130 #if defined(OS_ANDROID)
3131 GetRenderWidget()->DidChangeBodyBackgroundColor(
3132 render_view_
->webwidget_
->backgroundColor());
3135 GetRenderWidget()->QueueMessage(
3136 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_
),
3137 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE
);
3140 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame
* frame
) {
3141 DCHECK(!frame_
|| frame_
== frame
);
3142 // TODO(nasko): Move implementation here. Needed methods:
3143 // * StartNavStateSyncTimerIfNecessary
3144 render_view_
->didChangeScrollOffset(frame
);
3147 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame
* frame
) {
3148 DCHECK(!frame_
|| frame_
== frame
);
3149 if (!frame
->parent()) {
3150 render_view_
->Send(new ViewHostMsg_WillInsertBody(
3151 render_view_
->GetRoutingID()));
3155 void RenderFrameImpl::reportFindInPageMatchCount(int request_id
,
3157 bool final_update
) {
3158 int active_match_ordinal
= -1; // -1 = don't update active match ordinal
3160 active_match_ordinal
= 0;
3162 render_view_
->Send(new ViewHostMsg_Find_Reply(
3163 render_view_
->GetRoutingID(), request_id
, count
,
3164 gfx::Rect(), active_match_ordinal
, final_update
));
3167 void RenderFrameImpl::reportFindInPageSelection(
3169 int active_match_ordinal
,
3170 const blink::WebRect
& selection_rect
) {
3171 render_view_
->Send(new ViewHostMsg_Find_Reply(
3172 render_view_
->GetRoutingID(), request_id
, -1, selection_rect
,
3173 active_match_ordinal
, false));
3176 void RenderFrameImpl::requestStorageQuota(
3177 blink::WebLocalFrame
* frame
,
3178 blink::WebStorageQuotaType type
,
3179 unsigned long long requested_size
,
3180 blink::WebStorageQuotaCallbacks callbacks
) {
3181 DCHECK(!frame_
|| frame_
== frame
);
3182 WebSecurityOrigin origin
= frame
->document().securityOrigin();
3183 if (origin
.isUnique()) {
3184 // Unique origins cannot store persistent state.
3185 callbacks
.didFail(blink::WebStorageQuotaErrorAbort
);
3188 ChildThread::current()->quota_dispatcher()->RequestStorageQuota(
3189 render_view_
->GetRoutingID(),
3190 GURL(origin
.toString()),
3191 static_cast<storage::StorageType
>(type
),
3193 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks
));
3196 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle
* handle
) {
3197 WebSocketBridge
* impl
= static_cast<WebSocketBridge
*>(handle
);
3198 impl
->set_render_frame_id(routing_id_
);
3201 blink::WebGeolocationClient
* RenderFrameImpl::geolocationClient() {
3202 if (!geolocation_dispatcher_
)
3203 geolocation_dispatcher_
= new GeolocationDispatcher(this);
3204 return geolocation_dispatcher_
;
3207 blink::WebPushClient
* RenderFrameImpl::pushClient() {
3208 if (!push_messaging_dispatcher_
)
3209 push_messaging_dispatcher_
= new PushMessagingDispatcher(this);
3210 return push_messaging_dispatcher_
;
3213 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3214 blink::WebLocalFrame
* frame
,
3215 blink::WebRTCPeerConnectionHandler
* handler
) {
3216 DCHECK(!frame_
|| frame_
== frame
);
3217 #if defined(ENABLE_WEBRTC)
3218 static_cast<RTCPeerConnectionHandler
*>(handler
)->associateWithFrame(frame
);
3222 blink::WebUserMediaClient
* RenderFrameImpl::userMediaClient() {
3223 if (!web_user_media_client_
)
3224 InitializeUserMediaClient();
3225 return web_user_media_client_
;
3228 blink::WebMIDIClient
* RenderFrameImpl::webMIDIClient() {
3229 if (!midi_dispatcher_
)
3230 midi_dispatcher_
= new MidiDispatcher(this);
3231 return midi_dispatcher_
;
3234 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3235 blink::WebLocalFrame
* source_frame
,
3236 blink::WebFrame
* target_frame
,
3237 blink::WebSecurityOrigin target_origin
,
3238 blink::WebDOMMessageEvent event
) {
3239 DCHECK(!frame_
|| frame_
== target_frame
);
3241 if (!is_swapped_out_
)
3244 ViewMsg_PostMessage_Params params
;
3245 params
.is_data_raw_string
= false;
3246 params
.data
= event
.data().toString();
3247 params
.source_origin
= event
.origin();
3248 if (!target_origin
.isNull())
3249 params
.target_origin
= target_origin
.toString();
3251 blink::WebMessagePortChannelArray channels
= event
.releaseChannels();
3252 if (!channels
.isEmpty()) {
3253 std::vector
<int> message_port_ids(channels
.size());
3254 // Extract the port IDs from the channel array.
3255 for (size_t i
= 0; i
< channels
.size(); ++i
) {
3256 WebMessagePortChannelImpl
* webchannel
=
3257 static_cast<WebMessagePortChannelImpl
*>(channels
[i
]);
3258 message_port_ids
[i
] = webchannel
->message_port_id();
3259 webchannel
->QueueMessages();
3260 DCHECK_NE(message_port_ids
[i
], MSG_ROUTING_NONE
);
3262 params
.message_port_ids
= message_port_ids
;
3265 // Include the routing ID for the source frame (if one exists), which the
3266 // browser process will translate into the routing ID for the equivalent
3267 // frame in the target process.
3268 params
.source_routing_id
= MSG_ROUTING_NONE
;
3270 RenderViewImpl
* source_view
=
3271 RenderViewImpl::FromWebView(source_frame
->view());
3273 params
.source_routing_id
= source_view
->routing_id();
3276 Send(new ViewHostMsg_RouteMessageEvent(render_view_
->routing_id_
, params
));
3280 blink::WebString
RenderFrameImpl::userAgentOverride(blink::WebLocalFrame
* frame
,
3281 const blink::WebURL
& url
) {
3282 DCHECK(!frame_
|| frame_
== frame
);
3283 std::string user_agent_override_for_url
=
3284 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url
));
3285 if (!user_agent_override_for_url
.empty())
3286 return WebString::fromUTF8(user_agent_override_for_url
);
3288 if (!render_view_
->webview() || !render_view_
->webview()->mainFrame() ||
3289 render_view_
->renderer_preferences_
.user_agent_override
.empty()) {
3290 return blink::WebString();
3293 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3294 // associated with it, so the checks below are not valid. Temporarily
3295 // return early and fix properly as part of https://crbug.com/426555.
3296 if (render_view_
->webview()->mainFrame()->isWebRemoteFrame())
3297 return blink::WebString();
3299 // If we're in the middle of committing a load, the data source we need
3300 // will still be provisional.
3301 WebFrame
* main_frame
= render_view_
->webview()->mainFrame();
3302 WebDataSource
* data_source
= NULL
;
3303 if (main_frame
->provisionalDataSource())
3304 data_source
= main_frame
->provisionalDataSource();
3306 data_source
= main_frame
->dataSource();
3308 InternalDocumentStateData
* internal_data
= data_source
?
3309 InternalDocumentStateData::FromDataSource(data_source
) : NULL
;
3310 if (internal_data
&& internal_data
->is_overriding_user_agent())
3311 return WebString::fromUTF8(
3312 render_view_
->renderer_preferences_
.user_agent_override
);
3313 return blink::WebString();
3316 blink::WebString
RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame
* frame
) {
3317 DCHECK(!frame_
|| frame_
== frame
);
3318 if (render_view_
->renderer_preferences_
.enable_do_not_track
)
3319 return WebString::fromUTF8("1");
3323 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame
* frame
,
3324 bool default_value
) {
3325 DCHECK(!frame_
|| frame_
== frame
);
3329 bool blocked
= true;
3330 render_view_
->Send(new ViewHostMsg_Are3DAPIsBlocked(
3331 render_view_
->GetRoutingID(),
3332 GURL(frame
->top()->document().securityOrigin().toString()),
3333 THREE_D_API_TYPE_WEBGL
,
3338 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame
* frame
,
3339 int arb_robustness_status_code
) {
3340 DCHECK(!frame_
|| frame_
== frame
);
3341 render_view_
->Send(new ViewHostMsg_DidLose3DContext(
3342 GURL(frame
->top()->document().securityOrigin().toString()),
3343 THREE_D_API_TYPE_WEBGL
,
3344 arb_robustness_status_code
));
3347 blink::WebScreenOrientationClient
*
3348 RenderFrameImpl::webScreenOrientationClient() {
3349 if (!screen_orientation_dispatcher_
)
3350 screen_orientation_dispatcher_
= new ScreenOrientationDispatcher(this);
3351 return screen_orientation_dispatcher_
;
3354 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource
& data_source
) {
3355 ServiceWorkerNetworkProvider
* provider
=
3356 ServiceWorkerNetworkProvider::FromDocumentState(
3357 DocumentState::FromDataSource(&data_source
));
3358 return provider
->context()->controller_handle_id() !=
3359 kInvalidServiceWorkerHandleId
;
3362 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource
& data_source
) {
3363 ServiceWorkerNetworkProvider
* provider
=
3364 ServiceWorkerNetworkProvider::FromDocumentState(
3365 DocumentState::FromDataSource(&data_source
));
3367 if (provider
->context()->controller())
3368 return provider
->context()->controller()->version_id();
3369 return kInvalidServiceWorkerVersionId
;
3372 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject
& obj
,
3373 blink::WebAXEvent event
) {
3374 HandleWebAccessibilityEvent(obj
, event
);
3377 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3380 const blink::WebAXObject
& start_object
,
3382 const blink::WebAXObject
& end_object
,
3384 if (renderer_accessibility_
) {
3385 renderer_accessibility_
->HandleAccessibilityFindInPageResult(
3386 identifier
, match_index
, start_object
, start_offset
,
3387 end_object
, end_offset
);
3391 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame
* frame
)
3393 DCHECK(!frame_
|| frame_
== frame
);
3395 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, DidChangeManifest());
3398 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer
* player
) {
3399 Send(new FrameHostMsg_MediaPlayingNotification(
3400 routing_id_
, reinterpret_cast<int64
>(player
), player
->hasVideo(),
3401 player
->hasAudio(), player
->isRemote()));
3404 void RenderFrameImpl::DidPause(blink::WebMediaPlayer
* player
) {
3405 Send(new FrameHostMsg_MediaPausedNotification(
3406 routing_id_
, reinterpret_cast<int64
>(player
)));
3409 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer
* player
) {
3413 void RenderFrameImpl::AddObserver(RenderFrameObserver
* observer
) {
3414 observers_
.AddObserver(observer
);
3417 void RenderFrameImpl::RemoveObserver(RenderFrameObserver
* observer
) {
3418 observer
->RenderFrameGone();
3419 observers_
.RemoveObserver(observer
);
3422 void RenderFrameImpl::OnStop() {
3424 frame_
->stopLoading();
3425 if (!frame_
->parent())
3426 FOR_EACH_OBSERVER(RenderViewObserver
, render_view_
->observers_
, OnStop());
3428 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, OnStop());
3431 void RenderFrameImpl::WasHidden() {
3432 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasHidden());
3435 void RenderFrameImpl::WasShown() {
3436 FOR_EACH_OBSERVER(RenderFrameObserver
, observers_
, WasShown());
3439 bool RenderFrameImpl::IsHidden() {
3440 return GetRenderWidget()->is_hidden();
3443 // Tell the embedding application that the URL of the active page has changed.
3444 void RenderFrameImpl::SendDidCommitProvisionalLoad(blink::WebFrame
* frame
) {
3445 DCHECK(!frame_
|| frame_
== frame
);
3446 WebDataSource
* ds
= frame
->dataSource();
3449 const WebURLRequest
& request
= ds
->request();
3450 const WebURLResponse
& response
= ds
->response();
3452 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3453 NavigationState
* navigation_state
= document_state
->navigation_state();
3454 InternalDocumentStateData
* internal_data
=
3455 InternalDocumentStateData::FromDocumentState(document_state
);
3457 FrameHostMsg_DidCommitProvisionalLoad_Params params
;
3458 params
.http_status_code
= response
.httpStatusCode();
3459 params
.url_is_unreachable
= ds
->hasUnreachableURL();
3460 params
.is_post
= false;
3461 params
.post_id
= -1;
3462 params
.page_id
= render_view_
->page_id_
;
3463 // We need to track the RenderViewHost routing_id because of downstream
3464 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3465 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3466 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3467 // based on the ID stored in the resource requests. Once those dependencies
3468 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3469 // client to be based on the routing_id of the RenderFrameHost.
3470 params
.render_view_routing_id
= render_view_
->routing_id();
3471 params
.socket_address
.set_host(response
.remoteIPAddress().utf8());
3472 params
.socket_address
.set_port(response
.remotePort());
3473 WebURLResponseExtraDataImpl
* extra_data
= GetExtraDataFromResponse(response
);
3475 params
.was_fetched_via_proxy
= extra_data
->was_fetched_via_proxy();
3476 params
.was_within_same_page
= navigation_state
->was_within_same_page();
3477 params
.security_info
= response
.securityInfo();
3479 // Set the URL to be displayed in the browser UI to the user.
3480 params
.url
= GetLoadingUrl();
3481 DCHECK(!is_swapped_out_
|| params
.url
== GURL(kSwappedOutURL
));
3483 if (frame
->document().baseURL() != params
.url
)
3484 params
.base_url
= frame
->document().baseURL();
3486 GetRedirectChain(ds
, ¶ms
.redirects
);
3487 params
.should_update_history
= !ds
->hasUnreachableURL() &&
3488 !response
.isMultipartPayload() && (response
.httpStatusCode() != 404);
3490 params
.searchable_form_url
= internal_data
->searchable_form_url();
3491 params
.searchable_form_encoding
= internal_data
->searchable_form_encoding();
3493 params
.gesture
= render_view_
->navigation_gesture_
;
3494 render_view_
->navigation_gesture_
= NavigationGestureUnknown
;
3496 // Make navigation state a part of the DidCommitProvisionalLoad message so
3497 // that commited entry has it at all times.
3498 HistoryEntry
* entry
= render_view_
->history_controller()->GetCurrentEntry();
3500 params
.page_state
= HistoryEntryToPageState(entry
);
3502 params
.page_state
= PageState::CreateFromURL(request
.url());
3504 if (!frame
->parent()) {
3505 // Top-level navigation.
3507 // Reset the zoom limits in case a plugin had changed them previously. This
3508 // will also call us back which will cause us to send a message to
3509 // update WebContentsImpl.
3510 render_view_
->webview()->zoomLimitsChanged(
3511 ZoomFactorToZoomLevel(kMinimumZoomFactor
),
3512 ZoomFactorToZoomLevel(kMaximumZoomFactor
));
3514 // Set zoom level, but don't do it for full-page plugin since they don't use
3515 // the same zoom settings.
3516 HostZoomLevels::iterator host_zoom
=
3517 render_view_
->host_zoom_levels_
.find(GURL(request
.url()));
3518 if (render_view_
->webview()->mainFrame()->document().isPluginDocument()) {
3519 // Reset the zoom levels for plugins.
3520 render_view_
->webview()->setZoomLevel(0);
3522 // If the zoom level is not found, then do nothing. In-page navigation
3523 // relies on not changing the zoom level in this case.
3524 if (host_zoom
!= render_view_
->host_zoom_levels_
.end())
3525 render_view_
->webview()->setZoomLevel(host_zoom
->second
);
3528 if (host_zoom
!= render_view_
->host_zoom_levels_
.end()) {
3529 // This zoom level was merely recorded transiently for this load. We can
3530 // erase it now. If at some point we reload this page, the browser will
3531 // send us a new, up-to-date zoom level.
3532 render_view_
->host_zoom_levels_
.erase(host_zoom
);
3535 // Update contents MIME type for main frame.
3536 params
.contents_mime_type
= ds
->response().mimeType().utf8();
3538 params
.transition
= navigation_state
->transition_type();
3539 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
3540 // If the main frame does a load, it should not be reported as a subframe
3541 // navigation. This can occur in the following case:
3542 // 1. You're on a site with frames.
3543 // 2. You do a subframe navigation. This is stored with transition type
3545 // 3. You navigate to some non-frame site, say, google.com.
3546 // 4. You navigate back to the page from step 2. Since it was initially
3547 // MANUAL_SUBFRAME, it will be that same transition type here.
3548 // We don't want that, because any navigation that changes the toplevel
3549 // frame should be tracked as a toplevel navigation (this allows us to
3550 // update the URL bar, etc).
3551 params
.transition
= ui::PAGE_TRANSITION_LINK
;
3554 // If the page contained a client redirect (meta refresh, document.loc...),
3555 // set the referrer and transition appropriately.
3556 if (ds
->isClientRedirect()) {
3558 Referrer(params
.redirects
[0], ds
->request().referrerPolicy());
3559 params
.transition
= ui::PageTransitionFromInt(
3560 params
.transition
| ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
3562 params
.referrer
= RenderViewImpl::GetReferrerFromRequest(
3563 frame
, ds
->request());
3566 base::string16 method
= request
.httpMethod();
3567 if (EqualsASCII(method
, "POST")) {
3568 params
.is_post
= true;
3569 params
.post_id
= ExtractPostId(entry
->root());
3572 // Send the user agent override back.
3573 params
.is_overriding_user_agent
= internal_data
->is_overriding_user_agent();
3575 // Track the URL of the original request. We use the first entry of the
3576 // redirect chain if it exists because the chain may have started in another
3578 params
.original_request_url
= GetOriginalRequestURL(ds
);
3580 params
.history_list_was_cleared
=
3581 navigation_state
->history_list_was_cleared();
3583 // Save some histogram data so we can compute the average memory used per
3584 // page load of the glyphs.
3585 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3586 blink::WebGlyphCache::pageCount());
3588 // This message needs to be sent before any of allowScripts(),
3589 // allowImages(), allowPlugins() is called for the new page, so that when
3590 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3591 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3592 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3594 // Subframe navigation: the type depends on whether this navigation
3595 // generated a new session history entry. When they do generate a session
3596 // history entry, it means the user initiated the navigation and we should
3597 // mark it as such. This test checks if this is the first time
3598 // SendDidCommitProvisionalLoad has been called since WillNavigateToURL was
3599 // called to initiate the load.
3600 if (render_view_
->page_id_
> render_view_
->last_page_id_sent_to_browser_
)
3601 params
.transition
= ui::PAGE_TRANSITION_MANUAL_SUBFRAME
;
3603 params
.transition
= ui::PAGE_TRANSITION_AUTO_SUBFRAME
;
3605 DCHECK(!navigation_state
->history_list_was_cleared());
3606 params
.history_list_was_cleared
= false;
3608 // Don't send this message while the subframe is swapped out.
3609 if (!is_swapped_out())
3610 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_
, params
));
3613 render_view_
->last_page_id_sent_to_browser_
=
3614 std::max(render_view_
->last_page_id_sent_to_browser_
,
3615 render_view_
->page_id_
);
3617 // If we end up reusing this WebRequest (for example, due to a #ref click),
3618 // we don't want the transition type to persist. Just clear it.
3619 navigation_state
->set_transition_type(ui::PAGE_TRANSITION_LINK
);
3622 WebElement
RenderFrameImpl::GetFocusedElement() {
3623 WebDocument doc
= frame_
->document();
3625 return doc
.focusedElement();
3627 return WebElement();
3630 void RenderFrameImpl::didStartLoading(bool to_different_document
) {
3631 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3633 render_view_
->FrameDidStartLoading(frame_
);
3634 Send(new FrameHostMsg_DidStartLoading(routing_id_
, to_different_document
));
3637 void RenderFrameImpl::didStopLoading() {
3638 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3640 render_view_
->FrameDidStopLoading(frame_
);
3641 Send(new FrameHostMsg_DidStopLoading(routing_id_
));
3644 void RenderFrameImpl::didChangeLoadProgress(double load_progress
) {
3645 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_
, load_progress
));
3648 void RenderFrameImpl::HandleWebAccessibilityEvent(
3649 const blink::WebAXObject
& obj
, blink::WebAXEvent event
) {
3650 if (renderer_accessibility_
)
3651 renderer_accessibility_
->HandleWebAccessibilityEvent(obj
, event
);
3654 void RenderFrameImpl::FocusedNodeChanged(const WebNode
& node
) {
3655 if (renderer_accessibility_
)
3656 renderer_accessibility_
->FocusedNodeChanged(node
);
3660 void RenderFrameImpl::OnRequestNavigation(
3661 const CommonNavigationParams
& common_params
,
3662 const RequestNavigationParams
& request_params
) {
3663 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3664 switches::kEnableBrowserSideNavigation
));
3665 WebURLRequest request
=
3666 CreateURLRequestForNavigation(common_params
,
3668 scoped_ptr
<StreamOverrideParameters
>(),
3669 frame_
->isViewSourceModeEnabled());
3670 BeginNavigation(&request
);
3674 void RenderFrameImpl::OnCommitNavigation(
3675 const ResourceResponseHead
& response
,
3676 const GURL
& stream_url
,
3677 const CommonNavigationParams
& common_params
,
3678 const CommitNavigationParams
& commit_params
) {
3679 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3680 switches::kEnableBrowserSideNavigation
));
3681 bool is_reload
= false;
3682 WebURLRequest::CachePolicy cache_policy
=
3683 WebURLRequest::UseProtocolCachePolicy
;
3684 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3685 common_params
.url
, common_params
.navigation_type
,
3686 commit_params
.page_state
, false, -1, -1, &is_reload
, &cache_policy
)) {
3690 GetContentClient()->SetActiveURL(common_params
.url
);
3692 // Create a WebURLRequest that blink can use to get access to the body of the
3693 // response through a stream in the browser. Blink will then commit the
3695 // TODO(clamy): Have the navigation commit directly, without going through
3696 // loading a WebURLRequest.
3697 scoped_ptr
<StreamOverrideParameters
> stream_override(
3698 new StreamOverrideParameters());
3699 stream_override
->stream_url
= stream_url
;
3700 stream_override
->response
= response
;
3701 WebURLRequest request
=
3702 CreateURLRequestForNavigation(common_params
,
3703 RequestNavigationParams(),
3704 stream_override
.Pass(),
3705 frame_
->isViewSourceModeEnabled());
3707 // Make sure that blink loader will not try to use browser side navigation for
3708 // this request (since it already went to the browser).
3709 request
.setCheckForBrowserSideNavigation(false);
3711 // Record this before starting the load. A lower bound of this time is needed
3712 // to sanitize the navigationStart override set below.
3713 base::TimeTicks renderer_navigation_start
= base::TimeTicks::Now();
3714 frame_
->loadRequest(request
);
3715 UpdateFrameNavigationTiming(
3716 frame_
, commit_params
.browser_navigation_start
,
3717 renderer_navigation_start
);
3720 WebNavigationPolicy
RenderFrameImpl::DecidePolicyForNavigation(
3721 RenderFrame
* render_frame
,
3722 const NavigationPolicyInfo
& info
) {
3724 // The handlenavigation API is deprecated and will be removed once
3725 // crbug.com/325351 is resolved.
3726 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
) &&
3727 GetContentClient()->renderer()->HandleNavigation(
3729 static_cast<DocumentState
*>(info
.extraData
),
3730 render_view_
->opener_id_
,
3733 info
.navigationType
,
3736 return blink::WebNavigationPolicyIgnore
;
3740 Referrer
referrer(RenderViewImpl::GetReferrerFromRequest(info
.frame
,
3742 const CommandLine
& command_line
= *CommandLine::ForCurrentProcess();
3744 bool is_subframe
= !!info
.frame
->parent();
3746 if (command_line
.HasSwitch(switches::kSitePerProcess
) && is_subframe
) {
3747 // There's no reason to ignore navigations on subframes, since the swap out
3748 // logic no longer applies.
3750 if (is_swapped_out_
) {
3751 if (info
.urlRequest
.url() != GURL(kSwappedOutURL
)) {
3752 // Targeted links may try to navigate a swapped out frame. Allow the
3753 // browser process to navigate the tab instead. Note that it is also
3754 // possible for non-targeted navigations (from this view) to arrive
3755 // here just after we are swapped out. It's ok to send them to the
3756 // browser, as long as they're for the top level frame.
3757 // TODO(creis): Ensure this supports targeted form submissions when
3758 // fixing http://crbug.com/101395.
3759 if (info
.frame
->parent() == NULL
) {
3760 OpenURL(info
.frame
, info
.urlRequest
.url(), referrer
,
3761 info
.defaultPolicy
);
3762 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3765 // We should otherwise ignore in-process iframe navigations, if they
3766 // arrive just after we are swapped out.
3767 return blink::WebNavigationPolicyIgnore
;
3770 // Allow kSwappedOutURL to complete.
3771 return info
.defaultPolicy
;
3775 // Webkit is asking whether to navigate to a new URL.
3776 // This is fine normally, except if we're showing UI from one security
3777 // context and they're trying to navigate to a different context.
3778 const GURL
& url
= info
.urlRequest
.url();
3780 // A content initiated navigation may have originated from a link-click,
3781 // script, drag-n-drop operation, etc.
3782 bool is_content_initiated
= static_cast<DocumentState
*>(info
.extraData
)->
3783 navigation_state()->is_content_initiated();
3786 // If --enable-strict-site-isolation is enabled, send all top-level
3787 // navigations to the browser to let it swap processes when crossing site
3788 // boundaries. This is currently expected to break some script calls and
3789 // navigations, such as form submissions.
3790 bool force_swap_due_to_flag
=
3791 command_line
.HasSwitch(switches::kEnableStrictSiteIsolation
);
3792 if (force_swap_due_to_flag
&&
3793 !info
.frame
->parent() && (is_content_initiated
|| info
.isRedirect
)) {
3794 WebString origin_str
= info
.frame
->document().securityOrigin().toString();
3795 GURL
frame_url(origin_str
.utf8().data());
3796 // TODO(cevans): revisit whether this site check is still necessary once
3797 // crbug.com/101395 is fixed.
3798 bool same_domain_or_host
=
3799 net::registry_controlled_domains::SameDomainOrHost(
3802 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES
);
3803 // Only keep same-site (domain + scheme) and data URLs in the same process.
3805 (same_domain_or_host
&& frame_url
.scheme() == url
.scheme()) ||
3806 url
.SchemeIs(url::kDataScheme
);
3807 if (!is_same_site
) {
3808 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
3809 return blink::WebNavigationPolicyIgnore
;
3813 // If the browser is interested, then give it a chance to look at the request.
3814 if (is_content_initiated
) {
3816 ((info
.navigationType
== blink::WebNavigationTypeFormSubmitted
) ||
3817 (info
.navigationType
== blink::WebNavigationTypeFormResubmitted
)) &&
3818 EqualsASCII(info
.urlRequest
.httpMethod(), "POST");
3819 bool browser_handles_request
=
3820 render_view_
->renderer_preferences_
3821 .browser_handles_non_local_top_level_requests
3822 && IsNonLocalTopLevelNavigation(url
, info
.frame
, info
.navigationType
,
3824 if (!browser_handles_request
) {
3825 browser_handles_request
= IsTopLevelNavigation(info
.frame
) &&
3826 render_view_
->renderer_preferences_
3827 .browser_handles_all_top_level_requests
;
3830 if (browser_handles_request
) {
3831 OpenURL(info
.frame
, url
, referrer
, info
.defaultPolicy
);
3832 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3836 // Use the frame's original request's URL rather than the document's URL for
3837 // subsequent checks. For a popup, the document's URL may become the opener
3838 // window's URL if the opener has called document.write().
3839 // See http://crbug.com/93517.
3840 GURL
old_url(info
.frame
->dataSource()->request().url());
3842 // Detect when we're crossing a permission-based boundary (e.g. into or out of
3843 // an extension or app origin, leaving a WebUI page, etc). We only care about
3844 // top-level navigations (not iframes). But we sometimes navigate to
3845 // about:blank to clear a tab, and we want to still allow that.
3847 // Note: this is known to break POST submissions when crossing process
3848 // boundaries until http://crbug.com/101395 is fixed. This is better for
3849 // security than loading a WebUI, extension or app page in the wrong process.
3850 // POST requests don't work because this mechanism does not preserve form
3851 // POST data. We will need to send the request's httpBody data up to the
3852 // browser process, and issue a special POST navigation in WebKit (via
3853 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
3854 // for examples of how to send the httpBody data.
3855 if (!info
.frame
->parent() && is_content_initiated
&&
3856 !url
.SchemeIs(url::kAboutScheme
)) {
3857 bool send_referrer
= false;
3859 // All navigations to or from WebUI URLs or within WebUI-enabled
3860 // RenderProcesses must be handled by the browser process so that the
3861 // correct bindings and data sources can be registered.
3862 // Similarly, navigations to view-source URLs or within ViewSource mode
3863 // must be handled by the browser process (except for reloads - those are
3864 // safe to leave within the renderer).
3865 // Lastly, access to file:// URLs from non-file:// URL pages must be
3866 // handled by the browser so that ordinary renderer processes don't get
3867 // blessed with file permissions.
3868 int cumulative_bindings
= RenderProcess::current()->GetEnabledBindings();
3869 bool is_initial_navigation
= render_view_
->page_id_
== -1;
3870 bool should_fork
= HasWebUIScheme(url
) || HasWebUIScheme(old_url
) ||
3871 (cumulative_bindings
& BINDINGS_POLICY_WEB_UI
) ||
3872 url
.SchemeIs(kViewSourceScheme
) ||
3873 (info
.frame
->isViewSourceModeEnabled() &&
3874 info
.navigationType
!= blink::WebNavigationTypeReload
);
3876 if (!should_fork
&& url
.SchemeIs(url::kFileScheme
)) {
3877 // Fork non-file to file opens. Check the opener URL if this is the
3878 // initial navigation in a newly opened window.
3879 GURL
source_url(old_url
);
3880 if (is_initial_navigation
&& source_url
.is_empty() &&
3881 info
.frame
->opener())
3882 source_url
= info
.frame
->opener()->top()->document().url();
3883 DCHECK(!source_url
.is_empty());
3884 should_fork
= !source_url
.SchemeIs(url::kFileScheme
);
3888 // Give the embedder a chance.
3889 should_fork
= GetContentClient()->renderer()->ShouldFork(
3890 info
.frame
, url
, info
.urlRequest
.httpMethod().utf8(),
3891 is_initial_navigation
, info
.isRedirect
, &send_referrer
);
3895 OpenURL(info
.frame
, url
, send_referrer
? referrer
: Referrer(),
3896 info
.defaultPolicy
);
3897 return blink::WebNavigationPolicyIgnore
; // Suppress the load here.
3901 // Detect when a page is "forking" a new tab that can be safely rendered in
3902 // its own process. This is done by sites like Gmail that try to open links
3903 // in new windows without script connections back to the original page. We
3904 // treat such cases as browser navigations (in which we will create a new
3905 // renderer for a cross-site navigation), rather than WebKit navigations.
3907 // We use the following heuristic to decide whether to fork a new page in its
3909 // The parent page must open a new tab to about:blank, set the new tab's
3910 // window.opener to null, and then redirect the tab to a cross-site URL using
3913 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
3916 // Must start from a tab showing about:blank, which is later redirected.
3917 old_url
== GURL(url::kAboutBlankURL
) &&
3918 // Must be the first real navigation of the tab.
3919 render_view_
->historyBackListCount() < 1 &&
3920 render_view_
->historyForwardListCount() < 1 &&
3921 // The parent page must have set the child's window.opener to null before
3922 // redirecting to the desired URL.
3923 info
.frame
->opener() == NULL
&&
3924 // Must be a top-level frame.
3925 info
.frame
->parent() == NULL
&&
3926 // Must not have issued the request from this page.
3927 is_content_initiated
&&
3928 // Must be targeted at the current tab.
3929 info
.defaultPolicy
== blink::WebNavigationPolicyCurrentTab
&&
3930 // Must be a JavaScript navigation, which appears as "other".
3931 info
.navigationType
== blink::WebNavigationTypeOther
;
3934 // Open the URL via the browser, not via WebKit.
3935 OpenURL(info
.frame
, url
, Referrer(), info
.defaultPolicy
);
3936 return blink::WebNavigationPolicyIgnore
;
3939 // PlzNavigate: send the request to the browser if needed.
3940 if (CommandLine::ForCurrentProcess()->HasSwitch(
3941 switches::kEnableBrowserSideNavigation
) &&
3942 info
.urlRequest
.checkForBrowserSideNavigation()) {
3943 BeginNavigation(&info
.urlRequest
);
3944 return blink::WebNavigationPolicyIgnore
;
3947 return info
.defaultPolicy
;
3950 void RenderFrameImpl::OpenURL(WebFrame
* frame
,
3952 const Referrer
& referrer
,
3953 WebNavigationPolicy policy
) {
3954 DCHECK_EQ(frame_
, frame
);
3956 FrameHostMsg_OpenURL_Params params
;
3958 params
.referrer
= referrer
;
3959 params
.disposition
= RenderViewImpl::NavigationPolicyToDisposition(policy
);
3960 WebDataSource
* ds
= frame
->provisionalDataSource();
3962 DocumentState
* document_state
= DocumentState::FromDataSource(ds
);
3963 NavigationState
* navigation_state
= document_state
->navigation_state();
3964 if (navigation_state
->is_content_initiated()) {
3965 params
.should_replace_current_entry
= ds
->replacesCurrentHistoryItem();
3967 // This is necessary to preserve the should_replace_current_entry value on
3968 // cross-process redirects, in the event it was set by a previous process.
3970 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3971 // NavigationState::should_replace_current_entry().
3972 params
.should_replace_current_entry
=
3973 navigation_state
->should_replace_current_entry();
3976 params
.should_replace_current_entry
= false;
3978 params
.user_gesture
= WebUserGestureIndicator::isProcessingUserGesture();
3979 if (GetContentClient()->renderer()->AllowPopup())
3980 params
.user_gesture
= true;
3982 if (policy
== blink::WebNavigationPolicyNewBackgroundTab
||
3983 policy
== blink::WebNavigationPolicyNewForegroundTab
||
3984 policy
== blink::WebNavigationPolicyNewWindow
||
3985 policy
== blink::WebNavigationPolicyNewPopup
) {
3986 WebUserGestureIndicator::consumeUserGesture();
3989 Send(new FrameHostMsg_OpenURL(routing_id_
, params
));
3992 void RenderFrameImpl::UpdateEncoding(WebFrame
* frame
,
3993 const std::string
& encoding_name
) {
3994 // Only update main frame's encoding_name.
3995 if (!frame
->parent())
3996 Send(new FrameHostMsg_UpdateEncoding(routing_id_
, encoding_name
));
3999 void RenderFrameImpl::SyncSelectionIfRequired() {
4000 base::string16 text
;
4003 #if defined(ENABLE_PLUGINS)
4004 if (render_view_
->focused_pepper_plugin_
) {
4005 render_view_
->focused_pepper_plugin_
->GetSurroundingText(&text
, &range
);
4006 offset
= 0; // Pepper API does not support offset reporting.
4007 // TODO(kinaba): cut as needed.
4011 size_t location
, length
;
4012 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4013 &location
, &length
)) {
4017 range
= gfx::Range(location
, location
+ length
);
4019 if (GetRenderWidget()->webwidget()->textInputInfo().type
!=
4020 blink::WebTextInputTypeNone
) {
4021 // If current focused element is editable, we will send 100 more chars
4022 // before and after selection. It is for input method surrounding text
4024 if (location
> kExtraCharsBeforeAndAfterSelection
)
4025 offset
= location
- kExtraCharsBeforeAndAfterSelection
;
4028 length
= location
+ length
- offset
+ kExtraCharsBeforeAndAfterSelection
;
4029 WebRange webrange
= WebRange::fromDocumentRange(frame_
, offset
, length
);
4030 if (!webrange
.isNull())
4031 text
= WebRange::fromDocumentRange(
4032 frame_
, offset
, length
).toPlainText();
4035 text
= frame_
->selectionAsText();
4036 // http://crbug.com/101435
4037 // In some case, frame->selectionAsText() returned text's length is not
4038 // equal to the length returned from webwidget()->caretOrSelectionRange().
4039 // So we have to set the range according to text.length().
4040 range
.set_end(range
.start() + text
.length());
4044 // Sometimes we get repeated didChangeSelection calls from webkit when
4045 // the selection hasn't actually changed. We don't want to report these
4046 // because it will cause us to continually claim the X clipboard.
4047 if (selection_text_offset_
!= offset
||
4048 selection_range_
!= range
||
4049 selection_text_
!= text
) {
4050 selection_text_
= text
;
4051 selection_text_offset_
= offset
;
4052 selection_range_
= range
;
4053 SetSelectedText(text
, offset
, range
);
4055 GetRenderWidget()->UpdateSelectionBounds();
4058 void RenderFrameImpl::InitializeUserMediaClient() {
4059 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4062 #if defined(OS_ANDROID)
4063 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC
))
4067 #if defined(ENABLE_WEBRTC)
4068 DCHECK(!web_user_media_client_
);
4069 web_user_media_client_
= new UserMediaClientImpl(
4071 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4072 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4076 WebMediaPlayer
* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4077 const blink::WebURL
& url
,
4078 WebMediaPlayerClient
* client
) {
4079 #if defined(ENABLE_WEBRTC)
4080 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4082 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON
) != 0;
4083 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon
);
4084 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4085 return new WebMediaPlayerMS(frame_
, client
, weak_factory_
.GetWeakPtr(),
4086 new RenderMediaLog(),
4087 CreateRendererFactory());
4090 #endif // defined(ENABLE_WEBRTC)
4093 scoped_ptr
<MediaStreamRendererFactory
>
4094 RenderFrameImpl::CreateRendererFactory() {
4095 #if defined(ENABLE_WEBRTC)
4096 return scoped_ptr
<MediaStreamRendererFactory
>(
4097 new MediaStreamRendererFactory());
4099 return scoped_ptr
<MediaStreamRendererFactory
>(
4100 static_cast<MediaStreamRendererFactory
*>(NULL
));
4104 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4106 FrameMsg_Navigate_Type::Value navigate_type
,
4107 const PageState
& state
,
4109 int pending_history_list_offset
,
4112 WebURLRequest::CachePolicy
* cache_policy
) {
4113 MaybeHandleDebugURL(url
);
4114 if (!render_view_
->webview())
4118 RenderViewObserver
, render_view_
->observers_
, Navigate(url
));
4120 // If this is a stale back/forward (due to a recent navigation the browser
4121 // didn't know about), ignore it.
4122 if (check_history
&& render_view_
->IsBackForwardToStaleEntry(
4123 state
, pending_history_list_offset
, page_id
, *is_reload
))
4126 if (!is_swapped_out_
|| frame_
->parent())
4129 // This is a swapped out main frame, so swap the renderer back in.
4130 // We marked the view as hidden when swapping the view out, so be sure to
4131 // reset the visibility state before navigating to the new URL.
4132 render_view_
->webview()->setVisibilityState(
4133 render_view_
->visibilityState(), false);
4135 // If this is an attempt to reload while we are swapped out, we should not
4136 // reload swappedout://, but the previous page, which is stored in
4137 // params.state. Setting is_reload to false will treat this like a back
4138 // navigation to accomplish that.
4140 *cache_policy
= WebURLRequest::ReloadIgnoringCacheData
;
4142 // We refresh timezone when a view is swapped in since timezone
4143 // can get out of sync when the system timezone is updated while
4144 // the view is swapped out.
4145 RenderThreadImpl::NotifyTimezoneChange();
4147 render_view_
->SetSwappedOut(false);
4148 is_swapped_out_
= false;
4152 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest
* request
) {
4153 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4154 switches::kEnableBrowserSideNavigation
));
4156 // TODO(clamy): Execute the beforeunload event.
4158 // Note: At this stage, the goal is to apply all the modifications the
4159 // renderer wants to make to the request, and then send it to the browser, so
4160 // that the actual network request can be started. Ideally, all such
4161 // modifications should take place in willSendRequest, and in the
4162 // implementation of willSendRequest for the various InspectorAgents
4165 // TODO(clamy): Apply devtools override.
4166 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4168 willSendRequest(frame_
, 0, *request
, blink::WebURLResponse());
4170 // TODO(clamy): Same-document navigations should not be sent back to the
4172 // TODO(clamy): Data urls should not be sent back to the browser either.
4173 Send(new FrameHostMsg_BeginNavigation(routing_id_
,
4174 MakeBeginNavigationParams(request
),
4175 MakeCommonNavigationParams(request
)));
4178 GURL
RenderFrameImpl::GetLoadingUrl() const {
4179 WebDataSource
* ds
= frame_
->dataSource();
4180 if (ds
->hasUnreachableURL())
4181 return ds
->unreachableURL();
4183 const WebURLRequest
& request
= ds
->request();
4184 return request
.url();
4187 #if defined(OS_ANDROID)
4189 WebMediaPlayer
* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4190 const blink::WebURL
& url
,
4191 WebMediaPlayerClient
* client
,
4192 blink::WebContentDecryptionModule
* initial_cdm
) {
4193 GpuChannelHost
* gpu_channel_host
=
4194 RenderThreadImpl::current()->EstablishGpuChannelSync(
4195 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE
);
4196 if (!gpu_channel_host
) {
4197 LOG(ERROR
) << "Failed to establish GPU channel for media player";
4201 scoped_refptr
<StreamTextureFactory
> stream_texture_factory
;
4202 if (SynchronousCompositorFactory
* factory
=
4203 SynchronousCompositorFactory::GetInstance()) {
4204 stream_texture_factory
= factory
->CreateStreamTextureFactory(routing_id_
);
4206 scoped_refptr
<webkit::gpu::ContextProviderWebContext
> context_provider
=
4207 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4209 if (!context_provider
.get()) {
4210 LOG(ERROR
) << "Failed to get context3d for media player";
4214 stream_texture_factory
= StreamTextureFactoryImpl::Create(
4215 context_provider
, gpu_channel_host
, routing_id_
);
4218 return new WebMediaPlayerAndroid(
4221 weak_factory_
.GetWeakPtr(),
4222 GetMediaPlayerManager(),
4225 stream_texture_factory
,
4226 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4227 new RenderMediaLog());
4230 RendererMediaPlayerManager
* RenderFrameImpl::GetMediaPlayerManager() {
4231 if (!media_player_manager_
)
4232 media_player_manager_
= new RendererMediaPlayerManager(this);
4233 return media_player_manager_
;
4236 #endif // defined(OS_ANDROID)
4238 #if defined(ENABLE_BROWSER_CDMS)
4239 RendererCdmManager
* RenderFrameImpl::GetCdmManager() {
4241 cdm_manager_
= new RendererCdmManager(this);
4242 return cdm_manager_
;
4244 #endif // defined(ENABLE_BROWSER_CDMS)
4246 } // namespace content