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/encrypted_media_player_support_impl.h"
74 #include "content/renderer/media/crypto/render_cdm_factory.h"
75 #include "content/renderer/media/media_stream_dispatcher.h"
76 #include "content/renderer/media/media_stream_renderer_factory.h"
77 #include "content/renderer/media/midi_dispatcher.h"
78 #include "content/renderer/media/render_media_log.h"
79 #include "content/renderer/media/user_media_client_impl.h"
80 #include "content/renderer/media/webcontentdecryptionmodule_impl.h"
81 #include "content/renderer/media/webmediaplayer_ms.h"
82 #include "content/renderer/mojo/service_registry_js_wrapper.h"
83 #include "content/renderer/notification_permission_dispatcher.h"
84 #include "content/renderer/notification_provider.h"
85 #include "content/renderer/npapi/plugin_channel_host.h"
86 #include "content/renderer/push_messaging_dispatcher.h"
87 #include "content/renderer/push_permission_dispatcher.h"
88 #include "content/renderer/render_frame_proxy.h"
89 #include "content/renderer/render_process.h"
90 #include "content/renderer/render_thread_impl.h"
91 #include "content/renderer/render_view_impl.h"
92 #include "content/renderer/render_widget_fullscreen_pepper.h"
93 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
94 #include "content/renderer/renderer_webcolorchooser_impl.h"
95 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
96 #include "content/renderer/shared_worker_repository.h"
97 #include "content/renderer/v8_value_converter_impl.h"
98 #include "content/renderer/websharedworker_proxy.h"
99 #include "gin/modules/module_registry.h"
100 #include "media/base/audio_renderer_mixer_input.h"
101 #include "media/base/renderer.h"
102 #include "media/blink/webmediaplayer_impl.h"
103 #include "media/blink/webmediaplayer_params.h"
104 #include "media/filters/gpu_video_accelerator_factories.h"
105 #include "mojo/edk/js/core.h"
106 #include "mojo/edk/js/support.h"
107 #include "net/base/data_url.h"
108 #include "net/base/net_errors.h"
109 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
110 #include "net/http/http_util.h"
111 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
112 #include "third_party/WebKit/public/platform/WebString.h"
113 #include "third_party/WebKit/public/platform/WebURL.h"
114 #include "third_party/WebKit/public/platform/WebURLError.h"
115 #include "third_party/WebKit/public/platform/WebURLResponse.h"
116 #include "third_party/WebKit/public/platform/WebVector.h"
117 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
118 #include "third_party/WebKit/public/web/WebDocument.h"
119 #include "third_party/WebKit/public/web/WebGlyphCache.h"
120 #include "third_party/WebKit/public/web/WebLocalFrame.h"
121 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
122 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
123 #include "third_party/WebKit/public/web/WebPlugin.h"
124 #include "third_party/WebKit/public/web/WebPluginParams.h"
125 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
126 #include "third_party/WebKit/public/web/WebRange.h"
127 #include "third_party/WebKit/public/web/WebScriptSource.h"
128 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
129 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
130 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
131 #include "third_party/WebKit/public/web/WebSurroundingText.h"
132 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
133 #include "third_party/WebKit/public/web/WebView.h"
135 #if defined(ENABLE_PLUGINS)
136 #include "content/renderer/npapi/webplugin_impl.h"
137 #include "content/renderer/pepper/pepper_browser_connection.h"
138 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
139 #include "content/renderer/pepper/pepper_webplugin_impl.h"
140 #include "content/renderer/pepper/plugin_module.h"
141 #include "content/renderer/pepper/plugin_power_saver_helper.h"
144 #if defined(ENABLE_WEBRTC)
145 #include "content/renderer/media/rtc_peer_connection_handler.h"
148 #if defined(OS_ANDROID)
149 #include <cpu-features.h>
151 #include "content/common/gpu/client/context_provider_command_buffer.h"
152 #include "content/renderer/android/synchronous_compositor_factory.h"
153 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
154 #include "content/renderer/media/android/renderer_media_player_manager.h"
155 #include "content/renderer/media/android/stream_texture_factory_impl.h"
156 #include "content/renderer/media/android/webmediaplayer_android.h"
159 #if defined(ENABLE_PEPPER_CDMS)
160 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
161 #elif defined(ENABLE_BROWSER_CDMS)
162 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
165 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
166 #include "xwalk/tizen/renderer/media/renderer_mediaplayer_manager.h"
167 #include "xwalk/tizen/renderer/media/mediaplayer_impl.h"
170 using blink::WebContextMenuData;
171 using blink::WebData;
172 using blink::WebDataSource;
173 using blink::WebDocument;
174 using blink::WebElement;
175 using blink::WebExternalPopupMenu;
176 using blink::WebExternalPopupMenuClient;
177 using blink::WebFrame;
178 using blink::WebHistoryItem;
179 using blink::WebHTTPBody;
180 using blink::WebLocalFrame;
181 using blink::WebMediaPlayer;
182 using blink::WebMediaPlayerClient;
183 using blink::WebNavigationPolicy;
184 using blink::WebNavigationType;
185 using blink::WebNode;
186 using blink::WebPluginParams;
187 using blink::WebPopupMenuInfo;
188 using blink::WebRange;
189 using blink::WebReferrerPolicy;
190 using blink::WebScriptSource;
191 using blink::WebSearchableFormData;
192 using blink::WebSecurityOrigin;
193 using blink::WebSecurityPolicy;
194 using blink::WebServiceWorkerProvider;
195 using blink::WebStorageQuotaCallbacks;
196 using blink::WebString;
198 using blink::WebURLError;
199 using blink::WebURLRequest;
200 using blink::WebURLResponse;
201 using blink::WebUserGestureIndicator;
202 using blink::WebVector;
203 using blink::WebView;
205 using base::TimeDelta;
211 const char kDefaultAcceptHeader[] =
212 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
214 const char kAcceptHeader[] = "Accept";
216 const size_t kExtraCharsBeforeAndAfterSelection = 100;
218 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
219 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
220 LAZY_INSTANCE_INITIALIZER;
222 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
223 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
225 int64 ExtractPostId(const WebHistoryItem& item) {
229 if (item.httpBody().isNull())
232 return item.httpBody().identifier();
235 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
236 const WebURLResponse& response) {
237 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
240 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
241 // Replace any occurrences of swappedout:// with about:blank.
242 const WebURL& blank_url = GURL(url::kAboutBlankURL);
243 WebVector<WebURL> urls;
244 ds->redirectChain(urls);
245 result->reserve(urls.size());
246 for (size_t i = 0; i < urls.size(); ++i) {
247 if (urls[i] != GURL(kSwappedOutURL))
248 result->push_back(urls[i]);
250 result->push_back(blank_url);
254 // Returns the original request url. If there is no redirect, the original
255 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
256 // frame was loaded by loadData, the original url will be ds->unreachableURL()
257 static GURL GetOriginalRequestURL(WebDataSource* ds) {
258 // WebDataSource has unreachable URL means that the frame is loaded through
259 // blink::WebFrame::loadData(), and the base URL will be in the redirect
260 // chain. However, we never visited the baseURL. So in this case, we should
261 // use the unreachable URL as the original URL.
262 if (ds->hasUnreachableURL())
263 return ds->unreachableURL();
265 std::vector<GURL> redirects;
266 GetRedirectChain(ds, &redirects);
267 if (!redirects.empty())
268 return redirects.at(0);
270 return ds->originalRequest().url();
273 NOINLINE static void CrashIntentionally() {
274 // NOTE(shess): Crash directly rather than using NOTREACHED() so
275 // that the signature is easier to triage in crash reports.
276 volatile int* zero = NULL;
280 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
281 NOINLINE static void MaybeTriggerAsanError(const GURL& url) {
282 // NOTE(rogerm): We intentionally perform an invalid heap access here in
283 // order to trigger an Address Sanitizer (ASAN) error report.
284 const char kCrashDomain[] = "crash";
285 const char kHeapOverflow[] = "/heap-overflow";
286 const char kHeapUnderflow[] = "/heap-underflow";
287 const char kUseAfterFree[] = "/use-after-free";
288 #if defined(SYZYASAN)
289 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
290 const char kCorruptHeap[] = "/corrupt-heap";
293 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
299 std::string crash_type(url.path());
300 if (crash_type == kHeapOverflow) {
301 base::debug::AsanHeapOverflow();
302 } else if (crash_type == kHeapUnderflow ) {
303 base::debug::AsanHeapUnderflow();
304 } else if (crash_type == kUseAfterFree) {
305 base::debug::AsanHeapUseAfterFree();
306 #if defined(SYZYASAN)
307 } else if (crash_type == kCorruptHeapBlock) {
308 base::debug::AsanCorruptHeapBlock();
309 } else if (crash_type == kCorruptHeap) {
310 base::debug::AsanCorruptHeap();
314 #endif // ADDRESS_SANITIZER || SYZYASAN
316 static void MaybeHandleDebugURL(const GURL& url) {
317 if (!url.SchemeIs(kChromeUIScheme))
319 if (url == GURL(kChromeUICrashURL)) {
320 CrashIntentionally();
321 } else if (url == GURL(kChromeUIDumpURL)) {
322 // This URL will only correctly create a crash dump file if content is
323 // hosted in a process that has correctly called
324 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
325 // of base::debug::DumpWithoutCrashing for more details.
326 base::debug::DumpWithoutCrashing();
327 } else if (url == GURL(kChromeUIKillURL)) {
328 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
329 } else if (url == GURL(kChromeUIHangURL)) {
331 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
333 } else if (url == GURL(kChromeUIShorthangURL)) {
334 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
337 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
338 MaybeTriggerAsanError(url);
339 #endif // ADDRESS_SANITIZER || SYZYASAN
342 // Returns false unless this is a top-level navigation.
343 static bool IsTopLevelNavigation(WebFrame* frame) {
344 return frame->parent() == NULL;
347 // Returns false unless this is a top-level navigation that crosses origins.
348 static bool IsNonLocalTopLevelNavigation(const GURL& url,
350 WebNavigationType type,
352 if (!IsTopLevelNavigation(frame))
355 // Navigations initiated within Webkit are not sent out to the external host
356 // in the following cases.
357 // 1. The url scheme is not http/https
358 // 2. The origin of the url and the opener is the same in which case the
359 // opener relationship is maintained.
360 // 3. Reloads/form submits/back forward navigations
361 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
364 if (type != blink::WebNavigationTypeReload &&
365 type != blink::WebNavigationTypeBackForward && !is_form_post) {
366 // The opener relationship between the new window and the parent allows the
367 // new window to script the parent and vice versa. This is not allowed if
368 // the origins of the two domains are different. This can be treated as a
369 // top level navigation and routed back to the host.
370 blink::WebFrame* opener = frame->opener();
374 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
380 WebURLRequest CreateURLRequestForNavigation(
381 const CommonNavigationParams& common_params,
382 const RequestNavigationParams& request_params,
383 scoped_ptr<StreamOverrideParameters> stream_override,
384 bool is_view_source_mode_enabled) {
385 WebURLRequest request(common_params.url);
386 if (is_view_source_mode_enabled)
387 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
389 if (common_params.referrer.url.is_valid()) {
390 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
391 common_params.referrer.policy,
393 WebString::fromUTF8(common_params.referrer.url.spec()));
394 if (!web_referrer.isEmpty())
395 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
398 if (!request_params.extra_headers.empty()) {
399 for (net::HttpUtil::HeadersIterator i(request_params.extra_headers.begin(),
400 request_params.extra_headers.end(),
403 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
404 WebString::fromUTF8(i.values()));
408 if (request_params.is_post) {
409 request.setHTTPMethod(WebString::fromUTF8("POST"));
412 WebHTTPBody http_body;
413 http_body.initialize();
414 const char* data = NULL;
415 if (request_params.browser_initiated_post_data.size()) {
416 data = reinterpret_cast<const char*>(
417 &request_params.browser_initiated_post_data.front());
419 http_body.appendData(
420 WebData(data, request_params.browser_initiated_post_data.size()));
421 request.setHTTPBody(http_body);
424 RequestExtraData* extra_data = new RequestExtraData();
425 extra_data->set_stream_override(stream_override.Pass());
426 request.setExtraData(extra_data);
430 void UpdateFrameNavigationTiming(WebFrame* frame,
431 base::TimeTicks browser_navigation_start,
432 base::TimeTicks renderer_navigation_start) {
433 // The browser provides the navigation_start time to bootstrap the
434 // Navigation Timing information for the browser-initiated navigations. In
435 // case of cross-process navigations, this carries over the time of
436 // finishing the onbeforeunload handler of the previous page.
437 DCHECK(!browser_navigation_start.is_null());
438 if (frame->provisionalDataSource()) {
439 // |browser_navigation_start| is likely before this process existed, so we
440 // can't use InterProcessTimeTicksConverter. We need at least to ensure
441 // that the browser-side navigation start we set is not later than the one
442 // on the renderer side.
443 base::TimeTicks navigation_start = std::min(
444 browser_navigation_start, renderer_navigation_start);
445 double navigation_start_seconds =
446 (navigation_start - base::TimeTicks()).InSecondsF();
447 frame->provisionalDataSource()->setNavigationStartTime(
448 navigation_start_seconds);
449 // TODO(clamy): We need to provide additional timing values for the
450 // Navigation Timing API to work with browser-side navigations.
455 FrameHostMsg_BeginNavigation_Params MakeBeginNavigationParams(
456 const blink::WebURLRequest& request) {
457 FrameHostMsg_BeginNavigation_Params params;
458 params.method = request.httpMethod().latin1();
459 params.headers = GetWebURLRequestHeaders(request);
460 params.load_flags = GetLoadFlagsForWebURLRequest(request);
461 // TODO(clamy): fill the http body.
462 params.has_user_gesture = request.hasUserGesture();
467 CommonNavigationParams MakeCommonNavigationParams(
468 const blink::WebURLRequest& request) {
469 const RequestExtraData kEmptyData;
470 const RequestExtraData* extra_data =
471 static_cast<RequestExtraData*>(request.extraData());
473 extra_data = &kEmptyData;
474 CommonNavigationParams params;
475 params.url = request.url();
476 params.referrer = Referrer(
477 GURL(request.httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
478 request.referrerPolicy());
479 params.transition = extra_data->transition_type();
485 static RenderFrameImpl* (*g_create_render_frame_impl)(RenderViewImpl*, int32) =
489 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
491 DCHECK(routing_id != MSG_ROUTING_NONE);
493 if (g_create_render_frame_impl)
494 return g_create_render_frame_impl(render_view, routing_id);
496 return new RenderFrameImpl(render_view, routing_id);
500 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
501 RoutingIDFrameMap::iterator iter =
502 g_routing_id_frame_map.Get().find(routing_id);
503 if (iter != g_routing_id_frame_map.Get().end())
509 void RenderFrameImpl::CreateFrame(int routing_id,
510 int parent_routing_id,
511 int proxy_routing_id) {
512 // TODO(nasko): For now, this message is only sent for subframes, as the
513 // top level frame is created when the RenderView is created through the
515 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
517 blink::WebLocalFrame* web_frame;
518 RenderFrameImpl* render_frame;
519 if (proxy_routing_id == MSG_ROUTING_NONE) {
520 RenderFrameProxy* parent_proxy =
521 RenderFrameProxy::FromRoutingID(parent_routing_id);
522 // If the browser is sending a valid parent routing id, it should already
523 // be created and registered.
525 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
527 // Create the RenderFrame and WebLocalFrame, linking the two.
529 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
530 web_frame = parent_web_frame->createLocalChild("", render_frame);
532 RenderFrameProxy* proxy =
533 RenderFrameProxy::FromRoutingID(proxy_routing_id);
535 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
536 web_frame = blink::WebLocalFrame::create(render_frame);
537 render_frame->proxy_routing_id_ = proxy_routing_id;
538 web_frame->initializeToReplaceRemoteFrame(proxy->web_frame());
540 render_frame->SetWebFrame(web_frame);
541 render_frame->Initialize();
545 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
546 return RenderFrameImpl::FromWebFrame(web_frame);
550 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
551 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
552 if (iter != g_frame_map.Get().end())
558 void RenderFrameImpl::InstallCreateHook(
559 RenderFrameImpl* (*create_render_frame_impl)(RenderViewImpl*, int32)) {
560 CHECK(!g_create_render_frame_impl);
561 g_create_render_frame_impl = create_render_frame_impl;
564 // RenderFrameImpl ----------------------------------------------------------
565 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
567 render_view_(render_view->AsWeakPtr()),
568 routing_id_(routing_id),
569 is_swapped_out_(false),
570 render_frame_proxy_(NULL),
571 is_detaching_(false),
572 proxy_routing_id_(MSG_ROUTING_NONE),
573 #if defined(ENABLE_PLUGINS)
574 plugin_power_saver_helper_(NULL),
577 selection_text_offset_(0),
578 selection_range_(gfx::Range::InvalidRange()),
579 handling_select_range_(false),
580 notification_permission_dispatcher_(NULL),
581 notification_provider_(NULL),
582 web_user_media_client_(NULL),
583 midi_dispatcher_(NULL),
584 #if defined(OS_ANDROID)
585 media_player_manager_(NULL),
587 #if defined(ENABLE_BROWSER_CDMS)
590 #if defined(VIDEO_HOLE)
591 contains_media_player_(false),
593 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
594 media_player_manager_(NULL),
596 geolocation_dispatcher_(NULL),
597 push_messaging_dispatcher_(NULL),
598 screen_orientation_dispatcher_(NULL),
599 manifest_manager_(NULL),
600 accessibility_mode_(AccessibilityModeOff),
601 renderer_accessibility_(NULL),
602 weak_factory_(this) {
603 std::pair<RoutingIDFrameMap::iterator, bool> result =
604 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
605 CHECK(result.second) << "Inserting a duplicate item.";
607 RenderThread::Get()->AddRoute(routing_id_, this);
609 render_view_->RegisterRenderFrame(this);
611 // Everything below subclasses RenderFrameObserver and is automatically
612 // deleted when the RenderFrame gets deleted.
613 #if defined(OS_ANDROID)
614 new GinJavaBridgeDispatcher(this);
617 #if defined(ENABLE_PLUGINS)
618 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
621 #if defined(ENABLE_NOTIFICATIONS)
622 notification_provider_ = new NotificationProvider(this);
625 manifest_manager_ = new ManifestManager(this);
628 RenderFrameImpl::~RenderFrameImpl() {
629 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
630 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
632 #if defined(VIDEO_HOLE)
633 if (contains_media_player_)
634 render_view_->UnregisterVideoHoleFrame(this);
637 if (render_frame_proxy_)
638 delete render_frame_proxy_;
640 render_view_->UnregisterRenderFrame(this);
641 g_routing_id_frame_map.Get().erase(routing_id_);
642 RenderThread::Get()->RemoveRoute(routing_id_);
645 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
648 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
649 std::make_pair(web_frame, this));
650 CHECK(result.second) << "Inserting a duplicate item.";
655 void RenderFrameImpl::Initialize() {
656 #if defined(ENABLE_PLUGINS)
657 new PepperBrowserConnection(this);
659 new SharedWorkerRepository(this);
661 if (!frame_->parent())
662 new ImageLoadingHelper(this);
664 // We delay calling this until we have the WebFrame so that any observer or
665 // embedder can call GetWebFrame on any RenderFrame.
666 GetContentClient()->renderer()->RenderFrameCreated(this);
669 RenderWidget* RenderFrameImpl::GetRenderWidget() {
670 return render_view_.get();
673 #if defined(ENABLE_PLUGINS)
674 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
675 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
676 DidCreatePepperPlugin(host));
677 if (host->GetPluginName() == kFlashPluginName) {
678 RenderThread::Get()->RecordAction(
679 base::UserMetricsAction("FrameLoadWithFlash"));
683 void RenderFrameImpl::PepperDidChangeCursor(
684 PepperPluginInstanceImpl* instance,
685 const blink::WebCursorInfo& cursor) {
686 // Update the cursor appearance immediately if the requesting plugin is the
687 // one which receives the last mouse event. Otherwise, the new cursor won't be
688 // picked up until the plugin gets the next input event. That is bad if, e.g.,
689 // the plugin would like to set an invisible cursor when there isn't any user
690 // input for a while.
691 if (instance == render_view_->pepper_last_mouse_event_target())
692 GetRenderWidget()->didChangeCursor(cursor);
695 void RenderFrameImpl::PepperDidReceiveMouseEvent(
696 PepperPluginInstanceImpl* instance) {
697 render_view_->set_pepper_last_mouse_event_target(instance);
700 void RenderFrameImpl::PepperTextInputTypeChanged(
701 PepperPluginInstanceImpl* instance) {
702 if (instance != render_view_->focused_pepper_plugin())
705 GetRenderWidget()->UpdateTextInputType();
706 if (renderer_accessibility())
707 renderer_accessibility()->FocusedNodeChanged(WebNode());
710 void RenderFrameImpl::PepperCaretPositionChanged(
711 PepperPluginInstanceImpl* instance) {
712 if (instance != render_view_->focused_pepper_plugin())
714 GetRenderWidget()->UpdateSelectionBounds();
717 void RenderFrameImpl::PepperCancelComposition(
718 PepperPluginInstanceImpl* instance) {
719 if (instance != render_view_->focused_pepper_plugin())
721 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
722 #if defined(OS_MACOSX) || defined(USE_AURA)
723 GetRenderWidget()->UpdateCompositionInfo(true);
727 void RenderFrameImpl::PepperSelectionChanged(
728 PepperPluginInstanceImpl* instance) {
729 if (instance != render_view_->focused_pepper_plugin())
731 SyncSelectionIfRequired();
734 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
735 PepperPluginInstanceImpl* plugin) {
737 if (render_view_->webview() && render_view_->webview()->mainFrame())
738 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
739 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
740 GetRenderWidget()->routing_id(), plugin, active_url,
741 GetRenderWidget()->screenInfo());
742 widget->show(blink::WebNavigationPolicyIgnore);
746 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
747 if (!render_view_->focused_pepper_plugin())
749 return render_view_->focused_pepper_plugin()->
750 IsPluginAcceptingCompositionEvents();
753 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
754 base::ProcessId plugin_pid) {
755 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
756 // routing_id_ as a result.
757 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
760 void RenderFrameImpl::SimulateImeSetComposition(
761 const base::string16& text,
762 const std::vector<blink::WebCompositionUnderline>& underlines,
765 render_view_->OnImeSetComposition(
766 text, underlines, selection_start, selection_end);
769 void RenderFrameImpl::SimulateImeConfirmComposition(
770 const base::string16& text,
771 const gfx::Range& replacement_range) {
772 render_view_->OnImeConfirmComposition(text, replacement_range, false);
775 void RenderFrameImpl::OnImeSetComposition(
776 const base::string16& text,
777 const std::vector<blink::WebCompositionUnderline>& underlines,
780 // When a PPAPI plugin has focus, we bypass WebKit.
781 if (!IsPepperAcceptingCompositionEvents()) {
782 pepper_composition_text_ = text;
784 // TODO(kinaba) currently all composition events are sent directly to
785 // plugins. Use DOM event mechanism after WebKit is made aware about
786 // plugins that support composition.
787 // The code below mimics the behavior of WebCore::Editor::setComposition.
789 // Empty -> nonempty: composition started.
790 if (pepper_composition_text_.empty() && !text.empty()) {
791 render_view_->focused_pepper_plugin()->HandleCompositionStart(
794 // Nonempty -> empty: composition canceled.
795 if (!pepper_composition_text_.empty() && text.empty()) {
796 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
799 pepper_composition_text_ = text;
800 // Nonempty: composition is ongoing.
801 if (!pepper_composition_text_.empty()) {
802 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
803 pepper_composition_text_, underlines, selection_start,
809 void RenderFrameImpl::OnImeConfirmComposition(
810 const base::string16& text,
811 const gfx::Range& replacement_range,
812 bool keep_selection) {
813 // When a PPAPI plugin has focus, we bypass WebKit.
814 // Here, text.empty() has a special meaning. It means to commit the last
815 // update of composition text (see
816 // RenderWidgetHost::ImeConfirmComposition()).
817 const base::string16& last_text = text.empty() ? pepper_composition_text_
820 // last_text is empty only when both text and pepper_composition_text_ is.
822 if (last_text.empty())
825 if (!IsPepperAcceptingCompositionEvents()) {
826 base::i18n::UTF16CharIterator iterator(&last_text);
828 while (iterator.Advance()) {
829 blink::WebKeyboardEvent char_event;
830 char_event.type = blink::WebInputEvent::Char;
831 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
832 char_event.modifiers = 0;
833 char_event.windowsKeyCode = last_text[i];
834 char_event.nativeKeyCode = last_text[i];
836 const int32 char_start = i;
837 for (; i < iterator.array_pos(); ++i) {
838 char_event.text[i - char_start] = last_text[i];
839 char_event.unmodifiedText[i - char_start] = last_text[i];
842 if (GetRenderWidget()->webwidget())
843 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
846 // Mimics the order of events sent by WebKit.
847 // See WebCore::Editor::setComposition() for the corresponding code.
848 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
849 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
851 pepper_composition_text_.clear();
854 PluginPowerSaverHelper* RenderFrameImpl::plugin_power_saver_helper() {
855 DCHECK(plugin_power_saver_helper_);
856 return plugin_power_saver_helper_;
858 #endif // defined(ENABLE_PLUGINS)
860 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
861 if (!web_user_media_client_)
862 InitializeUserMediaClient();
863 return web_user_media_client_ ?
864 web_user_media_client_->media_stream_dispatcher() : NULL;
867 bool RenderFrameImpl::Send(IPC::Message* message) {
872 if (frame_->parent() == NULL &&
873 (is_swapped_out_ || render_view_->is_swapped_out())) {
874 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
879 // In most cases, send IPCs through the proxy when swapped out. In some
880 // calls the associated RenderViewImpl routing id is used to send
881 // messages, so don't use the proxy.
882 if (render_frame_proxy_ && message->routing_id() == routing_id_)
883 return render_frame_proxy_->Send(message);
886 return RenderThread::Get()->Send(message);
889 #if defined(OS_MACOSX) || defined(OS_ANDROID)
890 void RenderFrameImpl::DidHideExternalPopupMenu() {
891 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
892 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
893 external_popup_menu_.reset();
897 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
898 // TODO(kenrb): document() should not be null, but as a transitional step
899 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
900 // to this method. This happens for a top-level remote frame, where a
901 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
902 // around and is still able to receive messages.
903 if (!frame_->document().isNull())
904 GetContentClient()->SetActiveURL(frame_->document().url());
906 ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
907 RenderFrameObserver* observer;
908 while ((observer = it.GetNext()) != NULL) {
909 if (observer->OnMessageReceived(msg))
914 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
915 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
916 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
917 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
918 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
919 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
920 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
921 OnCustomContextMenuAction)
922 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
923 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
924 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
925 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
926 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
927 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
928 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
929 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
930 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
931 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
932 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
933 OnMoveRangeSelectionExtent)
934 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
935 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
936 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
937 OnExtendSelectionAndDelete)
938 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
939 OnSetCompositionFromExistingText)
940 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
941 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
942 OnJavaScriptExecuteRequest)
943 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
944 OnJavaScriptExecuteRequestForTests)
945 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
946 OnSetEditableSelectionOffsets)
947 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
948 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
949 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
950 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
951 OnTextSurroundingSelectionRequest)
952 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
953 OnAddStyleSheetByURL)
954 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
955 OnSetAccessibilityMode)
956 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
957 IPC_MESSAGE_HANDLER(FrameMsg_RequestNavigation, OnRequestNavigation)
958 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
959 #if defined(OS_ANDROID)
960 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
961 #elif defined(OS_MACOSX)
962 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
963 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
965 IPC_END_MESSAGE_MAP()
970 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
971 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
973 "url", params.common_params.url.possibly_invalid_spec());
975 RenderViewImpl::IsReload(params.common_params.navigation_type);
976 WebURLRequest::CachePolicy cache_policy =
977 WebURLRequest::UseProtocolCachePolicy;
978 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
979 params.common_params.url, params.common_params.navigation_type,
980 params.commit_params.page_state, true, params.pending_history_list_offset,
981 params.page_id, &is_reload, &cache_policy)) {
985 int pending_history_list_offset = params.pending_history_list_offset;
986 int current_history_list_offset = params.current_history_list_offset;
987 int current_history_list_length = params.current_history_list_length;
988 if (params.should_clear_history_list) {
989 CHECK_EQ(pending_history_list_offset, -1);
990 CHECK_EQ(current_history_list_offset, -1);
991 CHECK_EQ(current_history_list_length, 0);
993 render_view_->history_list_offset_ = current_history_list_offset;
994 render_view_->history_list_length_ = current_history_list_length;
995 if (render_view_->history_list_length_ >= 0) {
996 render_view_->history_page_ids_.resize(
997 render_view_->history_list_length_, -1);
999 if (pending_history_list_offset >= 0 &&
1000 pending_history_list_offset < render_view_->history_list_length_) {
1001 render_view_->history_page_ids_[pending_history_list_offset] =
1005 GetContentClient()->SetActiveURL(params.common_params.url);
1007 WebFrame* frame = frame_;
1008 if (!params.frame_to_navigate.empty()) {
1009 // TODO(nasko): Move this lookup to the browser process.
1010 frame = render_view_->webview()->findFrameByName(
1011 WebString::fromUTF8(params.frame_to_navigate));
1012 CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate;
1015 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
1016 // We cannot reload if we do not have any history state. This happens, for
1017 // example, when recovering from a crash.
1019 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
1022 render_view_->pending_navigation_params_.reset(
1023 new FrameMsg_Navigate_Params(params));
1025 // If we are reloading, then WebKit will use the history state of the current
1026 // page, so we should just ignore any given history state. Otherwise, if we
1027 // have history state, then we need to navigate to it, which corresponds to a
1028 // back/forward navigation event.
1030 bool reload_original_url =
1031 (params.common_params.navigation_type ==
1032 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
1033 bool ignore_cache = (params.common_params.navigation_type ==
1034 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
1036 if (reload_original_url)
1037 frame->reloadWithOverrideURL(params.common_params.url, true);
1039 frame->reload(ignore_cache);
1040 } else if (params.commit_params.page_state.IsValid()) {
1041 // We must know the page ID of the page we are navigating back to.
1042 DCHECK_NE(params.page_id, -1);
1043 scoped_ptr<HistoryEntry> entry =
1044 PageStateToHistoryEntry(params.commit_params.page_state);
1046 // Ensure we didn't save the swapped out URL in UpdateState, since the
1047 // browser should never be telling us to navigate to swappedout://.
1048 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
1049 render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy);
1051 } else if (!params.base_url_for_data_url.is_empty()) {
1052 // A loadData request with a specified base URL.
1053 std::string mime_type, charset, data;
1054 if (net::DataURL::Parse(
1055 params.common_params.url, &mime_type, &charset, &data)) {
1057 WebData(data.c_str(), data.length()),
1058 WebString::fromUTF8(mime_type),
1059 WebString::fromUTF8(charset),
1060 params.base_url_for_data_url,
1061 params.history_url_for_data_url,
1064 CHECK(false) << "Invalid URL passed: "
1065 << params.common_params.url.possibly_invalid_spec();
1068 // Navigate to the given URL.
1069 WebURLRequest request =
1070 CreateURLRequestForNavigation(params.common_params,
1071 params.request_params,
1072 scoped_ptr<StreamOverrideParameters>(),
1073 frame->isViewSourceModeEnabled());
1075 // A session history navigation should have been accompanied by state.
1076 CHECK_EQ(params.page_id, -1);
1078 // Record this before starting the load, we need a lower bound of this time
1079 // to sanitize the navigationStart override set below.
1080 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
1081 frame->loadRequest(request);
1083 UpdateFrameNavigationTiming(
1084 frame, params.commit_params.browser_navigation_start,
1085 renderer_navigation_start);
1088 // In case LoadRequest failed before DidCreateDataSource was called.
1089 render_view_->pending_navigation_params_.reset();
1092 void RenderFrameImpl::BindServiceRegistry(
1093 mojo::ScopedMessagePipeHandle service_provider_handle) {
1094 service_registry_.BindRemoteServiceProvider(service_provider_handle.Pass());
1097 ManifestManager* RenderFrameImpl::manifest_manager() {
1098 return manifest_manager_;
1101 void RenderFrameImpl::OnBeforeUnload() {
1102 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1104 // TODO(creis): Right now, this is only called on the main frame. Make the
1105 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1107 CHECK(!frame_->parent());
1109 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1110 bool proceed = frame_->dispatchBeforeUnloadEvent();
1111 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1112 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1113 before_unload_start_time,
1114 before_unload_end_time));
1117 void RenderFrameImpl::OnSwapOut(int proxy_routing_id) {
1118 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1119 RenderFrameProxy* proxy = NULL;
1120 bool is_site_per_process =
1121 CommandLine::ForCurrentProcess()->HasSwitch(switches::kSitePerProcess);
1122 bool is_main_frame = !frame_->parent();
1124 // Only run unload if we're not swapped out yet, but send the ack either way.
1125 if (!is_swapped_out_ || !render_view_->is_swapped_out_) {
1126 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1127 // a different process. This involves running the unload handler and
1128 // clearing the page. We also allow this process to exit if there are no
1129 // other active RenderFrames in it.
1131 // Send an UpdateState message before we get swapped out.
1132 render_view_->SyncNavigationState();
1134 // If we need a proxy to replace this, create it now so its routing id is
1135 // registered for receiving IPC messages.
1136 if (proxy_routing_id != MSG_ROUTING_NONE) {
1137 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1141 // Synchronously run the unload handler before sending the ACK.
1142 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1143 // unload on subframes as well.
1145 frame_->dispatchUnloadEvent();
1147 // Swap out and stop sending any IPC messages that are not ACKs.
1148 // TODO(nasko): Do we need RenderFrameImpl::is_swapped_out_ anymore?
1150 render_view_->SetSwappedOut(true);
1151 is_swapped_out_ = true;
1153 // Now that we're swapped out and filtering IPC messages, stop loading to
1154 // ensure that no other in-progress navigation continues. We do this here
1155 // to avoid sending a DidStopLoading message to the browser process.
1156 // TODO(creis): Should we be stopping all frames here and using
1157 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1161 // Transfer settings such as initial drawing parameters to the remote frame,
1162 // if one is created, that will replace this frame.
1163 if (!is_main_frame && proxy)
1164 proxy->web_frame()->initializeFromFrame(frame_);
1166 // Replace the page with a blank dummy URL. The unload handler will not be
1167 // run a second time, thanks to a check in FrameLoader::stopLoading.
1168 // TODO(creis): Need to add a better way to do this that avoids running the
1169 // beforeunload handler. For now, we just run it a second time silently.
1170 if (!is_site_per_process || is_main_frame)
1171 render_view_->NavigateToSwappedOutURL(frame_);
1173 // Let WebKit know that this view is hidden so it can drop resources and
1174 // stop compositing.
1175 // TODO(creis): Support this for subframes as well.
1176 if (is_main_frame) {
1177 render_view_->webview()->setVisibilityState(
1178 blink::WebPageVisibilityStateHidden, false);
1182 // It is now safe to show modal dialogs again.
1183 // TODO(creis): Deal with modal dialogs from subframes.
1185 render_view_->suppress_dialogs_until_swap_out_ = false;
1187 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1189 // Now that all of the cleanup is complete and the browser side is notified,
1190 // start using the RenderFrameProxy, if one is created.
1192 if (!is_main_frame) {
1193 frame_->swap(proxy->web_frame());
1194 if (is_site_per_process) {
1195 // TODO(nasko): delete the frame here, since we've replaced it with a
1199 set_render_frame_proxy(proxy);
1203 // Safe to exit if no one else is using the process.
1205 render_view_->WasSwappedOut();
1208 void RenderFrameImpl::OnContextMenuClosed(
1209 const CustomContextMenuContext& custom_context) {
1210 if (custom_context.request_id) {
1211 // External request, should be in our map.
1212 ContextMenuClient* client =
1213 pending_context_menus_.Lookup(custom_context.request_id);
1215 client->OnMenuClosed(custom_context.request_id);
1216 pending_context_menus_.Remove(custom_context.request_id);
1219 if (custom_context.link_followed.is_valid()) {
1221 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1222 custom_context.link_followed);
1224 // Internal request, forward to WebKit.
1225 context_menu_node_.reset();
1229 void RenderFrameImpl::OnCustomContextMenuAction(
1230 const CustomContextMenuContext& custom_context,
1232 if (custom_context.request_id) {
1233 // External context menu request, look in our map.
1234 ContextMenuClient* client =
1235 pending_context_menus_.Lookup(custom_context.request_id);
1237 client->OnMenuAction(custom_context.request_id, action);
1239 // Internal request, forward to WebKit.
1240 render_view_->webview()->performCustomContextMenuAction(action);
1244 void RenderFrameImpl::OnUndo() {
1245 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1248 void RenderFrameImpl::OnRedo() {
1249 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1252 void RenderFrameImpl::OnCut() {
1253 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1254 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1257 void RenderFrameImpl::OnCopy() {
1258 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1259 WebNode current_node = context_menu_node_.isNull() ?
1260 GetFocusedElement() : context_menu_node_;
1261 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1264 void RenderFrameImpl::OnPaste() {
1265 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1266 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1269 void RenderFrameImpl::OnPasteAndMatchStyle() {
1270 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1271 frame_->executeCommand(
1272 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1275 #if defined(OS_MACOSX)
1276 void RenderFrameImpl::OnCopyToFindPboard() {
1277 // Since the find pasteboard supports only plain text, this can be simpler
1278 // than the |OnCopy()| case.
1279 if (frame_->hasSelection()) {
1280 base::string16 selection = frame_->selectionAsText();
1281 RenderThread::Get()->Send(
1282 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1287 void RenderFrameImpl::OnDelete() {
1288 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1291 void RenderFrameImpl::OnSelectAll() {
1292 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1293 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1296 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1297 const gfx::Point& extent) {
1298 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1299 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1301 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1302 frame_->selectRange(base, extent);
1305 void RenderFrameImpl::OnUnselect() {
1306 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1307 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1310 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1311 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1312 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1313 GetRenderWidget()->routing_id()));
1315 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1316 frame_->moveRangeSelectionExtent(point);
1319 void RenderFrameImpl::OnReplace(const base::string16& text) {
1320 if (!frame_->hasSelection())
1321 frame_->selectWordAroundCaret();
1323 frame_->replaceSelection(text);
1326 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1327 if (!frame_->hasSelection())
1330 frame_->replaceMisspelledRange(text);
1333 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1334 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1337 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1338 const base::string16& jscript,
1340 bool notify_result) {
1341 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1342 TRACE_EVENT_SCOPE_THREAD);
1344 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1345 v8::Handle<v8::Value> result =
1346 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1348 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1351 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1352 const base::string16& jscript,
1354 bool notify_result) {
1355 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1356 TRACE_EVENT_SCOPE_THREAD);
1358 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1359 v8::Handle<v8::Value> result =
1360 frame_->executeScriptAndReturnValueForTests(WebScriptSource(jscript));
1362 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1365 void RenderFrameImpl::HandleJavascriptExecutionResult(
1366 const base::string16& jscript,
1369 v8::Handle<v8::Value> result) {
1370 if (notify_result) {
1371 base::ListValue list;
1372 if (!result.IsEmpty()) {
1373 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1374 v8::Context::Scope context_scope(context);
1375 V8ValueConverterImpl converter;
1376 converter.SetDateAllowed(true);
1377 converter.SetRegExpAllowed(true);
1378 base::Value* result_value = converter.FromV8Value(result, context);
1379 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
1381 list.Set(0, base::Value::CreateNullValue());
1383 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1387 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1388 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1389 if (!GetRenderWidget()->ShouldHandleImeEvent())
1391 ImeEventGuard guard(GetRenderWidget());
1392 frame_->setEditableSelectionOffsets(start, end);
1395 void RenderFrameImpl::OnSetCompositionFromExistingText(
1397 const std::vector<blink::WebCompositionUnderline>& underlines) {
1398 if (!GetRenderWidget()->ShouldHandleImeEvent())
1400 ImeEventGuard guard(GetRenderWidget());
1401 frame_->setCompositionFromExistingText(start, end, underlines);
1404 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1405 if (!GetRenderWidget()->ShouldHandleImeEvent())
1407 ImeEventGuard guard(GetRenderWidget());
1408 frame_->extendSelectionAndDelete(before, after);
1411 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1412 if (accessibility_mode_ == new_mode)
1414 accessibility_mode_ = new_mode;
1415 if (renderer_accessibility_) {
1416 // Note: this isn't called automatically by the destructor because
1417 // there'd be no point in calling it in frame teardown, only if there's
1418 // an accessibility mode change but the frame is persisting.
1419 renderer_accessibility_->DisableAccessibility();
1421 delete renderer_accessibility_;
1422 renderer_accessibility_ = NULL;
1424 if (accessibility_mode_ == AccessibilityModeOff)
1427 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1428 renderer_accessibility_ = new RendererAccessibility(this);
1431 void RenderFrameImpl::OnDisownOpener() {
1432 // TODO(creis): We should only see this for main frames for now. To support
1433 // disowning the opener on subframes, we will need to move WebContentsImpl's
1434 // opener_ to FrameTreeNode.
1435 CHECK(!frame_->parent());
1437 if (frame_->opener())
1438 frame_->setOpener(NULL);
1441 #if defined(OS_ANDROID)
1442 void RenderFrameImpl::OnSelectPopupMenuItems(
1444 const std::vector<int>& selected_indices) {
1445 // It is possible to receive more than one of these calls if the user presses
1446 // a select faster than it takes for the show-select-popup IPC message to make
1447 // it to the browser UI thread. Ignore the extra-messages.
1448 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1449 if (!external_popup_menu_)
1452 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1453 external_popup_menu_.reset();
1457 #if defined(OS_MACOSX)
1458 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1459 if (external_popup_menu_ == NULL)
1461 external_popup_menu_->DidSelectItem(selected_index);
1462 external_popup_menu_.reset();
1466 void RenderFrameImpl::OnReload(bool ignore_cache) {
1467 frame_->reload(ignore_cache);
1470 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1471 blink::WebSurroundingText surroundingText;
1472 surroundingText.initialize(frame_->selectionRange(), max_length);
1474 if (surroundingText.isNull()) {
1475 // |surroundingText| might not be correctly initialized, for example if
1476 // |frame_->selectionRange().isNull()|, in other words, if there was no
1478 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1479 routing_id_, base::string16(), 0, 0));
1483 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1485 surroundingText.textContent(),
1486 surroundingText.startOffsetInTextContent(),
1487 surroundingText.endOffsetInTextContent()));
1490 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1491 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1494 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1495 frame_->document().setIsTransitionDocument();
1496 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1499 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector) {
1500 frame_->document().setIsTransitionDocument();
1501 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector));
1504 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1505 const base::string16& message,
1506 const base::string16& default_value,
1507 const GURL& frame_url,
1508 base::string16* result) {
1509 // Don't allow further dialogs if we are waiting to swap out, since the
1510 // PageGroupLoadDeferrer in our stack prevents it.
1511 if (render_view()->suppress_dialogs_until_swap_out_)
1514 bool success = false;
1515 base::string16 result_temp;
1517 result = &result_temp;
1519 render_view()->SendAndRunNestedMessageLoop(
1520 new FrameHostMsg_RunJavaScriptMessage(
1521 routing_id_, message, default_value, frame_url, type, &success,
1526 void RenderFrameImpl::LoadNavigationErrorPage(
1527 const WebURLRequest& failed_request,
1528 const WebURLError& error,
1530 std::string error_html;
1531 GetContentClient()->renderer()->GetNavigationErrorStrings(
1532 render_view(), frame_, failed_request, error, &error_html, NULL);
1534 frame_->loadHTMLString(error_html,
1535 GURL(kUnreachableWebDataURL),
1536 error.unreachableURL,
1540 void RenderFrameImpl::DidCommitCompositorFrame() {
1542 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1545 RenderView* RenderFrameImpl::GetRenderView() {
1546 return render_view_.get();
1549 int RenderFrameImpl::GetRoutingID() {
1553 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1558 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1559 return render_view_->GetWebkitPreferences();
1562 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1563 const ContextMenuParams& params) {
1564 DCHECK(client); // A null client means "internal" when we issue callbacks.
1565 ContextMenuParams our_params(params);
1566 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1567 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1568 return our_params.custom_context.request_id;
1571 void RenderFrameImpl::CancelContextMenu(int request_id) {
1572 DCHECK(pending_context_menus_.Lookup(request_id));
1573 pending_context_menus_.Remove(request_id);
1576 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1577 return context_menu_node_;
1580 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1581 blink::WebFrame* frame,
1582 const WebPluginInfo& info,
1583 const blink::WebPluginParams& params) {
1584 DCHECK_EQ(frame_, frame);
1585 #if defined(ENABLE_PLUGINS)
1586 bool pepper_plugin_was_registered = false;
1587 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1588 this, info, &pepper_plugin_was_registered));
1589 if (pepper_plugin_was_registered) {
1590 if (pepper_module.get()) {
1591 return new PepperWebPluginImpl(pepper_module.get(), params, this);
1594 #if defined(OS_CHROMEOS)
1595 LOG(WARNING) << "Pepper module/plugin creation failed.";
1598 // TODO(jam): change to take RenderFrame.
1599 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1606 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1607 const blink::WebURLRequest& request,
1608 blink::WebNavigationPolicy policy) {
1609 DCHECK(!frame_ || frame_ == frame);
1610 loadURLExternally(frame, request, policy, WebString());
1613 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1614 OnJavaScriptExecuteRequest(javascript, 0, false);
1617 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1618 return &service_registry_;
1621 bool RenderFrameImpl::IsFTPDirectoryListing() {
1622 WebURLResponseExtraDataImpl* extra_data =
1623 GetExtraDataFromResponse(frame_->dataSource()->response());
1624 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1627 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1628 render_view_->GetBrowserPluginManager()->Attach(element_instance_id);
1631 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1633 const gfx::Range& range) {
1634 // Use the routing id of Render Widget Host.
1635 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1641 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1642 v8::Isolate* isolate,
1643 v8::Handle<v8::Context> context) {
1644 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1645 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1648 v8::HandleScope handle_scope(isolate);
1649 registry->AddBuiltinModule(
1650 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1651 registry->AddBuiltinModule(isolate,
1652 mojo::js::Support::kModuleName,
1653 mojo::js::Support::GetModule(isolate));
1654 registry->AddBuiltinModule(
1656 ServiceRegistryJsWrapper::kModuleName,
1657 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1660 // blink::WebFrameClient implementation ----------------------------------------
1662 blink::WebPluginPlaceholder* RenderFrameImpl::createPluginPlaceholder(
1663 blink::WebLocalFrame* frame,
1664 const blink::WebPluginParams& params) {
1665 DCHECK_EQ(frame_, frame);
1666 return GetContentClient()
1668 ->CreatePluginPlaceholder(this, frame, params)
1672 blink::WebPlugin* RenderFrameImpl::createPlugin(
1673 blink::WebLocalFrame* frame,
1674 const blink::WebPluginParams& params) {
1675 DCHECK_EQ(frame_, frame);
1676 blink::WebPlugin* plugin = NULL;
1677 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1678 this, frame, params, &plugin)) {
1682 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1683 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1684 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1685 kBrowserPluginMimeType, GURL(params.url)));
1686 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1687 render_view_.get(), frame, browser_plugin_delegate.Pass());
1690 #if defined(ENABLE_PLUGINS)
1692 std::string mime_type;
1694 Send(new FrameHostMsg_GetPluginInfo(
1695 routing_id_, params.url, frame->top()->document().url(),
1696 params.mimeType.utf8(), &found, &info, &mime_type));
1700 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1701 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1702 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1703 this, mime_type, GURL(params.url)));
1704 return render_view_->GetBrowserPluginManager()->CreateBrowserPlugin(
1705 render_view_.get(), frame, browser_plugin_delegate.Pass());
1709 WebPluginParams params_to_use = params;
1710 params_to_use.mimeType = WebString::fromUTF8(mime_type);
1711 return CreatePlugin(frame, info, params_to_use);
1714 #endif // defined(ENABLE_PLUGINS)
1717 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1718 blink::WebLocalFrame* frame,
1719 const blink::WebURL& url,
1720 blink::WebMediaPlayerClient* client) {
1721 return createMediaPlayer(frame, url, client, NULL);
1724 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1725 blink::WebLocalFrame* frame,
1726 const blink::WebURL& url,
1727 blink::WebMediaPlayerClient* client,
1728 blink::WebContentDecryptionModule* initial_cdm) {
1729 #if defined(VIDEO_HOLE)
1730 if (!contains_media_player_) {
1731 render_view_->RegisterVideoHoleFrame(this);
1732 contains_media_player_ = true;
1734 #endif // defined(VIDEO_HOLE)
1736 blink::WebMediaStream web_stream(
1737 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
1738 if (!web_stream.isNull())
1739 return CreateWebMediaPlayerForMediaStream(url, client);
1741 #if defined(OS_ANDROID)
1742 return CreateAndroidWebMediaPlayer(url, client, initial_cdm);
1744 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1745 media::WebMediaPlayerParams params(
1746 base::Bind(&ContentRendererClient::DeferMediaLoad,
1747 base::Unretained(GetContentClient()->renderer()),
1748 static_cast<RenderFrame*>(this)),
1749 render_thread->GetAudioRendererMixerManager()->CreateInput(
1750 render_view_->routing_id_, routing_id_),
1751 *render_thread->GetAudioHardwareConfig(),
1752 new RenderMediaLog(),
1753 render_thread->GetGpuFactories(),
1754 render_thread->GetMediaThreadTaskRunner(),
1755 render_thread->compositor_message_loop_proxy(),
1756 base::Bind(&EncryptedMediaPlayerSupportImpl::Create),
1759 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
1760 tizen::MediaPlayerImpl* media_player = new tizen::MediaPlayerImpl(
1761 frame, client, weak_factory_.GetWeakPtr(),
1762 GetTizenMediaPlayerManager(), params);
1763 return media_player;
1765 return new media::WebMediaPlayerImpl(
1766 frame, client, weak_factory_.GetWeakPtr(), nullptr, params);
1767 #endif // defined(OS_ANDROID)
1770 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
1771 tizen::RendererMediaPlayerManager*
1772 RenderFrameImpl::GetTizenMediaPlayerManager() {
1773 if (!media_player_manager_)
1774 media_player_manager_ = new tizen::RendererMediaPlayerManager(this);
1776 return media_player_manager_;
1780 blink::WebContentDecryptionModule*
1781 RenderFrameImpl::createContentDecryptionModule(
1782 blink::WebLocalFrame* frame,
1783 const blink::WebSecurityOrigin& security_origin,
1784 const blink::WebString& key_system) {
1785 DCHECK(!frame_ || frame_ == frame);
1787 #if defined(ENABLE_PEPPER_CDMS)
1788 RenderCdmFactory cdm_factory(
1789 base::Bind(&PepperCdmWrapperImpl::Create, frame));
1790 #elif defined(ENABLE_BROWSER_CDMS)
1791 RenderCdmFactory cdm_factory(GetCdmManager());
1793 RenderCdmFactory cdm_factory;
1796 return WebContentDecryptionModuleImpl::Create(&cdm_factory, security_origin,
1800 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
1801 blink::WebLocalFrame* frame,
1802 blink::WebApplicationCacheHostClient* client) {
1803 if (!frame || !frame->view())
1805 DCHECK(!frame_ || frame_ == frame);
1806 return new RendererWebApplicationCacheHostImpl(
1807 RenderViewImpl::FromWebView(frame->view()), client,
1808 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1811 blink::WebWorkerPermissionClientProxy*
1812 RenderFrameImpl::createWorkerPermissionClientProxy(
1813 blink::WebLocalFrame* frame) {
1814 if (!frame || !frame->view())
1816 DCHECK(!frame_ || frame_ == frame);
1817 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1821 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
1822 const WebPopupMenuInfo& popup_menu_info,
1823 WebExternalPopupMenuClient* popup_menu_client) {
1824 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1825 // An IPC message is sent to the browser to build and display the actual
1826 // popup. The user could have time to click a different select by the time
1827 // the popup is shown. In that case external_popup_menu_ is non NULL.
1828 // By returning NULL in that case, we instruct Blink to cancel that new
1829 // popup. So from the user perspective, only the first one will show, and
1830 // will have to close the first one before another one can be shown.
1831 if (external_popup_menu_)
1833 external_popup_menu_.reset(
1834 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1835 if (render_view_->screen_metrics_emulator_) {
1836 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
1837 external_popup_menu_.get(),
1838 render_view_->screen_metrics_emulator_.get());
1840 return external_popup_menu_.get();
1846 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
1847 DCHECK(!frame_ || frame_ == frame);
1848 return &cookie_jar_;
1851 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
1852 blink::WebLocalFrame* frame) {
1853 DCHECK(!frame_ || frame_ == frame);
1854 // At this point we should have non-null data source.
1855 DCHECK(frame->dataSource());
1856 if (!ChildThread::current())
1857 return NULL; // May be null in some tests.
1858 ServiceWorkerNetworkProvider* provider =
1859 ServiceWorkerNetworkProvider::FromDocumentState(
1860 DocumentState::FromDataSource(frame->dataSource()));
1861 return new WebServiceWorkerProviderImpl(
1862 ChildThread::current()->thread_safe_sender(),
1863 provider ? provider->context() : NULL);
1866 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
1867 DCHECK(!frame_ || frame_ == frame);
1868 // Notify the browser process that it is no longer safe to show the pending
1869 // URL of the main frame, since a URL spoof is now possible.
1870 if (!frame->parent() && render_view_->page_id_ == -1)
1871 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
1874 blink::WebFrame* RenderFrameImpl::createChildFrame(
1875 blink::WebLocalFrame* parent,
1876 const blink::WebString& name) {
1877 // Synchronously notify the browser of a child frame creation to get the
1878 // routing_id for the RenderFrame.
1879 int child_routing_id = MSG_ROUTING_NONE;
1880 Send(new FrameHostMsg_CreateChildFrame(routing_id_,
1881 base::UTF16ToUTF8(name),
1882 &child_routing_id));
1883 // Allocation of routing id failed, so we can't create a child frame. This can
1884 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
1886 if (child_routing_id == MSG_ROUTING_NONE) {
1887 #if !defined(OS_LINUX)
1888 // DumpWithoutCrashing() crashes on Linux in renderer processes when
1889 // breakpad and sandboxing are enabled: crbug.com/349600
1890 base::debug::Alias(parent);
1891 base::debug::Alias(&routing_id_);
1892 bool render_view_is_swapped_out = GetRenderWidget()->is_swapped_out();
1893 base::debug::Alias(&render_view_is_swapped_out);
1894 bool render_view_is_closing = GetRenderWidget()->closing();
1895 base::debug::Alias(&render_view_is_closing);
1896 base::debug::Alias(&is_swapped_out_);
1897 base::debug::DumpWithoutCrashing();
1902 // Create the RenderFrame and WebLocalFrame, linking the two.
1903 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
1904 render_view_.get(), child_routing_id);
1905 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
1906 child_render_frame->SetWebFrame(web_frame);
1908 // Add the frame to the frame tree and initialize it.
1909 parent->appendChild(web_frame);
1910 child_render_frame->Initialize();
1915 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
1916 DCHECK(!frame_ || frame_ == frame);
1917 // We only need to notify the browser if the active, top-level frame clears
1918 // its opener. We can ignore cases where a swapped out frame clears its
1919 // opener after hearing about it from the browser, and the browser does not
1920 // (yet) care about subframe openers.
1921 if (render_view_->is_swapped_out_ || frame->parent())
1924 // Notify WebContents and all its swapped out RenderViews.
1925 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
1928 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
1929 // NOTE: This function is called on the frame that is being detached and not
1930 // the parent frame. This is different from createChildFrame() which is
1931 // called on the parent frame.
1932 CHECK(!is_detaching_);
1933 DCHECK(!frame_ || frame_ == frame);
1935 bool is_subframe = !!frame->parent();
1937 Send(new FrameHostMsg_Detach(routing_id_));
1939 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
1940 // sent before setting |is_detaching_| to true. In contrast, Observers
1941 // should only be notified afterwards so they cannot call back into here and
1942 // have IPCs fired off.
1943 is_detaching_ = true;
1945 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1946 FrameDetached(frame));
1948 // We need to clean up subframes by removing them from the map and deleting
1949 // the RenderFrameImpl. In contrast, the main frame is owned by its
1950 // containing RenderViewHost (so that they have the same lifetime), so only
1951 // removal from the map is needed and no deletion.
1952 FrameMap::iterator it = g_frame_map.Get().find(frame);
1953 CHECK(it != g_frame_map.Get().end());
1954 CHECK_EQ(it->second, this);
1955 g_frame_map.Get().erase(it);
1958 frame->parent()->removeChild(frame);
1960 // |frame| is invalid after here.
1965 // Object is invalid after this point.
1969 void RenderFrameImpl::frameFocused() {
1970 Send(new FrameHostMsg_FrameFocused(routing_id_));
1973 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
1974 DCHECK(!frame_ || frame_ == frame);
1976 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
1977 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1978 FrameWillClose(frame));
1981 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
1982 const blink::WebString& name) {
1983 DCHECK(!frame_ || frame_ == frame);
1984 if (!render_view_->renderer_preferences_.report_frame_name_changes)
1987 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeName(name));
1990 void RenderFrameImpl::didMatchCSS(
1991 blink::WebLocalFrame* frame,
1992 const blink::WebVector<blink::WebString>& newly_matching_selectors,
1993 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
1994 DCHECK(!frame_ || frame_ == frame);
1996 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
1998 newly_matching_selectors,
1999 stopped_matching_selectors));
2002 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2003 const blink::WebString& source) {
2004 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2008 void RenderFrameImpl::didAddMessageToConsole(
2009 const blink::WebConsoleMessage& message,
2010 const blink::WebString& source_name,
2011 unsigned source_line,
2012 const blink::WebString& stack_trace) {
2013 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2014 switch (message.level) {
2015 case blink::WebConsoleMessage::LevelDebug:
2016 log_severity = logging::LOG_VERBOSE;
2018 case blink::WebConsoleMessage::LevelLog:
2019 case blink::WebConsoleMessage::LevelInfo:
2020 log_severity = logging::LOG_INFO;
2022 case blink::WebConsoleMessage::LevelWarning:
2023 log_severity = logging::LOG_WARNING;
2025 case blink::WebConsoleMessage::LevelError:
2026 log_severity = logging::LOG_ERROR;
2032 if (shouldReportDetailedMessageForSource(source_name)) {
2034 RenderFrameObserver, observers_,
2035 DetailedConsoleMessageAdded(message.text,
2039 static_cast<int32>(log_severity)));
2042 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2043 static_cast<int32>(log_severity),
2045 static_cast<int32>(source_line),
2049 void RenderFrameImpl::loadURLExternally(
2050 blink::WebLocalFrame* frame,
2051 const blink::WebURLRequest& request,
2052 blink::WebNavigationPolicy policy,
2053 const blink::WebString& suggested_name) {
2054 DCHECK(!frame_ || frame_ == frame);
2055 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2056 if (policy == blink::WebNavigationPolicyDownload) {
2057 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2058 request.url(), referrer,
2061 OpenURL(frame, request.url(), referrer, policy);
2065 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2066 const NavigationPolicyInfo& info) {
2067 DCHECK(!frame_ || frame_ == info.frame);
2068 return DecidePolicyForNavigation(this, info);
2071 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2072 blink::WebFrame* frame) {
2073 DCHECK(!frame_ || frame_ == frame);
2074 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2077 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2078 const blink::WebFormElement& form) {
2079 DCHECK(!frame_ || frame_ == frame);
2081 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2082 WillSendSubmitEvent(frame, form));
2085 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2086 const blink::WebFormElement& form) {
2087 DCHECK(!frame_ || frame_ == frame);
2088 DocumentState* document_state =
2089 DocumentState::FromDataSource(frame->provisionalDataSource());
2090 NavigationState* navigation_state = document_state->navigation_state();
2091 InternalDocumentStateData* internal_data =
2092 InternalDocumentStateData::FromDocumentState(document_state);
2094 if (ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2095 ui::PAGE_TRANSITION_LINK)) {
2096 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2099 // Save these to be processed when the ensuing navigation is committed.
2100 WebSearchableFormData web_searchable_form_data(form);
2101 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2102 internal_data->set_searchable_form_encoding(
2103 web_searchable_form_data.encoding().utf8());
2105 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2106 WillSubmitForm(frame, form));
2109 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2110 blink::WebDataSource* datasource) {
2111 DCHECK(!frame_ || frame_ == frame);
2113 // TODO(nasko): Move implementation here. Needed state:
2114 // * pending_navigation_params_
2117 // * PopulateDocumentStateFromPending
2118 // * CreateNavigationStateFromPending
2119 render_view_->didCreateDataSource(frame, datasource);
2121 // Create the serviceworker's per-document network observing object.
2122 scoped_ptr<ServiceWorkerNetworkProvider>
2123 network_provider(new ServiceWorkerNetworkProvider());
2124 ServiceWorkerNetworkProvider::AttachToDocumentState(
2125 DocumentState::FromDataSource(datasource),
2126 network_provider.Pass());
2129 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2130 bool is_transition_navigation) {
2131 DCHECK(!frame_ || frame_ == frame);
2132 WebDataSource* ds = frame->provisionalDataSource();
2134 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2135 // callback is invoked.
2139 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2140 "id", routing_id_, "url", ds->request().url().string().utf8());
2141 DocumentState* document_state = DocumentState::FromDataSource(ds);
2143 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2144 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2146 render_view_->is_swapped_out()) <<
2147 "Heard swappedout:// when not swapped out.";
2149 // Update the request time if WebKit has better knowledge of it.
2150 if (document_state->request_time().is_null()) {
2151 double event_time = ds->triggeringEventTime();
2152 if (event_time != 0.0)
2153 document_state->set_request_time(Time::FromDoubleT(event_time));
2156 // Start time is only set after request time.
2157 document_state->set_start_load_time(Time::Now());
2159 bool is_top_most = !frame->parent();
2161 render_view_->set_navigation_gesture(
2162 WebUserGestureIndicator::isProcessingUserGesture() ?
2163 NavigationGestureUser : NavigationGestureAuto);
2164 } else if (ds->replacesCurrentHistoryItem()) {
2165 // Subframe navigations that don't add session history items must be
2166 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2167 // handle loading of error pages.
2168 document_state->navigation_state()->set_transition_type(
2169 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2172 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2173 DidStartProvisionalLoad(frame));
2174 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2176 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2177 routing_id_, ds->request().url(), is_transition_navigation));
2180 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2181 blink::WebLocalFrame* frame) {
2182 DCHECK(!frame_ || frame_ == frame);
2183 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2186 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame* frame,
2187 const blink::WebURLError& error) {
2188 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2190 DCHECK(!frame_ || frame_ == frame);
2191 WebDataSource* ds = frame->provisionalDataSource();
2194 const WebURLRequest& failed_request = ds->request();
2196 // Notify the browser that we failed a provisional load with an error.
2198 // Note: It is important this notification occur before DidStopLoading so the
2199 // SSL manager can react to the provisional load failure before being
2200 // notified the load stopped.
2202 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2203 DidFailProvisionalLoad(frame, error));
2204 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2205 DidFailProvisionalLoad(error));
2207 bool show_repost_interstitial =
2208 (error.reason == net::ERR_CACHE_MISS &&
2209 EqualsASCII(failed_request.httpMethod(), "POST"));
2211 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
2212 params.error_code = error.reason;
2213 GetContentClient()->renderer()->GetNavigationErrorStrings(
2219 ¶ms.error_description);
2220 params.url = error.unreachableURL;
2221 params.showing_repost_interstitial = show_repost_interstitial;
2222 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2223 routing_id_, params));
2225 // Don't display an error page if this is simply a cancelled load. Aside
2226 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2227 if (error.reason == net::ERR_ABORTED)
2230 // Don't display "client blocked" error page if browser has asked us not to.
2231 if (error.reason == net::ERR_BLOCKED_BY_CLIENT &&
2232 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
2236 // Allow the embedder to suppress an error page.
2237 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2238 error.unreachableURL)) {
2242 if (RenderThreadImpl::current() &&
2243 RenderThreadImpl::current()->layout_test_mode()) {
2247 // Make sure we never show errors in view source mode.
2248 frame->enableViewSourceMode(false);
2250 DocumentState* document_state = DocumentState::FromDataSource(ds);
2251 NavigationState* navigation_state = document_state->navigation_state();
2253 // If this is a failed back/forward/reload navigation, then we need to do a
2254 // 'replace' load. This is necessary to avoid messing up session history.
2255 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2256 // as session history is concerned.
2258 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2261 // TODO(davidben): This should also take the failed navigation's replacement
2262 // state into account, if a location.replace() failed.
2264 navigation_state->pending_page_id() != -1 ||
2265 ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2266 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2268 // If we failed on a browser initiated request, then make sure that our error
2269 // page load is regarded as the same browser initiated request.
2270 if (!navigation_state->is_content_initiated()) {
2271 render_view_->pending_navigation_params_.reset(
2272 new FrameMsg_Navigate_Params);
2273 render_view_->pending_navigation_params_->page_id =
2274 navigation_state->pending_page_id();
2275 render_view_->pending_navigation_params_->pending_history_list_offset =
2276 navigation_state->pending_history_list_offset();
2277 render_view_->pending_navigation_params_->should_clear_history_list =
2278 navigation_state->history_list_was_cleared();
2279 render_view_->pending_navigation_params_->common_params.transition =
2280 navigation_state->transition_type();
2281 render_view_->pending_navigation_params_->request_time =
2282 document_state->request_time();
2283 render_view_->pending_navigation_params_->should_replace_current_entry =
2287 // Load an error page.
2288 LoadNavigationErrorPage(failed_request, error, replace);
2291 void RenderFrameImpl::didCommitProvisionalLoad(
2292 blink::WebLocalFrame* frame,
2293 const blink::WebHistoryItem& item,
2294 blink::WebHistoryCommitType commit_type) {
2295 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2297 "url", GetLoadingUrl().possibly_invalid_spec());
2298 DCHECK(!frame_ || frame_ == frame);
2299 DocumentState* document_state =
2300 DocumentState::FromDataSource(frame->dataSource());
2301 NavigationState* navigation_state = document_state->navigation_state();
2303 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2304 RenderFrameProxy* proxy =
2305 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2307 proxy->web_frame()->swap(frame_);
2308 proxy_routing_id_ = MSG_ROUTING_NONE;
2311 // When we perform a new navigation, we need to update the last committed
2312 // session history entry with state for the page we are leaving. Do this
2313 // before updating the HistoryController state.
2314 render_view_->UpdateSessionHistory(frame);
2316 render_view_->history_controller()->UpdateForCommit(this, item, commit_type,
2317 navigation_state->was_within_same_page());
2319 InternalDocumentStateData* internal_data =
2320 InternalDocumentStateData::FromDocumentState(document_state);
2322 if (document_state->commit_load_time().is_null())
2323 document_state->set_commit_load_time(Time::Now());
2325 if (internal_data->must_reset_scroll_and_scale_state()) {
2326 render_view_->webview()->resetScrollAndScaleState();
2327 internal_data->set_must_reset_scroll_and_scale_state(false);
2329 internal_data->set_use_error_page(false);
2331 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2332 if (is_new_navigation) {
2333 // We bump our Page ID to correspond with the new session history entry.
2334 render_view_->page_id_ = render_view_->next_page_id_++;
2336 // Don't update history_page_ids_ (etc) for kSwappedOutURL, since
2337 // we don't want to forget the entry that was there, and since we will
2338 // never come back to kSwappedOutURL. Note that we have to call
2339 // UpdateSessionHistory and update page_id_ even in this case, so that
2340 // the current entry gets a state update and so that we don't send a
2341 // state update to the wrong entry when we swap back in.
2342 if (GetLoadingUrl() != GURL(kSwappedOutURL)) {
2343 // Advance our offset in session history, applying the length limit.
2344 // There is now no forward history.
2345 render_view_->history_list_offset_++;
2346 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2347 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2348 render_view_->history_list_length_ =
2349 render_view_->history_list_offset_ + 1;
2350 render_view_->history_page_ids_.resize(
2351 render_view_->history_list_length_, -1);
2352 render_view_->history_page_ids_[render_view_->history_list_offset_] =
2353 render_view_->page_id_;
2356 // Inspect the navigation_state on this frame to see if the navigation
2357 // corresponds to a session history navigation... Note: |frame| may or
2358 // may not be the toplevel frame, but for the case of capturing session
2359 // history, the first committed frame suffices. We keep track of whether
2360 // we've seen this commit before so that only capture session history once
2363 // Note that we need to check if the page ID changed. In the case of a
2364 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2365 // previous URL and the current page ID, which would be wrong.
2366 if (navigation_state->pending_page_id() != -1 &&
2367 navigation_state->pending_page_id() != render_view_->page_id_ &&
2368 !navigation_state->request_committed()) {
2369 // This is a successful session history navigation!
2370 render_view_->page_id_ = navigation_state->pending_page_id();
2372 render_view_->history_list_offset_ =
2373 navigation_state->pending_history_list_offset();
2375 // If the history list is valid, our list of page IDs should be correct.
2376 DCHECK(render_view_->history_list_length_ <= 0 ||
2377 render_view_->history_list_offset_ < 0 ||
2378 render_view_->history_list_offset_ >=
2379 render_view_->history_list_length_ ||
2380 render_view_->history_page_ids_[render_view_->history_list_offset_]
2381 == render_view_->page_id_);
2386 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2387 CHECK(sent); // http://crbug.com/407376
2389 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2390 DidCommitProvisionalLoad(frame, is_new_navigation));
2391 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2392 DidCommitProvisionalLoad(is_new_navigation));
2394 if (!frame->parent()) { // Only for top frames.
2395 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2396 if (render_thread_impl) { // Can be NULL in tests.
2397 render_thread_impl->histogram_customizer()->
2398 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2399 RenderViewImpl::GetRenderViewCount());
2403 // Remember that we've already processed this request, so we don't update
2404 // the session history again. We do this regardless of whether this is
2405 // a session history navigation, because if we attempted a session history
2406 // navigation without valid HistoryItem state, WebCore will think it is a
2408 navigation_state->set_request_committed(true);
2410 SendDidCommitProvisionalLoad(frame);
2412 // Check whether we have new encoding name.
2413 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2416 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2417 DCHECK(!frame_ || frame_ == frame);
2418 // TODO(nasko): Move implementation here. Needed state:
2419 // * enabled_bindings_
2420 // * dom_automation_controller_
2421 // * stats_collection_controller_
2423 render_view_->didClearWindowObject(frame);
2425 if (render_view_->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION)
2426 DomAutomationController::Install(this, frame);
2428 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2431 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2432 DCHECK(!frame_ || frame_ == frame);
2434 // Notify the browser about non-blank documents loading in the top frame.
2435 GURL url = frame->document().url();
2436 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2437 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2438 // frame->tree()->top().
2439 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2440 if (frame == main_frame) {
2441 // For now, don't remember plugin zoom values. We don't want to mix them
2442 // with normal web content (i.e. a fixed layout plugin would usually want
2444 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2445 render_view_->GetRoutingID(),
2446 main_frame->document().isPluginDocument()));
2450 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2451 DidCreateDocumentElement(frame));
2454 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2455 const blink::WebString& title,
2456 blink::WebTextDirection direction) {
2457 DCHECK(!frame_ || frame_ == frame);
2458 // Ignore all but top level navigations.
2459 if (!frame->parent()) {
2460 base::string16 title16 = title;
2461 base::debug::TraceLog::GetInstance()->UpdateProcessLabel(
2462 routing_id_, base::UTF16ToUTF8(title16));
2464 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2465 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2466 shortened_title, direction));
2469 // Also check whether we have new encoding name.
2470 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2473 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2474 blink::WebIconURL::Type icon_type) {
2475 DCHECK(!frame_ || frame_ == frame);
2476 // TODO(nasko): Investigate wheather implementation should move here.
2477 render_view_->didChangeIcon(frame, icon_type);
2480 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2481 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2483 DCHECK(!frame_ || frame_ == frame);
2484 WebDataSource* ds = frame->dataSource();
2485 DocumentState* document_state = DocumentState::FromDataSource(ds);
2486 document_state->set_finish_document_load_time(Time::Now());
2488 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2490 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2491 DidFinishDocumentLoad(frame));
2492 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2494 // Check whether we have new encoding name.
2495 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2498 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2499 DCHECK(!frame_ || frame_ == frame);
2500 if (!frame->parent())
2501 Send(new FrameHostMsg_DocumentOnLoadCompleted(routing_id_));
2504 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2505 const blink::WebURLError& error) {
2506 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2508 DCHECK(!frame_ || frame_ == frame);
2509 // TODO(nasko): Move implementation here. No state needed.
2510 WebDataSource* ds = frame->dataSource();
2513 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2514 DidFailLoad(frame, error));
2516 const WebURLRequest& failed_request = ds->request();
2517 base::string16 error_description;
2518 GetContentClient()->renderer()->GetNavigationErrorStrings(
2524 &error_description);
2525 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2526 failed_request.url(),
2528 error_description));
2531 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2532 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2534 DCHECK(!frame_ || frame_ == frame);
2535 WebDataSource* ds = frame->dataSource();
2536 DocumentState* document_state = DocumentState::FromDataSource(ds);
2537 if (document_state->finish_load_time().is_null()) {
2538 if (!frame->parent()) {
2539 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2540 TRACE_EVENT_SCOPE_PROCESS);
2542 document_state->set_finish_load_time(Time::Now());
2545 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2546 DidFinishLoad(frame));
2547 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2549 // Don't send this message while the frame is swapped out.
2550 if (is_swapped_out())
2553 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2554 ds->request().url()));
2557 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2558 const blink::WebHistoryItem& item,
2559 blink::WebHistoryCommitType commit_type) {
2560 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2562 DCHECK(!frame_ || frame_ == frame);
2563 // If this was a reference fragment navigation that we initiated, then we
2564 // could end up having a non-null pending navigation params. We just need to
2565 // update the ExtraData on the datasource so that others who read the
2566 // ExtraData will get the new NavigationState. Similarly, if we did not
2567 // initiate this navigation, then we need to take care to reset any pre-
2568 // existing navigation state to a content-initiated navigation state.
2569 // DidCreateDataSource conveniently takes care of this for us.
2570 didCreateDataSource(frame, frame->dataSource());
2572 DocumentState* document_state =
2573 DocumentState::FromDataSource(frame->dataSource());
2574 NavigationState* new_state = document_state->navigation_state();
2575 new_state->set_was_within_same_page(true);
2577 didCommitProvisionalLoad(frame, item, commit_type);
2580 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2581 DCHECK(!frame_ || frame_ == frame);
2582 // TODO(nasko): Move implementation here. Needed methods:
2583 // * StartNavStateSyncTimerIfNecessary
2584 render_view_->didUpdateCurrentHistoryItem(frame);
2587 // TODO(zhenw): This will be removed once the blink side implementation is done.
2588 void RenderFrameImpl::addNavigationTransitionData(
2589 const blink::WebString& allowed_destination_host_pattern,
2590 const blink::WebString& selector,
2591 const blink::WebString& markup) {
2592 FrameHostMsg_AddNavigationTransitionData_Params params;
2593 params.render_frame_id = routing_id_;
2594 params.allowed_destination_host_pattern =
2595 allowed_destination_host_pattern.utf8();
2596 params.selector = selector.utf8();
2597 params.markup = markup.utf8();
2599 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2602 void RenderFrameImpl::addNavigationTransitionData(
2603 const blink::WebString& allowed_destination_host_pattern,
2604 const blink::WebString& selector,
2605 const blink::WebString& markup,
2606 const blink::WebVector<blink::WebString>& web_names,
2607 const blink::WebVector<blink::WebRect>& web_rects) {
2608 FrameHostMsg_AddNavigationTransitionData_Params params;
2609 params.render_frame_id = routing_id_;
2610 params.allowed_destination_host_pattern =
2611 allowed_destination_host_pattern.utf8();
2612 params.selector = selector.utf8();
2613 params.markup = markup.utf8();
2614 params.elements.resize(web_names.size());
2615 for (size_t i = 0; i < web_names.size(); i++) {
2616 params.elements[i].name = web_names[i].utf8();
2617 params.elements[i].rect = gfx::Rect(web_rects[i]);
2620 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2623 void RenderFrameImpl::didChangeThemeColor() {
2624 if (frame_->parent())
2627 Send(new FrameHostMsg_DidChangeThemeColor(
2628 routing_id_, frame_->document().themeColor()));
2631 void RenderFrameImpl::requestNotificationPermission(
2632 const blink::WebSecurityOrigin& origin,
2633 blink::WebNotificationPermissionCallback* callback) {
2634 if (!notification_permission_dispatcher_) {
2635 notification_permission_dispatcher_ =
2636 new NotificationPermissionDispatcher(this);
2639 notification_permission_dispatcher_->RequestPermission(origin, callback);
2642 blink::WebNotificationPresenter* RenderFrameImpl::notificationPresenter() {
2643 return notification_provider_;
2646 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2647 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2650 if (is_empty_selection)
2651 selection_text_.clear();
2653 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2654 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2655 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2656 // to notify the selection was changed. Focus change should be notified
2657 // before selection change.
2658 GetRenderWidget()->UpdateTextInputType();
2659 SyncSelectionIfRequired();
2660 #if defined(OS_ANDROID)
2661 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
2662 RenderWidget::FROM_NON_IME);
2666 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
2667 blink::WebColorChooserClient* client,
2668 const blink::WebColor& initial_color,
2669 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2670 RendererWebColorChooserImpl* color_chooser =
2671 new RendererWebColorChooserImpl(this, client);
2672 std::vector<ColorSuggestion> color_suggestions;
2673 for (size_t i = 0; i < suggestions.size(); i++) {
2674 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
2676 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2677 return color_chooser;
2680 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
2681 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2684 frame_->document().url(),
2688 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
2689 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2692 frame_->document().url(),
2696 bool RenderFrameImpl::runModalPromptDialog(
2697 const blink::WebString& message,
2698 const blink::WebString& default_value,
2699 blink::WebString* actual_value) {
2700 base::string16 result;
2701 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2704 frame_->document().url(),
2707 actual_value->assign(result);
2711 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2713 const blink::WebString& message) {
2714 // If we are swapping out, we have already run the beforeunload handler.
2715 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2716 // at all, to avoid running it twice.
2717 if (render_view()->is_swapped_out_)
2720 // Don't allow further dialogs if we are waiting to swap out, since the
2721 // PageGroupLoadDeferrer in our stack prevents it.
2722 if (render_view()->suppress_dialogs_until_swap_out_)
2725 bool success = false;
2726 // This is an ignored return value, but is included so we can accept the same
2727 // response as RunJavaScriptMessage.
2728 base::string16 ignored_result;
2729 render_view()->SendAndRunNestedMessageLoop(
2730 new FrameHostMsg_RunBeforeUnloadConfirm(
2731 routing_id_, frame_->document().url(), message, is_reload,
2732 &success, &ignored_result));
2736 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
2737 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
2738 params.source_type = GetRenderWidget()->context_menu_source_type();
2739 GetRenderWidget()->OnShowHostContextMenu(¶ms);
2740 if (GetRenderWidget()->has_host_context_menu_location()) {
2741 params.x = GetRenderWidget()->host_context_menu_location().x();
2742 params.y = GetRenderWidget()->host_context_menu_location().y();
2745 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2746 // it. We replace it with an empty GURL so the appropriate items are disabled
2747 // in the context menu.
2748 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2749 // data encoded images. We should have a way to save them.
2750 if (params.src_url.spec().size() > GetMaxURLChars())
2751 params.src_url = GURL();
2752 context_menu_node_ = data.node;
2754 #if defined(OS_ANDROID)
2755 gfx::Rect start_rect;
2757 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
2758 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
2759 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
2762 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
2765 void RenderFrameImpl::clearContextMenu() {
2766 context_menu_node_.reset();
2769 void RenderFrameImpl::willSendRequest(
2770 blink::WebLocalFrame* frame,
2771 unsigned identifier,
2772 blink::WebURLRequest& request,
2773 const blink::WebURLResponse& redirect_response) {
2774 DCHECK(!frame_ || frame_ == frame);
2775 // The request my be empty during tests.
2776 if (request.url().isEmpty())
2779 // Set the first party for cookies url if it has not been set yet (new
2780 // requests). For redirects, it is updated by WebURLLoaderImpl.
2781 if (request.firstPartyForCookies().isEmpty()) {
2782 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
2783 request.setFirstPartyForCookies(request.url());
2785 // TODO(nasko): When the top-level frame is remote, there is no document.
2786 // This is broken and should be fixed to propagate the first party.
2787 WebFrame* top = frame->top();
2788 if (top->isWebLocalFrame()) {
2789 request.setFirstPartyForCookies(
2790 frame->top()->document().firstPartyForCookies());
2795 WebFrame* top_frame = frame->top();
2796 // TODO(nasko): Hack around asking about top-frame data source. This means
2797 // for out-of-process iframes we are treating the current frame as the
2798 // top-level frame, which is wrong.
2799 if (!top_frame || top_frame->isWebRemoteFrame())
2801 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
2802 WebDataSource* top_data_source = top_frame->dataSource();
2803 WebDataSource* data_source =
2804 provisional_data_source ? provisional_data_source : top_data_source;
2806 ui::PageTransition transition_type = ui::PAGE_TRANSITION_LINK;
2807 DocumentState* document_state = DocumentState::FromDataSource(data_source);
2808 DCHECK(document_state);
2809 InternalDocumentStateData* internal_data =
2810 InternalDocumentStateData::FromDocumentState(document_state);
2811 NavigationState* navigation_state = document_state->navigation_state();
2812 transition_type = navigation_state->transition_type();
2814 GURL request_url(request.url());
2816 if (GetContentClient()->renderer()->WillSendRequest(
2820 request.firstPartyForCookies(),
2822 request.setURL(WebURL(new_url));
2825 if (internal_data->is_cache_policy_override_set())
2826 request.setCachePolicy(internal_data->cache_policy_override());
2828 // The request's extra data may indicate that we should set a custom user
2829 // agent. This needs to be done here, after WebKit is through with setting the
2830 // user agent on its own. Similarly, it may indicate that we should set an
2831 // X-Requested-With header. This must be done here to avoid breaking CORS
2833 // PlzNavigate: there may also be a stream url associated with the request.
2834 WebString custom_user_agent;
2835 WebString requested_with;
2836 scoped_ptr<StreamOverrideParameters> stream_override;
2837 if (request.extraData()) {
2838 RequestExtraData* old_extra_data =
2839 static_cast<RequestExtraData*>(request.extraData());
2841 custom_user_agent = old_extra_data->custom_user_agent();
2842 if (!custom_user_agent.isNull()) {
2843 if (custom_user_agent.isEmpty())
2844 request.clearHTTPHeaderField("User-Agent");
2846 request.setHTTPHeaderField("User-Agent", custom_user_agent);
2849 requested_with = old_extra_data->requested_with();
2850 if (!requested_with.isNull()) {
2851 if (requested_with.isEmpty())
2852 request.clearHTTPHeaderField("X-Requested-With");
2854 request.setHTTPHeaderField("X-Requested-With", requested_with);
2856 stream_override = old_extra_data->TakeStreamOverrideOwnership();
2859 // Add the default accept header for frame request if it has not been set
2861 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2862 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
2863 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
2864 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
2865 WebString::fromUTF8(kDefaultAcceptHeader));
2868 // Add an empty HTTP origin header for non GET methods if none is currently
2870 request.addHTTPOriginIfNeeded(WebString());
2872 // Attach |should_replace_current_entry| state to requests so that, should
2873 // this navigation later require a request transfer, all state is preserved
2874 // when it is re-created in the new process.
2875 bool should_replace_current_entry = false;
2876 if (navigation_state->is_content_initiated()) {
2877 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
2879 // If the navigation is browser-initiated, the NavigationState contains the
2880 // correct value instead of the WebDataSource.
2882 // TODO(davidben): Avoid this awkward duplication of state. See comment on
2883 // NavigationState::should_replace_current_entry().
2884 should_replace_current_entry =
2885 navigation_state->should_replace_current_entry();
2888 int provider_id = kInvalidServiceWorkerProviderId;
2889 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
2890 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
2891 // |provisionalDataSource| may be null in some content::ResourceFetcher
2892 // use cases, we don't hook those requests.
2893 if (frame->provisionalDataSource()) {
2894 ServiceWorkerNetworkProvider* provider =
2895 ServiceWorkerNetworkProvider::FromDocumentState(
2896 DocumentState::FromDataSource(frame->provisionalDataSource()));
2897 provider_id = provider->provider_id();
2899 } else if (frame->dataSource()) {
2900 ServiceWorkerNetworkProvider* provider =
2901 ServiceWorkerNetworkProvider::FromDocumentState(
2902 DocumentState::FromDataSource(frame->dataSource()));
2903 provider_id = provider->provider_id();
2906 WebFrame* parent = frame->parent();
2907 int parent_routing_id = MSG_ROUTING_NONE;
2909 parent_routing_id = -1;
2910 } else if (parent->isWebLocalFrame()) {
2911 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
2913 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
2916 RequestExtraData* extra_data = new RequestExtraData();
2917 extra_data->set_visibility_state(render_view_->visibilityState());
2918 extra_data->set_custom_user_agent(custom_user_agent);
2919 extra_data->set_requested_with(requested_with);
2920 extra_data->set_render_frame_id(routing_id_);
2921 extra_data->set_is_main_frame(frame == top_frame);
2922 extra_data->set_frame_origin(
2923 GURL(frame->document().securityOrigin().toString()));
2924 extra_data->set_parent_is_main_frame(frame->parent() == top_frame);
2925 extra_data->set_parent_render_frame_id(parent_routing_id);
2926 extra_data->set_allow_download(navigation_state->allow_download());
2927 extra_data->set_transition_type(transition_type);
2928 extra_data->set_should_replace_current_entry(should_replace_current_entry);
2929 extra_data->set_transferred_request_child_id(
2930 navigation_state->transferred_request_child_id());
2931 extra_data->set_transferred_request_request_id(
2932 navigation_state->transferred_request_request_id());
2933 extra_data->set_service_worker_provider_id(provider_id);
2934 extra_data->set_stream_override(stream_override.Pass());
2935 request.setExtraData(extra_data);
2937 DocumentState* top_document_state =
2938 DocumentState::FromDataSource(top_data_source);
2939 if (top_document_state) {
2940 // TODO(gavinp): separate out prefetching and prerender field trials
2941 // if the rel=prerender rel type is sticking around.
2942 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
2943 top_document_state->set_was_prefetcher(true);
2946 // This is an instance where we embed a copy of the routing id
2947 // into the data portion of the message. This can cause problems if we
2948 // don't register this id on the browser side, since the download manager
2949 // expects to find a RenderViewHost based off the id.
2950 request.setRequestorID(render_view_->GetRoutingID());
2951 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
2953 if (!navigation_state->extra_headers().empty()) {
2954 for (net::HttpUtil::HeadersIterator i(
2955 navigation_state->extra_headers().begin(),
2956 navigation_state->extra_headers().end(), "\n");
2958 if (LowerCaseEqualsASCII(i.name(), "referer")) {
2959 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
2960 blink::WebReferrerPolicyDefault,
2962 WebString::fromUTF8(i.values()));
2963 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
2965 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
2966 WebString::fromUTF8(i.values()));
2971 if (!render_view_->renderer_preferences_.enable_referrers)
2972 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
2975 void RenderFrameImpl::didReceiveResponse(
2976 blink::WebLocalFrame* frame,
2977 unsigned identifier,
2978 const blink::WebURLResponse& response) {
2979 DCHECK(!frame_ || frame_ == frame);
2980 // Only do this for responses that correspond to a provisional data source
2981 // of the top-most frame. If we have a provisional data source, then we
2982 // can't have any sub-resources yet, so we know that this response must
2983 // correspond to a frame load.
2984 if (!frame->provisionalDataSource() || frame->parent())
2987 // If we are in view source mode, then just let the user see the source of
2988 // the server's error page.
2989 if (frame->isViewSourceModeEnabled())
2992 DocumentState* document_state =
2993 DocumentState::FromDataSource(frame->provisionalDataSource());
2994 int http_status_code = response.httpStatusCode();
2996 // Record page load flags.
2997 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
2999 document_state->set_was_fetched_via_spdy(
3000 extra_data->was_fetched_via_spdy());
3001 document_state->set_was_npn_negotiated(
3002 extra_data->was_npn_negotiated());
3003 document_state->set_npn_negotiated_protocol(
3004 extra_data->npn_negotiated_protocol());
3005 document_state->set_was_alternate_protocol_available(
3006 extra_data->was_alternate_protocol_available());
3007 document_state->set_connection_info(
3008 extra_data->connection_info());
3009 document_state->set_was_fetched_via_proxy(
3010 extra_data->was_fetched_via_proxy());
3011 document_state->set_proxy_server(
3012 extra_data->proxy_server());
3014 InternalDocumentStateData* internal_data =
3015 InternalDocumentStateData::FromDocumentState(document_state);
3016 internal_data->set_http_status_code(http_status_code);
3017 // Whether or not the http status code actually corresponds to an error is
3018 // only checked when the page is done loading, if |use_error_page| is
3020 internal_data->set_use_error_page(true);
3023 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
3024 unsigned identifier) {
3025 DCHECK(!frame_ || frame_ == frame);
3026 InternalDocumentStateData* internal_data =
3027 InternalDocumentStateData::FromDataSource(frame->dataSource());
3028 if (!internal_data->use_error_page())
3031 // Do not show error page when DevTools is attached.
3032 if (render_view_->devtools_agent_->IsAttached())
3035 // Display error page, if appropriate.
3036 std::string error_domain = "http";
3037 int http_status_code = internal_data->http_status_code();
3038 if (GetContentClient()->renderer()->HasErrorPage(
3039 http_status_code, &error_domain)) {
3041 error.unreachableURL = frame->document().url();
3042 error.domain = WebString::fromUTF8(error_domain);
3043 error.reason = http_status_code;
3044 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
3048 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3049 blink::WebLocalFrame* frame,
3050 const blink::WebURLRequest& request,
3051 const blink::WebURLResponse& response) {
3052 DCHECK(!frame_ || frame_ == frame);
3053 // The recipients of this message have no use for data: URLs: they don't
3054 // affect the page's insecure content list and are not in the disk cache. To
3055 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3056 // filter them out here.
3057 GURL url(request.url());
3058 if (url.SchemeIs(url::kDataScheme))
3061 // Let the browser know we loaded a resource from the memory cache. This
3062 // message is needed to display the correct SSL indicators.
3063 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3064 render_view_->GetRoutingID(),
3066 response.securityInfo(),
3067 request.httpMethod().utf8(),
3068 response.mimeType().utf8(),
3069 WebURLRequestToResourceType(request)));
3072 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3073 DCHECK(!frame_ || frame_ == frame);
3074 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
3075 render_view_->GetRoutingID()));
3078 void RenderFrameImpl::didRunInsecureContent(
3079 blink::WebLocalFrame* frame,
3080 const blink::WebSecurityOrigin& origin,
3081 const blink::WebURL& target) {
3082 DCHECK(!frame_ || frame_ == frame);
3083 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
3084 render_view_->GetRoutingID(),
3085 origin.toString().utf8(),
3089 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3090 DCHECK(!frame_ || frame_ == frame);
3091 #if defined(ENABLE_PLUGINS)
3092 if (frame != render_view_->webview()->mainFrame())
3094 PluginChannelHost::Broadcast(
3095 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3099 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3100 v8::Handle<v8::Context> context,
3101 int extension_group,
3103 DCHECK(!frame_ || frame_ == frame);
3104 GetContentClient()->renderer()->DidCreateScriptContext(
3105 frame, context, extension_group, world_id);
3108 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3109 v8::Handle<v8::Context> context,
3111 DCHECK(!frame_ || frame_ == frame);
3113 FOR_EACH_OBSERVER(RenderFrameObserver,
3115 WillReleaseScriptContext(context, world_id));
3118 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3119 blink::WebLocalFrame* frame) {
3120 DCHECK(!frame_ || frame_ == frame);
3121 if (frame->parent())
3124 InternalDocumentStateData* data =
3125 InternalDocumentStateData::FromDataSource(frame->dataSource());
3126 data->set_did_first_visually_non_empty_layout(true);
3128 #if defined(OS_ANDROID)
3129 GetRenderWidget()->DidChangeBodyBackgroundColor(
3130 render_view_->webwidget_->backgroundColor());
3133 GetRenderWidget()->QueueMessage(
3134 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3135 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3138 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3139 DCHECK(!frame_ || frame_ == frame);
3140 // TODO(nasko): Move implementation here. Needed methods:
3141 // * StartNavStateSyncTimerIfNecessary
3142 render_view_->didChangeScrollOffset(frame);
3145 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3146 DCHECK(!frame_ || frame_ == frame);
3147 if (!frame->parent()) {
3148 render_view_->Send(new ViewHostMsg_WillInsertBody(
3149 render_view_->GetRoutingID()));
3153 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3155 bool final_update) {
3156 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3158 active_match_ordinal = 0;
3160 render_view_->Send(new ViewHostMsg_Find_Reply(
3161 render_view_->GetRoutingID(), request_id, count,
3162 gfx::Rect(), active_match_ordinal, final_update));
3165 void RenderFrameImpl::reportFindInPageSelection(
3167 int active_match_ordinal,
3168 const blink::WebRect& selection_rect) {
3169 render_view_->Send(new ViewHostMsg_Find_Reply(
3170 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3171 active_match_ordinal, false));
3174 void RenderFrameImpl::requestStorageQuota(
3175 blink::WebLocalFrame* frame,
3176 blink::WebStorageQuotaType type,
3177 unsigned long long requested_size,
3178 blink::WebStorageQuotaCallbacks callbacks) {
3179 DCHECK(!frame_ || frame_ == frame);
3180 WebSecurityOrigin origin = frame->document().securityOrigin();
3181 if (origin.isUnique()) {
3182 // Unique origins cannot store persistent state.
3183 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3186 ChildThread::current()->quota_dispatcher()->RequestStorageQuota(
3187 render_view_->GetRoutingID(),
3188 GURL(origin.toString()),
3189 static_cast<storage::StorageType>(type),
3191 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3194 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3195 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3196 impl->set_render_frame_id(routing_id_);
3199 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3200 if (!geolocation_dispatcher_)
3201 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3202 return geolocation_dispatcher_;
3205 void RenderFrameImpl::requestPushPermission(blink::WebCallback* callback) {
3206 if (!push_permission_dispatcher_)
3207 push_permission_dispatcher_ = new PushPermissionDispatcher(this);
3208 push_permission_dispatcher_->RequestPermission(callback);
3211 blink::WebPushClient* RenderFrameImpl::pushClient() {
3212 if (!push_messaging_dispatcher_)
3213 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3214 return push_messaging_dispatcher_;
3217 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3218 blink::WebLocalFrame* frame,
3219 blink::WebRTCPeerConnectionHandler* handler) {
3220 DCHECK(!frame_ || frame_ == frame);
3221 #if defined(ENABLE_WEBRTC)
3222 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3226 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3227 if (!web_user_media_client_)
3228 InitializeUserMediaClient();
3229 return web_user_media_client_;
3232 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3233 if (!midi_dispatcher_)
3234 midi_dispatcher_ = new MidiDispatcher(this);
3235 return midi_dispatcher_;
3238 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3239 blink::WebLocalFrame* source_frame,
3240 blink::WebFrame* target_frame,
3241 blink::WebSecurityOrigin target_origin,
3242 blink::WebDOMMessageEvent event) {
3243 DCHECK(!frame_ || frame_ == target_frame);
3245 if (!render_view_->is_swapped_out_)
3248 ViewMsg_PostMessage_Params params;
3249 params.is_data_raw_string = false;
3250 params.data = event.data().toString();
3251 params.source_origin = event.origin();
3252 if (!target_origin.isNull())
3253 params.target_origin = target_origin.toString();
3255 blink::WebMessagePortChannelArray channels = event.releaseChannels();
3256 if (!channels.isEmpty()) {
3257 std::vector<int> message_port_ids(channels.size());
3258 // Extract the port IDs from the channel array.
3259 for (size_t i = 0; i < channels.size(); ++i) {
3260 WebMessagePortChannelImpl* webchannel =
3261 static_cast<WebMessagePortChannelImpl*>(channels[i]);
3262 message_port_ids[i] = webchannel->message_port_id();
3263 webchannel->QueueMessages();
3264 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
3266 params.message_port_ids = message_port_ids;
3269 // Include the routing ID for the source frame (if one exists), which the
3270 // browser process will translate into the routing ID for the equivalent
3271 // frame in the target process.
3272 params.source_routing_id = MSG_ROUTING_NONE;
3274 RenderViewImpl* source_view =
3275 RenderViewImpl::FromWebView(source_frame->view());
3277 params.source_routing_id = source_view->routing_id();
3280 Send(new ViewHostMsg_RouteMessageEvent(render_view_->routing_id_, params));
3284 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3285 const blink::WebURL& url) {
3286 DCHECK(!frame_ || frame_ == frame);
3287 std::string user_agent_override_for_url =
3288 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3289 if (!user_agent_override_for_url.empty())
3290 return WebString::fromUTF8(user_agent_override_for_url);
3292 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3293 render_view_->renderer_preferences_.user_agent_override.empty()) {
3294 return blink::WebString();
3297 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3298 // associated with it, so the checks below are not valid. Temporarily
3299 // return early and fix properly as part of https://crbug.com/426555.
3300 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3301 return blink::WebString();
3303 // If we're in the middle of committing a load, the data source we need
3304 // will still be provisional.
3305 WebFrame* main_frame = render_view_->webview()->mainFrame();
3306 WebDataSource* data_source = NULL;
3307 if (main_frame->provisionalDataSource())
3308 data_source = main_frame->provisionalDataSource();
3310 data_source = main_frame->dataSource();
3312 InternalDocumentStateData* internal_data = data_source ?
3313 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3314 if (internal_data && internal_data->is_overriding_user_agent())
3315 return WebString::fromUTF8(
3316 render_view_->renderer_preferences_.user_agent_override);
3317 return blink::WebString();
3320 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3321 DCHECK(!frame_ || frame_ == frame);
3322 if (render_view_->renderer_preferences_.enable_do_not_track)
3323 return WebString::fromUTF8("1");
3327 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3328 bool default_value) {
3329 DCHECK(!frame_ || frame_ == frame);
3333 bool blocked = true;
3334 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3335 render_view_->GetRoutingID(),
3336 GURL(frame->top()->document().securityOrigin().toString()),
3337 THREE_D_API_TYPE_WEBGL,
3342 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3343 int arb_robustness_status_code) {
3344 DCHECK(!frame_ || frame_ == frame);
3345 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3346 GURL(frame->top()->document().securityOrigin().toString()),
3347 THREE_D_API_TYPE_WEBGL,
3348 arb_robustness_status_code));
3351 blink::WebScreenOrientationClient*
3352 RenderFrameImpl::webScreenOrientationClient() {
3353 if (!screen_orientation_dispatcher_)
3354 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3355 return screen_orientation_dispatcher_;
3358 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3359 ServiceWorkerNetworkProvider* provider =
3360 ServiceWorkerNetworkProvider::FromDocumentState(
3361 DocumentState::FromDataSource(&data_source));
3362 return provider->context()->controller_handle_id() !=
3363 kInvalidServiceWorkerHandleId;
3366 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3367 ServiceWorkerNetworkProvider* provider =
3368 ServiceWorkerNetworkProvider::FromDocumentState(
3369 DocumentState::FromDataSource(&data_source));
3371 if (provider->context()->controller())
3372 return provider->context()->controller()->version_id();
3373 return kInvalidServiceWorkerVersionId;
3376 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3377 blink::WebAXEvent event) {
3378 HandleWebAccessibilityEvent(obj, event);
3381 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3384 const blink::WebAXObject& start_object,
3386 const blink::WebAXObject& end_object,
3388 if (renderer_accessibility_) {
3389 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3390 identifier, match_index, start_object, start_offset,
3391 end_object, end_offset);
3395 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame)
3397 DCHECK(!frame_ || frame_ == frame);
3399 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3402 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3403 Send(new FrameHostMsg_MediaPlayingNotification(
3404 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3405 player->hasAudio(), player->isRemote()));
3408 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3409 Send(new FrameHostMsg_MediaPausedNotification(
3410 routing_id_, reinterpret_cast<int64>(player)));
3413 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3417 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3418 observers_.AddObserver(observer);
3421 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3422 observer->RenderFrameGone();
3423 observers_.RemoveObserver(observer);
3426 void RenderFrameImpl::OnStop() {
3428 frame_->stopLoading();
3429 if (!frame_->parent())
3430 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3432 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3435 void RenderFrameImpl::WasHidden() {
3436 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3439 void RenderFrameImpl::WasShown() {
3440 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3443 bool RenderFrameImpl::IsHidden() {
3444 return GetRenderWidget()->is_hidden();
3447 // Tell the embedding application that the URL of the active page has changed.
3448 void RenderFrameImpl::SendDidCommitProvisionalLoad(blink::WebFrame* frame) {
3449 DCHECK(!frame_ || frame_ == frame);
3450 WebDataSource* ds = frame->dataSource();
3453 const WebURLRequest& request = ds->request();
3454 const WebURLResponse& response = ds->response();
3456 DocumentState* document_state = DocumentState::FromDataSource(ds);
3457 NavigationState* navigation_state = document_state->navigation_state();
3458 InternalDocumentStateData* internal_data =
3459 InternalDocumentStateData::FromDocumentState(document_state);
3461 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3462 params.http_status_code = response.httpStatusCode();
3463 params.url_is_unreachable = ds->hasUnreachableURL();
3464 params.is_post = false;
3465 params.post_id = -1;
3466 params.page_id = render_view_->page_id_;
3467 // We need to track the RenderViewHost routing_id because of downstream
3468 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3469 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3470 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3471 // based on the ID stored in the resource requests. Once those dependencies
3472 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3473 // client to be based on the routing_id of the RenderFrameHost.
3474 params.render_view_routing_id = render_view_->routing_id();
3475 params.socket_address.set_host(response.remoteIPAddress().utf8());
3476 params.socket_address.set_port(response.remotePort());
3477 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3479 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3480 params.was_within_same_page = navigation_state->was_within_same_page();
3481 params.security_info = response.securityInfo();
3483 // Set the URL to be displayed in the browser UI to the user.
3484 params.url = GetLoadingUrl();
3485 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3487 if (frame->document().baseURL() != params.url)
3488 params.base_url = frame->document().baseURL();
3490 GetRedirectChain(ds, ¶ms.redirects);
3491 params.should_update_history = !ds->hasUnreachableURL() &&
3492 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3494 params.searchable_form_url = internal_data->searchable_form_url();
3495 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3497 params.gesture = render_view_->navigation_gesture_;
3498 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3500 // Make navigation state a part of the DidCommitProvisionalLoad message so
3501 // that commited entry has it at all times.
3502 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3504 params.page_state = HistoryEntryToPageState(entry);
3506 params.page_state = PageState::CreateFromURL(request.url());
3508 if (!frame->parent()) {
3509 // Top-level navigation.
3511 // Reset the zoom limits in case a plugin had changed them previously. This
3512 // will also call us back which will cause us to send a message to
3513 // update WebContentsImpl.
3514 render_view_->webview()->zoomLimitsChanged(
3515 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3516 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3518 // Set zoom level, but don't do it for full-page plugin since they don't use
3519 // the same zoom settings.
3520 HostZoomLevels::iterator host_zoom =
3521 render_view_->host_zoom_levels_.find(GURL(request.url()));
3522 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3523 // Reset the zoom levels for plugins.
3524 render_view_->webview()->setZoomLevel(0);
3526 // If the zoom level is not found, then do nothing. In-page navigation
3527 // relies on not changing the zoom level in this case.
3528 if (host_zoom != render_view_->host_zoom_levels_.end())
3529 render_view_->webview()->setZoomLevel(host_zoom->second);
3532 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3533 // This zoom level was merely recorded transiently for this load. We can
3534 // erase it now. If at some point we reload this page, the browser will
3535 // send us a new, up-to-date zoom level.
3536 render_view_->host_zoom_levels_.erase(host_zoom);
3539 // Update contents MIME type for main frame.
3540 params.contents_mime_type = ds->response().mimeType().utf8();
3542 params.transition = navigation_state->transition_type();
3543 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3544 // If the main frame does a load, it should not be reported as a subframe
3545 // navigation. This can occur in the following case:
3546 // 1. You're on a site with frames.
3547 // 2. You do a subframe navigation. This is stored with transition type
3549 // 3. You navigate to some non-frame site, say, google.com.
3550 // 4. You navigate back to the page from step 2. Since it was initially
3551 // MANUAL_SUBFRAME, it will be that same transition type here.
3552 // We don't want that, because any navigation that changes the toplevel
3553 // frame should be tracked as a toplevel navigation (this allows us to
3554 // update the URL bar, etc).
3555 params.transition = ui::PAGE_TRANSITION_LINK;
3558 // If the page contained a client redirect (meta refresh, document.loc...),
3559 // set the referrer and transition appropriately.
3560 if (ds->isClientRedirect()) {
3562 Referrer(params.redirects[0], ds->request().referrerPolicy());
3563 params.transition = ui::PageTransitionFromInt(
3564 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3566 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3567 frame, ds->request());
3570 base::string16 method = request.httpMethod();
3571 if (EqualsASCII(method, "POST")) {
3572 params.is_post = true;
3573 params.post_id = ExtractPostId(entry->root());
3576 // Send the user agent override back.
3577 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
3579 // Track the URL of the original request. We use the first entry of the
3580 // redirect chain if it exists because the chain may have started in another
3582 params.original_request_url = GetOriginalRequestURL(ds);
3584 params.history_list_was_cleared =
3585 navigation_state->history_list_was_cleared();
3587 // Save some histogram data so we can compute the average memory used per
3588 // page load of the glyphs.
3589 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3590 blink::WebGlyphCache::pageCount());
3592 // This message needs to be sent before any of allowScripts(),
3593 // allowImages(), allowPlugins() is called for the new page, so that when
3594 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3595 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3596 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3598 // Subframe navigation: the type depends on whether this navigation
3599 // generated a new session history entry. When they do generate a session
3600 // history entry, it means the user initiated the navigation and we should
3601 // mark it as such. This test checks if this is the first time
3602 // SendDidCommitProvisionalLoad has been called since WillNavigateToURL was
3603 // called to initiate the load.
3604 if (render_view_->page_id_ > render_view_->last_page_id_sent_to_browser_)
3605 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
3607 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
3609 DCHECK(!navigation_state->history_list_was_cleared());
3610 params.history_list_was_cleared = false;
3612 // Don't send this message while the subframe is swapped out.
3613 if (!is_swapped_out())
3614 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3617 render_view_->last_page_id_sent_to_browser_ =
3618 std::max(render_view_->last_page_id_sent_to_browser_,
3619 render_view_->page_id_);
3621 // If we end up reusing this WebRequest (for example, due to a #ref click),
3622 // we don't want the transition type to persist. Just clear it.
3623 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
3626 WebElement RenderFrameImpl::GetFocusedElement() {
3627 WebDocument doc = frame_->document();
3629 return doc.focusedElement();
3631 return WebElement();
3634 void RenderFrameImpl::didStartLoading(bool to_different_document) {
3635 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3637 render_view_->FrameDidStartLoading(frame_);
3638 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
3641 void RenderFrameImpl::didStopLoading() {
3642 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3644 render_view_->FrameDidStopLoading(frame_);
3645 Send(new FrameHostMsg_DidStopLoading(routing_id_));
3648 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
3649 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
3652 void RenderFrameImpl::HandleWebAccessibilityEvent(
3653 const blink::WebAXObject& obj, blink::WebAXEvent event) {
3654 if (renderer_accessibility_)
3655 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
3658 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
3659 if (renderer_accessibility_)
3660 renderer_accessibility_->FocusedNodeChanged(node);
3664 void RenderFrameImpl::OnRequestNavigation(
3665 const CommonNavigationParams& common_params,
3666 const RequestNavigationParams& request_params) {
3667 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3668 switches::kEnableBrowserSideNavigation));
3670 // TODO(clamy): Execute the beforeunload event.
3672 WebURLRequest request =
3673 CreateURLRequestForNavigation(common_params,
3675 scoped_ptr<StreamOverrideParameters>(),
3676 frame_->isViewSourceModeEnabled());
3678 // Note: At this stage, the goal is to apply all the modifications the
3679 // renderer wants to make to the request, and then send it to the browser, so
3680 // that the actual network request can be started. Ideally, all such
3681 // modifications should take place in willSendRequest, and in the
3682 // implementation of willSendRequest for the various InspectorAgents
3685 // TODO(clamy): Apply devtools override.
3686 // TODO(clamy): Make sure that navigation requests are not modified somewhere
3688 willSendRequest(frame_, 0, request, blink::WebURLResponse());
3690 // TODO(clamy): Same-document navigations should not be sent back to the
3692 Send(new FrameHostMsg_BeginNavigation(routing_id_,
3693 MakeBeginNavigationParams(request),
3694 MakeCommonNavigationParams(request)));
3698 void RenderFrameImpl::OnCommitNavigation(
3699 const ResourceResponseHead& response,
3700 const GURL& stream_url,
3701 const CommonNavigationParams& common_params,
3702 const CommitNavigationParams& commit_params) {
3703 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
3704 switches::kEnableBrowserSideNavigation));
3705 bool is_reload = false;
3706 WebURLRequest::CachePolicy cache_policy =
3707 WebURLRequest::UseProtocolCachePolicy;
3708 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3709 common_params.url, common_params.navigation_type,
3710 commit_params.page_state, false, -1, -1, &is_reload, &cache_policy)) {
3714 GetContentClient()->SetActiveURL(common_params.url);
3716 // Create a WebURLRequest that blink can use to get access to the body of the
3717 // response through a stream in the browser. Blink will then commit the
3719 // TODO(clamy): Have the navigation commit directly, without going through
3720 // loading a WebURLRequest.
3721 scoped_ptr<StreamOverrideParameters> stream_override(
3722 new StreamOverrideParameters());
3723 stream_override->stream_url = stream_url;
3724 stream_override->response = response;
3725 WebURLRequest request =
3726 CreateURLRequestForNavigation(common_params,
3727 RequestNavigationParams(),
3728 stream_override.Pass(),
3729 frame_->isViewSourceModeEnabled());
3731 // Record this before starting the load. A lower bound of this time is needed
3732 // to sanitize the navigationStart override set below.
3733 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
3734 frame_->loadRequest(request);
3735 UpdateFrameNavigationTiming(
3736 frame_, commit_params.browser_navigation_start,
3737 renderer_navigation_start);
3740 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
3741 RenderFrame* render_frame,
3742 const NavigationPolicyInfo& info) {
3744 // The handlenavigation API is deprecated and will be removed once
3745 // crbug.com/325351 is resolved.
3746 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
3747 GetContentClient()->renderer()->HandleNavigation(
3749 static_cast<DocumentState*>(info.extraData),
3750 render_view_->opener_id_,
3753 info.navigationType,
3756 return blink::WebNavigationPolicyIgnore;
3760 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
3762 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
3764 bool is_subframe = !!info.frame->parent();
3766 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe) {
3767 // There's no reason to ignore navigations on subframes, since the swap out
3768 // logic no longer applies.
3770 if (is_swapped_out_ || render_view_->is_swapped_out()) {
3771 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
3772 // Targeted links may try to navigate a swapped out frame. Allow the
3773 // browser process to navigate the tab instead. Note that it is also
3774 // possible for non-targeted navigations (from this view) to arrive
3775 // here just after we are swapped out. It's ok to send them to the
3776 // browser, as long as they're for the top level frame.
3777 // TODO(creis): Ensure this supports targeted form submissions when
3778 // fixing http://crbug.com/101395.
3779 if (info.frame->parent() == NULL) {
3780 OpenURL(info.frame, info.urlRequest.url(), referrer,
3781 info.defaultPolicy);
3782 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3785 // We should otherwise ignore in-process iframe navigations, if they
3786 // arrive just after we are swapped out.
3787 return blink::WebNavigationPolicyIgnore;
3790 // Allow kSwappedOutURL to complete.
3791 return info.defaultPolicy;
3795 // Webkit is asking whether to navigate to a new URL.
3796 // This is fine normally, except if we're showing UI from one security
3797 // context and they're trying to navigate to a different context.
3798 const GURL& url = info.urlRequest.url();
3800 // A content initiated navigation may have originated from a link-click,
3801 // script, drag-n-drop operation, etc.
3802 bool is_content_initiated = static_cast<DocumentState*>(info.extraData)->
3803 navigation_state()->is_content_initiated();
3806 // If --enable-strict-site-isolation is enabled, send all top-level
3807 // navigations to the browser to let it swap processes when crossing site
3808 // boundaries. This is currently expected to break some script calls and
3809 // navigations, such as form submissions.
3810 bool force_swap_due_to_flag =
3811 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
3812 if (force_swap_due_to_flag &&
3813 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
3814 WebString origin_str = info.frame->document().securityOrigin().toString();
3815 GURL frame_url(origin_str.utf8().data());
3816 // TODO(cevans): revisit whether this site check is still necessary once
3817 // crbug.com/101395 is fixed.
3818 bool same_domain_or_host =
3819 net::registry_controlled_domains::SameDomainOrHost(
3822 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
3823 // Only keep same-site (domain + scheme) and data URLs in the same process.
3825 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
3826 url.SchemeIs(url::kDataScheme);
3827 if (!is_same_site) {
3828 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3829 return blink::WebNavigationPolicyIgnore;
3833 // If the browser is interested, then give it a chance to look at the request.
3834 if (is_content_initiated) {
3836 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
3837 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
3838 EqualsASCII(info.urlRequest.httpMethod(), "POST");
3839 bool browser_handles_request =
3840 render_view_->renderer_preferences_
3841 .browser_handles_non_local_top_level_requests
3842 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
3844 if (!browser_handles_request) {
3845 browser_handles_request = IsTopLevelNavigation(info.frame) &&
3846 render_view_->renderer_preferences_
3847 .browser_handles_all_top_level_requests;
3850 if (browser_handles_request) {
3851 OpenURL(info.frame, url, referrer, info.defaultPolicy);
3852 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3856 // Use the frame's original request's URL rather than the document's URL for
3857 // subsequent checks. For a popup, the document's URL may become the opener
3858 // window's URL if the opener has called document.write().
3859 // See http://crbug.com/93517.
3860 GURL old_url(info.frame->dataSource()->request().url());
3862 // Detect when we're crossing a permission-based boundary (e.g. into or out of
3863 // an extension or app origin, leaving a WebUI page, etc). We only care about
3864 // top-level navigations (not iframes). But we sometimes navigate to
3865 // about:blank to clear a tab, and we want to still allow that.
3867 // Note: this is known to break POST submissions when crossing process
3868 // boundaries until http://crbug.com/101395 is fixed. This is better for
3869 // security than loading a WebUI, extension or app page in the wrong process.
3870 // POST requests don't work because this mechanism does not preserve form
3871 // POST data. We will need to send the request's httpBody data up to the
3872 // browser process, and issue a special POST navigation in WebKit (via
3873 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
3874 // for examples of how to send the httpBody data.
3875 if (!info.frame->parent() && is_content_initiated &&
3876 !url.SchemeIs(url::kAboutScheme)) {
3877 bool send_referrer = false;
3879 // All navigations to or from WebUI URLs or within WebUI-enabled
3880 // RenderProcesses must be handled by the browser process so that the
3881 // correct bindings and data sources can be registered.
3882 // Similarly, navigations to view-source URLs or within ViewSource mode
3883 // must be handled by the browser process (except for reloads - those are
3884 // safe to leave within the renderer).
3885 // Lastly, access to file:// URLs from non-file:// URL pages must be
3886 // handled by the browser so that ordinary renderer processes don't get
3887 // blessed with file permissions.
3888 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
3889 bool is_initial_navigation = render_view_->page_id_ == -1;
3890 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
3891 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
3892 url.SchemeIs(kViewSourceScheme) ||
3893 (info.frame->isViewSourceModeEnabled() &&
3894 info.navigationType != blink::WebNavigationTypeReload);
3896 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
3897 // Fork non-file to file opens. Check the opener URL if this is the
3898 // initial navigation in a newly opened window.
3899 GURL source_url(old_url);
3900 if (is_initial_navigation && source_url.is_empty() &&
3901 info.frame->opener())
3902 source_url = info.frame->opener()->top()->document().url();
3903 DCHECK(!source_url.is_empty());
3904 should_fork = !source_url.SchemeIs(url::kFileScheme);
3908 // Give the embedder a chance.
3909 should_fork = GetContentClient()->renderer()->ShouldFork(
3910 info.frame, url, info.urlRequest.httpMethod().utf8(),
3911 is_initial_navigation, info.isRedirect, &send_referrer);
3915 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
3916 info.defaultPolicy);
3917 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3921 // Detect when a page is "forking" a new tab that can be safely rendered in
3922 // its own process. This is done by sites like Gmail that try to open links
3923 // in new windows without script connections back to the original page. We
3924 // treat such cases as browser navigations (in which we will create a new
3925 // renderer for a cross-site navigation), rather than WebKit navigations.
3927 // We use the following heuristic to decide whether to fork a new page in its
3929 // The parent page must open a new tab to about:blank, set the new tab's
3930 // window.opener to null, and then redirect the tab to a cross-site URL using
3933 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
3936 // Must start from a tab showing about:blank, which is later redirected.
3937 old_url == GURL(url::kAboutBlankURL) &&
3938 // Must be the first real navigation of the tab.
3939 render_view_->historyBackListCount() < 1 &&
3940 render_view_->historyForwardListCount() < 1 &&
3941 // The parent page must have set the child's window.opener to null before
3942 // redirecting to the desired URL.
3943 info.frame->opener() == NULL &&
3944 // Must be a top-level frame.
3945 info.frame->parent() == NULL &&
3946 // Must not have issued the request from this page.
3947 is_content_initiated &&
3948 // Must be targeted at the current tab.
3949 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
3950 // Must be a JavaScript navigation, which appears as "other".
3951 info.navigationType == blink::WebNavigationTypeOther;
3954 // Open the URL via the browser, not via WebKit.
3955 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
3956 return blink::WebNavigationPolicyIgnore;
3959 return info.defaultPolicy;
3962 void RenderFrameImpl::OpenURL(WebFrame* frame,
3964 const Referrer& referrer,
3965 WebNavigationPolicy policy) {
3966 DCHECK_EQ(frame_, frame);
3968 FrameHostMsg_OpenURL_Params params;
3970 params.referrer = referrer;
3971 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
3972 WebDataSource* ds = frame->provisionalDataSource();
3974 DocumentState* document_state = DocumentState::FromDataSource(ds);
3975 NavigationState* navigation_state = document_state->navigation_state();
3976 if (navigation_state->is_content_initiated()) {
3977 params.should_replace_current_entry = ds->replacesCurrentHistoryItem();
3979 // This is necessary to preserve the should_replace_current_entry value on
3980 // cross-process redirects, in the event it was set by a previous process.
3982 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3983 // NavigationState::should_replace_current_entry().
3984 params.should_replace_current_entry =
3985 navigation_state->should_replace_current_entry();
3988 params.should_replace_current_entry = false;
3990 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3991 if (GetContentClient()->renderer()->AllowPopup())
3992 params.user_gesture = true;
3994 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
3995 policy == blink::WebNavigationPolicyNewForegroundTab ||
3996 policy == blink::WebNavigationPolicyNewWindow ||
3997 policy == blink::WebNavigationPolicyNewPopup) {
3998 WebUserGestureIndicator::consumeUserGesture();
4001 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4004 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4005 const std::string& encoding_name) {
4006 // Only update main frame's encoding_name.
4007 if (!frame->parent())
4008 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4011 void RenderFrameImpl::SyncSelectionIfRequired() {
4012 base::string16 text;
4015 #if defined(ENABLE_PLUGINS)
4016 if (render_view_->focused_pepper_plugin_) {
4017 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4018 offset = 0; // Pepper API does not support offset reporting.
4019 // TODO(kinaba): cut as needed.
4023 size_t location, length;
4024 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4025 &location, &length)) {
4029 range = gfx::Range(location, location + length);
4031 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4032 blink::WebTextInputTypeNone) {
4033 // If current focused element is editable, we will send 100 more chars
4034 // before and after selection. It is for input method surrounding text
4036 if (location > kExtraCharsBeforeAndAfterSelection)
4037 offset = location - kExtraCharsBeforeAndAfterSelection;
4040 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4041 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4042 if (!webrange.isNull())
4043 text = WebRange::fromDocumentRange(
4044 frame_, offset, length).toPlainText();
4047 text = frame_->selectionAsText();
4048 // http://crbug.com/101435
4049 // In some case, frame->selectionAsText() returned text's length is not
4050 // equal to the length returned from webwidget()->caretOrSelectionRange().
4051 // So we have to set the range according to text.length().
4052 range.set_end(range.start() + text.length());
4056 // Sometimes we get repeated didChangeSelection calls from webkit when
4057 // the selection hasn't actually changed. We don't want to report these
4058 // because it will cause us to continually claim the X clipboard.
4059 if (selection_text_offset_ != offset ||
4060 selection_range_ != range ||
4061 selection_text_ != text) {
4062 selection_text_ = text;
4063 selection_text_offset_ = offset;
4064 selection_range_ = range;
4065 SetSelectedText(text, offset, range);
4067 GetRenderWidget()->UpdateSelectionBounds();
4070 void RenderFrameImpl::InitializeUserMediaClient() {
4071 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4074 #if defined(OS_ANDROID)
4075 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableWebRTC))
4079 #if defined(ENABLE_WEBRTC)
4080 DCHECK(!web_user_media_client_);
4081 web_user_media_client_ = new UserMediaClientImpl(
4083 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4084 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4088 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4089 const blink::WebURL& url,
4090 WebMediaPlayerClient* client) {
4091 #if defined(ENABLE_WEBRTC)
4092 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4094 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4095 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4096 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4097 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4098 new RenderMediaLog(),
4099 CreateRendererFactory());
4102 #endif // defined(ENABLE_WEBRTC)
4105 scoped_ptr<MediaStreamRendererFactory>
4106 RenderFrameImpl::CreateRendererFactory() {
4107 #if defined(ENABLE_WEBRTC)
4108 return scoped_ptr<MediaStreamRendererFactory>(
4109 new MediaStreamRendererFactory());
4111 return scoped_ptr<MediaStreamRendererFactory>(
4112 static_cast<MediaStreamRendererFactory*>(NULL));
4116 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4118 FrameMsg_Navigate_Type::Value navigate_type,
4119 const PageState& state,
4121 int pending_history_list_offset,
4124 WebURLRequest::CachePolicy* cache_policy) {
4125 MaybeHandleDebugURL(url);
4126 if (!render_view_->webview())
4130 RenderViewObserver, render_view_->observers_, Navigate(url));
4132 // If this is a stale back/forward (due to a recent navigation the browser
4133 // didn't know about), ignore it.
4134 if (check_history && render_view_->IsBackForwardToStaleEntry(
4135 state, pending_history_list_offset, page_id, *is_reload))
4138 if (!render_view_->is_swapped_out_ ||
4139 GetWebFrame() != render_view_->webview()->mainFrame())
4142 // This is a swapped out main frame, so swap the renderer back in.
4143 // We marked the view as hidden when swapping the view out, so be sure to
4144 // reset the visibility state before navigating to the new URL.
4145 render_view_->webview()->setVisibilityState(
4146 render_view_->visibilityState(), false);
4148 // If this is an attempt to reload while we are swapped out, we should not
4149 // reload swappedout://, but the previous page, which is stored in
4150 // params.state. Setting is_reload to false will treat this like a back
4151 // navigation to accomplish that.
4153 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4155 // We refresh timezone when a view is swapped in since timezone
4156 // can get out of sync when the system timezone is updated while
4157 // the view is swapped out.
4158 RenderThreadImpl::NotifyTimezoneChange();
4160 render_view_->SetSwappedOut(false);
4161 is_swapped_out_ = false;
4165 GURL RenderFrameImpl::GetLoadingUrl() const {
4166 WebDataSource* ds = frame_->dataSource();
4167 if (ds->hasUnreachableURL())
4168 return ds->unreachableURL();
4170 const WebURLRequest& request = ds->request();
4171 return request.url();
4174 #if defined(OS_ANDROID)
4176 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4177 const blink::WebURL& url,
4178 WebMediaPlayerClient* client,
4179 blink::WebContentDecryptionModule* initial_cdm) {
4180 GpuChannelHost* gpu_channel_host =
4181 RenderThreadImpl::current()->EstablishGpuChannelSync(
4182 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4183 if (!gpu_channel_host) {
4184 LOG(ERROR) << "Failed to establish GPU channel for media player";
4188 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4189 if (SynchronousCompositorFactory* factory =
4190 SynchronousCompositorFactory::GetInstance()) {
4191 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4193 scoped_refptr<webkit::gpu::ContextProviderWebContext> context_provider =
4194 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4196 if (!context_provider.get()) {
4197 LOG(ERROR) << "Failed to get context3d for media player";
4201 stream_texture_factory = StreamTextureFactoryImpl::Create(
4202 context_provider, gpu_channel_host, routing_id_);
4205 return new WebMediaPlayerAndroid(
4208 weak_factory_.GetWeakPtr(),
4209 GetMediaPlayerManager(),
4212 stream_texture_factory,
4213 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4214 new RenderMediaLog());
4217 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4218 if (!media_player_manager_)
4219 media_player_manager_ = new RendererMediaPlayerManager(this);
4220 return media_player_manager_;
4223 #endif // defined(OS_ANDROID)
4225 #if defined(ENABLE_BROWSER_CDMS)
4226 RendererCdmManager* RenderFrameImpl::GetCdmManager() {
4228 cdm_manager_ = new RendererCdmManager(this);
4229 return cdm_manager_;
4231 #endif // defined(ENABLE_BROWSER_CDMS)
4233 } // namespace content