Fix a couple bugs in the settings_page_header wrt breadcrumbs.
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blobf67a40a2a53ed746c35dccead80b3d1f505057bb
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"
7 #include <map>
8 #include <string>
10 #include "base/auto_reset.h"
11 #include "base/command_line.h"
12 #include "base/debug/alias.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/i18n/char_iterator.h"
16 #include "base/metrics/histogram.h"
17 #include "base/process/process.h"
18 #include "base/strings/string16.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/time/time.h"
22 #include "cc/base/switches.h"
23 #include "content/child/appcache/appcache_dispatcher.h"
24 #include "content/child/permissions/permission_dispatcher.h"
25 #include "content/child/plugin_messages.h"
26 #include "content/child/quota_dispatcher.h"
27 #include "content/child/request_extra_data.h"
28 #include "content/child/service_worker/service_worker_handle_reference.h"
29 #include "content/child/service_worker/service_worker_network_provider.h"
30 #include "content/child/service_worker/service_worker_provider_context.h"
31 #include "content/child/service_worker/web_service_worker_provider_impl.h"
32 #include "content/child/v8_value_converter_impl.h"
33 #include "content/child/web_url_loader_impl.h"
34 #include "content/child/web_url_request_util.h"
35 #include "content/child/webmessageportchannel_impl.h"
36 #include "content/child/websocket_bridge.h"
37 #include "content/child/weburlresponse_extradata_impl.h"
38 #include "content/common/clipboard_messages.h"
39 #include "content/common/frame_messages.h"
40 #include "content/common/frame_replication_state.h"
41 #include "content/common/input_messages.h"
42 #include "content/common/navigation_params.h"
43 #include "content/common/service_worker/service_worker_types.h"
44 #include "content/common/swapped_out_messages.h"
45 #include "content/common/view_messages.h"
46 #include "content/public/common/bindings_policy.h"
47 #include "content/public/common/content_constants.h"
48 #include "content/public/common/content_switches.h"
49 #include "content/public/common/context_menu_params.h"
50 #include "content/public/common/page_state.h"
51 #include "content/public/common/resource_response.h"
52 #include "content/public/common/url_constants.h"
53 #include "content/public/common/url_utils.h"
54 #include "content/public/renderer/browser_plugin_delegate.h"
55 #include "content/public/renderer/content_renderer_client.h"
56 #include "content/public/renderer/context_menu_client.h"
57 #include "content/public/renderer/document_state.h"
58 #include "content/public/renderer/isolated_world_ids.h"
59 #include "content/public/renderer/navigation_state.h"
60 #include "content/public/renderer/render_frame_observer.h"
61 #include "content/public/renderer/renderer_ppapi_host.h"
62 #include "content/renderer/accessibility/renderer_accessibility.h"
63 #include "content/renderer/browser_plugin/browser_plugin.h"
64 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
65 #include "content/renderer/child_frame_compositing_helper.h"
66 #include "content/renderer/context_menu_params_builder.h"
67 #include "content/renderer/devtools/devtools_agent.h"
68 #include "content/renderer/dom_automation_controller.h"
69 #include "content/renderer/dom_utils.h"
70 #include "content/renderer/external_popup_menu.h"
71 #include "content/renderer/geolocation_dispatcher.h"
72 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
73 #include "content/renderer/history_controller.h"
74 #include "content/renderer/history_serialization.h"
75 #include "content/renderer/image_loading_helper.h"
76 #include "content/renderer/ime_event_guard.h"
77 #include "content/renderer/internal_document_state_data.h"
78 #include "content/renderer/manifest/manifest_manager.h"
79 #include "content/renderer/media/audio_renderer_mixer_manager.h"
80 #include "content/renderer/media/crypto/render_cdm_factory.h"
81 #include "content/renderer/media/media_permission_dispatcher.h"
82 #include "content/renderer/media/media_stream_dispatcher.h"
83 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
84 #include "content/renderer/media/midi_dispatcher.h"
85 #include "content/renderer/media/render_media_log.h"
86 #include "content/renderer/media/user_media_client_impl.h"
87 #include "content/renderer/media/webmediaplayer_ms.h"
88 #include "content/renderer/memory_benchmarking_extension.h"
89 #include "content/renderer/mojo/service_registry_js_wrapper.h"
90 #include "content/renderer/navigation_state_impl.h"
91 #include "content/renderer/notification_permission_dispatcher.h"
92 #include "content/renderer/npapi/plugin_channel_host.h"
93 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
94 #include "content/renderer/presentation/presentation_dispatcher.h"
95 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
96 #include "content/renderer/render_frame_proxy.h"
97 #include "content/renderer/render_process.h"
98 #include "content/renderer/render_thread_impl.h"
99 #include "content/renderer/render_view_impl.h"
100 #include "content/renderer/render_widget_fullscreen_pepper.h"
101 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
102 #include "content/renderer/renderer_webcolorchooser_impl.h"
103 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
104 #include "content/renderer/shared_worker_repository.h"
105 #include "content/renderer/skia_benchmarking_extension.h"
106 #include "content/renderer/stats_collection_controller.h"
107 #include "content/renderer/web_ui_extension.h"
108 #include "content/renderer/websharedworker_proxy.h"
109 #include "gin/modules/module_registry.h"
110 #include "media/base/audio_renderer_mixer_input.h"
111 #include "media/base/media_log.h"
112 #include "media/blink/webencryptedmediaclient_impl.h"
113 #include "media/blink/webmediaplayer_impl.h"
114 #include "media/blink/webmediaplayer_params.h"
115 #include "media/renderers/gpu_video_accelerator_factories.h"
116 #include "net/base/data_url.h"
117 #include "net/base/net_errors.h"
118 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
119 #include "net/http/http_util.h"
120 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
121 #include "third_party/WebKit/public/platform/WebString.h"
122 #include "third_party/WebKit/public/platform/WebURL.h"
123 #include "third_party/WebKit/public/platform/WebURLError.h"
124 #include "third_party/WebKit/public/platform/WebURLResponse.h"
125 #include "third_party/WebKit/public/platform/WebVector.h"
126 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
127 #include "third_party/WebKit/public/web/WebDocument.h"
128 #include "third_party/WebKit/public/web/WebFrameWidget.h"
129 #include "third_party/WebKit/public/web/WebGlyphCache.h"
130 #include "third_party/WebKit/public/web/WebKit.h"
131 #include "third_party/WebKit/public/web/WebLocalFrame.h"
132 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
133 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
134 #include "third_party/WebKit/public/web/WebPlugin.h"
135 #include "third_party/WebKit/public/web/WebPluginParams.h"
136 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
137 #include "third_party/WebKit/public/web/WebRange.h"
138 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
139 #include "third_party/WebKit/public/web/WebScriptSource.h"
140 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
141 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
142 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
143 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
144 #include "third_party/WebKit/public/web/WebSettings.h"
145 #include "third_party/WebKit/public/web/WebSurroundingText.h"
146 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
147 #include "third_party/WebKit/public/web/WebView.h"
148 #include "third_party/mojo/src/mojo/edk/js/core.h"
149 #include "third_party/mojo/src/mojo/edk/js/support.h"
151 #if defined(ENABLE_PLUGINS)
152 #include "content/renderer/npapi/webplugin_impl.h"
153 #include "content/renderer/pepper/pepper_browser_connection.h"
154 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
155 #include "content/renderer/pepper/pepper_webplugin_impl.h"
156 #include "content/renderer/pepper/plugin_module.h"
157 #endif
159 #if defined(ENABLE_WEBRTC)
160 #include "content/renderer/media/rtc_peer_connection_handler.h"
161 #endif
163 #if defined(OS_ANDROID)
164 #include <cpu-features.h>
166 #include "content/common/gpu/client/context_provider_command_buffer.h"
167 #include "content/renderer/android/synchronous_compositor_factory.h"
168 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
169 #include "content/renderer/media/android/renderer_media_player_manager.h"
170 #include "content/renderer/media/android/stream_texture_factory_impl.h"
171 #include "content/renderer/media/android/webmediaplayer_android.h"
172 #else
173 #include "cc/blink/context_provider_web_context.h"
174 #endif
176 #if defined(ENABLE_PEPPER_CDMS)
177 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
178 #elif defined(ENABLE_BROWSER_CDMS)
179 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
180 #endif
182 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
183 #include "content/renderer/media/content_media_service_provider.h"
184 #include "media/mojo/services/mojo_renderer_factory.h"
185 #else
186 #include "media/renderers/default_renderer_factory.h"
187 #endif
189 using blink::WebContextMenuData;
190 using blink::WebData;
191 using blink::WebDataSource;
192 using blink::WebDocument;
193 using blink::WebDOMEvent;
194 using blink::WebDOMMessageEvent;
195 using blink::WebElement;
196 using blink::WebExternalPopupMenu;
197 using blink::WebExternalPopupMenuClient;
198 using blink::WebFrame;
199 using blink::WebHistoryItem;
200 using blink::WebHTTPBody;
201 using blink::WebLocalFrame;
202 using blink::WebMediaPlayer;
203 using blink::WebMediaPlayerClient;
204 using blink::WebNavigationPolicy;
205 using blink::WebNavigationType;
206 using blink::WebNode;
207 using blink::WebPluginParams;
208 using blink::WebPopupMenuInfo;
209 using blink::WebRange;
210 using blink::WebReferrerPolicy;
211 using blink::WebScriptSource;
212 using blink::WebSearchableFormData;
213 using blink::WebSecurityOrigin;
214 using blink::WebSecurityPolicy;
215 using blink::WebSerializedScriptValue;
216 using blink::WebServiceWorkerProvider;
217 using blink::WebStorageQuotaCallbacks;
218 using blink::WebString;
219 using blink::WebURL;
220 using blink::WebURLError;
221 using blink::WebURLRequest;
222 using blink::WebURLResponse;
223 using blink::WebUserGestureIndicator;
224 using blink::WebVector;
225 using blink::WebView;
226 using base::Time;
227 using base::TimeDelta;
229 namespace content {
231 namespace {
233 const char kDefaultAcceptHeader[] =
234 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
235 "*;q=0.8";
236 const char kAcceptHeader[] = "Accept";
238 const size_t kExtraCharsBeforeAndAfterSelection = 100;
240 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
241 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
242 LAZY_INSTANCE_INITIALIZER;
244 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
245 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
247 int64 ExtractPostId(HistoryEntry* entry) {
248 if (!entry)
249 return -1;
251 const WebHistoryItem& item = entry->root();
252 if (item.isNull() || item.httpBody().isNull())
253 return -1;
255 return item.httpBody().identifier();
258 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
259 const WebURLResponse& response) {
260 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
263 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
264 // Replace any occurrences of swappedout:// with about:blank.
265 const WebURL& blank_url = GURL(url::kAboutBlankURL);
266 WebVector<WebURL> urls;
267 ds->redirectChain(urls);
268 result->reserve(urls.size());
269 for (size_t i = 0; i < urls.size(); ++i) {
270 if (urls[i] != GURL(kSwappedOutURL))
271 result->push_back(urls[i]);
272 else
273 result->push_back(blank_url);
277 // Returns the original request url. If there is no redirect, the original
278 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
279 // frame was loaded by loadData, the original url will be ds->unreachableURL()
280 GURL GetOriginalRequestURL(WebDataSource* ds) {
281 // WebDataSource has unreachable URL means that the frame is loaded through
282 // blink::WebFrame::loadData(), and the base URL will be in the redirect
283 // chain. However, we never visited the baseURL. So in this case, we should
284 // use the unreachable URL as the original URL.
285 if (ds->hasUnreachableURL())
286 return ds->unreachableURL();
288 std::vector<GURL> redirects;
289 GetRedirectChain(ds, &redirects);
290 if (!redirects.empty())
291 return redirects.at(0);
293 return ds->originalRequest().url();
296 NOINLINE void CrashIntentionally() {
297 // NOTE(shess): Crash directly rather than using NOTREACHED() so
298 // that the signature is easier to triage in crash reports.
299 volatile int* zero = NULL;
300 *zero = 0;
303 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
304 NOINLINE void MaybeTriggerAsanError(const GURL& url) {
305 // NOTE(rogerm): We intentionally perform an invalid heap access here in
306 // order to trigger an Address Sanitizer (ASAN) error report.
307 const char kCrashDomain[] = "crash";
308 const char kHeapOverflow[] = "/heap-overflow";
309 const char kHeapUnderflow[] = "/heap-underflow";
310 const char kUseAfterFree[] = "/use-after-free";
311 #if defined(SYZYASAN)
312 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
313 const char kCorruptHeap[] = "/corrupt-heap";
314 #endif
316 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
317 return;
319 if (!url.has_path())
320 return;
322 std::string crash_type(url.path());
323 if (crash_type == kHeapOverflow) {
324 base::debug::AsanHeapOverflow();
325 } else if (crash_type == kHeapUnderflow ) {
326 base::debug::AsanHeapUnderflow();
327 } else if (crash_type == kUseAfterFree) {
328 base::debug::AsanHeapUseAfterFree();
329 #if defined(SYZYASAN)
330 } else if (crash_type == kCorruptHeapBlock) {
331 base::debug::AsanCorruptHeapBlock();
332 } else if (crash_type == kCorruptHeap) {
333 base::debug::AsanCorruptHeap();
334 #endif
337 #endif // ADDRESS_SANITIZER || SYZYASAN
339 void MaybeHandleDebugURL(const GURL& url) {
340 if (!url.SchemeIs(kChromeUIScheme))
341 return;
342 if (url == GURL(kChromeUICrashURL)) {
343 CrashIntentionally();
344 } else if (url == GURL(kChromeUIDumpURL)) {
345 // This URL will only correctly create a crash dump file if content is
346 // hosted in a process that has correctly called
347 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
348 // of base::debug::DumpWithoutCrashing for more details.
349 base::debug::DumpWithoutCrashing();
350 } else if (url == GURL(kChromeUIKillURL)) {
351 base::Process::Current().Terminate(1, false);
352 } else if (url == GURL(kChromeUIHangURL)) {
353 for (;;) {
354 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
356 } else if (url == GURL(kChromeUIShorthangURL)) {
357 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
360 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
361 MaybeTriggerAsanError(url);
362 #endif // ADDRESS_SANITIZER || SYZYASAN
365 // Returns false unless this is a top-level navigation.
366 bool IsTopLevelNavigation(WebFrame* frame) {
367 return frame->parent() == NULL;
370 // Returns false unless this is a top-level navigation that crosses origins.
371 bool IsNonLocalTopLevelNavigation(const GURL& url,
372 WebFrame* frame,
373 WebNavigationType type,
374 bool is_form_post) {
375 if (!IsTopLevelNavigation(frame))
376 return false;
378 // Navigations initiated within Webkit are not sent out to the external host
379 // in the following cases.
380 // 1. The url scheme is not http/https
381 // 2. The origin of the url and the opener is the same in which case the
382 // opener relationship is maintained.
383 // 3. Reloads/form submits/back forward navigations
384 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
385 return false;
387 if (type != blink::WebNavigationTypeReload &&
388 type != blink::WebNavigationTypeBackForward && !is_form_post) {
389 // The opener relationship between the new window and the parent allows the
390 // new window to script the parent and vice versa. This is not allowed if
391 // the origins of the two domains are different. This can be treated as a
392 // top level navigation and routed back to the host.
393 blink::WebFrame* opener = frame->opener();
394 if (!opener)
395 return true;
397 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
398 return true;
400 return false;
403 WebURLRequest CreateURLRequestForNavigation(
404 const CommonNavigationParams& common_params,
405 scoped_ptr<StreamOverrideParameters> stream_override,
406 bool is_view_source_mode_enabled) {
407 WebURLRequest request(common_params.url);
408 if (is_view_source_mode_enabled)
409 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
411 if (common_params.referrer.url.is_valid()) {
412 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
413 common_params.referrer.policy,
414 common_params.url,
415 WebString::fromUTF8(common_params.referrer.url.spec()));
416 if (!web_referrer.isEmpty())
417 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
420 RequestExtraData* extra_data = new RequestExtraData();
421 extra_data->set_stream_override(stream_override.Pass());
422 request.setExtraData(extra_data);
424 // Set the ui timestamp for this navigation. Currently the timestamp here is
425 // only non empty when the navigation was triggered by an Android intent. The
426 // timestamp is converted to a double version supported by blink. It will be
427 // passed back to the browser in the DidCommitProvisionalLoad and the
428 // DocumentLoadComplete IPCs.
429 base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
430 request.setUiStartTime(ui_timestamp.InSecondsF());
431 request.setInputPerfMetricReportPolicy(
432 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
433 common_params.report_type));
434 return request;
437 void UpdateFrameNavigationTiming(WebFrame* frame,
438 base::TimeTicks browser_navigation_start,
439 base::TimeTicks renderer_navigation_start) {
440 // The browser provides the navigation_start time to bootstrap the
441 // Navigation Timing information for the browser-initiated navigations. In
442 // case of cross-process navigations, this carries over the time of
443 // finishing the onbeforeunload handler of the previous page.
444 DCHECK(!browser_navigation_start.is_null());
445 if (frame->provisionalDataSource()) {
446 // |browser_navigation_start| is likely before this process existed, so we
447 // can't use InterProcessTimeTicksConverter. We need at least to ensure
448 // that the browser-side navigation start we set is not later than the one
449 // on the renderer side.
450 base::TimeTicks navigation_start = std::min(
451 browser_navigation_start, renderer_navigation_start);
452 double navigation_start_seconds =
453 (navigation_start - base::TimeTicks()).InSecondsF();
454 frame->provisionalDataSource()->setNavigationStartTime(
455 navigation_start_seconds);
456 // TODO(clamy): We need to provide additional timing values for the
457 // Navigation Timing API to work with browser-side navigations.
461 // PlzNavigate
462 CommonNavigationParams MakeCommonNavigationParams(
463 blink::WebURLRequest* request) {
464 const RequestExtraData kEmptyData;
465 const RequestExtraData* extra_data =
466 static_cast<RequestExtraData*>(request->extraData());
467 if (!extra_data)
468 extra_data = &kEmptyData;
469 Referrer referrer(
470 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
471 request->referrerPolicy());
473 // Set the ui timestamp for this navigation. Currently the timestamp here is
474 // only non empty when the navigation was triggered by an Android intent, or
475 // by the user clicking on a link. The timestamp is converted from a double
476 // version supported by blink. It will be passed back to the renderer in the
477 // CommitNavigation IPC, and then back to the browser again in the
478 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
479 base::TimeTicks ui_timestamp =
480 base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
481 FrameMsg_UILoadMetricsReportType::Value report_type =
482 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
483 request->inputPerfMetricReportPolicy());
484 return CommonNavigationParams(request->url(), referrer,
485 extra_data->transition_type(),
486 FrameMsg_Navigate_Type::NORMAL, true,
487 ui_timestamp, report_type, GURL(), GURL());
490 #if !defined(OS_ANDROID)
491 media::Context3D GetSharedMainThreadContext3D() {
492 cc::ContextProvider* provider =
493 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
494 if (!provider)
495 return media::Context3D();
496 return media::Context3D(provider->ContextGL(), provider->GrContext());
498 #endif
500 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
501 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
502 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
503 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
506 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
507 nullptr;
509 } // namespace
511 // static
512 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
513 int32 routing_id) {
514 DCHECK(routing_id != MSG_ROUTING_NONE);
516 if (g_create_render_frame_impl)
517 return g_create_render_frame_impl(render_view, routing_id);
518 else
519 return new RenderFrameImpl(render_view, routing_id);
522 // static
523 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
524 RoutingIDFrameMap::iterator iter =
525 g_routing_id_frame_map.Get().find(routing_id);
526 if (iter != g_routing_id_frame_map.Get().end())
527 return iter->second;
528 return NULL;
531 // static
532 void RenderFrameImpl::CreateFrame(
533 int routing_id,
534 int parent_routing_id,
535 int previous_sibling_routing_id,
536 int proxy_routing_id,
537 const FrameReplicationState& replicated_state,
538 CompositorDependencies* compositor_deps,
539 const FrameMsg_NewFrame_WidgetParams& widget_params) {
540 // TODO(nasko): For now, this message is only sent for subframes, as the
541 // top level frame is created when the RenderView is created through the
542 // ViewMsg_New IPC.
543 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
545 blink::WebLocalFrame* web_frame;
546 RenderFrameImpl* render_frame;
547 if (proxy_routing_id == MSG_ROUTING_NONE) {
548 RenderFrameProxy* parent_proxy =
549 RenderFrameProxy::FromRoutingID(parent_routing_id);
550 // If the browser is sending a valid parent routing id, it should already
551 // be created and registered.
552 CHECK(parent_proxy);
553 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
555 blink::WebFrame* previous_sibling_web_frame = nullptr;
556 RenderFrameProxy* previous_sibling_proxy =
557 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id);
558 if (previous_sibling_proxy)
559 previous_sibling_web_frame = previous_sibling_proxy->web_frame();
561 // Create the RenderFrame and WebLocalFrame, linking the two.
562 render_frame =
563 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
564 web_frame = parent_web_frame->createLocalChild(
565 replicated_state.scope, WebString::fromUTF8(replicated_state.name),
566 replicated_state.sandbox_flags, render_frame,
567 previous_sibling_web_frame);
568 } else {
569 RenderFrameProxy* proxy =
570 RenderFrameProxy::FromRoutingID(proxy_routing_id);
571 CHECK(proxy);
572 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
573 web_frame =
574 blink::WebLocalFrame::create(replicated_state.scope, render_frame);
575 render_frame->proxy_routing_id_ = proxy_routing_id;
576 web_frame->initializeToReplaceRemoteFrame(
577 proxy->web_frame(), WebString::fromUTF8(replicated_state.name),
578 replicated_state.sandbox_flags);
580 render_frame->SetWebFrame(web_frame);
582 if (widget_params.routing_id != MSG_ROUTING_NONE) {
583 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
584 switches::kSitePerProcess));
585 render_frame->render_widget_ = RenderWidget::CreateForFrame(
586 widget_params.routing_id, widget_params.surface_id,
587 widget_params.hidden, render_frame->render_view_->screen_info(),
588 compositor_deps, web_frame);
589 // TODO(kenrb): Observing shouldn't be necessary when we sort out
590 // WasShown and WasHidden, separating page-level visibility from
591 // frame-level visibility.
592 render_frame->render_widget_->RegisterRenderFrame(render_frame);
595 render_frame->Initialize();
598 // static
599 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
600 return RenderFrameImpl::FromWebFrame(web_frame);
603 // static
604 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
605 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
606 if (iter != g_frame_map.Get().end())
607 return iter->second;
608 return NULL;
611 // static
612 void RenderFrameImpl::InstallCreateHook(
613 CreateRenderFrameImplFunction create_render_frame_impl) {
614 CHECK(!g_create_render_frame_impl);
615 g_create_render_frame_impl = create_render_frame_impl;
618 // RenderFrameImpl ----------------------------------------------------------
619 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
620 : frame_(NULL),
621 is_subframe_(false),
622 is_local_root_(false),
623 render_view_(render_view->AsWeakPtr()),
624 routing_id_(routing_id),
625 is_swapped_out_(false),
626 render_frame_proxy_(NULL),
627 is_detaching_(false),
628 proxy_routing_id_(MSG_ROUTING_NONE),
629 #if defined(ENABLE_PLUGINS)
630 plugin_power_saver_helper_(NULL),
631 #endif
632 cookie_jar_(this),
633 selection_text_offset_(0),
634 selection_range_(gfx::Range::InvalidRange()),
635 handling_select_range_(false),
636 notification_permission_dispatcher_(NULL),
637 web_user_media_client_(NULL),
638 media_permission_dispatcher_(NULL),
639 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
640 content_media_service_provider_(NULL),
641 #endif
642 midi_dispatcher_(NULL),
643 #if defined(OS_ANDROID)
644 media_player_manager_(NULL),
645 #endif
646 #if defined(ENABLE_BROWSER_CDMS)
647 cdm_manager_(NULL),
648 #endif
649 cdm_factory_(NULL),
650 #if defined(VIDEO_HOLE)
651 contains_media_player_(false),
652 #endif
653 devtools_agent_(nullptr),
654 geolocation_dispatcher_(NULL),
655 push_messaging_dispatcher_(NULL),
656 presentation_dispatcher_(NULL),
657 screen_orientation_dispatcher_(NULL),
658 manifest_manager_(NULL),
659 accessibility_mode_(AccessibilityModeOff),
660 renderer_accessibility_(NULL),
661 weak_factory_(this) {
662 std::pair<RoutingIDFrameMap::iterator, bool> result =
663 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
664 CHECK(result.second) << "Inserting a duplicate item.";
666 RenderThread::Get()->AddRoute(routing_id_, this);
668 render_view_->RegisterRenderFrame(this);
670 // Everything below subclasses RenderFrameObserver and is automatically
671 // deleted when the RenderFrame gets deleted.
672 #if defined(OS_ANDROID)
673 new GinJavaBridgeDispatcher(this);
674 #endif
676 #if defined(ENABLE_PLUGINS)
677 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
678 #endif
680 manifest_manager_ = new ManifestManager(this);
683 RenderFrameImpl::~RenderFrameImpl() {
684 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
685 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
687 #if defined(VIDEO_HOLE)
688 if (contains_media_player_)
689 render_view_->UnregisterVideoHoleFrame(this);
690 #endif
692 if (!is_subframe_) {
693 // RenderFrameProxy is "owned" by RenderFrameImpl in the case it is
694 // the main frame. Ensure it is deleted along with this object.
695 if (render_frame_proxy_) {
696 // The following method calls back into this object and clears
697 // |render_frame_proxy_|.
698 render_frame_proxy_->frameDetached(
699 blink::WebRemoteFrameClient::DetachType::Remove);
702 // Ensure the RenderView doesn't point to this object, once it is destroyed.
703 CHECK_EQ(render_view_->main_render_frame_, this);
704 render_view_->main_render_frame_ = nullptr;
707 render_view_->UnregisterRenderFrame(this);
708 g_routing_id_frame_map.Get().erase(routing_id_);
709 RenderThread::Get()->RemoveRoute(routing_id_);
712 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
713 DCHECK(!frame_);
715 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
716 std::make_pair(web_frame, this));
717 CHECK(result.second) << "Inserting a duplicate item.";
719 frame_ = web_frame;
722 void RenderFrameImpl::Initialize() {
723 is_subframe_ = !!frame_->parent();
724 is_local_root_ = !frame_->parent() || frame_->parent()->isWebRemoteFrame();
726 #if defined(ENABLE_PLUGINS)
727 new PepperBrowserConnection(this);
728 #endif
729 new SharedWorkerRepository(this);
731 if (!frame_->parent())
732 new ImageLoadingHelper(this);
734 if (is_local_root_ && !render_frame_proxy_) {
735 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
736 // when |this| is deleted.
737 devtools_agent_ = new DevToolsAgent(this);
740 // We delay calling this until we have the WebFrame so that any observer or
741 // embedder can call GetWebFrame on any RenderFrame.
742 GetContentClient()->renderer()->RenderFrameCreated(this);
745 RenderWidget* RenderFrameImpl::GetRenderWidget() {
746 return render_view_.get();
749 #if defined(ENABLE_PLUGINS)
750 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
751 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
752 DidCreatePepperPlugin(host));
753 if (host->GetPluginName() == kFlashPluginName) {
754 RenderThread::Get()->RecordAction(
755 base::UserMetricsAction("FrameLoadWithFlash"));
759 void RenderFrameImpl::PepperDidChangeCursor(
760 PepperPluginInstanceImpl* instance,
761 const blink::WebCursorInfo& cursor) {
762 // Update the cursor appearance immediately if the requesting plugin is the
763 // one which receives the last mouse event. Otherwise, the new cursor won't be
764 // picked up until the plugin gets the next input event. That is bad if, e.g.,
765 // the plugin would like to set an invisible cursor when there isn't any user
766 // input for a while.
767 if (instance == render_view_->pepper_last_mouse_event_target())
768 GetRenderWidget()->didChangeCursor(cursor);
771 void RenderFrameImpl::PepperDidReceiveMouseEvent(
772 PepperPluginInstanceImpl* instance) {
773 render_view_->set_pepper_last_mouse_event_target(instance);
776 void RenderFrameImpl::PepperTextInputTypeChanged(
777 PepperPluginInstanceImpl* instance) {
778 if (instance != render_view_->focused_pepper_plugin())
779 return;
781 GetRenderWidget()->UpdateTextInputType();
783 FocusedNodeChangedForAccessibility(WebNode());
786 void RenderFrameImpl::PepperCaretPositionChanged(
787 PepperPluginInstanceImpl* instance) {
788 if (instance != render_view_->focused_pepper_plugin())
789 return;
790 GetRenderWidget()->UpdateSelectionBounds();
793 void RenderFrameImpl::PepperCancelComposition(
794 PepperPluginInstanceImpl* instance) {
795 if (instance != render_view_->focused_pepper_plugin())
796 return;
797 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
798 #if defined(OS_MACOSX) || defined(USE_AURA)
799 GetRenderWidget()->UpdateCompositionInfo(true);
800 #endif
803 void RenderFrameImpl::PepperSelectionChanged(
804 PepperPluginInstanceImpl* instance) {
805 if (instance != render_view_->focused_pepper_plugin())
806 return;
807 SyncSelectionIfRequired();
810 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
811 PepperPluginInstanceImpl* plugin) {
812 GURL active_url;
813 if (render_view_->webview() && render_view_->webview()->mainFrame())
814 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
815 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
816 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
817 plugin, active_url, GetRenderWidget()->screenInfo());
818 widget->show(blink::WebNavigationPolicyIgnore);
819 return widget;
822 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
823 if (!render_view_->focused_pepper_plugin())
824 return false;
825 return render_view_->focused_pepper_plugin()->
826 IsPluginAcceptingCompositionEvents();
829 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
830 base::ProcessId plugin_pid) {
831 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
832 // routing_id_ as a result.
833 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
836 void RenderFrameImpl::SimulateImeSetComposition(
837 const base::string16& text,
838 const std::vector<blink::WebCompositionUnderline>& underlines,
839 int selection_start,
840 int selection_end) {
841 render_view_->OnImeSetComposition(
842 text, underlines, selection_start, selection_end);
845 void RenderFrameImpl::SimulateImeConfirmComposition(
846 const base::string16& text,
847 const gfx::Range& replacement_range) {
848 render_view_->OnImeConfirmComposition(text, replacement_range, false);
851 void RenderFrameImpl::OnImeSetComposition(
852 const base::string16& text,
853 const std::vector<blink::WebCompositionUnderline>& underlines,
854 int selection_start,
855 int selection_end) {
856 // When a PPAPI plugin has focus, we bypass WebKit.
857 if (!IsPepperAcceptingCompositionEvents()) {
858 pepper_composition_text_ = text;
859 } else {
860 // TODO(kinaba) currently all composition events are sent directly to
861 // plugins. Use DOM event mechanism after WebKit is made aware about
862 // plugins that support composition.
863 // The code below mimics the behavior of WebCore::Editor::setComposition.
865 // Empty -> nonempty: composition started.
866 if (pepper_composition_text_.empty() && !text.empty()) {
867 render_view_->focused_pepper_plugin()->HandleCompositionStart(
868 base::string16());
870 // Nonempty -> empty: composition canceled.
871 if (!pepper_composition_text_.empty() && text.empty()) {
872 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
873 base::string16());
875 pepper_composition_text_ = text;
876 // Nonempty: composition is ongoing.
877 if (!pepper_composition_text_.empty()) {
878 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
879 pepper_composition_text_, underlines, selection_start,
880 selection_end);
885 void RenderFrameImpl::OnImeConfirmComposition(
886 const base::string16& text,
887 const gfx::Range& replacement_range,
888 bool keep_selection) {
889 // When a PPAPI plugin has focus, we bypass WebKit.
890 // Here, text.empty() has a special meaning. It means to commit the last
891 // update of composition text (see
892 // RenderWidgetHost::ImeConfirmComposition()).
893 const base::string16& last_text = text.empty() ? pepper_composition_text_
894 : text;
896 // last_text is empty only when both text and pepper_composition_text_ is.
897 // Ignore it.
898 if (last_text.empty())
899 return;
901 if (!IsPepperAcceptingCompositionEvents()) {
902 base::i18n::UTF16CharIterator iterator(&last_text);
903 int32 i = 0;
904 while (iterator.Advance()) {
905 blink::WebKeyboardEvent char_event;
906 char_event.type = blink::WebInputEvent::Char;
907 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
908 char_event.modifiers = 0;
909 char_event.windowsKeyCode = last_text[i];
910 char_event.nativeKeyCode = last_text[i];
912 const int32 char_start = i;
913 for (; i < iterator.array_pos(); ++i) {
914 char_event.text[i - char_start] = last_text[i];
915 char_event.unmodifiedText[i - char_start] = last_text[i];
918 if (GetRenderWidget()->webwidget())
919 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
921 } else {
922 // Mimics the order of events sent by WebKit.
923 // See WebCore::Editor::setComposition() for the corresponding code.
924 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
925 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
927 pepper_composition_text_.clear();
929 #endif // defined(ENABLE_PLUGINS)
931 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
932 if (!web_user_media_client_)
933 InitializeUserMediaClient();
934 return web_user_media_client_ ?
935 web_user_media_client_->media_stream_dispatcher() : NULL;
938 bool RenderFrameImpl::Send(IPC::Message* message) {
939 if (is_detaching_) {
940 delete message;
941 return false;
943 if (is_swapped_out_) {
944 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
945 delete message;
946 return false;
950 return RenderThread::Get()->Send(message);
953 #if defined(OS_MACOSX) || defined(OS_ANDROID)
954 void RenderFrameImpl::DidHideExternalPopupMenu() {
955 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
956 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
957 external_popup_menu_.reset();
959 #endif
961 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
962 // We may get here while detaching, when the WebFrame has been deleted. Do
963 // not process any messages in this state.
964 if (!frame_)
965 return false;
967 // TODO(kenrb): document() should not be null, but as a transitional step
968 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
969 // to this method. This happens for a top-level remote frame, where a
970 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
971 // around and is still able to receive messages.
972 if (!frame_->document().isNull())
973 GetContentClient()->SetActiveURL(frame_->document().url());
975 base::ObserverListBase<RenderFrameObserver>::Iterator it(&observers_);
976 RenderFrameObserver* observer;
977 while ((observer = it.GetNext()) != NULL) {
978 if (observer->OnMessageReceived(msg))
979 return true;
982 bool handled = true;
983 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
984 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
985 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
986 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
987 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
988 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
989 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
990 OnCustomContextMenuAction)
991 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
992 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
993 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
994 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
995 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
996 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
997 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
998 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
999 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1000 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1001 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
1002 OnMoveRangeSelectionExtent)
1003 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1004 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1005 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
1006 OnExtendSelectionAndDelete)
1007 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
1008 OnSetCompositionFromExistingText)
1009 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
1010 OnExecuteNoValueEditCommand)
1011 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
1012 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole, OnAddMessageToConsole)
1013 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
1014 OnJavaScriptExecuteRequest)
1015 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
1016 OnJavaScriptExecuteRequestForTests)
1017 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld,
1018 OnJavaScriptExecuteRequestInIsolatedWorld)
1019 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
1020 OnVisualStateRequest)
1021 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
1022 OnSetEditableSelectionOffsets)
1023 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
1024 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
1025 OnTextSurroundingSelectionRequest)
1026 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
1027 OnSetAccessibilityMode)
1028 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree,
1029 OnSnapshotAccessibilityTree)
1030 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
1031 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
1032 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags, OnDidUpdateSandboxFlags)
1033 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings,
1034 OnTextTrackSettingsChanged)
1035 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent, OnPostMessageEvent)
1036 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation, OnFailedNavigation)
1037 #if defined(OS_ANDROID)
1038 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1039 #elif defined(OS_MACOSX)
1040 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1041 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1042 #endif
1043 IPC_END_MESSAGE_MAP()
1045 return handled;
1048 void RenderFrameImpl::OnNavigate(
1049 const CommonNavigationParams& common_params,
1050 const StartNavigationParams& start_params,
1051 const RequestNavigationParams& request_params) {
1052 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1053 switches::kEnableBrowserSideNavigation));
1054 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_,
1055 "url", common_params.url.possibly_invalid_spec());
1056 NavigateInternal(common_params, start_params, request_params,
1057 scoped_ptr<StreamOverrideParameters>());
1060 void RenderFrameImpl::NavigateToSwappedOutURL() {
1061 // We use loadRequest instead of loadHTMLString because the former commits
1062 // synchronously. Otherwise a new navigation can interrupt the navigation
1063 // to kSwappedOutURL. If that happens to be to the page we had been
1064 // showing, then WebKit will never send a commit and we'll be left spinning.
1065 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1066 // the navigation to swappedout:// is not announced to the browser side.
1067 is_swapped_out_ = true;
1068 GURL swappedOutURL(kSwappedOutURL);
1069 WebURLRequest request(swappedOutURL);
1070 frame_->loadRequest(request);
1073 void RenderFrameImpl::BindServiceRegistry(
1074 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1075 mojo::ServiceProviderPtr exposed_services) {
1076 service_registry_.Bind(services.Pass());
1077 service_registry_.BindRemoteServiceProvider(exposed_services.Pass());
1080 ManifestManager* RenderFrameImpl::manifest_manager() {
1081 return manifest_manager_;
1084 void RenderFrameImpl::SetPendingNavigationParams(
1085 scoped_ptr<NavigationParams> navigation_params) {
1086 pending_navigation_params_ = navigation_params.Pass();
1089 void RenderFrameImpl::OnBeforeUnload() {
1090 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1091 "id", routing_id_);
1092 // TODO(creis): Right now, this is only called on the main frame. Make the
1093 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1094 // it.
1095 CHECK(!frame_->parent());
1097 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1098 bool proceed = frame_->dispatchBeforeUnloadEvent();
1099 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1100 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1101 before_unload_start_time,
1102 before_unload_end_time));
1105 void RenderFrameImpl::OnSwapOut(
1106 int proxy_routing_id,
1107 bool is_loading,
1108 const FrameReplicationState& replicated_frame_state) {
1109 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1110 RenderFrameProxy* proxy = NULL;
1111 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
1112 switches::kSitePerProcess);
1113 bool is_main_frame = !frame_->parent();
1115 // Only run unload if we're not swapped out yet, but send the ack either way.
1116 if (!is_swapped_out_) {
1117 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1118 // a different process. This involves running the unload handler and
1119 // clearing the page. We also allow this process to exit if there are no
1120 // other active RenderFrames in it.
1122 // Send an UpdateState message before we get swapped out.
1123 render_view_->SyncNavigationState();
1125 // If we need a proxy to replace this, create it now so its routing id is
1126 // registered for receiving IPC messages.
1127 if (proxy_routing_id != MSG_ROUTING_NONE) {
1128 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
1129 this, proxy_routing_id, replicated_frame_state.scope);
1132 // Synchronously run the unload handler before sending the ACK.
1133 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1134 // unload on subframes as well.
1135 if (is_main_frame)
1136 frame_->dispatchUnloadEvent();
1138 // Swap out and stop sending any IPC messages that are not ACKs.
1139 if (is_main_frame)
1140 render_view_->SetSwappedOut(true);
1141 is_swapped_out_ = true;
1143 // Set the proxy here, since OnStop() below could cause an onload event
1144 // handler to execute, which could trigger code such as
1145 // willCheckAndDispatchMessageEvent() that needs the proxy.
1146 if (proxy)
1147 set_render_frame_proxy(proxy);
1149 // Now that we're swapped out and filtering IPC messages, stop loading to
1150 // ensure that no other in-progress navigation continues. We do this here
1151 // to avoid sending a DidStopLoading message to the browser process.
1152 // TODO(creis): Should we be stopping all frames here and using
1153 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1154 // frame?
1155 OnStop();
1157 // Transfer settings such as initial drawing parameters to the remote frame,
1158 // if one is created, that will replace this frame.
1159 if (!is_main_frame && proxy)
1160 proxy->web_frame()->initializeFromFrame(frame_);
1162 // Replace the page with a blank dummy URL. The unload handler will not be
1163 // run a second time, thanks to a check in FrameLoader::stopLoading.
1164 // TODO(creis): Need to add a better way to do this that avoids running the
1165 // beforeunload handler. For now, we just run it a second time silently.
1166 if (!is_site_per_process || is_main_frame)
1167 NavigateToSwappedOutURL();
1169 // Let WebKit know that this view is hidden so it can drop resources and
1170 // stop compositing.
1171 // TODO(creis): Support this for subframes as well.
1172 if (is_main_frame) {
1173 render_view_->webview()->setVisibilityState(
1174 blink::WebPageVisibilityStateHidden, false);
1178 // It is now safe to show modal dialogs again.
1179 // TODO(creis): Deal with modal dialogs from subframes.
1180 if (is_main_frame)
1181 render_view_->suppress_dialogs_until_swap_out_ = false;
1183 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1185 // Now that all of the cleanup is complete and the browser side is notified,
1186 // start using the RenderFrameProxy, if one is created.
1187 if (proxy) {
1188 if (!is_main_frame) {
1189 frame_->swap(proxy->web_frame());
1191 if (is_loading)
1192 proxy->OnDidStartLoading();
1194 if (is_site_per_process) {
1195 // TODO(nasko): delete the frame here, since we've replaced it with a
1196 // proxy.
1201 // In --site-per-process, initialize the WebRemoteFrame with the replication
1202 // state passed by the process that is now rendering the frame.
1203 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1204 // in that case we leave the LocalFrame as the main frame visible to Blink
1205 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1206 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1207 // When we do an unconditional swap for all frames, we can remove
1208 // !is_main_frame below.
1209 if (is_site_per_process && proxy && !is_main_frame)
1210 proxy->SetReplicatedState(replicated_frame_state);
1212 // Safe to exit if no one else is using the process.
1213 if (is_main_frame)
1214 render_view_->WasSwappedOut();
1217 void RenderFrameImpl::OnContextMenuClosed(
1218 const CustomContextMenuContext& custom_context) {
1219 if (custom_context.request_id) {
1220 // External request, should be in our map.
1221 ContextMenuClient* client =
1222 pending_context_menus_.Lookup(custom_context.request_id);
1223 if (client) {
1224 client->OnMenuClosed(custom_context.request_id);
1225 pending_context_menus_.Remove(custom_context.request_id);
1227 } else {
1228 if (custom_context.link_followed.is_valid()) {
1229 frame_->sendPings(
1230 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1231 custom_context.link_followed);
1233 // Internal request, forward to WebKit.
1234 context_menu_node_.reset();
1238 void RenderFrameImpl::OnCustomContextMenuAction(
1239 const CustomContextMenuContext& custom_context,
1240 unsigned action) {
1241 if (custom_context.request_id) {
1242 // External context menu request, look in our map.
1243 ContextMenuClient* client =
1244 pending_context_menus_.Lookup(custom_context.request_id);
1245 if (client)
1246 client->OnMenuAction(custom_context.request_id, action);
1247 } else {
1248 // Internal request, forward to WebKit.
1249 render_view_->webview()->performCustomContextMenuAction(action);
1253 void RenderFrameImpl::OnUndo() {
1254 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1257 void RenderFrameImpl::OnRedo() {
1258 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1261 void RenderFrameImpl::OnCut() {
1262 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1263 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1266 void RenderFrameImpl::OnCopy() {
1267 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1268 WebNode current_node = context_menu_node_.isNull() ?
1269 GetFocusedElement() : context_menu_node_;
1270 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1273 void RenderFrameImpl::OnPaste() {
1274 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1275 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1278 void RenderFrameImpl::OnPasteAndMatchStyle() {
1279 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1280 frame_->executeCommand(
1281 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1284 #if defined(OS_MACOSX)
1285 void RenderFrameImpl::OnCopyToFindPboard() {
1286 // Since the find pasteboard supports only plain text, this can be simpler
1287 // than the |OnCopy()| case.
1288 if (frame_->hasSelection()) {
1289 base::string16 selection = frame_->selectionAsText();
1290 RenderThread::Get()->Send(
1291 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1294 #endif
1296 void RenderFrameImpl::OnDelete() {
1297 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1300 void RenderFrameImpl::OnSelectAll() {
1301 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1302 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1305 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1306 const gfx::Point& extent) {
1307 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1308 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1310 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1311 frame_->selectRange(base, extent);
1314 void RenderFrameImpl::OnUnselect() {
1315 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1316 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1319 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1320 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1321 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1322 GetRenderWidget()->routing_id()));
1324 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1325 frame_->moveRangeSelectionExtent(point);
1328 void RenderFrameImpl::OnReplace(const base::string16& text) {
1329 if (!frame_->hasSelection())
1330 frame_->selectWordAroundCaret();
1332 frame_->replaceSelection(text);
1335 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1336 if (!frame_->hasSelection())
1337 return;
1339 frame_->replaceMisspelledRange(text);
1342 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1343 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1346 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level,
1347 const std::string& message) {
1348 if (devtools_agent_)
1349 devtools_agent_->AddMessageToConsole(level, message);
1352 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1353 const base::string16& jscript,
1354 int id,
1355 bool notify_result) {
1356 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1357 TRACE_EVENT_SCOPE_THREAD);
1359 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1360 v8::Local<v8::Value> result =
1361 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1363 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1366 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1367 const base::string16& jscript,
1368 int id,
1369 bool notify_result,
1370 bool has_user_gesture) {
1371 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1372 TRACE_EVENT_SCOPE_THREAD);
1374 // A bunch of tests expect to run code in the context of a user gesture, which
1375 // can grant additional privileges (e.g. the ability to create popups).
1376 scoped_ptr<blink::WebScopedUserGesture> gesture(
1377 has_user_gesture ? new blink::WebScopedUserGesture : nullptr);
1378 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1379 v8::Local<v8::Value> result =
1380 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1382 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1385 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1386 const base::string16& jscript,
1387 int id,
1388 bool notify_result,
1389 int world_id) {
1390 TRACE_EVENT_INSTANT0("test_tracing",
1391 "OnJavaScriptExecuteRequestInIsolatedWorld",
1392 TRACE_EVENT_SCOPE_THREAD);
1394 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
1395 world_id > ISOLATED_WORLD_ID_MAX) {
1396 // Return if the world_id is not valid. world_id is passed as a plain int
1397 // over IPC and needs to be verified here, in the IPC endpoint.
1398 NOTREACHED();
1399 return;
1402 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1403 WebScriptSource script = WebScriptSource(jscript);
1404 JavaScriptIsolatedWorldRequest* request = new JavaScriptIsolatedWorldRequest(
1405 id, notify_result, routing_id_, weak_factory_.GetWeakPtr());
1406 frame_->requestExecuteScriptInIsolatedWorld(world_id, &script, 1, 0, false,
1407 request);
1410 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1411 int id,
1412 bool notify_result,
1413 int routing_id,
1414 base::WeakPtr<RenderFrameImpl> render_frame_impl)
1415 : id_(id),
1416 notify_result_(notify_result),
1417 routing_id_(routing_id),
1418 render_frame_impl_(render_frame_impl) {
1421 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1422 ~JavaScriptIsolatedWorldRequest() {
1425 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1426 const blink::WebVector<v8::Local<v8::Value>>& result) {
1427 if (!render_frame_impl_.get()) {
1428 return;
1431 if (notify_result_) {
1432 base::ListValue list;
1433 if (!result.isEmpty()) {
1434 // It's safe to always use the main world context when converting
1435 // here. V8ValueConverterImpl shouldn't actually care about the
1436 // context scope, and it switches to v8::Object's creation context
1437 // when encountered. (from extensions/renderer/script_injection.cc)
1438 v8::Local<v8::Context> context =
1439 render_frame_impl_.get()->frame_->mainWorldScriptContext();
1440 v8::Context::Scope context_scope(context);
1441 V8ValueConverterImpl converter;
1442 converter.SetDateAllowed(true);
1443 converter.SetRegExpAllowed(true);
1444 for (const auto& value : result) {
1445 scoped_ptr<base::Value> result_value(
1446 converter.FromV8Value(value, context));
1447 list.Append(result_value ? result_value.Pass()
1448 : base::Value::CreateNullValue());
1450 } else {
1451 list.Set(0, base::Value::CreateNullValue());
1453 render_frame_impl_.get()->Send(
1454 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id_, list));
1457 delete this;
1460 void RenderFrameImpl::HandleJavascriptExecutionResult(
1461 const base::string16& jscript,
1462 int id,
1463 bool notify_result,
1464 v8::Local<v8::Value> result) {
1465 if (notify_result) {
1466 base::ListValue list;
1467 if (!result.IsEmpty()) {
1468 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1469 v8::Context::Scope context_scope(context);
1470 V8ValueConverterImpl converter;
1471 converter.SetDateAllowed(true);
1472 converter.SetRegExpAllowed(true);
1473 scoped_ptr<base::Value> result_value(
1474 converter.FromV8Value(result, context));
1475 list.Set(0, result_value ? result_value.Pass()
1476 : base::Value::CreateNullValue());
1477 } else {
1478 list.Set(0, base::Value::CreateNullValue());
1480 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1484 void RenderFrameImpl::OnVisualStateRequest(uint64 id) {
1485 GetRenderWidget()->QueueMessage(
1486 new FrameHostMsg_VisualStateResponse(routing_id_, id),
1487 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1490 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1491 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1492 if (!GetRenderWidget()->ShouldHandleImeEvent())
1493 return;
1494 ImeEventGuard guard(GetRenderWidget());
1495 frame_->setEditableSelectionOffsets(start, end);
1498 void RenderFrameImpl::OnSetCompositionFromExistingText(
1499 int start, int end,
1500 const std::vector<blink::WebCompositionUnderline>& underlines) {
1501 if (!GetRenderWidget()->ShouldHandleImeEvent())
1502 return;
1503 ImeEventGuard guard(GetRenderWidget());
1504 frame_->setCompositionFromExistingText(start, end, underlines);
1507 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
1508 frame_->executeCommand(WebString::fromUTF8(name), GetFocusedElement());
1511 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1512 if (!GetRenderWidget()->ShouldHandleImeEvent())
1513 return;
1514 ImeEventGuard guard(GetRenderWidget());
1515 frame_->extendSelectionAndDelete(before, after);
1518 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1519 if (accessibility_mode_ == new_mode)
1520 return;
1521 accessibility_mode_ = new_mode;
1522 if (renderer_accessibility_) {
1523 // Note: this isn't called automatically by the destructor because
1524 // there'd be no point in calling it in frame teardown, only if there's
1525 // an accessibility mode change but the frame is persisting.
1526 renderer_accessibility_->DisableAccessibility();
1528 delete renderer_accessibility_;
1529 renderer_accessibility_ = NULL;
1531 if (accessibility_mode_ == AccessibilityModeOff)
1532 return;
1534 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1535 renderer_accessibility_ = new RendererAccessibility(this);
1538 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) {
1539 ui::AXTreeUpdate response;
1540 RendererAccessibility::SnapshotAccessibilityTree(this, &response);
1541 Send(new AccessibilityHostMsg_SnapshotResponse(
1542 routing_id_, callback_id, response));
1545 void RenderFrameImpl::OnDisownOpener() {
1546 // TODO(creis): We should only see this for main frames for now. To support
1547 // disowning the opener on subframes, we will need to move WebContentsImpl's
1548 // opener_ to FrameTreeNode.
1549 CHECK(!frame_->parent());
1551 if (frame_->opener())
1552 frame_->setOpener(NULL);
1555 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags) {
1556 frame_->setFrameOwnerSandboxFlags(flags);
1559 void RenderFrameImpl::OnTextTrackSettingsChanged(
1560 const FrameMsg_TextTrackSettings_Params& params) {
1561 DCHECK(!frame_->parent());
1562 if (!render_view_->webview())
1563 return;
1564 render_view_->webview()->settings()->setTextTrackBackgroundColor(
1565 WebString::fromUTF8(params.text_track_background_color));
1566 render_view_->webview()->settings()->setTextTrackFontFamily(
1567 WebString::fromUTF8(params.text_track_font_family));
1568 render_view_->webview()->settings()->setTextTrackFontStyle(
1569 WebString::fromUTF8(params.text_track_font_style));
1570 render_view_->webview()->settings()->setTextTrackFontVariant(
1571 WebString::fromUTF8(params.text_track_font_variant));
1572 render_view_->webview()->settings()->setTextTrackTextColor(
1573 WebString::fromUTF8(params.text_track_text_color));
1574 render_view_->webview()->settings()->setTextTrackTextShadow(
1575 WebString::fromUTF8(params.text_track_text_shadow));
1576 render_view_->webview()->settings()->setTextTrackTextSize(
1577 WebString::fromUTF8(params.text_track_text_size));
1580 void RenderFrameImpl::OnPostMessageEvent(
1581 const FrameMsg_PostMessage_Params& params) {
1582 // Find the source frame if it exists.
1583 WebFrame* source_frame = NULL;
1584 if (params.source_view_routing_id != MSG_ROUTING_NONE) {
1585 // Support a legacy postMessage path for specifying a source RenderView;
1586 // this is currently used when sending messages to Android WebView.
1587 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1588 RenderViewImpl* source_view =
1589 RenderViewImpl::FromRoutingID(params.source_view_routing_id);
1590 if (source_view)
1591 source_frame = source_view->webview()->mainFrame();
1592 } else if (params.source_routing_id != MSG_ROUTING_NONE) {
1593 RenderFrameProxy* source_proxy =
1594 RenderFrameProxy::FromRoutingID(params.source_routing_id);
1595 if (source_proxy) {
1596 // Currently, navigating a top-level frame cross-process does not swap
1597 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1598 // WebRemoteFrame will not have an associated blink::Frame. If this is
1599 // the case for |source_proxy|, use the corresponding (swapped-out)
1600 // WebLocalFrame instead, so that event.source for this message can be
1601 // set and used properly.
1602 if (source_proxy->IsMainFrameDetachedFromTree())
1603 source_frame = source_proxy->render_view()->webview()->mainFrame();
1604 else
1605 source_frame = source_proxy->web_frame();
1609 // If the message contained MessagePorts, create the corresponding endpoints.
1610 blink::WebMessagePortChannelArray channels =
1611 WebMessagePortChannelImpl::CreatePorts(
1612 params.message_ports, params.new_routing_ids,
1613 base::ThreadTaskRunnerHandle::Get().get());
1615 WebSerializedScriptValue serialized_script_value;
1616 if (params.is_data_raw_string) {
1617 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1618 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1619 v8::Context::Scope context_scope(context);
1620 V8ValueConverterImpl converter;
1621 converter.SetDateAllowed(true);
1622 converter.SetRegExpAllowed(true);
1623 scoped_ptr<base::Value> value(new base::StringValue(params.data));
1624 v8::Local<v8::Value> result_value = converter.ToV8Value(value.get(),
1625 context);
1626 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
1627 } else {
1628 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
1631 // Create an event with the message. The next-to-last parameter to
1632 // initMessageEvent is the last event ID, which is not used with postMessage.
1633 WebDOMEvent event = frame_->document().createEvent("MessageEvent");
1634 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
1635 msg_event.initMessageEvent("message",
1636 // |canBubble| and |cancellable| are always false
1637 false, false,
1638 serialized_script_value,
1639 params.source_origin, source_frame, "", channels);
1641 // We must pass in the target_origin to do the security check on this side,
1642 // since it may have changed since the original postMessage call was made.
1643 WebSecurityOrigin target_origin;
1644 if (!params.target_origin.empty()) {
1645 target_origin =
1646 WebSecurityOrigin::createFromString(WebString(params.target_origin));
1648 frame_->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
1651 #if defined(OS_ANDROID)
1652 void RenderFrameImpl::OnSelectPopupMenuItems(
1653 bool canceled,
1654 const std::vector<int>& selected_indices) {
1655 // It is possible to receive more than one of these calls if the user presses
1656 // a select faster than it takes for the show-select-popup IPC message to make
1657 // it to the browser UI thread. Ignore the extra-messages.
1658 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1659 if (!external_popup_menu_)
1660 return;
1662 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1663 external_popup_menu_.reset();
1665 #endif
1667 #if defined(OS_MACOSX)
1668 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1669 if (external_popup_menu_ == NULL)
1670 return;
1671 external_popup_menu_->DidSelectItem(selected_index);
1672 external_popup_menu_.reset();
1674 #endif
1676 void RenderFrameImpl::OnReload(bool ignore_cache) {
1677 frame_->reload(ignore_cache);
1680 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1681 blink::WebSurroundingText surroundingText;
1682 surroundingText.initialize(frame_->selectionRange(), max_length);
1684 if (surroundingText.isNull()) {
1685 // |surroundingText| might not be correctly initialized, for example if
1686 // |frame_->selectionRange().isNull()|, in other words, if there was no
1687 // selection.
1688 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1689 routing_id_, base::string16(), 0, 0));
1690 return;
1693 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1694 routing_id_,
1695 surroundingText.textContent(),
1696 surroundingText.startOffsetInTextContent(),
1697 surroundingText.endOffsetInTextContent()));
1700 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1701 const base::string16& message,
1702 const base::string16& default_value,
1703 const GURL& frame_url,
1704 base::string16* result) {
1705 // Don't allow further dialogs if we are waiting to swap out, since the
1706 // PageGroupLoadDeferrer in our stack prevents it.
1707 if (render_view()->suppress_dialogs_until_swap_out_)
1708 return false;
1710 bool success = false;
1711 base::string16 result_temp;
1712 if (!result)
1713 result = &result_temp;
1715 render_view()->SendAndRunNestedMessageLoop(
1716 new FrameHostMsg_RunJavaScriptMessage(
1717 routing_id_, message, default_value, frame_url, type, &success,
1718 result));
1719 return success;
1722 void RenderFrameImpl::LoadNavigationErrorPage(
1723 const WebURLRequest& failed_request,
1724 const WebURLError& error,
1725 bool replace) {
1726 std::string error_html;
1727 GetContentClient()->renderer()->GetNavigationErrorStrings(
1728 render_view(), frame_, failed_request, error, &error_html, NULL);
1730 frame_->loadHTMLString(error_html,
1731 GURL(kUnreachableWebDataURL),
1732 error.unreachableURL,
1733 replace);
1736 void RenderFrameImpl::DidCommitCompositorFrame() {
1737 if (BrowserPluginManager::Get())
1738 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1739 FOR_EACH_OBSERVER(
1740 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1743 RenderView* RenderFrameImpl::GetRenderView() {
1744 return render_view_.get();
1747 int RenderFrameImpl::GetRoutingID() {
1748 return routing_id_;
1751 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1752 DCHECK(frame_);
1753 return frame_;
1756 WebElement RenderFrameImpl::GetFocusedElement() const {
1757 WebDocument doc = frame_->document();
1758 if (!doc.isNull())
1759 return doc.focusedElement();
1761 return WebElement();
1764 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1765 return render_view_->GetWebkitPreferences();
1768 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1769 const ContextMenuParams& params) {
1770 DCHECK(client); // A null client means "internal" when we issue callbacks.
1771 ContextMenuParams our_params(params);
1772 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1773 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1774 return our_params.custom_context.request_id;
1777 void RenderFrameImpl::CancelContextMenu(int request_id) {
1778 DCHECK(pending_context_menus_.Lookup(request_id));
1779 pending_context_menus_.Remove(request_id);
1782 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1783 return context_menu_node_;
1786 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1787 blink::WebFrame* frame,
1788 const WebPluginInfo& info,
1789 const blink::WebPluginParams& params,
1790 scoped_ptr<content::PluginInstanceThrottler> throttler) {
1791 DCHECK_EQ(frame_, frame);
1792 #if defined(ENABLE_PLUGINS)
1793 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1794 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1795 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1796 this, params.mimeType.utf8(), GURL(params.url)));
1797 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1798 this, browser_plugin_delegate.Pass());
1801 bool pepper_plugin_was_registered = false;
1802 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1803 this, info, &pepper_plugin_was_registered));
1804 if (pepper_plugin_was_registered) {
1805 if (pepper_module.get()) {
1806 return new PepperWebPluginImpl(
1807 pepper_module.get(), params, this,
1808 make_scoped_ptr(
1809 static_cast<PluginInstanceThrottlerImpl*>(throttler.release())));
1812 #if defined(OS_CHROMEOS)
1813 LOG(WARNING) << "Pepper module/plugin creation failed.";
1814 #else
1815 if (info.type == WebPluginInfo::PLUGIN_TYPE_NPAPI) {
1816 // TODO(jam): change to take RenderFrame.
1817 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1819 #endif
1820 #endif
1821 return NULL;
1824 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1825 const blink::WebURLRequest& request,
1826 blink::WebNavigationPolicy policy) {
1827 DCHECK(!frame_ || frame_ == frame);
1828 loadURLExternally(frame, request, policy, WebString());
1831 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1832 OnJavaScriptExecuteRequest(javascript, 0, false);
1835 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1836 return &service_registry_;
1839 #if defined(ENABLE_PLUGINS)
1840 void RenderFrameImpl::RegisterPeripheralPlugin(
1841 const GURL& content_origin,
1842 const base::Closure& unthrottle_callback) {
1843 return plugin_power_saver_helper_->RegisterPeripheralPlugin(
1844 content_origin, unthrottle_callback);
1846 #endif // defined(ENABLE_PLUGINS)
1848 bool RenderFrameImpl::IsFTPDirectoryListing() {
1849 WebURLResponseExtraDataImpl* extra_data =
1850 GetExtraDataFromResponse(frame_->dataSource()->response());
1851 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1854 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1855 BrowserPluginManager::Get()->Attach(element_instance_id);
1858 void RenderFrameImpl::DetachGuest(int element_instance_id) {
1859 BrowserPluginManager::Get()->Detach(element_instance_id);
1862 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1863 size_t offset,
1864 const gfx::Range& range) {
1865 // Use the routing id of Render Widget Host.
1866 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1867 selection_text,
1868 offset,
1869 range));
1872 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1873 v8::Isolate* isolate,
1874 v8::Local<v8::Context> context) {
1875 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1876 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1877 return;
1879 v8::HandleScope handle_scope(isolate);
1880 registry->AddBuiltinModule(
1881 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1882 registry->AddBuiltinModule(isolate,
1883 mojo::js::Support::kModuleName,
1884 mojo::js::Support::GetModule(isolate));
1885 registry->AddBuiltinModule(
1886 isolate,
1887 ServiceRegistryJsWrapper::kModuleName,
1888 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1891 // blink::WebFrameClient implementation ----------------------------------------
1893 blink::WebPluginPlaceholder* RenderFrameImpl::createPluginPlaceholder(
1894 blink::WebLocalFrame* frame,
1895 const blink::WebPluginParams& params) {
1896 DCHECK_EQ(frame_, frame);
1897 return GetContentClient()
1898 ->renderer()
1899 ->CreatePluginPlaceholder(this, frame, params)
1900 .release();
1903 blink::WebPlugin* RenderFrameImpl::createPlugin(
1904 blink::WebLocalFrame* frame,
1905 const blink::WebPluginParams& params) {
1906 DCHECK_EQ(frame_, frame);
1907 blink::WebPlugin* plugin = NULL;
1908 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1909 this, frame, params, &plugin)) {
1910 return plugin;
1913 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1914 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1915 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1916 kBrowserPluginMimeType, GURL(params.url)));
1917 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1918 this, browser_plugin_delegate.Pass());
1921 #if defined(ENABLE_PLUGINS)
1922 WebPluginInfo info;
1923 std::string mime_type;
1924 bool found = false;
1925 Send(new FrameHostMsg_GetPluginInfo(
1926 routing_id_, params.url, frame->top()->document().url(),
1927 params.mimeType.utf8(), &found, &info, &mime_type));
1928 if (!found)
1929 return NULL;
1931 WebPluginParams params_to_use = params;
1932 params_to_use.mimeType = WebString::fromUTF8(mime_type);
1933 return CreatePlugin(frame, info, params_to_use, nullptr /* throttler */);
1934 #else
1935 return NULL;
1936 #endif // defined(ENABLE_PLUGINS)
1939 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1940 blink::WebLocalFrame* frame,
1941 const blink::WebURL& url,
1942 blink::WebMediaPlayerClient* client,
1943 blink::WebContentDecryptionModule* initial_cdm) {
1944 #if defined(VIDEO_HOLE)
1945 if (!contains_media_player_) {
1946 render_view_->RegisterVideoHoleFrame(this);
1947 contains_media_player_ = true;
1949 #endif // defined(VIDEO_HOLE)
1951 blink::WebMediaStream web_stream(
1952 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
1953 if (!web_stream.isNull())
1954 return CreateWebMediaPlayerForMediaStream(url, client);
1956 #if defined(OS_ANDROID)
1957 return CreateAndroidWebMediaPlayer(url, client, GetMediaPermission(),
1958 initial_cdm);
1959 #else
1960 scoped_refptr<media::MediaLog> media_log(new RenderMediaLog());
1962 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1963 media::WebMediaPlayerParams params(
1964 base::Bind(&ContentRendererClient::DeferMediaLoad,
1965 base::Unretained(GetContentClient()->renderer()),
1966 static_cast<RenderFrame*>(this)),
1967 render_thread->GetAudioRendererMixerManager()->CreateInput(routing_id_),
1968 media_log, render_thread->GetMediaThreadTaskRunner(),
1969 render_thread->compositor_task_runner(),
1970 base::Bind(&GetSharedMainThreadContext3D), GetMediaPermission(),
1971 initial_cdm);
1973 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1974 scoped_ptr<media::RendererFactory> media_renderer_factory(
1975 new media::MojoRendererFactory(GetMediaServiceProvider()));
1976 #else
1977 scoped_ptr<media::RendererFactory> media_renderer_factory =
1978 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
1979 media_log);
1981 if (!media_renderer_factory.get()) {
1982 media_renderer_factory.reset(new media::DefaultRendererFactory(
1983 media_log, render_thread->GetGpuFactories(),
1984 *render_thread->GetAudioHardwareConfig()));
1986 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
1988 return new media::WebMediaPlayerImpl(
1989 frame, client, weak_factory_.GetWeakPtr(), media_renderer_factory.Pass(),
1990 GetCdmFactory(), params);
1991 #endif // defined(OS_ANDROID)
1994 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
1995 blink::WebLocalFrame* frame,
1996 blink::WebApplicationCacheHostClient* client) {
1997 if (!frame || !frame->view())
1998 return NULL;
1999 DCHECK(!frame_ || frame_ == frame);
2000 return new RendererWebApplicationCacheHostImpl(
2001 RenderViewImpl::FromWebView(frame->view()), client,
2002 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2005 blink::WebWorkerContentSettingsClientProxy*
2006 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2007 blink::WebLocalFrame* frame) {
2008 if (!frame || !frame->view())
2009 return NULL;
2010 DCHECK(!frame_ || frame_ == frame);
2011 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2012 this, frame);
2015 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
2016 const WebPopupMenuInfo& popup_menu_info,
2017 WebExternalPopupMenuClient* popup_menu_client) {
2018 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2019 // An IPC message is sent to the browser to build and display the actual
2020 // popup. The user could have time to click a different select by the time
2021 // the popup is shown. In that case external_popup_menu_ is non NULL.
2022 // By returning NULL in that case, we instruct Blink to cancel that new
2023 // popup. So from the user perspective, only the first one will show, and
2024 // will have to close the first one before another one can be shown.
2025 if (external_popup_menu_)
2026 return NULL;
2027 external_popup_menu_.reset(
2028 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
2029 if (render_view_->screen_metrics_emulator_) {
2030 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
2031 external_popup_menu_.get(),
2032 render_view_->screen_metrics_emulator_.get());
2034 return external_popup_menu_.get();
2035 #else
2036 return NULL;
2037 #endif
2040 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
2041 DCHECK(!frame_ || frame_ == frame);
2042 return &cookie_jar_;
2045 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
2046 blink::WebLocalFrame* frame) {
2047 DCHECK(!frame_ || frame_ == frame);
2048 // At this point we should have non-null data source.
2049 DCHECK(frame->dataSource());
2050 if (!ChildThreadImpl::current())
2051 return NULL; // May be null in some tests.
2052 ServiceWorkerNetworkProvider* provider =
2053 ServiceWorkerNetworkProvider::FromDocumentState(
2054 DocumentState::FromDataSource(frame->dataSource()));
2055 return new WebServiceWorkerProviderImpl(
2056 ChildThreadImpl::current()->thread_safe_sender(),
2057 provider ? provider->context() : NULL);
2060 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
2061 DCHECK(!frame_ || frame_ == frame);
2062 // If the request hasn't yet committed, notify the browser process that it is
2063 // no longer safe to show the pending URL of the main frame, since a URL spoof
2064 // is now possible. (If the request has committed, the browser already knows.)
2065 if (!frame->parent()) {
2066 DocumentState* document_state =
2067 DocumentState::FromDataSource(frame->dataSource());
2068 NavigationStateImpl* navigation_state =
2069 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2071 if (!navigation_state->request_committed()) {
2072 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
2077 blink::WebFrame* RenderFrameImpl::createChildFrame(
2078 blink::WebLocalFrame* parent,
2079 blink::WebTreeScopeType scope,
2080 const blink::WebString& name,
2081 blink::WebSandboxFlags sandbox_flags) {
2082 // Synchronously notify the browser of a child frame creation to get the
2083 // routing_id for the RenderFrame.
2084 int child_routing_id = MSG_ROUTING_NONE;
2085 Send(new FrameHostMsg_CreateChildFrame(routing_id_, scope,
2086 base::UTF16ToUTF8(name), sandbox_flags,
2087 &child_routing_id));
2089 // Allocation of routing id failed, so we can't create a child frame. This can
2090 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2091 // out state or synchronous IPC message above has failed.
2092 if (child_routing_id == MSG_ROUTING_NONE) {
2093 NOTREACHED() << "Failed to allocate routing id for child frame.";
2094 return nullptr;
2097 // Create the RenderFrame and WebLocalFrame, linking the two.
2098 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
2099 render_view_.get(), child_routing_id);
2100 blink::WebLocalFrame* web_frame =
2101 WebLocalFrame::create(scope, child_render_frame);
2102 child_render_frame->SetWebFrame(web_frame);
2104 // Add the frame to the frame tree and initialize it.
2105 parent->appendChild(web_frame);
2106 child_render_frame->Initialize();
2108 return web_frame;
2111 blink::WebFrame* RenderFrameImpl::createChildFrame(
2112 blink::WebLocalFrame* parent,
2113 const blink::WebString& name,
2114 blink::WebSandboxFlags sandbox_flags) {
2115 return createChildFrame(parent, blink::WebTreeScopeType::Document, name,
2116 sandbox_flags);
2119 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
2120 DCHECK(!frame_ || frame_ == frame);
2121 // We only need to notify the browser if the active, top-level frame clears
2122 // its opener. We can ignore cases where a swapped out frame clears its
2123 // opener after hearing about it from the browser, and the browser does not
2124 // (yet) care about subframe openers.
2125 if (is_swapped_out_ || frame->parent())
2126 return;
2128 // Notify WebContents and all its swapped out RenderViews.
2129 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
2132 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
2133 frameDetached(frame, DetachType::Remove);
2136 void RenderFrameImpl::frameDetached(blink::WebFrame* frame, DetachType type) {
2137 // NOTE: This function is called on the frame that is being detached and not
2138 // the parent frame. This is different from createChildFrame() which is
2139 // called on the parent frame.
2140 CHECK(!is_detaching_);
2141 DCHECK(!frame_ || frame_ == frame);
2143 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameDetached());
2144 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2145 FrameDetached(frame));
2147 // We only notify the browser process when the frame is being detached for
2148 // removal. If the frame is being detached for swap, we don't need to do this
2149 // since we are not modifiying the frame tree.
2150 if (type == DetachType::Remove)
2151 Send(new FrameHostMsg_Detach(routing_id_));
2153 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2154 // sent before setting |is_detaching_| to true.
2155 is_detaching_ = true;
2157 // We need to clean up subframes by removing them from the map and deleting
2158 // the RenderFrameImpl. In contrast, the main frame is owned by its
2159 // containing RenderViewHost (so that they have the same lifetime), so only
2160 // removal from the map is needed and no deletion.
2161 FrameMap::iterator it = g_frame_map.Get().find(frame);
2162 CHECK(it != g_frame_map.Get().end());
2163 CHECK_EQ(it->second, this);
2164 g_frame_map.Get().erase(it);
2166 if (is_subframe_) {
2167 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2168 switches::kSitePerProcess) && render_widget_) {
2169 render_widget_->UnregisterRenderFrame(this);
2172 // Only remove the frame from the renderer's frame tree if the frame is
2173 // being detached for removal. For swaps, WebFrame::swap already takes care
2174 // of replacing the frame with a RemoteFrame.
2175 if (type == DetachType::Remove)
2176 frame->parent()->removeChild(frame);
2179 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2180 // object may not be deleted immediately and other methods may try to access
2181 // it.
2182 frame->close();
2183 frame_ = nullptr;
2185 delete this;
2186 // Object is invalid after this point.
2189 void RenderFrameImpl::frameFocused() {
2190 Send(new FrameHostMsg_FrameFocused(routing_id_));
2193 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
2194 DCHECK(!frame_ || frame_ == frame);
2196 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
2197 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2198 FrameWillClose(frame));
2201 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
2202 const blink::WebString& name) {
2203 DCHECK(!frame_ || frame_ == frame);
2205 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2206 // updates may have performance implications for benchmarks like SunSpider.
2207 // For now, send these updates only for --site-per-process, which needs to
2208 // replicate frame names to frame proxies, and when
2209 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2210 // can be optimized further by only sending the update if there are any
2211 // remote frames in the frame tree, or delaying and batching up IPCs if
2212 // updates are happening too frequently.
2213 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
2214 switches::kSitePerProcess);
2215 if (is_site_per_process ||
2216 render_view_->renderer_preferences_.report_frame_name_changes) {
2217 Send(new FrameHostMsg_DidChangeName(routing_id_, base::UTF16ToUTF8(name)));
2221 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame* child_frame,
2222 blink::WebSandboxFlags flags) {
2223 int frame_routing_id = MSG_ROUTING_NONE;
2224 if (child_frame->isWebRemoteFrame()) {
2225 frame_routing_id =
2226 RenderFrameProxy::FromWebFrame(child_frame)->routing_id();
2227 } else {
2228 frame_routing_id =
2229 RenderFrameImpl::FromWebFrame(child_frame)->GetRoutingID();
2232 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_, frame_routing_id,
2233 flags));
2236 void RenderFrameImpl::didMatchCSS(
2237 blink::WebLocalFrame* frame,
2238 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2239 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2240 DCHECK(!frame_ || frame_ == frame);
2242 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2243 DidMatchCSS(frame,
2244 newly_matching_selectors,
2245 stopped_matching_selectors));
2248 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2249 const blink::WebString& source) {
2250 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2251 source);
2254 void RenderFrameImpl::didAddMessageToConsole(
2255 const blink::WebConsoleMessage& message,
2256 const blink::WebString& source_name,
2257 unsigned source_line,
2258 const blink::WebString& stack_trace) {
2259 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2260 switch (message.level) {
2261 case blink::WebConsoleMessage::LevelDebug:
2262 log_severity = logging::LOG_VERBOSE;
2263 break;
2264 case blink::WebConsoleMessage::LevelLog:
2265 case blink::WebConsoleMessage::LevelInfo:
2266 log_severity = logging::LOG_INFO;
2267 break;
2268 case blink::WebConsoleMessage::LevelWarning:
2269 log_severity = logging::LOG_WARNING;
2270 break;
2271 case blink::WebConsoleMessage::LevelError:
2272 log_severity = logging::LOG_ERROR;
2273 break;
2274 default:
2275 log_severity = logging::LOG_VERBOSE;
2278 if (shouldReportDetailedMessageForSource(source_name)) {
2279 FOR_EACH_OBSERVER(
2280 RenderFrameObserver, observers_,
2281 DetailedConsoleMessageAdded(message.text,
2282 source_name,
2283 stack_trace,
2284 source_line,
2285 static_cast<int32>(log_severity)));
2288 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2289 static_cast<int32>(log_severity),
2290 message.text,
2291 static_cast<int32>(source_line),
2292 source_name));
2295 void RenderFrameImpl::loadURLExternally(
2296 blink::WebLocalFrame* frame,
2297 const blink::WebURLRequest& request,
2298 blink::WebNavigationPolicy policy,
2299 const blink::WebString& suggested_name) {
2300 DCHECK(!frame_ || frame_ == frame);
2301 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2302 if (policy == blink::WebNavigationPolicyDownload) {
2303 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2304 request.url(), referrer,
2305 suggested_name));
2306 } else {
2307 OpenURL(frame, request.url(), referrer, policy);
2311 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2312 const NavigationPolicyInfo& info) {
2313 DCHECK(!frame_ || frame_ == info.frame);
2314 return DecidePolicyForNavigation(this, info);
2317 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2318 blink::WebFrame* frame) {
2319 DCHECK(!frame_ || frame_ == frame);
2320 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2323 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2324 const blink::WebFormElement& form) {
2325 DCHECK(!frame_ || frame_ == frame);
2327 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSendSubmitEvent(form));
2330 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2331 const blink::WebFormElement& form) {
2332 DCHECK(!frame_ || frame_ == frame);
2333 DocumentState* document_state =
2334 DocumentState::FromDataSource(frame->provisionalDataSource());
2335 NavigationStateImpl* navigation_state =
2336 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2337 InternalDocumentStateData* internal_data =
2338 InternalDocumentStateData::FromDocumentState(document_state);
2340 if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(),
2341 ui::PAGE_TRANSITION_LINK)) {
2342 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2345 // Save these to be processed when the ensuing navigation is committed.
2346 WebSearchableFormData web_searchable_form_data(form);
2347 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2348 internal_data->set_searchable_form_encoding(
2349 web_searchable_form_data.encoding().utf8());
2351 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form));
2354 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2355 blink::WebDataSource* datasource) {
2356 DCHECK(!frame_ || frame_ == frame);
2358 bool content_initiated = !pending_navigation_params_.get();
2360 // Make sure any previous redirect URLs end up in our new data source.
2361 if (pending_navigation_params_.get()) {
2362 for (const auto& i :
2363 pending_navigation_params_->request_params.redirects) {
2364 datasource->appendRedirect(i);
2368 DocumentState* document_state = DocumentState::FromDataSource(datasource);
2369 if (!document_state) {
2370 document_state = new DocumentState;
2371 datasource->setExtraData(document_state);
2372 if (!content_initiated)
2373 PopulateDocumentStateFromPending(document_state);
2376 // Carry over the user agent override flag, if it exists.
2377 blink::WebView* webview = render_view_->webview();
2378 if (content_initiated && webview && webview->mainFrame() &&
2379 webview->mainFrame()->isWebLocalFrame() &&
2380 webview->mainFrame()->dataSource()) {
2381 DocumentState* old_document_state =
2382 DocumentState::FromDataSource(webview->mainFrame()->dataSource());
2383 if (old_document_state) {
2384 InternalDocumentStateData* internal_data =
2385 InternalDocumentStateData::FromDocumentState(document_state);
2386 InternalDocumentStateData* old_internal_data =
2387 InternalDocumentStateData::FromDocumentState(old_document_state);
2388 internal_data->set_is_overriding_user_agent(
2389 old_internal_data->is_overriding_user_agent());
2393 // The rest of RenderView assumes that a WebDataSource will always have a
2394 // non-null NavigationState.
2395 if (content_initiated) {
2396 document_state->set_navigation_state(
2397 NavigationStateImpl::CreateContentInitiated());
2398 } else {
2399 document_state->set_navigation_state(CreateNavigationStateFromPending());
2400 pending_navigation_params_.reset();
2403 // DocumentState::referred_by_prefetcher_ is true if we are
2404 // navigating from a page that used prefetching using a link on that
2405 // page. We are early enough in the request process here that we
2406 // can still see the DocumentState of the previous page and set
2407 // this value appropriately.
2408 // TODO(gavinp): catch the important case of navigation in a new
2409 // renderer process.
2410 if (webview) {
2411 if (WebFrame* old_frame = webview->mainFrame()) {
2412 const WebURLRequest& original_request = datasource->originalRequest();
2413 const GURL referrer(
2414 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2415 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2416 DocumentState::FromDataSource(old_frame->dataSource())
2417 ->was_prefetcher()) {
2418 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2419 WebDataSource* old_frame_datasource = old_frame->dataSource();
2420 if (old_frame_datasource &&
2421 referrer == GURL(old_frame_datasource->request().url())) {
2422 document_state->set_was_referred_by_prefetcher(true);
2423 break;
2430 if (content_initiated) {
2431 const WebURLRequest& request = datasource->request();
2432 switch (request.cachePolicy()) {
2433 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2434 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2435 break;
2436 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2437 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2438 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2439 break;
2440 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2441 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK);
2442 break;
2443 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2444 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2445 break;
2446 default:
2447 NOTREACHED();
2451 // Create the serviceworker's per-document network observing object if it
2452 // does not exist (When navigation happens within a page, the provider already
2453 // exists).
2454 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2455 DocumentState::FromDataSource(datasource))) {
2456 scoped_ptr<ServiceWorkerNetworkProvider> network_provider(
2457 new ServiceWorkerNetworkProvider(routing_id_,
2458 SERVICE_WORKER_PROVIDER_FOR_WINDOW));
2459 ServiceWorkerNetworkProvider::AttachToDocumentState(
2460 DocumentState::FromDataSource(datasource),
2461 network_provider.Pass());
2465 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2466 double triggering_event_time) {
2467 DCHECK(!frame_ || frame_ == frame);
2468 WebDataSource* ds = frame->provisionalDataSource();
2470 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2471 // callback is invoked.
2472 if (!ds)
2473 return;
2475 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2476 "id", routing_id_, "url", ds->request().url().string().utf8());
2477 DocumentState* document_state = DocumentState::FromDataSource(ds);
2479 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2480 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2481 is_swapped_out_) <<
2482 "Heard swappedout:// when not swapped out.";
2484 // Update the request time if WebKit has better knowledge of it.
2485 if (document_state->request_time().is_null() &&
2486 triggering_event_time != 0.0) {
2487 document_state->set_request_time(Time::FromDoubleT(triggering_event_time));
2490 // Start time is only set after request time.
2491 document_state->set_start_load_time(Time::Now());
2493 bool is_top_most = !frame->parent();
2494 if (is_top_most) {
2495 render_view_->set_navigation_gesture(
2496 WebUserGestureIndicator::isProcessingUserGesture() ?
2497 NavigationGestureUser : NavigationGestureAuto);
2498 } else if (ds->replacesCurrentHistoryItem()) {
2499 // Subframe navigations that don't add session history items must be
2500 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2501 // handle loading of error pages.
2502 static_cast<NavigationStateImpl*>(document_state->navigation_state())
2503 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2506 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2507 DidStartProvisionalLoad(frame));
2508 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2510 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2511 routing_id_, ds->request().url()));
2514 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2515 blink::WebLocalFrame* frame) {
2516 DCHECK(!frame_ || frame_ == frame);
2517 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2520 void RenderFrameImpl::didFailProvisionalLoad(
2521 blink::WebLocalFrame* frame,
2522 const blink::WebURLError& error,
2523 blink::WebHistoryCommitType commit_type) {
2524 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2525 "id", routing_id_);
2526 DCHECK(!frame_ || frame_ == frame);
2527 WebDataSource* ds = frame->provisionalDataSource();
2528 DCHECK(ds);
2530 const WebURLRequest& failed_request = ds->request();
2532 // Notify the browser that we failed a provisional load with an error.
2534 // Note: It is important this notification occur before DidStopLoading so the
2535 // SSL manager can react to the provisional load failure before being
2536 // notified the load stopped.
2538 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2539 DidFailProvisionalLoad(frame, error));
2540 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2541 DidFailProvisionalLoad(error));
2543 SendFailedProvisionalLoad(failed_request, error, frame);
2545 if (!ShouldDisplayErrorPageForFailedLoad(error.reason, error.unreachableURL))
2546 return;
2548 // Make sure we never show errors in view source mode.
2549 frame->enableViewSourceMode(false);
2551 DocumentState* document_state = DocumentState::FromDataSource(ds);
2552 NavigationStateImpl* navigation_state =
2553 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2555 // If this is a failed back/forward/reload navigation, then we need to do a
2556 // 'replace' load. This is necessary to avoid messing up session history.
2557 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2558 // as session history is concerned.
2559 bool replace = commit_type != blink::WebStandardCommit;
2561 // If we failed on a browser initiated request, then make sure that our error
2562 // page load is regarded as the same browser initiated request.
2563 if (!navigation_state->IsContentInitiated()) {
2564 pending_navigation_params_.reset(new NavigationParams(
2565 navigation_state->common_params(), navigation_state->start_params(),
2566 navigation_state->request_params()));
2567 pending_navigation_params_->request_params.request_time =
2568 document_state->request_time();
2571 // Load an error page.
2572 LoadNavigationErrorPage(failed_request, error, replace);
2575 void RenderFrameImpl::didCommitProvisionalLoad(
2576 blink::WebLocalFrame* frame,
2577 const blink::WebHistoryItem& item,
2578 blink::WebHistoryCommitType commit_type) {
2579 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2580 "id", routing_id_,
2581 "url", GetLoadingUrl().possibly_invalid_spec());
2582 DCHECK(!frame_ || frame_ == frame);
2583 DocumentState* document_state =
2584 DocumentState::FromDataSource(frame->dataSource());
2585 NavigationStateImpl* navigation_state =
2586 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2588 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2589 RenderFrameProxy* proxy =
2590 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2591 CHECK(proxy);
2592 proxy->web_frame()->swap(frame_);
2593 proxy_routing_id_ = MSG_ROUTING_NONE;
2595 // If this is the main frame going from a remote frame to a local frame,
2596 // it needs to set RenderViewImpl's pointer for the main frame to itself.
2597 if (!is_subframe_) {
2598 CHECK(!render_view_->main_render_frame_);
2599 render_view_->main_render_frame_ = this;
2603 // When we perform a new navigation, we need to update the last committed
2604 // session history entry with state for the page we are leaving. Do this
2605 // before updating the HistoryController state.
2606 render_view_->UpdateSessionHistory(frame);
2608 render_view_->history_controller()->UpdateForCommit(
2609 this, item, commit_type, navigation_state->WasWithinSamePage());
2611 InternalDocumentStateData* internal_data =
2612 InternalDocumentStateData::FromDocumentState(document_state);
2614 if (document_state->commit_load_time().is_null())
2615 document_state->set_commit_load_time(Time::Now());
2617 if (internal_data->must_reset_scroll_and_scale_state()) {
2618 render_view_->webview()->resetScrollAndScaleState();
2619 internal_data->set_must_reset_scroll_and_scale_state(false);
2621 internal_data->set_use_error_page(false);
2623 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2624 if (is_new_navigation) {
2625 // We bump our Page ID to correspond with the new session history entry.
2626 render_view_->page_id_ = render_view_->next_page_id_++;
2628 // Don't update history list values for kSwappedOutURL, since
2629 // we don't want to forget the entry that was there, and since we will
2630 // never come back to kSwappedOutURL. Note that we have to call
2631 // UpdateSessionHistory and update page_id_ even in this case, so that
2632 // the current entry gets a state update and so that we don't send a
2633 // state update to the wrong entry when we swap back in.
2634 DCHECK_IMPLIES(
2635 navigation_state->start_params().should_replace_current_entry,
2636 render_view_->history_list_length_ > 0);
2637 if (GetLoadingUrl() != GURL(kSwappedOutURL) &&
2638 !navigation_state->start_params().should_replace_current_entry) {
2639 // Advance our offset in session history, applying the length limit.
2640 // There is now no forward history.
2641 render_view_->history_list_offset_++;
2642 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2643 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2644 render_view_->history_list_length_ =
2645 render_view_->history_list_offset_ + 1;
2647 } else {
2648 const RequestNavigationParams& request_params =
2649 navigation_state->request_params();
2650 if (request_params.nav_entry_id != 0 &&
2651 !request_params.intended_as_new_entry) {
2652 // This is a successful session history navigation!
2653 render_view_->page_id_ = request_params.page_id;
2655 render_view_->history_list_offset_ =
2656 request_params.pending_history_list_offset;
2660 bool sent = Send(
2661 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2662 CHECK(sent); // http://crbug.com/407376
2664 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2665 DidCommitProvisionalLoad(frame, is_new_navigation));
2666 FOR_EACH_OBSERVER(
2667 RenderFrameObserver, observers_,
2668 DidCommitProvisionalLoad(is_new_navigation,
2669 navigation_state->WasWithinSamePage()));
2671 if (!frame->parent()) { // Only for top frames.
2672 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2673 if (render_thread_impl) { // Can be NULL in tests.
2674 render_thread_impl->histogram_customizer()->
2675 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2676 RenderView::GetRenderViewCount());
2680 // Remember that we've already processed this request, so we don't update
2681 // the session history again. We do this regardless of whether this is
2682 // a session history navigation, because if we attempted a session history
2683 // navigation without valid HistoryItem state, WebCore will think it is a
2684 // new navigation.
2685 navigation_state->set_request_committed(true);
2687 SendDidCommitProvisionalLoad(frame, commit_type);
2689 // Check whether we have new encoding name.
2690 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2693 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2694 DCHECK(!frame_ || frame_ == frame);
2696 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidCreateNewDocument());
2697 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2698 DidCreateNewDocument(frame));
2701 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2702 DCHECK(!frame_ || frame_ == frame);
2704 int enabled_bindings = render_view_->GetEnabledBindings();
2706 if (enabled_bindings & BINDINGS_POLICY_WEB_UI)
2707 WebUIExtension::Install(frame);
2709 if (enabled_bindings & BINDINGS_POLICY_DOM_AUTOMATION)
2710 DomAutomationController::Install(this, frame);
2712 if (enabled_bindings & BINDINGS_POLICY_STATS_COLLECTION)
2713 StatsCollectionController::Install(frame);
2715 const base::CommandLine& command_line =
2716 *base::CommandLine::ForCurrentProcess();
2718 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
2719 GpuBenchmarking::Install(frame);
2721 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2722 MemoryBenchmarkingExtension::Install(frame);
2724 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2725 SkiaBenchmarking::Install(frame);
2727 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2728 DidClearWindowObject(frame));
2729 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2732 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2733 DCHECK(!frame_ || frame_ == frame);
2735 // Notify the browser about non-blank documents loading in the top frame.
2736 GURL url = frame->document().url();
2737 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2738 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2739 // frame->tree()->top().
2740 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2741 if (frame == main_frame) {
2742 // For now, don't remember plugin zoom values. We don't want to mix them
2743 // with normal web content (i.e. a fixed layout plugin would usually want
2744 // them different).
2745 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2746 render_view_->GetRoutingID(),
2747 main_frame->document().isPluginDocument()));
2751 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2752 DidCreateDocumentElement());
2753 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2754 DidCreateDocumentElement(frame));
2757 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2758 const blink::WebString& title,
2759 blink::WebTextDirection direction) {
2760 DCHECK(!frame_ || frame_ == frame);
2761 // Ignore all but top level navigations.
2762 if (!frame->parent()) {
2763 base::string16 title16 = title;
2764 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2765 routing_id_, base::UTF16ToUTF8(title16));
2767 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2768 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2769 shortened_title, direction));
2772 // Also check whether we have new encoding name.
2773 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2776 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2777 blink::WebIconURL::Type icon_type) {
2778 DCHECK(!frame_ || frame_ == frame);
2779 // TODO(nasko): Investigate wheather implementation should move here.
2780 render_view_->didChangeIcon(frame, icon_type);
2783 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2784 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2785 "id", routing_id_);
2786 DCHECK(!frame_ || frame_ == frame);
2787 WebDataSource* ds = frame->dataSource();
2788 DocumentState* document_state = DocumentState::FromDataSource(ds);
2789 document_state->set_finish_document_load_time(Time::Now());
2791 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2793 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2794 DidFinishDocumentLoad(frame));
2795 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2797 // Check whether we have new encoding name.
2798 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2801 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2802 DCHECK(!frame_ || frame_ == frame);
2803 if (!frame->parent()) {
2804 FrameMsg_UILoadMetricsReportType::Value report_type =
2805 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
2806 frame->dataSource()->request().inputPerfMetricReportPolicy());
2807 base::TimeTicks ui_timestamp = base::TimeTicks() +
2808 base::TimeDelta::FromSecondsD(
2809 frame->dataSource()->request().uiStartTime());
2811 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2812 routing_id_, report_type, ui_timestamp));
2816 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2817 const blink::WebURLError& error,
2818 blink::WebHistoryCommitType commit_type) {
2819 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2820 "id", routing_id_);
2821 DCHECK(!frame_ || frame_ == frame);
2822 // TODO(nasko): Move implementation here. No state needed.
2823 WebDataSource* ds = frame->dataSource();
2824 DCHECK(ds);
2826 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2827 DidFailLoad(frame, error));
2829 const WebURLRequest& failed_request = ds->request();
2830 base::string16 error_description;
2831 GetContentClient()->renderer()->GetNavigationErrorStrings(
2832 render_view_.get(),
2833 frame,
2834 failed_request,
2835 error,
2836 NULL,
2837 &error_description);
2838 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2839 failed_request.url(),
2840 error.reason,
2841 error_description));
2844 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2845 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2846 "id", routing_id_);
2847 DCHECK(!frame_ || frame_ == frame);
2848 WebDataSource* ds = frame->dataSource();
2849 DocumentState* document_state = DocumentState::FromDataSource(ds);
2850 if (document_state->finish_load_time().is_null()) {
2851 if (!frame->parent()) {
2852 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2853 TRACE_EVENT_SCOPE_PROCESS);
2855 document_state->set_finish_load_time(Time::Now());
2858 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2859 DidFinishLoad(frame));
2860 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2862 // Don't send this message while the frame is swapped out.
2863 if (is_swapped_out())
2864 return;
2866 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2867 ds->request().url()));
2870 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2871 const blink::WebHistoryItem& item,
2872 blink::WebHistoryCommitType commit_type) {
2873 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2874 "id", routing_id_);
2875 DCHECK(!frame_ || frame_ == frame);
2876 // If this was a reference fragment navigation that we initiated, then we
2877 // could end up having a non-null pending navigation params. We just need to
2878 // update the ExtraData on the datasource so that others who read the
2879 // ExtraData will get the new NavigationState. Similarly, if we did not
2880 // initiate this navigation, then we need to take care to reset any pre-
2881 // existing navigation state to a content-initiated navigation state.
2882 // didCreateDataSource conveniently takes care of this for us.
2883 didCreateDataSource(frame, frame->dataSource());
2885 DocumentState* document_state =
2886 DocumentState::FromDataSource(frame->dataSource());
2887 static_cast<NavigationStateImpl*>(document_state->navigation_state())
2888 ->set_was_within_same_page(true);
2890 didCommitProvisionalLoad(frame, item, commit_type);
2893 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2894 DCHECK(!frame_ || frame_ == frame);
2895 // TODO(nasko): Move implementation here. Needed methods:
2896 // * StartNavStateSyncTimerIfNecessary
2897 render_view_->didUpdateCurrentHistoryItem(frame);
2900 void RenderFrameImpl::didChangeThemeColor() {
2901 if (frame_->parent())
2902 return;
2904 Send(new FrameHostMsg_DidChangeThemeColor(
2905 routing_id_, frame_->document().themeColor()));
2908 void RenderFrameImpl::dispatchLoad() {
2909 Send(new FrameHostMsg_DispatchLoad(routing_id_));
2912 void RenderFrameImpl::requestNotificationPermission(
2913 const blink::WebSecurityOrigin& origin,
2914 blink::WebNotificationPermissionCallback* callback) {
2915 if (!notification_permission_dispatcher_) {
2916 notification_permission_dispatcher_ =
2917 new NotificationPermissionDispatcher(this);
2920 notification_permission_dispatcher_->RequestPermission(origin, callback);
2923 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2924 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2925 return;
2927 if (is_empty_selection)
2928 selection_text_.clear();
2930 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2931 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2932 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2933 // to notify the selection was changed. Focus change should be notified
2934 // before selection change.
2935 GetRenderWidget()->UpdateTextInputType();
2936 SyncSelectionIfRequired();
2937 #if defined(OS_ANDROID)
2938 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
2939 RenderWidget::FROM_NON_IME);
2940 #endif
2943 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
2944 blink::WebColorChooserClient* client,
2945 const blink::WebColor& initial_color,
2946 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2947 RendererWebColorChooserImpl* color_chooser =
2948 new RendererWebColorChooserImpl(this, client);
2949 std::vector<ColorSuggestion> color_suggestions;
2950 for (size_t i = 0; i < suggestions.size(); i++) {
2951 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
2953 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2954 return color_chooser;
2957 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
2958 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2959 message,
2960 base::string16(),
2961 frame_->document().url(),
2962 NULL);
2965 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
2966 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2967 message,
2968 base::string16(),
2969 frame_->document().url(),
2970 NULL);
2973 bool RenderFrameImpl::runModalPromptDialog(
2974 const blink::WebString& message,
2975 const blink::WebString& default_value,
2976 blink::WebString* actual_value) {
2977 base::string16 result;
2978 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2979 message,
2980 default_value,
2981 frame_->document().url(),
2982 &result);
2983 if (ok)
2984 actual_value->assign(result);
2985 return ok;
2988 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2989 bool is_reload,
2990 const blink::WebString& message) {
2991 // If we are swapping out, we have already run the beforeunload handler.
2992 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2993 // at all, to avoid running it twice.
2994 if (is_swapped_out_)
2995 return true;
2997 // Don't allow further dialogs if we are waiting to swap out, since the
2998 // PageGroupLoadDeferrer in our stack prevents it.
2999 if (render_view()->suppress_dialogs_until_swap_out_)
3000 return false;
3002 bool success = false;
3003 // This is an ignored return value, but is included so we can accept the same
3004 // response as RunJavaScriptMessage.
3005 base::string16 ignored_result;
3006 render_view()->SendAndRunNestedMessageLoop(
3007 new FrameHostMsg_RunBeforeUnloadConfirm(
3008 routing_id_, frame_->document().url(), message, is_reload,
3009 &success, &ignored_result));
3010 return success;
3013 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
3014 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
3015 params.source_type = GetRenderWidget()->context_menu_source_type();
3016 GetRenderWidget()->OnShowHostContextMenu(&params);
3017 if (GetRenderWidget()->has_host_context_menu_location()) {
3018 params.x = GetRenderWidget()->host_context_menu_location().x();
3019 params.y = GetRenderWidget()->host_context_menu_location().y();
3022 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3023 // it. We replace it with an empty GURL so the appropriate items are disabled
3024 // in the context menu.
3025 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3026 // data encoded images. We should have a way to save them.
3027 if (params.src_url.spec().size() > GetMaxURLChars())
3028 params.src_url = GURL();
3029 context_menu_node_ = data.node;
3031 #if defined(OS_ANDROID)
3032 gfx::Rect start_rect;
3033 gfx::Rect end_rect;
3034 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
3035 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
3036 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
3037 #endif
3039 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
3042 void RenderFrameImpl::clearContextMenu() {
3043 context_menu_node_.reset();
3046 void RenderFrameImpl::willSendRequest(
3047 blink::WebLocalFrame* frame,
3048 unsigned identifier,
3049 blink::WebURLRequest& request,
3050 const blink::WebURLResponse& redirect_response) {
3051 DCHECK(!frame_ || frame_ == frame);
3052 // The request my be empty during tests.
3053 if (request.url().isEmpty())
3054 return;
3056 // Set the first party for cookies url if it has not been set yet (new
3057 // requests). For redirects, it is updated by WebURLLoaderImpl.
3058 if (request.firstPartyForCookies().isEmpty()) {
3059 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
3060 request.setFirstPartyForCookies(request.url());
3061 } else {
3062 // TODO(nasko): When the top-level frame is remote, there is no document.
3063 // This is broken and should be fixed to propagate the first party.
3064 WebFrame* top = frame->top();
3065 if (top->isWebLocalFrame()) {
3066 request.setFirstPartyForCookies(
3067 frame->top()->document().firstPartyForCookies());
3072 WebFrame* top_frame = frame->top();
3073 // TODO(nasko): Hack around asking about top-frame data source. This means
3074 // for out-of-process iframes we are treating the current frame as the
3075 // top-level frame, which is wrong.
3076 if (!top_frame || top_frame->isWebRemoteFrame())
3077 top_frame = frame;
3078 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
3079 WebDataSource* top_data_source = top_frame->dataSource();
3080 WebDataSource* data_source =
3081 provisional_data_source ? provisional_data_source : top_data_source;
3083 DocumentState* document_state = DocumentState::FromDataSource(data_source);
3084 DCHECK(document_state);
3085 InternalDocumentStateData* internal_data =
3086 InternalDocumentStateData::FromDocumentState(document_state);
3087 NavigationStateImpl* navigation_state =
3088 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3089 ui::PageTransition transition_type = navigation_state->GetTransitionType();
3090 WebDataSource* frame_ds = frame->provisionalDataSource();
3091 if (frame_ds && frame_ds->isClientRedirect()) {
3092 transition_type = ui::PageTransitionFromInt(
3093 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3096 GURL request_url(request.url());
3097 GURL new_url;
3098 if (GetContentClient()->renderer()->WillSendRequest(
3099 frame,
3100 transition_type,
3101 request_url,
3102 request.firstPartyForCookies(),
3103 &new_url)) {
3104 request.setURL(WebURL(new_url));
3107 if (internal_data->is_cache_policy_override_set())
3108 request.setCachePolicy(internal_data->cache_policy_override());
3110 // The request's extra data may indicate that we should set a custom user
3111 // agent. This needs to be done here, after WebKit is through with setting the
3112 // user agent on its own. Similarly, it may indicate that we should set an
3113 // X-Requested-With header. This must be done here to avoid breaking CORS
3114 // checks.
3115 // PlzNavigate: there may also be a stream url associated with the request.
3116 WebString custom_user_agent;
3117 WebString requested_with;
3118 scoped_ptr<StreamOverrideParameters> stream_override;
3119 if (request.extraData()) {
3120 RequestExtraData* old_extra_data =
3121 static_cast<RequestExtraData*>(request.extraData());
3123 custom_user_agent = old_extra_data->custom_user_agent();
3124 if (!custom_user_agent.isNull()) {
3125 if (custom_user_agent.isEmpty())
3126 request.clearHTTPHeaderField("User-Agent");
3127 else
3128 request.setHTTPHeaderField("User-Agent", custom_user_agent);
3131 requested_with = old_extra_data->requested_with();
3132 if (!requested_with.isNull()) {
3133 if (requested_with.isEmpty())
3134 request.clearHTTPHeaderField("X-Requested-With");
3135 else
3136 request.setHTTPHeaderField("X-Requested-With", requested_with);
3138 stream_override = old_extra_data->TakeStreamOverrideOwnership();
3141 // Add the default accept header for frame request if it has not been set
3142 // already.
3143 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3144 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
3145 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
3146 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
3147 WebString::fromUTF8(kDefaultAcceptHeader));
3150 // Add an empty HTTP origin header for non GET methods if none is currently
3151 // present.
3152 request.addHTTPOriginIfNeeded(WebString());
3154 // Attach |should_replace_current_entry| state to requests so that, should
3155 // this navigation later require a request transfer, all state is preserved
3156 // when it is re-created in the new process.
3157 bool should_replace_current_entry = false;
3158 if (navigation_state->IsContentInitiated()) {
3159 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
3160 } else {
3161 // If the navigation is browser-initiated, the NavigationState contains the
3162 // correct value instead of the WebDataSource.
3164 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3165 // NavigationState::should_replace_current_entry().
3166 should_replace_current_entry =
3167 navigation_state->start_params().should_replace_current_entry;
3170 int provider_id = kInvalidServiceWorkerProviderId;
3171 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3172 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
3173 // |provisionalDataSource| may be null in some content::ResourceFetcher
3174 // use cases, we don't hook those requests.
3175 if (frame->provisionalDataSource()) {
3176 ServiceWorkerNetworkProvider* provider =
3177 ServiceWorkerNetworkProvider::FromDocumentState(
3178 DocumentState::FromDataSource(frame->provisionalDataSource()));
3179 provider_id = provider->provider_id();
3181 } else if (frame->dataSource()) {
3182 ServiceWorkerNetworkProvider* provider =
3183 ServiceWorkerNetworkProvider::FromDocumentState(
3184 DocumentState::FromDataSource(frame->dataSource()));
3185 provider_id = provider->provider_id();
3188 WebFrame* parent = frame->parent();
3189 int parent_routing_id = MSG_ROUTING_NONE;
3190 if (!parent) {
3191 parent_routing_id = -1;
3192 } else if (parent->isWebLocalFrame()) {
3193 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
3194 } else {
3195 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
3198 RequestExtraData* extra_data = new RequestExtraData();
3199 extra_data->set_visibility_state(render_view_->visibilityState());
3200 extra_data->set_custom_user_agent(custom_user_agent);
3201 extra_data->set_requested_with(requested_with);
3202 extra_data->set_render_frame_id(routing_id_);
3203 extra_data->set_is_main_frame(!parent);
3204 extra_data->set_frame_origin(
3205 GURL(frame->document().securityOrigin().toString()));
3206 extra_data->set_parent_is_main_frame(parent && !parent->parent());
3207 extra_data->set_parent_render_frame_id(parent_routing_id);
3208 extra_data->set_allow_download(
3209 navigation_state->common_params().allow_download);
3210 extra_data->set_transition_type(transition_type);
3211 extra_data->set_should_replace_current_entry(should_replace_current_entry);
3212 extra_data->set_transferred_request_child_id(
3213 navigation_state->start_params().transferred_request_child_id);
3214 extra_data->set_transferred_request_request_id(
3215 navigation_state->start_params().transferred_request_request_id);
3216 extra_data->set_service_worker_provider_id(provider_id);
3217 extra_data->set_stream_override(stream_override.Pass());
3218 request.setExtraData(extra_data);
3220 DocumentState* top_document_state =
3221 DocumentState::FromDataSource(top_data_source);
3222 if (top_document_state) {
3223 // TODO(gavinp): separate out prefetching and prerender field trials
3224 // if the rel=prerender rel type is sticking around.
3225 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
3226 top_document_state->set_was_prefetcher(true);
3229 // This is an instance where we embed a copy of the routing id
3230 // into the data portion of the message. This can cause problems if we
3231 // don't register this id on the browser side, since the download manager
3232 // expects to find a RenderViewHost based off the id.
3233 request.setRequestorID(render_view_->GetRoutingID());
3234 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3236 if (!navigation_state->start_params().extra_headers.empty()) {
3237 for (net::HttpUtil::HeadersIterator i(
3238 navigation_state->start_params().extra_headers.begin(),
3239 navigation_state->start_params().extra_headers.end(), "\n");
3240 i.GetNext();) {
3241 if (LowerCaseEqualsASCII(i.name(), "referer")) {
3242 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
3243 blink::WebReferrerPolicyDefault,
3244 request.url(),
3245 WebString::fromUTF8(i.values()));
3246 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
3247 } else {
3248 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
3249 WebString::fromUTF8(i.values()));
3254 if (!render_view_->renderer_preferences_.enable_referrers)
3255 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
3258 void RenderFrameImpl::didReceiveResponse(
3259 blink::WebLocalFrame* frame,
3260 unsigned identifier,
3261 const blink::WebURLResponse& response) {
3262 DCHECK(!frame_ || frame_ == frame);
3263 // Only do this for responses that correspond to a provisional data source
3264 // of the top-most frame. If we have a provisional data source, then we
3265 // can't have any sub-resources yet, so we know that this response must
3266 // correspond to a frame load.
3267 if (!frame->provisionalDataSource() || frame->parent())
3268 return;
3270 // If we are in view source mode, then just let the user see the source of
3271 // the server's error page.
3272 if (frame->isViewSourceModeEnabled())
3273 return;
3275 DocumentState* document_state =
3276 DocumentState::FromDataSource(frame->provisionalDataSource());
3277 int http_status_code = response.httpStatusCode();
3279 // Record page load flags.
3280 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3281 if (extra_data) {
3282 document_state->set_was_fetched_via_spdy(
3283 extra_data->was_fetched_via_spdy());
3284 document_state->set_was_npn_negotiated(
3285 extra_data->was_npn_negotiated());
3286 document_state->set_npn_negotiated_protocol(
3287 extra_data->npn_negotiated_protocol());
3288 document_state->set_was_alternate_protocol_available(
3289 extra_data->was_alternate_protocol_available());
3290 document_state->set_connection_info(
3291 extra_data->connection_info());
3292 document_state->set_was_fetched_via_proxy(
3293 extra_data->was_fetched_via_proxy());
3294 document_state->set_proxy_server(
3295 extra_data->proxy_server());
3297 InternalDocumentStateData* internal_data =
3298 InternalDocumentStateData::FromDocumentState(document_state);
3299 internal_data->set_http_status_code(http_status_code);
3300 // Whether or not the http status code actually corresponds to an error is
3301 // only checked when the page is done loading, if |use_error_page| is
3302 // still true.
3303 internal_data->set_use_error_page(true);
3306 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
3307 unsigned identifier) {
3308 DCHECK(!frame_ || frame_ == frame);
3309 InternalDocumentStateData* internal_data =
3310 InternalDocumentStateData::FromDataSource(frame->dataSource());
3311 if (!internal_data->use_error_page())
3312 return;
3314 // Do not show error page when DevTools is attached.
3315 RenderFrameImpl* localRoot = this;
3316 while (localRoot->frame_ && localRoot->frame_->parent() &&
3317 localRoot->frame_->parent()->isWebLocalFrame()) {
3318 localRoot = RenderFrameImpl::FromWebFrame(localRoot->frame_->parent());
3319 DCHECK(localRoot);
3321 if (localRoot->devtools_agent_ && localRoot->devtools_agent_->IsAttached())
3322 return;
3324 // Display error page, if appropriate.
3325 std::string error_domain = "http";
3326 int http_status_code = internal_data->http_status_code();
3327 if (GetContentClient()->renderer()->HasErrorPage(
3328 http_status_code, &error_domain)) {
3329 WebURLError error;
3330 error.unreachableURL = frame->document().url();
3331 error.domain = WebString::fromUTF8(error_domain);
3332 error.reason = http_status_code;
3333 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
3337 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3338 blink::WebLocalFrame* frame,
3339 const blink::WebURLRequest& request,
3340 const blink::WebURLResponse& response) {
3341 DCHECK(!frame_ || frame_ == frame);
3342 // The recipients of this message have no use for data: URLs: they don't
3343 // affect the page's insecure content list and are not in the disk cache. To
3344 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3345 // filter them out here.
3346 GURL url(request.url());
3347 if (url.SchemeIs(url::kDataScheme))
3348 return;
3350 // Let the browser know we loaded a resource from the memory cache. This
3351 // message is needed to display the correct SSL indicators.
3352 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3353 render_view_->GetRoutingID(),
3354 url,
3355 response.securityInfo(),
3356 request.httpMethod().utf8(),
3357 response.mimeType().utf8(),
3358 WebURLRequestToResourceType(request)));
3361 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3362 DCHECK(!frame_ || frame_ == frame);
3363 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
3364 render_view_->GetRoutingID()));
3367 void RenderFrameImpl::didRunInsecureContent(
3368 blink::WebLocalFrame* frame,
3369 const blink::WebSecurityOrigin& origin,
3370 const blink::WebURL& target) {
3371 DCHECK(!frame_ || frame_ == frame);
3372 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
3373 render_view_->GetRoutingID(),
3374 origin.toString().utf8(),
3375 target));
3378 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3379 DCHECK(!frame_ || frame_ == frame);
3380 #if defined(ENABLE_PLUGINS)
3381 if (frame != render_view_->webview()->mainFrame())
3382 return;
3383 PluginChannelHost::Broadcast(
3384 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3385 #endif
3388 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3389 v8::Local<v8::Context> context,
3390 int extension_group,
3391 int world_id) {
3392 DCHECK(!frame_ || frame_ == frame);
3394 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
3395 DidCreateScriptContext(context, extension_group, world_id));
3398 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3399 v8::Local<v8::Context> context,
3400 int world_id) {
3401 DCHECK(!frame_ || frame_ == frame);
3403 FOR_EACH_OBSERVER(RenderFrameObserver,
3404 observers_,
3405 WillReleaseScriptContext(context, world_id));
3408 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3409 blink::WebLocalFrame* frame) {
3410 DCHECK(!frame_ || frame_ == frame);
3411 if (frame->parent())
3412 return;
3414 InternalDocumentStateData* data =
3415 InternalDocumentStateData::FromDataSource(frame->dataSource());
3416 data->set_did_first_visually_non_empty_layout(true);
3418 #if defined(OS_ANDROID)
3419 GetRenderWidget()->DidChangeBodyBackgroundColor(
3420 render_view_->webwidget_->backgroundColor());
3421 #endif
3423 GetRenderWidget()->QueueMessage(
3424 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3425 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3428 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3429 DCHECK(!frame_ || frame_ == frame);
3430 // TODO(nasko): Move implementation here. Needed methods:
3431 // * StartNavStateSyncTimerIfNecessary
3432 render_view_->didChangeScrollOffset(frame);
3434 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeScrollOffset());
3437 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3438 DCHECK(!frame_ || frame_ == frame);
3439 if (!frame->parent()) {
3440 render_view_->Send(new ViewHostMsg_WillInsertBody(
3441 render_view_->GetRoutingID()));
3445 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3446 int count,
3447 bool final_update) {
3448 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3449 if (!count)
3450 active_match_ordinal = 0;
3452 render_view_->Send(new ViewHostMsg_Find_Reply(
3453 render_view_->GetRoutingID(), request_id, count,
3454 gfx::Rect(), active_match_ordinal, final_update));
3457 void RenderFrameImpl::reportFindInPageSelection(
3458 int request_id,
3459 int active_match_ordinal,
3460 const blink::WebRect& selection_rect) {
3461 render_view_->Send(new ViewHostMsg_Find_Reply(
3462 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3463 active_match_ordinal, false));
3466 void RenderFrameImpl::requestStorageQuota(
3467 blink::WebLocalFrame* frame,
3468 blink::WebStorageQuotaType type,
3469 unsigned long long requested_size,
3470 blink::WebStorageQuotaCallbacks callbacks) {
3471 DCHECK(!frame_ || frame_ == frame);
3472 WebSecurityOrigin origin = frame->document().securityOrigin();
3473 if (origin.isUnique()) {
3474 // Unique origins cannot store persistent state.
3475 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3476 return;
3478 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3479 render_view_->GetRoutingID(),
3480 GURL(origin.toString()),
3481 static_cast<storage::StorageType>(type),
3482 requested_size,
3483 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3486 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3487 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3488 impl->set_render_frame_id(routing_id_);
3491 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3492 if (!geolocation_dispatcher_)
3493 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3494 return geolocation_dispatcher_;
3497 blink::WebPresentationClient* RenderFrameImpl::presentationClient() {
3498 if (!presentation_dispatcher_)
3499 presentation_dispatcher_ = new PresentationDispatcher(this);
3500 return presentation_dispatcher_;
3503 blink::WebPushClient* RenderFrameImpl::pushClient() {
3504 if (!push_messaging_dispatcher_)
3505 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3506 return push_messaging_dispatcher_;
3509 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3510 blink::WebLocalFrame* frame,
3511 blink::WebRTCPeerConnectionHandler* handler) {
3512 DCHECK(!frame_ || frame_ == frame);
3513 #if defined(ENABLE_WEBRTC)
3514 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3515 #endif
3518 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3519 if (!web_user_media_client_)
3520 InitializeUserMediaClient();
3521 return web_user_media_client_;
3524 blink::WebEncryptedMediaClient* RenderFrameImpl::encryptedMediaClient() {
3525 if (!web_encrypted_media_client_) {
3526 web_encrypted_media_client_.reset(new media::WebEncryptedMediaClientImpl(
3527 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3528 // is destructed before |this|, and does not give away ownership of the
3529 // callback.
3530 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported,
3531 base::Unretained(this)),
3532 GetCdmFactory(), GetMediaPermission()));
3534 return web_encrypted_media_client_.get();
3537 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3538 if (!midi_dispatcher_)
3539 midi_dispatcher_ = new MidiDispatcher(this);
3540 return midi_dispatcher_;
3543 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3544 blink::WebLocalFrame* source_frame,
3545 blink::WebFrame* target_frame,
3546 blink::WebSecurityOrigin target_origin,
3547 blink::WebDOMMessageEvent event) {
3548 DCHECK(!frame_ || frame_ == target_frame);
3550 // Currently, a postMessage that targets a cross-process frame can be plumbed
3551 // either through this function or RenderFrameProxy::postMessageEvent. This
3552 // function is used when the target cross-process frame is a top-level frame
3553 // which has been swapped out. In that case, the corresponding WebLocalFrame
3554 // currently remains in the frame tree even in site-per-process mode (see
3555 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3556 // --site-per-process mode for all other cases.
3558 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3559 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3560 // cross-process postMessages.
3561 if (!is_swapped_out_)
3562 return false;
3564 // It is possible to get here on a swapped-out frame without a
3565 // |render_frame_proxy_|. This happens when:
3566 // - This process only has one active RenderView and is about to go away
3567 // (e.g., due to cross-process navigation).
3568 // - The top frame has a subframe with an unload handler.
3569 // - The subframe sends a postMessage to the top-level frame in its unload
3570 // handler.
3571 // See https://crbug.com/475651 for details. We return false here, since we
3572 // don't want to deliver the message to the new process in this case.
3573 if (!render_frame_proxy_)
3574 return false;
3576 render_frame_proxy_->postMessageEvent(
3577 source_frame, render_frame_proxy_->web_frame(), target_origin, event);
3578 return true;
3581 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3582 const blink::WebURL& url) {
3583 DCHECK(!frame_ || frame_ == frame);
3584 std::string user_agent_override_for_url =
3585 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3586 if (!user_agent_override_for_url.empty())
3587 return WebString::fromUTF8(user_agent_override_for_url);
3589 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3590 render_view_->renderer_preferences_.user_agent_override.empty()) {
3591 return blink::WebString();
3594 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3595 // associated with it, so the checks below are not valid. Temporarily
3596 // return early and fix properly as part of https://crbug.com/426555.
3597 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3598 return blink::WebString();
3600 // If we're in the middle of committing a load, the data source we need
3601 // will still be provisional.
3602 WebFrame* main_frame = render_view_->webview()->mainFrame();
3603 WebDataSource* data_source = NULL;
3604 if (main_frame->provisionalDataSource())
3605 data_source = main_frame->provisionalDataSource();
3606 else
3607 data_source = main_frame->dataSource();
3609 InternalDocumentStateData* internal_data = data_source ?
3610 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3611 if (internal_data && internal_data->is_overriding_user_agent())
3612 return WebString::fromUTF8(
3613 render_view_->renderer_preferences_.user_agent_override);
3614 return blink::WebString();
3617 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3618 DCHECK(!frame_ || frame_ == frame);
3619 if (render_view_->renderer_preferences_.enable_do_not_track)
3620 return WebString::fromUTF8("1");
3621 return WebString();
3624 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3625 bool default_value) {
3626 DCHECK(!frame_ || frame_ == frame);
3627 if (!default_value)
3628 return false;
3630 bool blocked = true;
3631 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3632 render_view_->GetRoutingID(),
3633 GURL(frame->top()->document().securityOrigin().toString()),
3634 THREE_D_API_TYPE_WEBGL,
3635 &blocked));
3636 return !blocked;
3639 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3640 int arb_robustness_status_code) {
3641 DCHECK(!frame_ || frame_ == frame);
3642 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3643 GURL(frame->top()->document().securityOrigin().toString()),
3644 THREE_D_API_TYPE_WEBGL,
3645 arb_robustness_status_code));
3648 blink::WebScreenOrientationClient*
3649 RenderFrameImpl::webScreenOrientationClient() {
3650 if (!screen_orientation_dispatcher_)
3651 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3652 return screen_orientation_dispatcher_;
3655 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3656 ServiceWorkerNetworkProvider* provider =
3657 ServiceWorkerNetworkProvider::FromDocumentState(
3658 DocumentState::FromDataSource(&data_source));
3659 return provider->context()->controller_handle_id() !=
3660 kInvalidServiceWorkerHandleId;
3663 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3664 ServiceWorkerNetworkProvider* provider =
3665 ServiceWorkerNetworkProvider::FromDocumentState(
3666 DocumentState::FromDataSource(&data_source));
3668 if (provider->context()->controller())
3669 return provider->context()->controller()->version_id();
3670 return kInvalidServiceWorkerVersionId;
3673 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3674 blink::WebAXEvent event) {
3675 HandleWebAccessibilityEvent(obj, event);
3678 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3679 int identifier,
3680 int match_index,
3681 const blink::WebAXObject& start_object,
3682 int start_offset,
3683 const blink::WebAXObject& end_object,
3684 int end_offset) {
3685 if (renderer_accessibility_) {
3686 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3687 identifier, match_index, start_object, start_offset,
3688 end_object, end_offset);
3692 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame) {
3693 DCHECK(!frame_ || frame_ == frame);
3695 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3698 void RenderFrameImpl::didChangeDefaultPresentation(
3699 blink::WebLocalFrame* frame) {
3700 DCHECK(!frame_ || frame_ == frame);
3702 FOR_EACH_OBSERVER(
3703 RenderFrameObserver, observers_, DidChangeDefaultPresentation());
3706 bool RenderFrameImpl::enterFullscreen() {
3707 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, true));
3708 return true;
3711 bool RenderFrameImpl::exitFullscreen() {
3712 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, false));
3713 return true;
3716 blink::WebPermissionClient* RenderFrameImpl::permissionClient() {
3717 if (!permission_client_)
3718 permission_client_.reset(new PermissionDispatcher(GetServiceRegistry()));
3720 return permission_client_.get();
3723 blink::WebAppBannerClient* RenderFrameImpl::appBannerClient() {
3724 if (!app_banner_client_) {
3725 app_banner_client_ =
3726 GetContentClient()->renderer()->CreateAppBannerClient(this);
3729 return app_banner_client_.get();
3732 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3733 Send(new FrameHostMsg_MediaPlayingNotification(
3734 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3735 player->hasAudio(), player->isRemote()));
3738 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3739 Send(new FrameHostMsg_MediaPausedNotification(
3740 routing_id_, reinterpret_cast<int64>(player)));
3743 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3744 DidPause(player);
3747 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3748 observers_.AddObserver(observer);
3751 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3752 observer->RenderFrameGone();
3753 observers_.RemoveObserver(observer);
3756 void RenderFrameImpl::OnStop() {
3757 DCHECK(frame_);
3758 frame_->stopLoading();
3759 if (!frame_->parent())
3760 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3762 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3765 void RenderFrameImpl::WasHidden() {
3766 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3769 void RenderFrameImpl::WasShown() {
3770 // TODO(kenrb): Need to figure out how to do this better. Should
3771 // VisibilityState remain a page-level concept or move to frames?
3772 // The semantics of 'Show' might have to change here.
3773 if (render_widget_) {
3774 static_cast<blink::WebFrameWidget*>(render_widget_->webwidget())->
3775 setVisibilityState(blink::WebPageVisibilityStateVisible, false);
3777 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3780 void RenderFrameImpl::WidgetWillClose() {
3781 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WidgetWillClose());
3784 bool RenderFrameImpl::IsHidden() {
3785 return GetRenderWidget()->is_hidden();
3788 // Tell the embedding application that the URL of the active page has changed.
3789 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3790 blink::WebFrame* frame,
3791 blink::WebHistoryCommitType commit_type) {
3792 DCHECK(!frame_ || frame_ == frame);
3793 WebDataSource* ds = frame->dataSource();
3794 DCHECK(ds);
3796 const WebURLRequest& request = ds->request();
3797 const WebURLResponse& response = ds->response();
3799 DocumentState* document_state = DocumentState::FromDataSource(ds);
3800 NavigationStateImpl* navigation_state =
3801 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3802 InternalDocumentStateData* internal_data =
3803 InternalDocumentStateData::FromDocumentState(document_state);
3805 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3806 params.http_status_code = response.httpStatusCode();
3807 params.url_is_unreachable = ds->hasUnreachableURL();
3808 params.is_post = false;
3809 params.intended_as_new_entry =
3810 navigation_state->request_params().intended_as_new_entry;
3811 params.did_create_new_entry = commit_type == blink::WebStandardCommit;
3812 params.post_id = -1;
3813 params.page_id = render_view_->page_id_;
3814 params.nav_entry_id = navigation_state->request_params().nav_entry_id;
3815 // We need to track the RenderViewHost routing_id because of downstream
3816 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3817 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3818 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3819 // based on the ID stored in the resource requests. Once those dependencies
3820 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3821 // client to be based on the routing_id of the RenderFrameHost.
3822 params.render_view_routing_id = render_view_->routing_id();
3823 params.socket_address.set_host(response.remoteIPAddress().utf8());
3824 params.socket_address.set_port(response.remotePort());
3825 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3826 if (extra_data)
3827 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3828 params.was_within_same_page = navigation_state->WasWithinSamePage();
3829 params.security_info = response.securityInfo();
3831 // Set the URL to be displayed in the browser UI to the user.
3832 params.url = GetLoadingUrl();
3833 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3835 // Set the origin of the frame. This will be replicated to the corresponding
3836 // RenderFrameProxies in other processes.
3837 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3838 // to https://crbug.com/439608 and will be replicated as unique origins.
3839 if (!is_swapped_out_) {
3840 WebString serialized_origin(frame->document().securityOrigin().toString());
3841 if (GURL(serialized_origin).IsStandard())
3842 params.origin = url::Origin(serialized_origin.utf8());
3845 if (frame->document().baseURL() != params.url)
3846 params.base_url = frame->document().baseURL();
3848 GetRedirectChain(ds, &params.redirects);
3849 params.should_update_history = !ds->hasUnreachableURL() &&
3850 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3852 params.searchable_form_url = internal_data->searchable_form_url();
3853 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3855 params.gesture = render_view_->navigation_gesture_;
3856 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3858 // Make navigation state a part of the DidCommitProvisionalLoad message so
3859 // that committed entry has it at all times.
3860 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3861 if (entry)
3862 params.page_state = HistoryEntryToPageState(entry);
3863 else
3864 params.page_state = PageState::CreateFromURL(request.url());
3866 if (!frame->parent()) {
3867 // Top-level navigation.
3869 // Reset the zoom limits in case a plugin had changed them previously. This
3870 // will also call us back which will cause us to send a message to
3871 // update WebContentsImpl.
3872 render_view_->webview()->zoomLimitsChanged(
3873 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3874 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3876 // Set zoom level, but don't do it for full-page plugin since they don't use
3877 // the same zoom settings.
3878 HostZoomLevels::iterator host_zoom =
3879 render_view_->host_zoom_levels_.find(GURL(request.url()));
3880 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3881 // Reset the zoom levels for plugins.
3882 render_view_->webview()->setZoomLevel(0);
3883 } else {
3884 // If the zoom level is not found, then do nothing. In-page navigation
3885 // relies on not changing the zoom level in this case.
3886 if (host_zoom != render_view_->host_zoom_levels_.end())
3887 render_view_->webview()->setZoomLevel(host_zoom->second);
3890 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3891 // This zoom level was merely recorded transiently for this load. We can
3892 // erase it now. If at some point we reload this page, the browser will
3893 // send us a new, up-to-date zoom level.
3894 render_view_->host_zoom_levels_.erase(host_zoom);
3897 // Update contents MIME type for main frame.
3898 params.contents_mime_type = ds->response().mimeType().utf8();
3900 params.transition = navigation_state->GetTransitionType();
3901 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3902 // If the main frame does a load, it should not be reported as a subframe
3903 // navigation. This can occur in the following case:
3904 // 1. You're on a site with frames.
3905 // 2. You do a subframe navigation. This is stored with transition type
3906 // MANUAL_SUBFRAME.
3907 // 3. You navigate to some non-frame site, say, google.com.
3908 // 4. You navigate back to the page from step 2. Since it was initially
3909 // MANUAL_SUBFRAME, it will be that same transition type here.
3910 // We don't want that, because any navigation that changes the toplevel
3911 // frame should be tracked as a toplevel navigation (this allows us to
3912 // update the URL bar, etc).
3913 params.transition = ui::PAGE_TRANSITION_LINK;
3916 // If the page contained a client redirect (meta refresh, document.loc...),
3917 // set the referrer and transition appropriately.
3918 if (ds->isClientRedirect()) {
3919 params.referrer =
3920 Referrer(params.redirects[0], ds->request().referrerPolicy());
3921 params.transition = ui::PageTransitionFromInt(
3922 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3923 } else {
3924 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3925 frame, ds->request());
3928 base::string16 method = request.httpMethod();
3929 if (EqualsASCII(method, "POST")) {
3930 params.is_post = true;
3931 params.post_id = ExtractPostId(entry);
3934 // Send the user agent override back.
3935 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
3937 // Track the URL of the original request. We use the first entry of the
3938 // redirect chain if it exists because the chain may have started in another
3939 // process.
3940 params.original_request_url = GetOriginalRequestURL(ds);
3942 params.history_list_was_cleared =
3943 navigation_state->request_params().should_clear_history_list;
3945 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
3946 frame->dataSource()->request().inputPerfMetricReportPolicy());
3947 params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD(
3948 frame->dataSource()->request().uiStartTime());
3950 // Save some histogram data so we can compute the average memory used per
3951 // page load of the glyphs.
3952 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3953 blink::WebGlyphCache::pageCount());
3955 // This message needs to be sent before any of allowScripts(),
3956 // allowImages(), allowPlugins() is called for the new page, so that when
3957 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3958 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3959 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3960 } else {
3961 // Subframe navigation: the type depends on whether this navigation
3962 // generated a new session history entry. When they do generate a session
3963 // history entry, it means the user initiated the navigation and we should
3964 // mark it as such.
3965 if (commit_type == blink::WebStandardCommit)
3966 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
3967 else
3968 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
3970 DCHECK(!navigation_state->request_params().should_clear_history_list);
3971 params.history_list_was_cleared = false;
3972 params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT;
3974 // Don't send this message while the subframe is swapped out.
3975 if (!is_swapped_out())
3976 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3979 // If we end up reusing this WebRequest (for example, due to a #ref click),
3980 // we don't want the transition type to persist. Just clear it.
3981 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
3984 void RenderFrameImpl::didStartLoading(bool to_different_document) {
3985 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3986 "id", routing_id_);
3987 render_view_->FrameDidStartLoading(frame_);
3988 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
3991 void RenderFrameImpl::didStopLoading() {
3992 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3993 "id", routing_id_);
3994 render_view_->FrameDidStopLoading(frame_);
3995 Send(new FrameHostMsg_DidStopLoading(routing_id_));
3998 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
3999 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
4002 void RenderFrameImpl::HandleWebAccessibilityEvent(
4003 const blink::WebAXObject& obj, blink::WebAXEvent event) {
4004 if (renderer_accessibility_)
4005 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
4008 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
4009 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FocusedNodeChanged(node));
4012 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) {
4013 if (renderer_accessibility())
4014 renderer_accessibility()->AccessibilityFocusedNodeChanged(node);
4017 // PlzNavigate
4018 void RenderFrameImpl::OnCommitNavigation(
4019 const ResourceResponseHead& response,
4020 const GURL& stream_url,
4021 const CommonNavigationParams& common_params,
4022 const RequestNavigationParams& request_params) {
4023 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4024 switches::kEnableBrowserSideNavigation));
4025 // This will override the url requested by the WebURLLoader, as well as
4026 // provide it with the response to the request.
4027 scoped_ptr<StreamOverrideParameters> stream_override(
4028 new StreamOverrideParameters());
4029 stream_override->stream_url = stream_url;
4030 stream_override->response = response;
4032 NavigateInternal(common_params, StartNavigationParams(), request_params,
4033 stream_override.Pass());
4036 void RenderFrameImpl::OnFailedNavigation(
4037 const CommonNavigationParams& common_params,
4038 const RequestNavigationParams& request_params,
4039 bool has_stale_copy_in_cache,
4040 int error_code) {
4041 bool is_reload = IsReload(common_params.navigation_type);
4042 bool is_history_navigation = request_params.page_state.IsValid();
4043 WebURLRequest::CachePolicy cache_policy =
4044 WebURLRequest::UseProtocolCachePolicy;
4045 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4046 common_params.url, is_history_navigation, request_params, &is_reload,
4047 &cache_policy)) {
4048 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4049 return;
4052 GetContentClient()->SetActiveURL(common_params.url);
4054 pending_navigation_params_.reset(new NavigationParams(
4055 common_params, StartNavigationParams(), request_params));
4057 // Inform the browser of the start of the provisional load. This is needed so
4058 // that the load is properly tracked by the WebNavigation API.
4059 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4060 routing_id_, common_params.url));
4062 // Send the provisional load failure.
4063 blink::WebURLError error =
4064 CreateWebURLError(common_params.url, has_stale_copy_in_cache, error_code);
4065 WebURLRequest failed_request = CreateURLRequestForNavigation(
4066 common_params, scoped_ptr<StreamOverrideParameters>(),
4067 frame_->isViewSourceModeEnabled());
4068 SendFailedProvisionalLoad(failed_request, error, frame_);
4070 if (!ShouldDisplayErrorPageForFailedLoad(error_code, common_params.url)) {
4071 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4072 return;
4075 // Make sure errors are not shown in view source mode.
4076 frame_->enableViewSourceMode(false);
4078 // Replace the current history entry in reloads, history navigations and loads
4079 // of the same url. This corresponds to Blink's notion of a standard
4080 // commit.
4081 // TODO(clamy): see if initial commits in subframes should be handled
4082 // separately.
4083 bool replace = is_reload || is_history_navigation ||
4084 common_params.url == GetLoadingUrl();
4085 LoadNavigationErrorPage(failed_request, error, replace);
4088 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
4089 RenderFrame* render_frame,
4090 const NavigationPolicyInfo& info) {
4091 #ifdef OS_ANDROID
4092 // The handlenavigation API is deprecated and will be removed once
4093 // crbug.com/325351 is resolved.
4094 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
4095 GetContentClient()->renderer()->HandleNavigation(
4096 render_frame,
4097 static_cast<DocumentState*>(info.extraData),
4098 render_view_->opener_id_,
4099 info.frame,
4100 info.urlRequest,
4101 info.navigationType,
4102 info.defaultPolicy,
4103 info.isRedirect)) {
4104 return blink::WebNavigationPolicyIgnore;
4106 #endif
4108 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
4109 info.urlRequest));
4110 const base::CommandLine& command_line =
4111 *base::CommandLine::ForCurrentProcess();
4113 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe_) {
4114 // There's no reason to ignore navigations on subframes, since the swap out
4115 // logic no longer applies.
4116 } else {
4117 if (is_swapped_out_) {
4118 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
4119 // Targeted links may try to navigate a swapped out frame. Allow the
4120 // browser process to navigate the tab instead. Note that it is also
4121 // possible for non-targeted navigations (from this view) to arrive
4122 // here just after we are swapped out. It's ok to send them to the
4123 // browser, as long as they're for the top level frame.
4124 // TODO(creis): Ensure this supports targeted form submissions when
4125 // fixing http://crbug.com/101395.
4126 if (info.frame->parent() == NULL) {
4127 OpenURL(info.frame, info.urlRequest.url(), referrer,
4128 info.defaultPolicy);
4129 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4132 // We should otherwise ignore in-process iframe navigations, if they
4133 // arrive just after we are swapped out.
4134 return blink::WebNavigationPolicyIgnore;
4137 // Allow kSwappedOutURL to complete.
4138 return info.defaultPolicy;
4142 // Webkit is asking whether to navigate to a new URL.
4143 // This is fine normally, except if we're showing UI from one security
4144 // context and they're trying to navigate to a different context.
4145 const GURL& url = info.urlRequest.url();
4147 // A content initiated navigation may have originated from a link-click,
4148 // script, drag-n-drop operation, etc.
4149 DocumentState* document_state = static_cast<DocumentState*>(info.extraData);
4150 bool is_content_initiated =
4151 document_state->navigation_state()->IsContentInitiated();
4153 // Experimental:
4154 // If --enable-strict-site-isolation is enabled, send all top-level
4155 // navigations to the browser to let it swap processes when crossing site
4156 // boundaries. This is currently expected to break some script calls and
4157 // navigations, such as form submissions.
4158 bool force_swap_due_to_flag =
4159 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
4160 if (force_swap_due_to_flag &&
4161 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
4162 WebString origin_str = info.frame->document().securityOrigin().toString();
4163 GURL frame_url(origin_str.utf8().data());
4164 // TODO(cevans): revisit whether this site check is still necessary once
4165 // crbug.com/101395 is fixed.
4166 bool same_domain_or_host =
4167 net::registry_controlled_domains::SameDomainOrHost(
4168 frame_url,
4169 url,
4170 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
4171 // Only keep same-site (domain + scheme) and data URLs in the same process.
4172 bool is_same_site =
4173 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
4174 url.SchemeIs(url::kDataScheme);
4175 if (!is_same_site) {
4176 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4177 return blink::WebNavigationPolicyIgnore;
4181 // If the browser is interested, then give it a chance to look at the request.
4182 if (is_content_initiated) {
4183 bool is_form_post =
4184 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
4185 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
4186 EqualsASCII(info.urlRequest.httpMethod(), "POST");
4187 bool browser_handles_request =
4188 render_view_->renderer_preferences_
4189 .browser_handles_non_local_top_level_requests
4190 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
4191 is_form_post);
4192 if (!browser_handles_request) {
4193 browser_handles_request = IsTopLevelNavigation(info.frame) &&
4194 render_view_->renderer_preferences_
4195 .browser_handles_all_top_level_requests;
4198 if (browser_handles_request) {
4199 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4200 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4204 // Use the frame's original request's URL rather than the document's URL for
4205 // subsequent checks. For a popup, the document's URL may become the opener
4206 // window's URL if the opener has called document.write().
4207 // See http://crbug.com/93517.
4208 GURL old_url(info.frame->dataSource()->request().url());
4210 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4211 // an extension or app origin, leaving a WebUI page, etc). We only care about
4212 // top-level navigations (not iframes). But we sometimes navigate to
4213 // about:blank to clear a tab, and we want to still allow that.
4215 // Note: this is known to break POST submissions when crossing process
4216 // boundaries until http://crbug.com/101395 is fixed. This is better for
4217 // security than loading a WebUI, extension or app page in the wrong process.
4218 // POST requests don't work because this mechanism does not preserve form
4219 // POST data. We will need to send the request's httpBody data up to the
4220 // browser process, and issue a special POST navigation in WebKit (via
4221 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4222 // for examples of how to send the httpBody data.
4223 if (!info.frame->parent() && is_content_initiated &&
4224 !url.SchemeIs(url::kAboutScheme)) {
4225 bool send_referrer = false;
4227 // All navigations to or from WebUI URLs or within WebUI-enabled
4228 // RenderProcesses must be handled by the browser process so that the
4229 // correct bindings and data sources can be registered.
4230 // Similarly, navigations to view-source URLs or within ViewSource mode
4231 // must be handled by the browser process (except for reloads - those are
4232 // safe to leave within the renderer).
4233 // Lastly, access to file:// URLs from non-file:// URL pages must be
4234 // handled by the browser so that ordinary renderer processes don't get
4235 // blessed with file permissions.
4236 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
4237 bool is_initial_navigation = render_view_->history_list_length_ == 0;
4238 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
4239 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
4240 url.SchemeIs(kViewSourceScheme) ||
4241 (info.frame->isViewSourceModeEnabled() &&
4242 info.navigationType != blink::WebNavigationTypeReload);
4244 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
4245 // Fork non-file to file opens. Check the opener URL if this is the
4246 // initial navigation in a newly opened window.
4247 GURL source_url(old_url);
4248 if (is_initial_navigation && source_url.is_empty() &&
4249 info.frame->opener())
4250 source_url = info.frame->opener()->top()->document().url();
4251 DCHECK(!source_url.is_empty());
4252 should_fork = !source_url.SchemeIs(url::kFileScheme);
4255 if (!should_fork) {
4256 // Give the embedder a chance.
4257 should_fork = GetContentClient()->renderer()->ShouldFork(
4258 info.frame, url, info.urlRequest.httpMethod().utf8(),
4259 is_initial_navigation, info.isRedirect, &send_referrer);
4262 if (should_fork) {
4263 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
4264 info.defaultPolicy);
4265 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4269 // Detect when a page is "forking" a new tab that can be safely rendered in
4270 // its own process. This is done by sites like Gmail that try to open links
4271 // in new windows without script connections back to the original page. We
4272 // treat such cases as browser navigations (in which we will create a new
4273 // renderer for a cross-site navigation), rather than WebKit navigations.
4275 // We use the following heuristic to decide whether to fork a new page in its
4276 // own process:
4277 // The parent page must open a new tab to about:blank, set the new tab's
4278 // window.opener to null, and then redirect the tab to a cross-site URL using
4279 // JavaScript.
4281 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4282 // (see below).
4283 bool is_fork =
4284 // Must start from a tab showing about:blank, which is later redirected.
4285 old_url == GURL(url::kAboutBlankURL) &&
4286 // Must be the first real navigation of the tab.
4287 render_view_->historyBackListCount() < 1 &&
4288 render_view_->historyForwardListCount() < 1 &&
4289 // The parent page must have set the child's window.opener to null before
4290 // redirecting to the desired URL.
4291 info.frame->opener() == NULL &&
4292 // Must be a top-level frame.
4293 info.frame->parent() == NULL &&
4294 // Must not have issued the request from this page.
4295 is_content_initiated &&
4296 // Must be targeted at the current tab.
4297 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
4298 // Must be a JavaScript navigation, which appears as "other".
4299 info.navigationType == blink::WebNavigationTypeOther;
4301 if (is_fork) {
4302 // Open the URL via the browser, not via WebKit.
4303 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
4304 return blink::WebNavigationPolicyIgnore;
4307 // PlzNavigate: send the request to the browser if needed.
4308 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4309 switches::kEnableBrowserSideNavigation) &&
4310 info.urlRequest.checkForBrowserSideNavigation()) {
4311 BeginNavigation(&info.urlRequest);
4312 return blink::WebNavigationPolicyIgnore;
4315 return info.defaultPolicy;
4318 void RenderFrameImpl::OpenURL(WebFrame* frame,
4319 const GURL& url,
4320 const Referrer& referrer,
4321 WebNavigationPolicy policy) {
4322 DCHECK_EQ(frame_, frame);
4324 FrameHostMsg_OpenURL_Params params;
4325 params.url = url;
4326 params.referrer = referrer;
4327 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
4328 WebDataSource* ds = frame->provisionalDataSource();
4329 if (ds) {
4330 DocumentState* document_state = DocumentState::FromDataSource(ds);
4331 NavigationStateImpl* navigation_state =
4332 static_cast<NavigationStateImpl*>(document_state->navigation_state());
4333 if (navigation_state->IsContentInitiated()) {
4334 params.should_replace_current_entry =
4335 ds->replacesCurrentHistoryItem() &&
4336 render_view_->history_list_length_;
4337 } else {
4338 // This is necessary to preserve the should_replace_current_entry value on
4339 // cross-process redirects, in the event it was set by a previous process.
4341 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4342 // NavigationState::should_replace_current_entry().
4343 params.should_replace_current_entry =
4344 navigation_state->start_params().should_replace_current_entry;
4346 } else {
4347 params.should_replace_current_entry = false;
4349 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
4350 if (GetContentClient()->renderer()->AllowPopup())
4351 params.user_gesture = true;
4353 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
4354 policy == blink::WebNavigationPolicyNewForegroundTab ||
4355 policy == blink::WebNavigationPolicyNewWindow ||
4356 policy == blink::WebNavigationPolicyNewPopup) {
4357 WebUserGestureIndicator::consumeUserGesture();
4360 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4363 void RenderFrameImpl::NavigateInternal(
4364 const CommonNavigationParams& common_params,
4365 const StartNavigationParams& start_params,
4366 const RequestNavigationParams& request_params,
4367 scoped_ptr<StreamOverrideParameters> stream_params) {
4368 bool browser_side_navigation =
4369 base::CommandLine::ForCurrentProcess()->HasSwitch(
4370 switches::kEnableBrowserSideNavigation);
4371 bool is_reload = IsReload(common_params.navigation_type);
4372 bool is_history_navigation = request_params.page_state.IsValid();
4373 WebURLRequest::CachePolicy cache_policy =
4374 WebURLRequest::UseProtocolCachePolicy;
4375 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4376 common_params.url, is_history_navigation, request_params, &is_reload,
4377 &cache_policy)) {
4378 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4379 return;
4382 GetContentClient()->SetActiveURL(common_params.url);
4384 // If this frame isn't in the same process as the main frame, it may naively
4385 // assume that this is the first navigation in the iframe, but this may not
4386 // actually be the case. Inform the frame's state machine if this frame has
4387 // already committed other loads.
4388 if (request_params.has_committed_real_load && frame_->parent())
4389 frame_->setCommittedFirstRealLoad();
4391 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
4392 // We cannot reload if we do not have any history state. This happens, for
4393 // example, when recovering from a crash.
4394 is_reload = false;
4395 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4398 pending_navigation_params_.reset(
4399 new NavigationParams(common_params, start_params, request_params));
4401 // If we are reloading, then Blink will use the history state of the current
4402 // page, so we should just ignore any given history state. Otherwise, if we
4403 // have history state, then we need to navigate to it, which corresponds to a
4404 // back/forward navigation event.
4405 if (is_reload && !browser_side_navigation) {
4406 // TODO(clamy): adapt this code for PlzNavigate. In particular the stream
4407 // override should be given to the generated request.
4408 bool reload_original_url =
4409 (common_params.navigation_type ==
4410 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
4411 bool ignore_cache = (common_params.navigation_type ==
4412 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
4414 if (reload_original_url)
4415 frame_->reloadWithOverrideURL(common_params.url, true);
4416 else
4417 frame_->reload(ignore_cache);
4418 } else if (is_history_navigation && !browser_side_navigation) {
4419 // TODO(clamy): adapt this code for PlzNavigate. In particular the stream
4420 // override should be given to the generated request.
4422 // We must know the page ID of the page we are navigating back to.
4423 DCHECK_NE(request_params.page_id, -1);
4424 // We must know the nav entry ID of the page we are navigating back to,
4425 // which should be the case because history navigations are routed via the
4426 // browser.
4427 DCHECK_NE(0, request_params.nav_entry_id);
4428 scoped_ptr<HistoryEntry> entry =
4429 PageStateToHistoryEntry(request_params.page_state);
4430 if (entry) {
4431 // Ensure we didn't save the swapped out URL in UpdateState, since the
4432 // browser should never be telling us to navigate to swappedout://.
4433 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
4434 scoped_ptr<NavigationParams> navigation_params(
4435 new NavigationParams(*pending_navigation_params_.get()));
4436 render_view_->history_controller()->GoToEntry(
4437 entry.Pass(), navigation_params.Pass(), cache_policy);
4439 } else if (!common_params.base_url_for_data_url.is_empty() ||
4440 (browser_side_navigation &&
4441 common_params.url.SchemeIs(url::kDataScheme))) {
4442 LoadDataURL(common_params, frame_);
4443 } else {
4444 // Navigate to the given URL.
4445 WebURLRequest request = CreateURLRequestForNavigation(
4446 common_params, stream_params.Pass(), frame_->isViewSourceModeEnabled());
4448 if (!start_params.extra_headers.empty() && !browser_side_navigation) {
4449 for (net::HttpUtil::HeadersIterator i(start_params.extra_headers.begin(),
4450 start_params.extra_headers.end(),
4451 "\n");
4452 i.GetNext();) {
4453 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
4454 WebString::fromUTF8(i.values()));
4458 if (start_params.is_post && !browser_side_navigation) {
4459 request.setHTTPMethod(WebString::fromUTF8("POST"));
4461 // Set post data.
4462 WebHTTPBody http_body;
4463 http_body.initialize();
4464 const char* data = nullptr;
4465 if (start_params.browser_initiated_post_data.size()) {
4466 data = reinterpret_cast<const char*>(
4467 &start_params.browser_initiated_post_data.front());
4469 http_body.appendData(
4470 WebData(data, start_params.browser_initiated_post_data.size()));
4471 request.setHTTPBody(http_body);
4474 // A session history navigation should have been accompanied by state.
4475 CHECK_EQ(request_params.page_id, -1);
4477 // PlzNavigate: Make sure that Blink's loader will not try to use browser
4478 // side navigation for this request (since it already went to the browser).
4479 if (browser_side_navigation)
4480 request.setCheckForBrowserSideNavigation(false);
4482 // Record this before starting the load. We need a lower bound of this time
4483 // to sanitize the navigationStart override set below.
4484 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
4485 frame_->loadRequest(request);
4487 UpdateFrameNavigationTiming(frame_, request_params.browser_navigation_start,
4488 renderer_navigation_start);
4491 // In case LoadRequest failed before didCreateDataSource was called.
4492 pending_navigation_params_.reset();
4495 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4496 const std::string& encoding_name) {
4497 // Only update main frame's encoding_name.
4498 if (!frame->parent())
4499 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4502 void RenderFrameImpl::SyncSelectionIfRequired() {
4503 base::string16 text;
4504 size_t offset;
4505 gfx::Range range;
4506 #if defined(ENABLE_PLUGINS)
4507 if (render_view_->focused_pepper_plugin_) {
4508 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4509 offset = 0; // Pepper API does not support offset reporting.
4510 // TODO(kinaba): cut as needed.
4511 } else
4512 #endif
4514 size_t location, length;
4515 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4516 &location, &length)) {
4517 return;
4520 range = gfx::Range(location, location + length);
4522 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4523 blink::WebTextInputTypeNone) {
4524 // If current focused element is editable, we will send 100 more chars
4525 // before and after selection. It is for input method surrounding text
4526 // feature.
4527 if (location > kExtraCharsBeforeAndAfterSelection)
4528 offset = location - kExtraCharsBeforeAndAfterSelection;
4529 else
4530 offset = 0;
4531 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4532 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4533 if (!webrange.isNull())
4534 text = webrange.toPlainText();
4535 } else {
4536 offset = location;
4537 text = frame_->selectionAsText();
4538 // http://crbug.com/101435
4539 // In some case, frame->selectionAsText() returned text's length is not
4540 // equal to the length returned from webwidget()->caretOrSelectionRange().
4541 // So we have to set the range according to text.length().
4542 range.set_end(range.start() + text.length());
4546 // Sometimes we get repeated didChangeSelection calls from webkit when
4547 // the selection hasn't actually changed. We don't want to report these
4548 // because it will cause us to continually claim the X clipboard.
4549 if (selection_text_offset_ != offset ||
4550 selection_range_ != range ||
4551 selection_text_ != text) {
4552 selection_text_ = text;
4553 selection_text_offset_ = offset;
4554 selection_range_ = range;
4555 SetSelectedText(text, offset, range);
4557 GetRenderWidget()->UpdateSelectionBounds();
4560 void RenderFrameImpl::InitializeUserMediaClient() {
4561 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4562 return;
4564 #if defined(OS_ANDROID)
4565 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4566 switches::kDisableWebRTC))
4567 return;
4568 #endif
4570 #if defined(ENABLE_WEBRTC)
4571 DCHECK(!web_user_media_client_);
4572 web_user_media_client_ = new UserMediaClientImpl(
4573 this,
4574 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4575 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4576 #endif
4579 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4580 const blink::WebURL& url,
4581 WebMediaPlayerClient* client) {
4582 #if defined(ENABLE_WEBRTC)
4583 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4584 bool found_neon =
4585 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4586 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4587 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4588 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4589 new RenderMediaLog(),
4590 CreateRendererFactory());
4591 #else
4592 return NULL;
4593 #endif // defined(ENABLE_WEBRTC)
4596 scoped_ptr<MediaStreamRendererFactory>
4597 RenderFrameImpl::CreateRendererFactory() {
4598 scoped_ptr<MediaStreamRendererFactory> factory =
4599 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4600 if (factory.get())
4601 return factory.Pass();
4602 #if defined(ENABLE_WEBRTC)
4603 return scoped_ptr<MediaStreamRendererFactory>(
4604 new MediaStreamRendererFactoryImpl());
4605 #else
4606 return scoped_ptr<MediaStreamRendererFactory>(
4607 static_cast<MediaStreamRendererFactory*>(NULL));
4608 #endif
4611 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4612 const GURL& url,
4613 bool is_history_navigation,
4614 const RequestNavigationParams& request_params,
4615 bool* is_reload,
4616 WebURLRequest::CachePolicy* cache_policy) {
4617 MaybeHandleDebugURL(url);
4618 if (!render_view_->webview())
4619 return false;
4621 FOR_EACH_OBSERVER(
4622 RenderViewObserver, render_view_->observers_, Navigate(url));
4624 // If this is a stale back/forward (due to a recent navigation the browser
4625 // didn't know about), ignore it. Only check if swapped in because if the
4626 // frame is swapped out, it won't commit before asking the browser.
4627 if (!render_view_->is_swapped_out() && is_history_navigation &&
4628 render_view_->history_list_offset_ !=
4629 request_params.current_history_list_offset) {
4630 return false;
4633 render_view_->history_list_offset_ =
4634 request_params.current_history_list_offset;
4635 render_view_->history_list_length_ =
4636 request_params.current_history_list_length;
4637 if (request_params.should_clear_history_list) {
4638 CHECK_EQ(-1, render_view_->history_list_offset_);
4639 CHECK_EQ(0, render_view_->history_list_length_);
4642 if (!is_swapped_out_ || frame_->parent())
4643 return true;
4645 // This is a swapped out main frame, so swap the renderer back in.
4646 // We marked the view as hidden when swapping the view out, so be sure to
4647 // reset the visibility state before navigating to the new URL.
4648 render_view_->webview()->setVisibilityState(
4649 render_view_->visibilityState(), false);
4651 // If this is an attempt to reload while we are swapped out, we should not
4652 // reload swappedout://, but the previous page, which is stored in
4653 // params.state. Setting is_reload to false will treat this like a back
4654 // navigation to accomplish that.
4655 *is_reload = false;
4656 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4658 // We refresh timezone when a view is swapped in since timezone
4659 // can get out of sync when the system timezone is updated while
4660 // the view is swapped out.
4661 RenderThreadImpl::NotifyTimezoneChange();
4663 render_view_->SetSwappedOut(false);
4664 is_swapped_out_ = false;
4665 return true;
4668 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4669 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4670 switches::kEnableBrowserSideNavigation));
4671 DCHECK(request);
4672 // TODO(clamy): Execute the beforeunload event.
4674 // Note: At this stage, the goal is to apply all the modifications the
4675 // renderer wants to make to the request, and then send it to the browser, so
4676 // that the actual network request can be started. Ideally, all such
4677 // modifications should take place in willSendRequest, and in the
4678 // implementation of willSendRequest for the various InspectorAgents
4679 // (devtools).
4681 // TODO(clamy): Apply devtools override.
4682 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4683 // else in blink.
4684 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4686 // TODO(clamy): Same-document navigations should not be sent back to the
4687 // browser.
4688 // TODO(clamy): Data urls should not be sent back to the browser either.
4689 Send(new FrameHostMsg_DidStartLoading(routing_id_, true));
4690 Send(new FrameHostMsg_BeginNavigation(
4691 routing_id_, MakeCommonNavigationParams(request),
4692 BeginNavigationParams(request->httpMethod().latin1(),
4693 GetWebURLRequestHeaders(*request),
4694 GetLoadFlagsForWebURLRequest(*request),
4695 request->hasUserGesture()),
4696 GetRequestBodyForWebURLRequest(*request)));
4699 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams& params,
4700 WebFrame* frame) {
4701 // A loadData request with a specified base URL.
4702 std::string mime_type, charset, data;
4703 if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) {
4704 const GURL base_url = params.base_url_for_data_url.is_empty() ?
4705 params.url : params.base_url_for_data_url;
4706 frame->loadData(
4707 WebData(data.c_str(), data.length()),
4708 WebString::fromUTF8(mime_type),
4709 WebString::fromUTF8(charset),
4710 base_url,
4711 params.history_url_for_data_url,
4712 false);
4713 } else {
4714 CHECK(false) << "Invalid URL passed: "
4715 << params.url.possibly_invalid_spec();
4719 void RenderFrameImpl::SendFailedProvisionalLoad(
4720 const blink::WebURLRequest& request,
4721 const blink::WebURLError& error,
4722 blink::WebLocalFrame* frame) {
4723 bool show_repost_interstitial = (error.reason == net::ERR_CACHE_MISS &&
4724 EqualsASCII(request.httpMethod(), "POST"));
4726 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
4727 params.error_code = error.reason;
4728 GetContentClient()->renderer()->GetNavigationErrorStrings(
4729 render_view_.get(), frame, request, error, NULL,
4730 &params.error_description);
4731 params.url = error.unreachableURL;
4732 params.showing_repost_interstitial = show_repost_interstitial;
4733 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_, params));
4736 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4737 int error_code,
4738 const GURL& unreachable_url) {
4739 // Don't display an error page if this is simply a cancelled load. Aside
4740 // from being dumb, Blink doesn't expect it and it will cause a crash.
4741 if (error_code == net::ERR_ABORTED)
4742 return false;
4744 // Don't display "client blocked" error page if browser has asked us not to.
4745 if (error_code == net::ERR_BLOCKED_BY_CLIENT &&
4746 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
4747 return false;
4750 // Allow the embedder to suppress an error page.
4751 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4752 this, unreachable_url)) {
4753 return false;
4756 if (RenderThreadImpl::current() &&
4757 RenderThreadImpl::current()->layout_test_mode()) {
4758 return false;
4761 return true;
4764 GURL RenderFrameImpl::GetLoadingUrl() const {
4765 WebDataSource* ds = frame_->dataSource();
4766 if (ds->hasUnreachableURL())
4767 return ds->unreachableURL();
4769 const WebURLRequest& request = ds->request();
4770 return request.url();
4773 void RenderFrameImpl::PopulateDocumentStateFromPending(
4774 DocumentState* document_state) {
4775 document_state->set_request_time(
4776 pending_navigation_params_->request_params.request_time);
4778 InternalDocumentStateData* internal_data =
4779 InternalDocumentStateData::FromDocumentState(document_state);
4781 if (!pending_navigation_params_->common_params.url.SchemeIs(
4782 url::kJavaScriptScheme) &&
4783 pending_navigation_params_->common_params.navigation_type ==
4784 FrameMsg_Navigate_Type::RESTORE) {
4785 // We're doing a load of a page that was restored from the last session. By
4786 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4787 // can result in stale data for pages that are set to expire. We explicitly
4788 // override that by setting the policy here so that as necessary we load
4789 // from the network.
4791 // TODO(davidben): Remove this in favor of passing a cache policy to the
4792 // loadHistoryItem call in OnNavigate. That requires not overloading
4793 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4794 // policy based on load type, etc".
4795 internal_data->set_cache_policy_override(
4796 WebURLRequest::UseProtocolCachePolicy);
4799 if (IsReload(pending_navigation_params_->common_params.navigation_type))
4800 document_state->set_load_type(DocumentState::RELOAD);
4801 else if (pending_navigation_params_->request_params.page_state.IsValid())
4802 document_state->set_load_type(DocumentState::HISTORY_LOAD);
4803 else
4804 document_state->set_load_type(DocumentState::NORMAL_LOAD);
4806 internal_data->set_is_overriding_user_agent(
4807 pending_navigation_params_->request_params.is_overriding_user_agent);
4808 internal_data->set_must_reset_scroll_and_scale_state(
4809 pending_navigation_params_->common_params.navigation_type ==
4810 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
4811 document_state->set_can_load_local_resources(
4812 pending_navigation_params_->request_params.can_load_local_resources);
4815 NavigationState* RenderFrameImpl::CreateNavigationStateFromPending() {
4816 // A navigation resulting from loading a javascript URL should not be treated
4817 // as a browser initiated event. Instead, we want it to look as if the page
4818 // initiated any load resulting from JS execution.
4819 if (!pending_navigation_params_->common_params.url.SchemeIs(
4820 url::kJavaScriptScheme)) {
4821 return NavigationStateImpl::CreateBrowserInitiated(
4822 pending_navigation_params_->common_params,
4823 pending_navigation_params_->start_params,
4824 pending_navigation_params_->request_params);
4826 return NavigationStateImpl::CreateContentInitiated();
4829 #if defined(OS_ANDROID)
4831 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4832 const blink::WebURL& url,
4833 WebMediaPlayerClient* client,
4834 media::MediaPermission* media_permission,
4835 blink::WebContentDecryptionModule* initial_cdm) {
4836 GpuChannelHost* gpu_channel_host =
4837 RenderThreadImpl::current()->EstablishGpuChannelSync(
4838 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4839 if (!gpu_channel_host) {
4840 LOG(ERROR) << "Failed to establish GPU channel for media player";
4841 return NULL;
4844 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4845 if (SynchronousCompositorFactory* factory =
4846 SynchronousCompositorFactory::GetInstance()) {
4847 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4848 } else {
4849 scoped_refptr<cc_blink::ContextProviderWebContext> context_provider =
4850 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4852 if (!context_provider.get()) {
4853 LOG(ERROR) << "Failed to get context3d for media player";
4854 return NULL;
4857 stream_texture_factory = StreamTextureFactoryImpl::Create(
4858 context_provider, gpu_channel_host, routing_id_);
4861 return new WebMediaPlayerAndroid(
4862 frame_, client, weak_factory_.GetWeakPtr(), GetMediaPlayerManager(),
4863 GetCdmFactory(), media_permission, initial_cdm, stream_texture_factory,
4864 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4865 new RenderMediaLog());
4868 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4869 if (!media_player_manager_)
4870 media_player_manager_ = new RendererMediaPlayerManager(this);
4871 return media_player_manager_;
4874 #endif // defined(OS_ANDROID)
4876 media::MediaPermission* RenderFrameImpl::GetMediaPermission() {
4877 if (!media_permission_dispatcher_)
4878 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
4879 return media_permission_dispatcher_;
4882 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
4883 media::MediaServiceProvider* RenderFrameImpl::GetMediaServiceProvider() {
4884 if (!content_media_service_provider_) {
4885 content_media_service_provider_ =
4886 new ContentMediaServiceProvider(this, GetServiceRegistry());
4888 return content_media_service_provider_;
4890 #endif
4892 bool RenderFrameImpl::AreSecureCodecsSupported() {
4893 #if defined(OS_ANDROID)
4894 // Hardware-secure codecs are only supported if secure surfaces are enabled.
4895 return render_view_->renderer_preferences_
4896 .use_video_overlay_for_embedded_encrypted_video;
4897 #else
4898 return false;
4899 #endif // defined(OS_ANDROID)
4902 media::CdmFactory* RenderFrameImpl::GetCdmFactory() {
4903 #if defined(ENABLE_BROWSER_CDMS)
4904 if (!cdm_manager_)
4905 cdm_manager_ = new RendererCdmManager(this);
4906 #endif // defined(ENABLE_BROWSER_CDMS)
4908 if (!cdm_factory_) {
4909 DCHECK(frame_);
4910 cdm_factory_ = new RenderCdmFactory(
4911 #if defined(ENABLE_PEPPER_CDMS)
4912 base::Bind(&PepperCdmWrapperImpl::Create, frame_),
4913 #elif defined(ENABLE_BROWSER_CDMS)
4914 cdm_manager_,
4915 #endif
4916 this);
4919 return cdm_factory_;
4922 } // namespace content