Infobar material design refresh: bg color
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
bloba0932d09c2b36848750051e576c4ccbe881eacf2
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/accessibility_messages.h"
39 #include "content/common/clipboard_messages.h"
40 #include "content/common/frame_messages.h"
41 #include "content/common/frame_replication_state.h"
42 #include "content/common/input_messages.h"
43 #include "content/common/navigation_params.h"
44 #include "content/common/service_worker/service_worker_types.h"
45 #include "content/common/site_isolation_policy.h"
46 #include "content/common/swapped_out_messages.h"
47 #include "content/common/view_messages.h"
48 #include "content/public/common/bindings_policy.h"
49 #include "content/public/common/content_constants.h"
50 #include "content/public/common/content_switches.h"
51 #include "content/public/common/context_menu_params.h"
52 #include "content/public/common/isolated_world_ids.h"
53 #include "content/public/common/page_state.h"
54 #include "content/public/common/resource_response.h"
55 #include "content/public/common/url_constants.h"
56 #include "content/public/common/url_utils.h"
57 #include "content/public/renderer/browser_plugin_delegate.h"
58 #include "content/public/renderer/content_renderer_client.h"
59 #include "content/public/renderer/context_menu_client.h"
60 #include "content/public/renderer/document_state.h"
61 #include "content/public/renderer/navigation_state.h"
62 #include "content/public/renderer/render_frame_observer.h"
63 #include "content/public/renderer/renderer_ppapi_host.h"
64 #include "content/renderer/accessibility/renderer_accessibility.h"
65 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
66 #include "content/renderer/browser_plugin/browser_plugin.h"
67 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
68 #include "content/renderer/child_frame_compositing_helper.h"
69 #include "content/renderer/context_menu_params_builder.h"
70 #include "content/renderer/devtools/devtools_agent.h"
71 #include "content/renderer/dom_automation_controller.h"
72 #include "content/renderer/external_popup_menu.h"
73 #include "content/renderer/geolocation_dispatcher.h"
74 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
75 #include "content/renderer/history_controller.h"
76 #include "content/renderer/history_serialization.h"
77 #include "content/renderer/image_downloader/image_downloader_impl.h"
78 #include "content/renderer/ime_event_guard.h"
79 #include "content/renderer/internal_document_state_data.h"
80 #include "content/renderer/manifest/manifest_manager.h"
81 #include "content/renderer/media/audio_renderer_mixer_manager.h"
82 #include "content/renderer/media/crypto/render_cdm_factory.h"
83 #include "content/renderer/media/media_permission_dispatcher.h"
84 #include "content/renderer/media/media_stream_dispatcher.h"
85 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
86 #include "content/renderer/media/midi_dispatcher.h"
87 #include "content/renderer/media/render_media_log.h"
88 #include "content/renderer/media/user_media_client_impl.h"
89 #include "content/renderer/media/webmediaplayer_ms.h"
90 #include "content/renderer/memory_benchmarking_extension.h"
91 #include "content/renderer/mojo/service_registry_js_wrapper.h"
92 #include "content/renderer/navigation_state_impl.h"
93 #include "content/renderer/notification_permission_dispatcher.h"
94 #include "content/renderer/npapi/plugin_channel_host.h"
95 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
96 #include "content/renderer/presentation/presentation_dispatcher.h"
97 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
98 #include "content/renderer/render_frame_proxy.h"
99 #include "content/renderer/render_process.h"
100 #include "content/renderer/render_thread_impl.h"
101 #include "content/renderer/render_view_impl.h"
102 #include "content/renderer/render_widget_fullscreen_pepper.h"
103 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
104 #include "content/renderer/renderer_webcolorchooser_impl.h"
105 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
106 #include "content/renderer/shared_worker_repository.h"
107 #include "content/renderer/skia_benchmarking_extension.h"
108 #include "content/renderer/stats_collection_controller.h"
109 #include "content/renderer/web_ui_extension.h"
110 #include "content/renderer/websharedworker_proxy.h"
111 #include "gin/modules/module_registry.h"
112 #include "media/base/audio_renderer_mixer_input.h"
113 #include "media/base/media_log.h"
114 #include "media/blink/webencryptedmediaclient_impl.h"
115 #include "media/blink/webmediaplayer_impl.h"
116 #include "media/renderers/gpu_video_accelerator_factories.h"
117 #include "mojo/common/url_type_converters.h"
118 #include "net/base/data_url.h"
119 #include "net/base/net_errors.h"
120 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
121 #include "net/http/http_util.h"
122 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
123 #include "third_party/WebKit/public/platform/WebString.h"
124 #include "third_party/WebKit/public/platform/WebURL.h"
125 #include "third_party/WebKit/public/platform/WebURLError.h"
126 #include "third_party/WebKit/public/platform/WebURLResponse.h"
127 #include "third_party/WebKit/public/platform/WebVector.h"
128 #include "third_party/WebKit/public/platform/modules/webusb/WebUSBClient.h"
129 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
130 #include "third_party/WebKit/public/web/WebDocument.h"
131 #include "third_party/WebKit/public/web/WebFrameWidget.h"
132 #include "third_party/WebKit/public/web/WebGlyphCache.h"
133 #include "third_party/WebKit/public/web/WebKit.h"
134 #include "third_party/WebKit/public/web/WebLocalFrame.h"
135 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
136 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
137 #include "third_party/WebKit/public/web/WebPlugin.h"
138 #include "third_party/WebKit/public/web/WebPluginParams.h"
139 #include "third_party/WebKit/public/web/WebRange.h"
140 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
141 #include "third_party/WebKit/public/web/WebScriptSource.h"
142 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
143 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
144 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
145 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
146 #include "third_party/WebKit/public/web/WebSettings.h"
147 #include "third_party/WebKit/public/web/WebSurroundingText.h"
148 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
149 #include "third_party/WebKit/public/web/WebView.h"
150 #include "third_party/mojo/src/mojo/edk/js/core.h"
151 #include "third_party/mojo/src/mojo/edk/js/support.h"
152 #include "url/url_util.h"
154 #if defined(ENABLE_PLUGINS)
155 #include "content/renderer/npapi/webplugin_impl.h"
156 #include "content/renderer/pepper/pepper_browser_connection.h"
157 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
158 #include "content/renderer/pepper/pepper_webplugin_impl.h"
159 #include "content/renderer/pepper/plugin_module.h"
160 #endif
162 #if defined(ENABLE_WEBRTC)
163 #include "content/renderer/media/rtc_peer_connection_handler.h"
164 #endif
166 #if defined(OS_ANDROID)
167 #include <cpu-features.h>
169 #include "content/common/gpu/client/context_provider_command_buffer.h"
170 #include "content/renderer/android/synchronous_compositor_factory.h"
171 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
172 #include "content/renderer/media/android/renderer_media_player_manager.h"
173 #include "content/renderer/media/android/stream_texture_factory_impl.h"
174 #include "content/renderer/media/android/webmediaplayer_android.h"
175 #else
176 #include "cc/blink/context_provider_web_context.h"
177 #include "content/renderer/usb/web_usb_client_impl.h"
178 #include "device/devices_app/public/cpp/constants.h"
179 #endif
181 #if defined(ENABLE_PEPPER_CDMS)
182 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
183 #elif defined(ENABLE_BROWSER_CDMS)
184 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
185 #endif
187 #if defined(ENABLE_MOJO_MEDIA)
188 #include "media/mojo/services/mojo_cdm_factory.h"
189 #include "media/mojo/services/mojo_renderer_factory.h"
190 #include "mojo/application/public/cpp/connect.h"
191 #include "mojo/application/public/interfaces/shell.mojom.h"
192 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
193 #else
194 #include "media/renderers/default_renderer_factory.h"
195 #endif
197 #if defined(ENABLE_WEBVR)
198 #include "content/renderer/vr/vr_dispatcher.h"
199 #endif
201 using blink::WebContentDecryptionModule;
202 using blink::WebContextMenuData;
203 using blink::WebData;
204 using blink::WebDataSource;
205 using blink::WebDocument;
206 using blink::WebDOMEvent;
207 using blink::WebDOMMessageEvent;
208 using blink::WebElement;
209 using blink::WebExternalPopupMenu;
210 using blink::WebExternalPopupMenuClient;
211 using blink::WebFrame;
212 using blink::WebHistoryItem;
213 using blink::WebHTTPBody;
214 using blink::WebLocalFrame;
215 using blink::WebMediaPlayer;
216 using blink::WebMediaPlayerClient;
217 using blink::WebMediaPlayerEncryptedMediaClient;
218 using blink::WebNavigationPolicy;
219 using blink::WebNavigationType;
220 using blink::WebNode;
221 using blink::WebPluginParams;
222 using blink::WebPopupMenuInfo;
223 using blink::WebRange;
224 using blink::WebReferrerPolicy;
225 using blink::WebScriptSource;
226 using blink::WebSearchableFormData;
227 using blink::WebSecurityOrigin;
228 using blink::WebSecurityPolicy;
229 using blink::WebSerializedScriptValue;
230 using blink::WebServiceWorkerProvider;
231 using blink::WebSettings;
232 using blink::WebStorageQuotaCallbacks;
233 using blink::WebString;
234 using blink::WebURL;
235 using blink::WebURLError;
236 using blink::WebURLRequest;
237 using blink::WebURLResponse;
238 using blink::WebUserGestureIndicator;
239 using blink::WebVector;
240 using blink::WebView;
241 using base::Time;
242 using base::TimeDelta;
244 namespace content {
246 namespace {
248 const char kDefaultAcceptHeader[] =
249 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
250 "*;q=0.8";
251 const char kAcceptHeader[] = "Accept";
253 const size_t kExtraCharsBeforeAndAfterSelection = 100;
255 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
256 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
257 LAZY_INSTANCE_INITIALIZER;
259 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
260 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
262 int64 ExtractPostId(HistoryEntry* entry) {
263 if (!entry)
264 return -1;
266 const WebHistoryItem& item = entry->root();
267 if (item.isNull() || item.httpBody().isNull())
268 return -1;
270 return item.httpBody().identifier();
273 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
274 const WebURLResponse& response) {
275 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
278 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
279 // Replace any occurrences of swappedout:// with about:blank.
280 const WebURL& blank_url = GURL(url::kAboutBlankURL);
281 WebVector<WebURL> urls;
282 ds->redirectChain(urls);
283 result->reserve(urls.size());
284 for (size_t i = 0; i < urls.size(); ++i) {
285 if (urls[i] != GURL(kSwappedOutURL))
286 result->push_back(urls[i]);
287 else
288 result->push_back(blank_url);
292 // Returns the original request url. If there is no redirect, the original
293 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
294 // frame was loaded by loadData, the original url will be ds->unreachableURL()
295 GURL GetOriginalRequestURL(WebDataSource* ds) {
296 // WebDataSource has unreachable URL means that the frame is loaded through
297 // blink::WebFrame::loadData(), and the base URL will be in the redirect
298 // chain. However, we never visited the baseURL. So in this case, we should
299 // use the unreachable URL as the original URL.
300 if (ds->hasUnreachableURL())
301 return ds->unreachableURL();
303 std::vector<GURL> redirects;
304 GetRedirectChain(ds, &redirects);
305 if (!redirects.empty())
306 return redirects.at(0);
308 return ds->originalRequest().url();
311 NOINLINE void CrashIntentionally() {
312 // NOTE(shess): Crash directly rather than using NOTREACHED() so
313 // that the signature is easier to triage in crash reports.
314 volatile int* zero = NULL;
315 *zero = 0;
318 NOINLINE void BadCastCrashIntentionally() {
319 class A {
320 virtual void f() {}
323 class B {
324 virtual void f() {}
327 A a;
328 (void)(B*)&a;
331 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
332 NOINLINE void MaybeTriggerAsanError(const GURL& url) {
333 // NOTE(rogerm): We intentionally perform an invalid heap access here in
334 // order to trigger an Address Sanitizer (ASAN) error report.
335 const char kCrashDomain[] = "crash";
336 const char kHeapOverflow[] = "/heap-overflow";
337 const char kHeapUnderflow[] = "/heap-underflow";
338 const char kUseAfterFree[] = "/use-after-free";
339 #if defined(SYZYASAN)
340 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
341 const char kCorruptHeap[] = "/corrupt-heap";
342 #endif
344 if (!url.DomainIs(kCrashDomain))
345 return;
347 if (!url.has_path())
348 return;
350 std::string crash_type(url.path());
351 if (crash_type == kHeapOverflow) {
352 base::debug::AsanHeapOverflow();
353 } else if (crash_type == kHeapUnderflow ) {
354 base::debug::AsanHeapUnderflow();
355 } else if (crash_type == kUseAfterFree) {
356 base::debug::AsanHeapUseAfterFree();
357 #if defined(SYZYASAN)
358 } else if (crash_type == kCorruptHeapBlock) {
359 base::debug::AsanCorruptHeapBlock();
360 } else if (crash_type == kCorruptHeap) {
361 base::debug::AsanCorruptHeap();
362 #endif
365 #endif // ADDRESS_SANITIZER || SYZYASAN
367 void MaybeHandleDebugURL(const GURL& url) {
368 if (!url.SchemeIs(kChromeUIScheme))
369 return;
370 if (url == GURL(kChromeUIBadCastCrashURL)) {
371 BadCastCrashIntentionally();
372 } else if (url == GURL(kChromeUICrashURL)) {
373 CrashIntentionally();
374 } else if (url == GURL(kChromeUIDumpURL)) {
375 // This URL will only correctly create a crash dump file if content is
376 // hosted in a process that has correctly called
377 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
378 // of base::debug::DumpWithoutCrashing for more details.
379 base::debug::DumpWithoutCrashing();
380 } else if (url == GURL(kChromeUIKillURL)) {
381 base::Process::Current().Terminate(1, false);
382 } else if (url == GURL(kChromeUIHangURL)) {
383 for (;;) {
384 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
386 } else if (url == GURL(kChromeUIShorthangURL)) {
387 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
390 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
391 MaybeTriggerAsanError(url);
392 #endif // ADDRESS_SANITIZER || SYZYASAN
395 // Returns false unless this is a top-level navigation.
396 bool IsTopLevelNavigation(WebFrame* frame) {
397 return frame->parent() == NULL;
400 // Returns false unless this is a top-level navigation that crosses origins.
401 bool IsNonLocalTopLevelNavigation(const GURL& url,
402 WebFrame* frame,
403 WebNavigationType type,
404 bool is_form_post) {
405 if (!IsTopLevelNavigation(frame))
406 return false;
408 // Navigations initiated within Webkit are not sent out to the external host
409 // in the following cases.
410 // 1. The url scheme is not http/https
411 // 2. The origin of the url and the opener is the same in which case the
412 // opener relationship is maintained.
413 // 3. Reloads/form submits/back forward navigations
414 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
415 return false;
417 if (type != blink::WebNavigationTypeReload &&
418 type != blink::WebNavigationTypeBackForward && !is_form_post) {
419 // The opener relationship between the new window and the parent allows the
420 // new window to script the parent and vice versa. This is not allowed if
421 // the origins of the two domains are different. This can be treated as a
422 // top level navigation and routed back to the host.
423 blink::WebFrame* opener = frame->opener();
424 if (!opener)
425 return true;
427 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
428 return true;
430 return false;
433 WebURLRequest CreateURLRequestForNavigation(
434 const CommonNavigationParams& common_params,
435 scoped_ptr<StreamOverrideParameters> stream_override,
436 bool is_view_source_mode_enabled) {
437 WebURLRequest request(common_params.url);
438 if (is_view_source_mode_enabled)
439 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
441 if (common_params.referrer.url.is_valid()) {
442 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
443 common_params.referrer.policy,
444 common_params.url,
445 WebString::fromUTF8(common_params.referrer.url.spec()));
446 if (!web_referrer.isEmpty())
447 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
450 RequestExtraData* extra_data = new RequestExtraData();
451 extra_data->set_stream_override(stream_override.Pass());
452 request.setExtraData(extra_data);
454 // Set the ui timestamp for this navigation. Currently the timestamp here is
455 // only non empty when the navigation was triggered by an Android intent. The
456 // timestamp is converted to a double version supported by blink. It will be
457 // passed back to the browser in the DidCommitProvisionalLoad and the
458 // DocumentLoadComplete IPCs.
459 base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
460 request.setUiStartTime(ui_timestamp.InSecondsF());
461 request.setInputPerfMetricReportPolicy(
462 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
463 common_params.report_type));
464 return request;
467 void UpdateFrameNavigationTiming(WebFrame* frame,
468 base::TimeTicks browser_navigation_start,
469 base::TimeTicks renderer_navigation_start) {
470 // The browser provides the navigation_start time to bootstrap the
471 // Navigation Timing information for the browser-initiated navigations. In
472 // case of cross-process navigations, this carries over the time of
473 // finishing the onbeforeunload handler of the previous page.
474 DCHECK(!browser_navigation_start.is_null());
475 if (frame->provisionalDataSource()) {
476 // |browser_navigation_start| is likely before this process existed, so we
477 // can't use InterProcessTimeTicksConverter. We need at least to ensure
478 // that the browser-side navigation start we set is not later than the one
479 // on the renderer side.
480 base::TimeTicks navigation_start = std::min(
481 browser_navigation_start, renderer_navigation_start);
482 double navigation_start_seconds =
483 (navigation_start - base::TimeTicks()).InSecondsF();
484 frame->provisionalDataSource()->setNavigationStartTime(
485 navigation_start_seconds);
486 // TODO(clamy): We need to provide additional timing values for the
487 // Navigation Timing API to work with browser-side navigations.
491 // PlzNavigate
492 CommonNavigationParams MakeCommonNavigationParams(
493 blink::WebURLRequest* request,
494 bool should_replace_current_entry) {
495 const RequestExtraData kEmptyData;
496 const RequestExtraData* extra_data =
497 static_cast<RequestExtraData*>(request->extraData());
498 if (!extra_data)
499 extra_data = &kEmptyData;
500 Referrer referrer(
501 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
502 request->referrerPolicy());
504 // Set the ui timestamp for this navigation. Currently the timestamp here is
505 // only non empty when the navigation was triggered by an Android intent, or
506 // by the user clicking on a link. The timestamp is converted from a double
507 // version supported by blink. It will be passed back to the renderer in the
508 // CommitNavigation IPC, and then back to the browser again in the
509 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
510 base::TimeTicks ui_timestamp =
511 base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
512 FrameMsg_UILoadMetricsReportType::Value report_type =
513 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
514 request->inputPerfMetricReportPolicy());
515 return CommonNavigationParams(
516 request->url(), referrer, extra_data->transition_type(),
517 FrameMsg_Navigate_Type::NORMAL, true, should_replace_current_entry,
518 ui_timestamp, report_type, GURL(), GURL());
521 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
522 media::Context3D GetSharedMainThreadContext3D() {
523 cc::ContextProvider* provider =
524 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
525 if (!provider)
526 return media::Context3D();
527 return media::Context3D(provider->ContextGL(), provider->GrContext());
529 #endif
531 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
532 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
533 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
534 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
537 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
538 nullptr;
540 void OnGotContentHandlerID(uint32_t content_handler_id) {}
542 } // namespace
544 // static
545 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
546 int32 routing_id) {
547 DCHECK(routing_id != MSG_ROUTING_NONE);
548 CreateParams params(render_view, routing_id);
550 if (g_create_render_frame_impl)
551 return g_create_render_frame_impl(params);
552 else
553 return new RenderFrameImpl(params);
556 // static
557 RenderFrame* RenderFrame::FromRoutingID(int routing_id) {
558 return RenderFrameImpl::FromRoutingID(routing_id);
561 // static
562 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int routing_id) {
563 RoutingIDFrameMap::iterator iter =
564 g_routing_id_frame_map.Get().find(routing_id);
565 if (iter != g_routing_id_frame_map.Get().end())
566 return iter->second;
567 return NULL;
570 // static
571 RenderFrameImpl* RenderFrameImpl::CreateMainFrame(RenderViewImpl* render_view,
572 int32 routing_id) {
573 RenderFrameImpl* render_frame =
574 RenderFrameImpl::Create(render_view, routing_id);
575 WebLocalFrame* web_frame =
576 WebLocalFrame::create(blink::WebTreeScopeType::Document, render_frame);
577 render_frame->SetWebFrame(web_frame);
578 render_view->webview()->setMainFrame(web_frame);
579 return render_frame;
582 // static
583 void RenderFrameImpl::CreateFrame(
584 int routing_id,
585 int parent_routing_id,
586 int previous_sibling_routing_id,
587 int proxy_routing_id,
588 const FrameReplicationState& replicated_state,
589 CompositorDependencies* compositor_deps,
590 const FrameMsg_NewFrame_WidgetParams& widget_params) {
591 blink::WebLocalFrame* web_frame;
592 RenderFrameImpl* render_frame;
593 if (proxy_routing_id == MSG_ROUTING_NONE) {
594 RenderFrameProxy* parent_proxy =
595 RenderFrameProxy::FromRoutingID(parent_routing_id);
596 // If the browser is sending a valid parent routing id, it should already
597 // be created and registered.
598 CHECK(parent_proxy);
599 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
601 blink::WebFrame* previous_sibling_web_frame = nullptr;
602 RenderFrameProxy* previous_sibling_proxy =
603 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id);
604 if (previous_sibling_proxy)
605 previous_sibling_web_frame = previous_sibling_proxy->web_frame();
607 // Create the RenderFrame and WebLocalFrame, linking the two.
608 render_frame =
609 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
610 web_frame = parent_web_frame->createLocalChild(
611 replicated_state.scope, WebString::fromUTF8(replicated_state.name),
612 replicated_state.sandbox_flags, render_frame,
613 previous_sibling_web_frame);
614 } else {
615 RenderFrameProxy* proxy =
616 RenderFrameProxy::FromRoutingID(proxy_routing_id);
617 CHECK(proxy);
618 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
619 web_frame =
620 blink::WebLocalFrame::create(replicated_state.scope, render_frame);
621 render_frame->proxy_routing_id_ = proxy_routing_id;
622 web_frame->initializeToReplaceRemoteFrame(
623 proxy->web_frame(), WebString::fromUTF8(replicated_state.name),
624 replicated_state.sandbox_flags);
626 render_frame->SetWebFrame(web_frame);
627 CHECK_IMPLIES(parent_routing_id == MSG_ROUTING_NONE, !web_frame->parent());
629 if (widget_params.routing_id != MSG_ROUTING_NONE) {
630 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
631 render_frame->render_widget_ = RenderWidget::CreateForFrame(
632 widget_params.routing_id, widget_params.surface_id,
633 widget_params.hidden, render_frame->render_view_->screen_info(),
634 compositor_deps, web_frame);
635 // TODO(kenrb): Observing shouldn't be necessary when we sort out
636 // WasShown and WasHidden, separating page-level visibility from
637 // frame-level visibility.
638 render_frame->render_widget_->RegisterRenderFrame(render_frame);
641 render_frame->Initialize();
644 // static
645 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
646 return RenderFrameImpl::FromWebFrame(web_frame);
649 // static
650 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
651 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
652 if (iter != g_frame_map.Get().end())
653 return iter->second;
654 return NULL;
657 // static
658 void RenderFrameImpl::InstallCreateHook(
659 CreateRenderFrameImplFunction create_render_frame_impl) {
660 CHECK(!g_create_render_frame_impl);
661 g_create_render_frame_impl = create_render_frame_impl;
664 // static
665 blink::WebFrame* RenderFrameImpl::ResolveOpener(int opener_frame_routing_id,
666 int* opener_view_routing_id) {
667 if (opener_view_routing_id)
668 *opener_view_routing_id = MSG_ROUTING_NONE;
670 if (opener_frame_routing_id == MSG_ROUTING_NONE)
671 return nullptr;
673 // Opener routing ID could refer to either a RenderFrameProxy or a
674 // RenderFrame, so need to check both.
675 RenderFrameProxy* opener_proxy =
676 RenderFrameProxy::FromRoutingID(opener_frame_routing_id);
677 if (opener_proxy) {
678 if (opener_view_routing_id)
679 *opener_view_routing_id = opener_proxy->render_view()->GetRoutingID();
681 // TODO(nasko,alexmos): This check won't be needed once swappedout:// is
682 // gone.
683 if (opener_proxy->IsMainFrameDetachedFromTree()) {
684 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
685 return opener_proxy->render_view()->webview()->mainFrame();
686 } else {
687 return opener_proxy->web_frame();
691 RenderFrameImpl* opener_frame =
692 RenderFrameImpl::FromRoutingID(opener_frame_routing_id);
693 if (opener_frame) {
694 if (opener_view_routing_id)
695 *opener_view_routing_id = opener_frame->render_view()->GetRoutingID();
696 return opener_frame->GetWebFrame();
699 return nullptr;
702 // RenderFrameImpl ----------------------------------------------------------
703 RenderFrameImpl::RenderFrameImpl(const CreateParams& params)
704 : frame_(NULL),
705 is_subframe_(false),
706 is_local_root_(false),
707 render_view_(params.render_view->AsWeakPtr()),
708 routing_id_(params.routing_id),
709 is_swapped_out_(false),
710 render_frame_proxy_(NULL),
711 is_detaching_(false),
712 proxy_routing_id_(MSG_ROUTING_NONE),
713 #if defined(ENABLE_PLUGINS)
714 plugin_power_saver_helper_(NULL),
715 #endif
716 cookie_jar_(this),
717 selection_text_offset_(0),
718 selection_range_(gfx::Range::InvalidRange()),
719 handling_select_range_(false),
720 notification_permission_dispatcher_(NULL),
721 web_user_media_client_(NULL),
722 media_permission_dispatcher_(NULL),
723 midi_dispatcher_(NULL),
724 #if defined(OS_ANDROID)
725 media_player_manager_(NULL),
726 #endif
727 #if defined(ENABLE_BROWSER_CDMS)
728 cdm_manager_(NULL),
729 #endif
730 #if defined(VIDEO_HOLE)
731 contains_media_player_(false),
732 #endif
733 has_played_media_(false),
734 devtools_agent_(nullptr),
735 geolocation_dispatcher_(NULL),
736 push_messaging_dispatcher_(NULL),
737 presentation_dispatcher_(NULL),
738 screen_orientation_dispatcher_(NULL),
739 manifest_manager_(NULL),
740 accessibility_mode_(AccessibilityModeOff),
741 renderer_accessibility_(NULL),
742 weak_factory_(this) {
743 std::pair<RoutingIDFrameMap::iterator, bool> result =
744 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
745 CHECK(result.second) << "Inserting a duplicate item.";
747 RenderThread::Get()->AddRoute(routing_id_, this);
749 render_view_->RegisterRenderFrame(this);
751 // Everything below subclasses RenderFrameObserver and is automatically
752 // deleted when the RenderFrame gets deleted.
753 #if defined(OS_ANDROID)
754 new GinJavaBridgeDispatcher(this);
755 #endif
757 #if defined(ENABLE_PLUGINS)
758 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
759 #endif
761 manifest_manager_ = new ManifestManager(this);
763 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_));
766 RenderFrameImpl::~RenderFrameImpl() {
767 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
768 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
770 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
772 #if defined(VIDEO_HOLE)
773 if (contains_media_player_)
774 render_view_->UnregisterVideoHoleFrame(this);
775 #endif
777 if (!is_subframe_) {
778 // When using swapped out frames, RenderFrameProxy is owned by
779 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
780 // along with this object.
781 if (render_frame_proxy_ &&
782 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
783 // The following method calls back into this object and clears
784 // |render_frame_proxy_|.
785 render_frame_proxy_->frameDetached(
786 blink::WebRemoteFrameClient::DetachType::Remove);
789 // Ensure the RenderView doesn't point to this object, once it is destroyed.
790 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
791 // is |this|, once the object is no longer leaked.
792 // See https://crbug.com/464764.
793 render_view_->main_render_frame_ = nullptr;
796 render_view_->UnregisterRenderFrame(this);
797 g_routing_id_frame_map.Get().erase(routing_id_);
798 RenderThread::Get()->RemoveRoute(routing_id_);
801 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
802 DCHECK(!frame_);
804 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
805 std::make_pair(web_frame, this));
806 CHECK(result.second) << "Inserting a duplicate item.";
808 frame_ = web_frame;
811 void RenderFrameImpl::Initialize() {
812 is_subframe_ = !!frame_->parent();
813 is_local_root_ = !frame_->parent() || frame_->parent()->isWebRemoteFrame();
815 #if defined(ENABLE_PLUGINS)
816 new PepperBrowserConnection(this);
817 #endif
818 new SharedWorkerRepository(this);
820 if (is_local_root_ && !render_frame_proxy_) {
821 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
822 // when |this| is deleted.
823 devtools_agent_ = new DevToolsAgent(this);
826 RegisterMojoServices();
828 // We delay calling this until we have the WebFrame so that any observer or
829 // embedder can call GetWebFrame on any RenderFrame.
830 GetContentClient()->renderer()->RenderFrameCreated(this);
833 RenderWidget* RenderFrameImpl::GetRenderWidget() {
834 return render_view_.get();
837 #if defined(ENABLE_PLUGINS)
838 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
839 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
840 DidCreatePepperPlugin(host));
841 if (host->GetPluginName() == kFlashPluginName) {
842 RenderThread::Get()->RecordAction(
843 base::UserMetricsAction("FrameLoadWithFlash"));
847 void RenderFrameImpl::PepperDidChangeCursor(
848 PepperPluginInstanceImpl* instance,
849 const blink::WebCursorInfo& cursor) {
850 // Update the cursor appearance immediately if the requesting plugin is the
851 // one which receives the last mouse event. Otherwise, the new cursor won't be
852 // picked up until the plugin gets the next input event. That is bad if, e.g.,
853 // the plugin would like to set an invisible cursor when there isn't any user
854 // input for a while.
855 if (instance == render_view_->pepper_last_mouse_event_target())
856 GetRenderWidget()->didChangeCursor(cursor);
859 void RenderFrameImpl::PepperDidReceiveMouseEvent(
860 PepperPluginInstanceImpl* instance) {
861 render_view_->set_pepper_last_mouse_event_target(instance);
864 void RenderFrameImpl::PepperTextInputTypeChanged(
865 PepperPluginInstanceImpl* instance) {
866 if (instance != render_view_->focused_pepper_plugin())
867 return;
869 GetRenderWidget()->UpdateTextInputState(
870 RenderWidget::NO_SHOW_IME, RenderWidget::FROM_NON_IME);
872 FocusedNodeChangedForAccessibility(WebNode());
875 void RenderFrameImpl::PepperCaretPositionChanged(
876 PepperPluginInstanceImpl* instance) {
877 if (instance != render_view_->focused_pepper_plugin())
878 return;
879 GetRenderWidget()->UpdateSelectionBounds();
882 void RenderFrameImpl::PepperCancelComposition(
883 PepperPluginInstanceImpl* instance) {
884 if (instance != render_view_->focused_pepper_plugin())
885 return;
886 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
887 #if defined(OS_MACOSX) || defined(USE_AURA)
888 GetRenderWidget()->UpdateCompositionInfo(true);
889 #endif
892 void RenderFrameImpl::PepperSelectionChanged(
893 PepperPluginInstanceImpl* instance) {
894 if (instance != render_view_->focused_pepper_plugin())
895 return;
896 SyncSelectionIfRequired();
899 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
900 PepperPluginInstanceImpl* plugin) {
901 GURL active_url;
902 if (render_view_->webview() && render_view_->webview()->mainFrame())
903 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
904 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
905 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
906 plugin, active_url, GetRenderWidget()->screenInfo());
907 widget->show(blink::WebNavigationPolicyIgnore);
908 return widget;
911 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
912 if (!render_view_->focused_pepper_plugin())
913 return false;
914 return render_view_->focused_pepper_plugin()->
915 IsPluginAcceptingCompositionEvents();
918 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
919 base::ProcessId plugin_pid) {
920 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
921 // routing_id_ as a result.
922 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
925 void RenderFrameImpl::SimulateImeSetComposition(
926 const base::string16& text,
927 const std::vector<blink::WebCompositionUnderline>& underlines,
928 int selection_start,
929 int selection_end) {
930 render_view_->OnImeSetComposition(
931 text, underlines, selection_start, selection_end);
934 void RenderFrameImpl::SimulateImeConfirmComposition(
935 const base::string16& text,
936 const gfx::Range& replacement_range) {
937 render_view_->OnImeConfirmComposition(text, replacement_range, false);
940 void RenderFrameImpl::OnImeSetComposition(
941 const base::string16& text,
942 const std::vector<blink::WebCompositionUnderline>& underlines,
943 int selection_start,
944 int selection_end) {
945 // When a PPAPI plugin has focus, we bypass WebKit.
946 if (!IsPepperAcceptingCompositionEvents()) {
947 pepper_composition_text_ = text;
948 } else {
949 // TODO(kinaba) currently all composition events are sent directly to
950 // plugins. Use DOM event mechanism after WebKit is made aware about
951 // plugins that support composition.
952 // The code below mimics the behavior of WebCore::Editor::setComposition.
954 // Empty -> nonempty: composition started.
955 if (pepper_composition_text_.empty() && !text.empty()) {
956 render_view_->focused_pepper_plugin()->HandleCompositionStart(
957 base::string16());
959 // Nonempty -> empty: composition canceled.
960 if (!pepper_composition_text_.empty() && text.empty()) {
961 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
962 base::string16());
964 pepper_composition_text_ = text;
965 // Nonempty: composition is ongoing.
966 if (!pepper_composition_text_.empty()) {
967 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
968 pepper_composition_text_, underlines, selection_start,
969 selection_end);
974 void RenderFrameImpl::OnImeConfirmComposition(
975 const base::string16& text,
976 const gfx::Range& replacement_range,
977 bool keep_selection) {
978 // When a PPAPI plugin has focus, we bypass WebKit.
979 // Here, text.empty() has a special meaning. It means to commit the last
980 // update of composition text (see
981 // RenderWidgetHost::ImeConfirmComposition()).
982 const base::string16& last_text = text.empty() ? pepper_composition_text_
983 : text;
985 // last_text is empty only when both text and pepper_composition_text_ is.
986 // Ignore it.
987 if (last_text.empty())
988 return;
990 if (!IsPepperAcceptingCompositionEvents()) {
991 base::i18n::UTF16CharIterator iterator(&last_text);
992 int32 i = 0;
993 while (iterator.Advance()) {
994 blink::WebKeyboardEvent char_event;
995 char_event.type = blink::WebInputEvent::Char;
996 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
997 char_event.modifiers = 0;
998 char_event.windowsKeyCode = last_text[i];
999 char_event.nativeKeyCode = last_text[i];
1001 const int32 char_start = i;
1002 for (; i < iterator.array_pos(); ++i) {
1003 char_event.text[i - char_start] = last_text[i];
1004 char_event.unmodifiedText[i - char_start] = last_text[i];
1007 if (GetRenderWidget()->webwidget())
1008 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
1010 } else {
1011 // Mimics the order of events sent by WebKit.
1012 // See WebCore::Editor::setComposition() for the corresponding code.
1013 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
1014 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
1016 pepper_composition_text_.clear();
1018 #endif // defined(ENABLE_PLUGINS)
1020 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
1021 if (!web_user_media_client_)
1022 InitializeUserMediaClient();
1023 return web_user_media_client_ ?
1024 web_user_media_client_->media_stream_dispatcher() : NULL;
1027 bool RenderFrameImpl::Send(IPC::Message* message) {
1028 if (is_detaching_) {
1029 delete message;
1030 return false;
1032 if (is_swapped_out_) {
1033 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
1034 delete message;
1035 return false;
1039 return RenderThread::Get()->Send(message);
1042 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1043 void RenderFrameImpl::DidHideExternalPopupMenu() {
1044 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
1045 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
1046 external_popup_menu_.reset();
1048 #endif
1050 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
1051 // We may get here while detaching, when the WebFrame has been deleted. Do
1052 // not process any messages in this state.
1053 if (!frame_)
1054 return false;
1056 // TODO(kenrb): document() should not be null, but as a transitional step
1057 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1058 // to this method. This happens for a top-level remote frame, where a
1059 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1060 // around and is still able to receive messages.
1061 if (!frame_->document().isNull())
1062 GetContentClient()->SetActiveURL(frame_->document().url());
1064 base::ObserverListBase<RenderFrameObserver>::Iterator it(&observers_);
1065 RenderFrameObserver* observer;
1066 while ((observer = it.GetNext()) != NULL) {
1067 if (observer->OnMessageReceived(msg))
1068 return true;
1071 bool handled = true;
1072 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
1073 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
1074 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
1075 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
1076 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
1077 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
1078 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
1079 OnCustomContextMenuAction)
1080 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
1081 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
1082 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
1083 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
1084 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
1085 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
1086 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
1087 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
1088 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1089 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset,
1090 OnAdjustSelectionByCharacterOffset)
1091 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1092 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
1093 OnMoveRangeSelectionExtent)
1094 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1095 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1096 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
1097 OnExtendSelectionAndDelete)
1098 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
1099 OnSetCompositionFromExistingText)
1100 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
1101 OnExecuteNoValueEditCommand)
1102 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
1103 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole, OnAddMessageToConsole)
1104 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
1105 OnJavaScriptExecuteRequest)
1106 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
1107 OnJavaScriptExecuteRequestForTests)
1108 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld,
1109 OnJavaScriptExecuteRequestInIsolatedWorld)
1110 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
1111 OnVisualStateRequest)
1112 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
1113 OnSetEditableSelectionOffsets)
1114 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
1115 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
1116 OnTextSurroundingSelectionRequest)
1117 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
1118 OnSetAccessibilityMode)
1119 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree,
1120 OnSnapshotAccessibilityTree)
1121 IPC_MESSAGE_HANDLER(FrameMsg_UpdateOpener, OnUpdateOpener)
1122 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
1123 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags, OnDidUpdateSandboxFlags)
1124 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings,
1125 OnTextTrackSettingsChanged)
1126 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent, OnPostMessageEvent)
1127 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation, OnFailedNavigation)
1128 #if defined(OS_ANDROID)
1129 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1130 #elif defined(OS_MACOSX)
1131 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1132 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1133 #endif
1134 IPC_END_MESSAGE_MAP()
1136 return handled;
1139 void RenderFrameImpl::OnNavigate(
1140 const CommonNavigationParams& common_params,
1141 const StartNavigationParams& start_params,
1142 const RequestNavigationParams& request_params) {
1143 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1144 switches::kEnableBrowserSideNavigation));
1145 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_,
1146 "url", common_params.url.possibly_invalid_spec());
1147 NavigateInternal(common_params, start_params, request_params,
1148 scoped_ptr<StreamOverrideParameters>());
1151 void RenderFrameImpl::NavigateToSwappedOutURL() {
1152 // We use loadRequest instead of loadHTMLString because the former commits
1153 // synchronously. Otherwise a new navigation can interrupt the navigation
1154 // to kSwappedOutURL. If that happens to be to the page we had been
1155 // showing, then WebKit will never send a commit and we'll be left spinning.
1156 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1157 // the navigation to swappedout:// is not announced to the browser side.
1158 is_swapped_out_ = true;
1159 GURL swappedOutURL(kSwappedOutURL);
1160 WebURLRequest request(swappedOutURL);
1161 frame_->loadRequest(request);
1164 void RenderFrameImpl::BindServiceRegistry(
1165 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1166 mojo::ServiceProviderPtr exposed_services) {
1167 service_registry_.Bind(services.Pass());
1168 service_registry_.BindRemoteServiceProvider(exposed_services.Pass());
1171 ManifestManager* RenderFrameImpl::manifest_manager() {
1172 return manifest_manager_;
1175 void RenderFrameImpl::SetPendingNavigationParams(
1176 scoped_ptr<NavigationParams> navigation_params) {
1177 pending_navigation_params_ = navigation_params.Pass();
1180 void RenderFrameImpl::OnBeforeUnload() {
1181 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1182 "id", routing_id_);
1183 // TODO(creis): Right now, this is only called on the main frame. Make the
1184 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1185 // it.
1186 CHECK(!frame_->parent());
1188 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1189 bool proceed = frame_->dispatchBeforeUnloadEvent();
1190 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1191 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1192 before_unload_start_time,
1193 before_unload_end_time));
1196 void RenderFrameImpl::OnSwapOut(
1197 int proxy_routing_id,
1198 bool is_loading,
1199 const FrameReplicationState& replicated_frame_state) {
1200 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1201 RenderFrameProxy* proxy = NULL;
1202 bool swapped_out_forbidden =
1203 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1204 bool is_main_frame = !frame_->parent();
1206 // This codepath should only be hit for subframes when in --site-per-process.
1207 CHECK_IMPLIES(!is_main_frame,
1208 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1210 // Only run unload if we're not swapped out yet, but send the ack either way.
1211 if (!is_swapped_out_) {
1212 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1213 // a different process. This involves running the unload handler and
1214 // clearing the page. We also allow this process to exit if there are no
1215 // other active RenderFrames in it.
1217 // Send an UpdateState message before we get swapped out.
1218 render_view_->SendUpdateState();
1220 // If we need a proxy to replace this, create it now so its routing id is
1221 // registered for receiving IPC messages.
1222 if (proxy_routing_id != MSG_ROUTING_NONE) {
1223 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
1224 this, proxy_routing_id, replicated_frame_state.scope);
1227 // Synchronously run the unload handler before sending the ACK.
1228 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1229 // unload on subframes as well.
1230 if (is_main_frame)
1231 frame_->dispatchUnloadEvent();
1233 // Swap out and stop sending any IPC messages that are not ACKs.
1234 if (is_main_frame)
1235 render_view_->SetSwappedOut(true);
1236 is_swapped_out_ = true;
1238 // Set the proxy here, since OnStop() below could cause an onload event
1239 // handler to execute, which could trigger code such as
1240 // willCheckAndDispatchMessageEvent() that needs the proxy.
1241 if (proxy)
1242 set_render_frame_proxy(proxy);
1244 // Now that we're swapped out and filtering IPC messages, stop loading to
1245 // ensure that no other in-progress navigation continues. We do this here
1246 // to avoid sending a DidStopLoading message to the browser process.
1247 // TODO(creis): Should we be stopping all frames here and using
1248 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1249 // frame?
1250 if (!swapped_out_forbidden)
1251 OnStop();
1253 // Transfer settings such as initial drawing parameters to the remote frame,
1254 // if one is created, that will replace this frame.
1255 if (!is_main_frame && proxy)
1256 proxy->web_frame()->initializeFromFrame(frame_);
1258 // Replace the page with a blank dummy URL. The unload handler will not be
1259 // run a second time, thanks to a check in FrameLoader::stopLoading.
1260 // TODO(creis): Need to add a better way to do this that avoids running the
1261 // beforeunload handler. For now, we just run it a second time silently.
1262 if (!swapped_out_forbidden)
1263 NavigateToSwappedOutURL();
1265 // Let WebKit know that this view is hidden so it can drop resources and
1266 // stop compositing.
1267 // TODO(creis): Support this for subframes as well.
1268 if (is_main_frame) {
1269 render_view_->webview()->setVisibilityState(
1270 blink::WebPageVisibilityStateHidden, false);
1274 // It is now safe to show modal dialogs again.
1275 // TODO(creis): Deal with modal dialogs from subframes.
1276 if (is_main_frame)
1277 render_view_->suppress_dialogs_until_swap_out_ = false;
1279 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1281 RenderViewImpl* render_view = render_view_.get();
1283 // Now that all of the cleanup is complete and the browser side is notified,
1284 // start using the RenderFrameProxy, if one is created.
1285 if (proxy && swapped_out_forbidden) {
1286 frame_->swap(proxy->web_frame());
1288 if (is_loading)
1289 proxy->OnDidStartLoading();
1292 // In --site-per-process, initialize the WebRemoteFrame with the replication
1293 // state passed by the process that is now rendering the frame.
1294 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1295 // in that case we leave the LocalFrame as the main frame visible to Blink
1296 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1297 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1298 // When we do an unconditional swap for all frames, we can remove
1299 // !is_main_frame below.
1300 if (proxy && swapped_out_forbidden)
1301 proxy->SetReplicatedState(replicated_frame_state);
1303 // Safe to exit if no one else is using the process.
1304 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1305 // the process based on the lifetime of this RenderFrameImpl object.
1306 if (is_main_frame) {
1307 render_view->WasSwappedOut();
1311 void RenderFrameImpl::OnContextMenuClosed(
1312 const CustomContextMenuContext& custom_context) {
1313 if (custom_context.request_id) {
1314 // External request, should be in our map.
1315 ContextMenuClient* client =
1316 pending_context_menus_.Lookup(custom_context.request_id);
1317 if (client) {
1318 client->OnMenuClosed(custom_context.request_id);
1319 pending_context_menus_.Remove(custom_context.request_id);
1321 } else {
1322 if (custom_context.link_followed.is_valid())
1323 frame_->sendPings(context_menu_node_, custom_context.link_followed);
1324 // Internal request, forward to WebKit.
1325 context_menu_node_.reset();
1329 void RenderFrameImpl::OnCustomContextMenuAction(
1330 const CustomContextMenuContext& custom_context,
1331 unsigned action) {
1332 if (custom_context.request_id) {
1333 // External context menu request, look in our map.
1334 ContextMenuClient* client =
1335 pending_context_menus_.Lookup(custom_context.request_id);
1336 if (client)
1337 client->OnMenuAction(custom_context.request_id, action);
1338 } else {
1339 // Internal request, forward to WebKit.
1340 render_view_->webview()->performCustomContextMenuAction(action);
1344 void RenderFrameImpl::OnUndo() {
1345 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1348 void RenderFrameImpl::OnRedo() {
1349 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1352 void RenderFrameImpl::OnCut() {
1353 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1354 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1357 void RenderFrameImpl::OnCopy() {
1358 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1359 WebNode current_node = context_menu_node_.isNull() ?
1360 GetFocusedElement() : context_menu_node_;
1361 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1364 void RenderFrameImpl::OnPaste() {
1365 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1366 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1369 void RenderFrameImpl::OnPasteAndMatchStyle() {
1370 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1371 frame_->executeCommand(
1372 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1375 #if defined(OS_MACOSX)
1376 void RenderFrameImpl::OnCopyToFindPboard() {
1377 // Since the find pasteboard supports only plain text, this can be simpler
1378 // than the |OnCopy()| case.
1379 if (frame_->hasSelection()) {
1380 base::string16 selection = frame_->selectionAsText();
1381 RenderThread::Get()->Send(
1382 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1385 #endif
1387 void RenderFrameImpl::OnDelete() {
1388 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1391 void RenderFrameImpl::OnSelectAll() {
1392 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1393 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1396 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1397 const gfx::Point& extent) {
1398 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1399 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1401 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1402 frame_->selectRange(base, extent);
1405 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust,
1406 int end_adjust) {
1407 size_t start, length;
1408 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1409 &start, &length)) {
1410 return;
1413 // Sanity checks to disallow empty and out of range selections.
1414 if (start_adjust - end_adjust > static_cast<int>(length)
1415 || static_cast<int>(start) + start_adjust < 0) {
1416 return;
1419 // A negative adjust amount moves the selection towards the beginning of
1420 // the document, a positive amount moves the selection towards the end of
1421 // the document.
1422 start += start_adjust;
1423 length += end_adjust - start_adjust;
1425 frame_->selectRange(WebRange::fromDocumentRange(frame_, start, length));
1428 void RenderFrameImpl::OnUnselect() {
1429 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1430 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1433 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1434 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1435 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1436 GetRenderWidget()->routing_id()));
1438 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1439 frame_->moveRangeSelectionExtent(point);
1442 void RenderFrameImpl::OnReplace(const base::string16& text) {
1443 if (!frame_->hasSelection())
1444 frame_->selectWordAroundCaret();
1446 frame_->replaceSelection(text);
1449 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1450 if (!frame_->hasSelection())
1451 return;
1453 frame_->replaceMisspelledRange(text);
1456 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1457 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1460 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level,
1461 const std::string& message) {
1462 AddMessageToConsole(level, message);
1465 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1466 const base::string16& jscript,
1467 int id,
1468 bool notify_result) {
1469 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1470 TRACE_EVENT_SCOPE_THREAD);
1472 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1473 v8::Local<v8::Value> result =
1474 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1476 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1479 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1480 const base::string16& jscript,
1481 int id,
1482 bool notify_result,
1483 bool has_user_gesture) {
1484 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1485 TRACE_EVENT_SCOPE_THREAD);
1487 // A bunch of tests expect to run code in the context of a user gesture, which
1488 // can grant additional privileges (e.g. the ability to create popups).
1489 scoped_ptr<blink::WebScopedUserGesture> gesture(
1490 has_user_gesture ? new blink::WebScopedUserGesture : nullptr);
1491 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1492 v8::Local<v8::Value> result =
1493 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1495 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1498 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1499 const base::string16& jscript,
1500 int id,
1501 bool notify_result,
1502 int world_id) {
1503 TRACE_EVENT_INSTANT0("test_tracing",
1504 "OnJavaScriptExecuteRequestInIsolatedWorld",
1505 TRACE_EVENT_SCOPE_THREAD);
1507 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
1508 world_id > ISOLATED_WORLD_ID_MAX) {
1509 // Return if the world_id is not valid. world_id is passed as a plain int
1510 // over IPC and needs to be verified here, in the IPC endpoint.
1511 NOTREACHED();
1512 return;
1515 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1516 WebScriptSource script = WebScriptSource(jscript);
1517 JavaScriptIsolatedWorldRequest* request = new JavaScriptIsolatedWorldRequest(
1518 id, notify_result, routing_id_, weak_factory_.GetWeakPtr());
1519 frame_->requestExecuteScriptInIsolatedWorld(world_id, &script, 1, 0, false,
1520 request);
1523 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1524 int id,
1525 bool notify_result,
1526 int routing_id,
1527 base::WeakPtr<RenderFrameImpl> render_frame_impl)
1528 : id_(id),
1529 notify_result_(notify_result),
1530 routing_id_(routing_id),
1531 render_frame_impl_(render_frame_impl) {
1534 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1535 ~JavaScriptIsolatedWorldRequest() {
1538 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1539 const blink::WebVector<v8::Local<v8::Value>>& result) {
1540 if (!render_frame_impl_.get()) {
1541 return;
1544 if (notify_result_) {
1545 base::ListValue list;
1546 if (!result.isEmpty()) {
1547 // It's safe to always use the main world context when converting
1548 // here. V8ValueConverterImpl shouldn't actually care about the
1549 // context scope, and it switches to v8::Object's creation context
1550 // when encountered. (from extensions/renderer/script_injection.cc)
1551 v8::Local<v8::Context> context =
1552 render_frame_impl_.get()->frame_->mainWorldScriptContext();
1553 v8::Context::Scope context_scope(context);
1554 V8ValueConverterImpl converter;
1555 converter.SetDateAllowed(true);
1556 converter.SetRegExpAllowed(true);
1557 for (const auto& value : result) {
1558 scoped_ptr<base::Value> result_value(
1559 converter.FromV8Value(value, context));
1560 list.Append(result_value ? result_value.Pass()
1561 : base::Value::CreateNullValue());
1563 } else {
1564 list.Set(0, base::Value::CreateNullValue());
1566 render_frame_impl_.get()->Send(
1567 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id_, list));
1570 delete this;
1573 void RenderFrameImpl::HandleJavascriptExecutionResult(
1574 const base::string16& jscript,
1575 int id,
1576 bool notify_result,
1577 v8::Local<v8::Value> result) {
1578 if (notify_result) {
1579 base::ListValue list;
1580 if (!result.IsEmpty()) {
1581 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1582 v8::Context::Scope context_scope(context);
1583 V8ValueConverterImpl converter;
1584 converter.SetDateAllowed(true);
1585 converter.SetRegExpAllowed(true);
1586 scoped_ptr<base::Value> result_value(
1587 converter.FromV8Value(result, context));
1588 list.Set(0, result_value ? result_value.Pass()
1589 : base::Value::CreateNullValue());
1590 } else {
1591 list.Set(0, base::Value::CreateNullValue());
1593 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1597 void RenderFrameImpl::OnVisualStateRequest(uint64 id) {
1598 GetRenderWidget()->QueueMessage(
1599 new FrameHostMsg_VisualStateResponse(routing_id_, id),
1600 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1603 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1604 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1605 if (!GetRenderWidget()->ShouldHandleImeEvent())
1606 return;
1607 ImeEventGuard guard(GetRenderWidget());
1608 frame_->setEditableSelectionOffsets(start, end);
1611 void RenderFrameImpl::OnSetCompositionFromExistingText(
1612 int start, int end,
1613 const std::vector<blink::WebCompositionUnderline>& underlines) {
1614 if (!GetRenderWidget()->ShouldHandleImeEvent())
1615 return;
1616 ImeEventGuard guard(GetRenderWidget());
1617 frame_->setCompositionFromExistingText(start, end, underlines);
1620 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
1621 frame_->executeCommand(WebString::fromUTF8(name), GetFocusedElement());
1624 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1625 if (!GetRenderWidget()->ShouldHandleImeEvent())
1626 return;
1628 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1630 ImeEventGuard guard(GetRenderWidget());
1631 blink::WebScopedUserGesture gesture_indicator;
1632 frame_->extendSelectionAndDelete(before, after);
1635 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1636 if (accessibility_mode_ == new_mode)
1637 return;
1638 accessibility_mode_ = new_mode;
1639 if (renderer_accessibility_) {
1640 // Note: this isn't called automatically by the destructor because
1641 // there'd be no point in calling it in frame teardown, only if there's
1642 // an accessibility mode change but the frame is persisting.
1643 renderer_accessibility_->DisableAccessibility();
1645 delete renderer_accessibility_;
1646 renderer_accessibility_ = NULL;
1648 if (accessibility_mode_ == AccessibilityModeOff)
1649 return;
1651 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1652 renderer_accessibility_ = new RendererAccessibility(this);
1655 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) {
1656 ui::AXTreeUpdate<AXContentNodeData> response;
1657 RendererAccessibility::SnapshotAccessibilityTree(this, &response);
1658 Send(new AccessibilityHostMsg_SnapshotResponse(
1659 routing_id_, callback_id, response));
1662 void RenderFrameImpl::OnUpdateOpener(int opener_routing_id) {
1663 WebFrame* opener = ResolveOpener(opener_routing_id, nullptr);
1664 frame_->setOpener(opener);
1667 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags) {
1668 frame_->setFrameOwnerSandboxFlags(flags);
1671 void RenderFrameImpl::OnTextTrackSettingsChanged(
1672 const FrameMsg_TextTrackSettings_Params& params) {
1673 DCHECK(!frame_->parent());
1674 if (!render_view_->webview())
1675 return;
1677 if (params.text_tracks_enabled) {
1678 render_view_->webview()->settings()->setTextTrackKindUserPreference(
1679 WebSettings::TextTrackKindUserPreference::Captions);
1680 } else {
1681 render_view_->webview()->settings()->setTextTrackKindUserPreference(
1682 WebSettings::TextTrackKindUserPreference::Default);
1684 render_view_->webview()->settings()->setTextTrackBackgroundColor(
1685 WebString::fromUTF8(params.text_track_background_color));
1686 render_view_->webview()->settings()->setTextTrackFontFamily(
1687 WebString::fromUTF8(params.text_track_font_family));
1688 render_view_->webview()->settings()->setTextTrackFontStyle(
1689 WebString::fromUTF8(params.text_track_font_style));
1690 render_view_->webview()->settings()->setTextTrackFontVariant(
1691 WebString::fromUTF8(params.text_track_font_variant));
1692 render_view_->webview()->settings()->setTextTrackTextColor(
1693 WebString::fromUTF8(params.text_track_text_color));
1694 render_view_->webview()->settings()->setTextTrackTextShadow(
1695 WebString::fromUTF8(params.text_track_text_shadow));
1696 render_view_->webview()->settings()->setTextTrackTextSize(
1697 WebString::fromUTF8(params.text_track_text_size));
1700 void RenderFrameImpl::OnPostMessageEvent(
1701 const FrameMsg_PostMessage_Params& params) {
1702 // Find the source frame if it exists.
1703 WebFrame* source_frame = NULL;
1704 if (params.source_routing_id != MSG_ROUTING_NONE) {
1705 RenderFrameProxy* source_proxy =
1706 RenderFrameProxy::FromRoutingID(params.source_routing_id);
1707 if (source_proxy) {
1708 // Currently, navigating a top-level frame cross-process does not swap
1709 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1710 // WebRemoteFrame will not have an associated blink::Frame. If this is
1711 // the case for |source_proxy|, use the corresponding (swapped-out)
1712 // WebLocalFrame instead, so that event.source for this message can be
1713 // set and used properly.
1714 if (source_proxy->IsMainFrameDetachedFromTree())
1715 source_frame = source_proxy->render_view()->webview()->mainFrame();
1716 else
1717 source_frame = source_proxy->web_frame();
1721 // If the message contained MessagePorts, create the corresponding endpoints.
1722 blink::WebMessagePortChannelArray channels =
1723 WebMessagePortChannelImpl::CreatePorts(
1724 params.message_ports, params.new_routing_ids,
1725 base::ThreadTaskRunnerHandle::Get().get());
1727 WebSerializedScriptValue serialized_script_value;
1728 if (params.is_data_raw_string) {
1729 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1730 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1731 v8::Context::Scope context_scope(context);
1732 V8ValueConverterImpl converter;
1733 converter.SetDateAllowed(true);
1734 converter.SetRegExpAllowed(true);
1735 scoped_ptr<base::Value> value(new base::StringValue(params.data));
1736 v8::Local<v8::Value> result_value = converter.ToV8Value(value.get(),
1737 context);
1738 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
1739 } else {
1740 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
1743 // Create an event with the message. The next-to-last parameter to
1744 // initMessageEvent is the last event ID, which is not used with postMessage.
1745 WebDOMEvent event = frame_->document().createEvent("MessageEvent");
1746 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
1747 msg_event.initMessageEvent("message",
1748 // |canBubble| and |cancellable| are always false
1749 false, false,
1750 serialized_script_value,
1751 params.source_origin, source_frame,
1752 frame_->document(), "", channels);
1754 // We must pass in the target_origin to do the security check on this side,
1755 // since it may have changed since the original postMessage call was made.
1756 WebSecurityOrigin target_origin;
1757 if (!params.target_origin.empty()) {
1758 target_origin =
1759 WebSecurityOrigin::createFromString(WebString(params.target_origin));
1761 frame_->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
1764 #if defined(OS_ANDROID)
1765 void RenderFrameImpl::OnSelectPopupMenuItems(
1766 bool canceled,
1767 const std::vector<int>& selected_indices) {
1768 // It is possible to receive more than one of these calls if the user presses
1769 // a select faster than it takes for the show-select-popup IPC message to make
1770 // it to the browser UI thread. Ignore the extra-messages.
1771 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1772 if (!external_popup_menu_)
1773 return;
1775 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1776 external_popup_menu_.reset();
1778 #endif
1780 #if defined(OS_MACOSX)
1781 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1782 if (external_popup_menu_ == NULL)
1783 return;
1784 external_popup_menu_->DidSelectItem(selected_index);
1785 external_popup_menu_.reset();
1787 #endif
1789 void RenderFrameImpl::OnReload(bool ignore_cache) {
1790 frame_->reload(ignore_cache);
1793 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1794 blink::WebSurroundingText surroundingText;
1795 surroundingText.initialize(frame_->selectionRange(), max_length);
1797 if (surroundingText.isNull()) {
1798 // |surroundingText| might not be correctly initialized, for example if
1799 // |frame_->selectionRange().isNull()|, in other words, if there was no
1800 // selection.
1801 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1802 routing_id_, base::string16(), 0, 0));
1803 return;
1806 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1807 routing_id_,
1808 surroundingText.textContent(),
1809 surroundingText.startOffsetInTextContent(),
1810 surroundingText.endOffsetInTextContent()));
1813 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1814 const base::string16& message,
1815 const base::string16& default_value,
1816 const GURL& frame_url,
1817 base::string16* result) {
1818 // Don't allow further dialogs if we are waiting to swap out, since the
1819 // PageGroupLoadDeferrer in our stack prevents it.
1820 if (render_view()->suppress_dialogs_until_swap_out_)
1821 return false;
1823 bool success = false;
1824 base::string16 result_temp;
1825 if (!result)
1826 result = &result_temp;
1828 render_view()->SendAndRunNestedMessageLoop(
1829 new FrameHostMsg_RunJavaScriptMessage(
1830 routing_id_, message, default_value, frame_url, type, &success,
1831 result));
1832 return success;
1835 void RenderFrameImpl::LoadNavigationErrorPage(
1836 const WebURLRequest& failed_request,
1837 const WebURLError& error,
1838 bool replace) {
1839 std::string error_html;
1840 GetContentClient()->renderer()->GetNavigationErrorStrings(
1841 render_view(), frame_, failed_request, error, &error_html, NULL);
1843 frame_->loadHTMLString(error_html,
1844 GURL(kUnreachableWebDataURL),
1845 error.unreachableURL,
1846 replace);
1849 void RenderFrameImpl::DidCommitCompositorFrame() {
1850 if (BrowserPluginManager::Get())
1851 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1852 FOR_EACH_OBSERVER(
1853 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1856 RenderView* RenderFrameImpl::GetRenderView() {
1857 return render_view_.get();
1860 int RenderFrameImpl::GetRoutingID() {
1861 return routing_id_;
1864 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1865 DCHECK(frame_);
1866 return frame_;
1869 WebElement RenderFrameImpl::GetFocusedElement() const {
1870 WebDocument doc = frame_->document();
1871 if (!doc.isNull())
1872 return doc.focusedElement();
1874 return WebElement();
1877 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1878 return render_view_->GetWebkitPreferences();
1881 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1882 const ContextMenuParams& params) {
1883 DCHECK(client); // A null client means "internal" when we issue callbacks.
1884 ContextMenuParams our_params(params);
1885 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1886 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1887 return our_params.custom_context.request_id;
1890 void RenderFrameImpl::CancelContextMenu(int request_id) {
1891 DCHECK(pending_context_menus_.Lookup(request_id));
1892 pending_context_menus_.Remove(request_id);
1895 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1896 return context_menu_node_;
1899 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1900 blink::WebFrame* frame,
1901 const WebPluginInfo& info,
1902 const blink::WebPluginParams& params,
1903 scoped_ptr<content::PluginInstanceThrottler> throttler) {
1904 DCHECK_EQ(frame_, frame);
1905 #if defined(ENABLE_PLUGINS)
1906 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1907 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1908 this, GetContentClient()
1909 ->renderer()
1910 ->CreateBrowserPluginDelegate(this, params.mimeType.utf8(),
1911 GURL(params.url))
1912 ->GetWeakPtr());
1915 bool pepper_plugin_was_registered = false;
1916 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1917 this, info, &pepper_plugin_was_registered));
1918 if (pepper_plugin_was_registered) {
1919 if (pepper_module.get()) {
1920 return new PepperWebPluginImpl(
1921 pepper_module.get(), params, this,
1922 make_scoped_ptr(
1923 static_cast<PluginInstanceThrottlerImpl*>(throttler.release())));
1926 #if defined(OS_CHROMEOS)
1927 LOG(WARNING) << "Pepper module/plugin creation failed.";
1928 #else
1929 if (info.type == WebPluginInfo::PLUGIN_TYPE_NPAPI) {
1930 // TODO(jam): change to take RenderFrame.
1931 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1933 #endif
1934 #endif
1935 return NULL;
1938 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1939 const blink::WebURLRequest& request,
1940 blink::WebNavigationPolicy policy) {
1941 DCHECK(!frame_ || frame_ == frame);
1942 loadURLExternally(frame, request, policy, WebString());
1945 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1946 OnJavaScriptExecuteRequest(javascript, 0, false);
1949 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1950 return &service_registry_;
1953 #if defined(ENABLE_PLUGINS)
1954 void RenderFrameImpl::RegisterPeripheralPlugin(
1955 const GURL& content_origin,
1956 const base::Closure& unthrottle_callback) {
1957 return plugin_power_saver_helper_->RegisterPeripheralPlugin(
1958 content_origin, unthrottle_callback);
1960 #endif // defined(ENABLE_PLUGINS)
1962 bool RenderFrameImpl::IsFTPDirectoryListing() {
1963 WebURLResponseExtraDataImpl* extra_data =
1964 GetExtraDataFromResponse(frame_->dataSource()->response());
1965 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1968 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1969 BrowserPluginManager::Get()->Attach(element_instance_id);
1972 void RenderFrameImpl::DetachGuest(int element_instance_id) {
1973 BrowserPluginManager::Get()->Detach(element_instance_id);
1976 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1977 size_t offset,
1978 const gfx::Range& range) {
1979 // Use the routing id of Render Widget Host.
1980 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1981 selection_text,
1982 offset,
1983 range));
1986 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1987 v8::Isolate* isolate,
1988 v8::Local<v8::Context> context) {
1989 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1990 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1991 return;
1993 v8::HandleScope handle_scope(isolate);
1994 registry->AddBuiltinModule(
1995 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1996 registry->AddBuiltinModule(isolate,
1997 mojo::js::Support::kModuleName,
1998 mojo::js::Support::GetModule(isolate));
1999 registry->AddBuiltinModule(
2000 isolate,
2001 ServiceRegistryJsWrapper::kModuleName,
2002 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
2005 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level,
2006 const std::string& message) {
2007 if (devtools_agent_)
2008 devtools_agent_->AddMessageToConsole(level, message);
2011 // blink::WebFrameClient implementation ----------------------------------------
2013 blink::WebPlugin* RenderFrameImpl::createPlugin(
2014 blink::WebLocalFrame* frame,
2015 const blink::WebPluginParams& params) {
2016 DCHECK_EQ(frame_, frame);
2017 blink::WebPlugin* plugin = NULL;
2018 if (GetContentClient()->renderer()->OverrideCreatePlugin(
2019 this, frame, params, &plugin)) {
2020 return plugin;
2023 if (base::UTF16ToUTF8(base::StringPiece16(params.mimeType)) ==
2024 kBrowserPluginMimeType) {
2025 return BrowserPluginManager::Get()->CreateBrowserPlugin(
2026 this, GetContentClient()
2027 ->renderer()
2028 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType,
2029 GURL(params.url))
2030 ->GetWeakPtr());
2033 #if defined(ENABLE_PLUGINS)
2034 WebPluginInfo info;
2035 std::string mime_type;
2036 bool found = false;
2037 WebString top_origin = frame->top()->securityOrigin().toString();
2038 Send(new FrameHostMsg_GetPluginInfo(routing_id_, params.url, GURL(top_origin),
2039 params.mimeType.utf8(), &found, &info,
2040 &mime_type));
2041 if (!found)
2042 return NULL;
2044 WebPluginParams params_to_use = params;
2045 params_to_use.mimeType = WebString::fromUTF8(mime_type);
2046 return CreatePlugin(frame, info, params_to_use, nullptr /* throttler */);
2047 #else
2048 return NULL;
2049 #endif // defined(ENABLE_PLUGINS)
2052 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
2053 blink::WebLocalFrame* frame,
2054 const blink::WebURL& url,
2055 WebMediaPlayerClient* client,
2056 WebMediaPlayerEncryptedMediaClient* encrypted_client,
2057 WebContentDecryptionModule* initial_cdm) {
2058 #if defined(VIDEO_HOLE)
2059 if (!contains_media_player_) {
2060 render_view_->RegisterVideoHoleFrame(this);
2061 contains_media_player_ = true;
2063 #endif // defined(VIDEO_HOLE)
2065 blink::WebMediaStream web_stream(
2066 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
2067 if (!web_stream.isNull())
2068 return CreateWebMediaPlayerForMediaStream(client);
2070 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2072 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2073 scoped_refptr<media::AudioRendererSink> audio_renderer_sink;
2074 media::WebMediaPlayerParams::Context3DCB context_3d_cb;
2075 #else
2076 scoped_refptr<media::AudioRendererSink> audio_renderer_sink =
2077 render_thread->GetAudioRendererMixerManager()->CreateInput(routing_id_);
2078 media::WebMediaPlayerParams::Context3DCB context_3d_cb =
2079 base::Bind(&GetSharedMainThreadContext3D);
2080 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2082 scoped_refptr<media::MediaLog> media_log(new RenderMediaLog());
2083 media::WebMediaPlayerParams params(
2084 base::Bind(&ContentRendererClient::DeferMediaLoad,
2085 base::Unretained(GetContentClient()->renderer()),
2086 static_cast<RenderFrame*>(this), has_played_media_),
2087 audio_renderer_sink, media_log, render_thread->GetMediaThreadTaskRunner(),
2088 render_thread->GetWorkerTaskRunner(),
2089 render_thread->compositor_task_runner(), context_3d_cb,
2090 GetMediaPermission(), initial_cdm);
2092 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2093 return CreateAndroidWebMediaPlayer(client, encrypted_client, params);
2094 #else
2095 #if defined(ENABLE_MOJO_MEDIA)
2096 scoped_ptr<media::RendererFactory> media_renderer_factory(
2097 new media::MojoRendererFactory(GetMediaServiceFactory()));
2098 #else
2099 scoped_ptr<media::RendererFactory> media_renderer_factory =
2100 GetContentClient()->renderer()->CreateMediaRendererFactory(
2101 this, render_thread->GetGpuFactories(), media_log);
2103 if (!media_renderer_factory.get()) {
2104 media_renderer_factory.reset(new media::DefaultRendererFactory(
2105 media_log, render_thread->GetGpuFactories(),
2106 *render_thread->GetAudioHardwareConfig()));
2108 #endif // defined(ENABLE_MOJO_MEDIA)
2110 return new media::WebMediaPlayerImpl(
2111 frame, client, encrypted_client, weak_factory_.GetWeakPtr(),
2112 media_renderer_factory.Pass(), GetCdmFactory(), params);
2113 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2116 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
2117 blink::WebLocalFrame* frame,
2118 blink::WebApplicationCacheHostClient* client) {
2119 if (!frame || !frame->view())
2120 return NULL;
2121 DCHECK(!frame_ || frame_ == frame);
2122 return new RendererWebApplicationCacheHostImpl(
2123 RenderViewImpl::FromWebView(frame->view()), client,
2124 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2127 blink::WebWorkerContentSettingsClientProxy*
2128 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2129 blink::WebLocalFrame* frame) {
2130 if (!frame || !frame->view())
2131 return NULL;
2132 DCHECK(!frame_ || frame_ == frame);
2133 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2134 this, frame);
2137 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
2138 const WebPopupMenuInfo& popup_menu_info,
2139 WebExternalPopupMenuClient* popup_menu_client) {
2140 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2141 // An IPC message is sent to the browser to build and display the actual
2142 // popup. The user could have time to click a different select by the time
2143 // the popup is shown. In that case external_popup_menu_ is non NULL.
2144 // By returning NULL in that case, we instruct Blink to cancel that new
2145 // popup. So from the user perspective, only the first one will show, and
2146 // will have to close the first one before another one can be shown.
2147 if (external_popup_menu_)
2148 return NULL;
2149 external_popup_menu_.reset(
2150 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
2151 if (render_view_->screen_metrics_emulator_) {
2152 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
2153 external_popup_menu_.get(),
2154 render_view_->screen_metrics_emulator_.get());
2156 return external_popup_menu_.get();
2157 #else
2158 return NULL;
2159 #endif
2162 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
2163 DCHECK(!frame_ || frame_ == frame);
2164 return &cookie_jar_;
2167 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
2168 blink::WebLocalFrame* frame) {
2169 DCHECK(!frame_ || frame_ == frame);
2170 // At this point we should have non-null data source.
2171 DCHECK(frame->dataSource());
2172 if (!ChildThreadImpl::current())
2173 return NULL; // May be null in some tests.
2174 ServiceWorkerNetworkProvider* provider =
2175 ServiceWorkerNetworkProvider::FromDocumentState(
2176 DocumentState::FromDataSource(frame->dataSource()));
2177 DCHECK(provider);
2178 return new WebServiceWorkerProviderImpl(
2179 ChildThreadImpl::current()->thread_safe_sender(),
2180 provider->context());
2183 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
2184 DCHECK(!frame_ || frame_ == frame);
2185 // If the request hasn't yet committed, notify the browser process that it is
2186 // no longer safe to show the pending URL of the main frame, since a URL spoof
2187 // is now possible. (If the request has committed, the browser already knows.)
2188 if (!frame->parent()) {
2189 DocumentState* document_state =
2190 DocumentState::FromDataSource(frame->dataSource());
2191 NavigationStateImpl* navigation_state =
2192 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2194 if (!navigation_state->request_committed()) {
2195 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
2200 blink::WebFrame* RenderFrameImpl::createChildFrame(
2201 blink::WebLocalFrame* parent,
2202 blink::WebTreeScopeType scope,
2203 const blink::WebString& name,
2204 blink::WebSandboxFlags sandbox_flags) {
2205 // Synchronously notify the browser of a child frame creation to get the
2206 // routing_id for the RenderFrame.
2207 int child_routing_id = MSG_ROUTING_NONE;
2208 Send(new FrameHostMsg_CreateChildFrame(
2209 routing_id_, scope,
2210 base::UTF16ToUTF8(base::StringPiece16(name)), sandbox_flags,
2211 &child_routing_id));
2213 // Allocation of routing id failed, so we can't create a child frame. This can
2214 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2215 // out state or synchronous IPC message above has failed.
2216 if (child_routing_id == MSG_ROUTING_NONE) {
2217 NOTREACHED() << "Failed to allocate routing id for child frame.";
2218 return nullptr;
2221 // Create the RenderFrame and WebLocalFrame, linking the two.
2222 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
2223 render_view_.get(), child_routing_id);
2224 blink::WebLocalFrame* web_frame =
2225 WebLocalFrame::create(scope, child_render_frame);
2226 child_render_frame->SetWebFrame(web_frame);
2228 // Add the frame to the frame tree and initialize it.
2229 parent->appendChild(web_frame);
2230 child_render_frame->Initialize();
2232 return web_frame;
2235 void RenderFrameImpl::didChangeOpener(blink::WebFrame* opener) {
2236 // Only active frames are able to disown their opener.
2237 if (!opener && is_swapped_out_)
2238 return;
2240 // Only a local frame should be able to update another frame's opener.
2241 DCHECK(!opener || opener->isWebLocalFrame());
2243 int opener_routing_id = opener ?
2244 RenderFrameImpl::FromWebFrame(opener->toWebLocalFrame())->GetRoutingID() :
2245 MSG_ROUTING_NONE;
2246 Send(new FrameHostMsg_DidChangeOpener(routing_id_, opener_routing_id));
2249 void RenderFrameImpl::frameDetached(blink::WebFrame* frame, DetachType type) {
2250 // NOTE: This function is called on the frame that is being detached and not
2251 // the parent frame. This is different from createChildFrame() which is
2252 // called on the parent frame.
2253 CHECK(!is_detaching_);
2254 DCHECK(!frame_ || frame_ == frame);
2256 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameDetached());
2257 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2258 FrameDetached(frame));
2260 // We only notify the browser process when the frame is being detached for
2261 // removal. If the frame is being detached for swap, we don't need to do this
2262 // since we are not modifiying the frame tree.
2263 if (type == DetachType::Remove)
2264 Send(new FrameHostMsg_Detach(routing_id_));
2266 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2267 // sent before setting |is_detaching_| to true.
2268 is_detaching_ = true;
2270 // Clean up the associated RenderWidget for the frame, if there is one.
2271 if (render_widget_) {
2272 render_widget_->UnregisterRenderFrame(this);
2273 render_widget_->CloseForFrame();
2276 // We need to clean up subframes by removing them from the map and deleting
2277 // the RenderFrameImpl. In contrast, the main frame is owned by its
2278 // containing RenderViewHost (so that they have the same lifetime), so only
2279 // removal from the map is needed and no deletion.
2280 FrameMap::iterator it = g_frame_map.Get().find(frame);
2281 CHECK(it != g_frame_map.Get().end());
2282 CHECK_EQ(it->second, this);
2283 g_frame_map.Get().erase(it);
2285 // Only remove the frame from the renderer's frame tree if the frame is
2286 // being detached for removal. In the case of a swap, the frame needs to
2287 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2288 if (is_subframe_ && type == DetachType::Remove)
2289 frame->parent()->removeChild(frame);
2291 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2292 // object may not be deleted immediately and other methods may try to access
2293 // it.
2294 frame->close();
2295 frame_ = nullptr;
2297 delete this;
2298 // Object is invalid after this point.
2301 void RenderFrameImpl::frameFocused() {
2302 Send(new FrameHostMsg_FrameFocused(routing_id_));
2305 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
2306 DCHECK(!frame_ || frame_ == frame);
2308 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
2309 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2310 FrameWillClose(frame));
2313 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
2314 const blink::WebString& name) {
2315 DCHECK(!frame_ || frame_ == frame);
2317 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2318 // updates may have performance implications for benchmarks like SunSpider.
2319 // For now, send these updates only for --site-per-process, which needs to
2320 // replicate frame names to frame proxies, and when
2321 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2322 // can be optimized further by only sending the update if there are any
2323 // remote frames in the frame tree, or delaying and batching up IPCs if
2324 // updates are happening too frequently.
2325 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2326 render_view_->renderer_preferences_.report_frame_name_changes) {
2327 Send(new FrameHostMsg_DidChangeName(
2328 routing_id_, base::UTF16ToUTF8(base::StringPiece16(name))));
2332 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame* child_frame,
2333 blink::WebSandboxFlags flags) {
2334 int frame_routing_id = MSG_ROUTING_NONE;
2335 if (child_frame->isWebRemoteFrame()) {
2336 frame_routing_id =
2337 RenderFrameProxy::FromWebFrame(child_frame)->routing_id();
2338 } else {
2339 frame_routing_id =
2340 RenderFrameImpl::FromWebFrame(child_frame)->GetRoutingID();
2343 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_, frame_routing_id,
2344 flags));
2347 void RenderFrameImpl::didMatchCSS(
2348 blink::WebLocalFrame* frame,
2349 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2350 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2351 DCHECK(!frame_ || frame_ == frame);
2353 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2354 DidMatchCSS(newly_matching_selectors,
2355 stopped_matching_selectors));
2358 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2359 const blink::WebString& source) {
2360 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2361 source);
2364 void RenderFrameImpl::didAddMessageToConsole(
2365 const blink::WebConsoleMessage& message,
2366 const blink::WebString& source_name,
2367 unsigned source_line,
2368 const blink::WebString& stack_trace) {
2369 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2370 switch (message.level) {
2371 case blink::WebConsoleMessage::LevelDebug:
2372 log_severity = logging::LOG_VERBOSE;
2373 break;
2374 case blink::WebConsoleMessage::LevelLog:
2375 case blink::WebConsoleMessage::LevelInfo:
2376 log_severity = logging::LOG_INFO;
2377 break;
2378 case blink::WebConsoleMessage::LevelWarning:
2379 log_severity = logging::LOG_WARNING;
2380 break;
2381 case blink::WebConsoleMessage::LevelError:
2382 log_severity = logging::LOG_ERROR;
2383 break;
2384 default:
2385 log_severity = logging::LOG_VERBOSE;
2388 if (shouldReportDetailedMessageForSource(source_name)) {
2389 FOR_EACH_OBSERVER(
2390 RenderFrameObserver, observers_,
2391 DetailedConsoleMessageAdded(message.text,
2392 source_name,
2393 stack_trace,
2394 source_line,
2395 static_cast<int32>(log_severity)));
2398 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2399 static_cast<int32>(log_severity),
2400 message.text,
2401 static_cast<int32>(source_line),
2402 source_name));
2405 void RenderFrameImpl::loadURLExternally(
2406 blink::WebLocalFrame* frame,
2407 const blink::WebURLRequest& request,
2408 blink::WebNavigationPolicy policy,
2409 const blink::WebString& suggested_name) {
2410 DCHECK(!frame_ || frame_ == frame);
2411 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2412 if (policy == blink::WebNavigationPolicyDownload) {
2413 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2414 GetRoutingID(),
2415 request.url(), referrer,
2416 suggested_name));
2417 } else {
2418 OpenURL(frame, request.url(), referrer, policy);
2422 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2423 const NavigationPolicyInfo& info) {
2424 DCHECK(!frame_ || frame_ == info.frame);
2425 return DecidePolicyForNavigation(this, info);
2428 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2429 blink::WebFrame* frame) {
2430 DCHECK(!frame_ || frame_ == frame);
2431 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2434 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2435 const blink::WebFormElement& form) {
2436 DCHECK(!frame_ || frame_ == frame);
2438 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSendSubmitEvent(form));
2441 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2442 const blink::WebFormElement& form) {
2443 DCHECK(!frame_ || frame_ == frame);
2444 DocumentState* document_state =
2445 DocumentState::FromDataSource(frame->provisionalDataSource());
2446 NavigationStateImpl* navigation_state =
2447 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2448 InternalDocumentStateData* internal_data =
2449 InternalDocumentStateData::FromDocumentState(document_state);
2451 if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(),
2452 ui::PAGE_TRANSITION_LINK)) {
2453 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2456 // Save these to be processed when the ensuing navigation is committed.
2457 WebSearchableFormData web_searchable_form_data(form);
2458 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2459 internal_data->set_searchable_form_encoding(
2460 web_searchable_form_data.encoding().utf8());
2462 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form));
2465 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2466 blink::WebDataSource* datasource) {
2467 DCHECK(!frame_ || frame_ == frame);
2469 bool content_initiated = !pending_navigation_params_.get();
2471 // Make sure any previous redirect URLs end up in our new data source.
2472 if (pending_navigation_params_.get()) {
2473 for (const auto& i :
2474 pending_navigation_params_->request_params.redirects) {
2475 datasource->appendRedirect(i);
2479 DocumentState* document_state = DocumentState::FromDataSource(datasource);
2480 if (!document_state) {
2481 document_state = new DocumentState;
2482 datasource->setExtraData(document_state);
2483 if (!content_initiated)
2484 PopulateDocumentStateFromPending(document_state);
2487 // Carry over the user agent override flag, if it exists.
2488 blink::WebView* webview = render_view_->webview();
2489 if (content_initiated && webview && webview->mainFrame() &&
2490 webview->mainFrame()->isWebLocalFrame() &&
2491 webview->mainFrame()->dataSource()) {
2492 DocumentState* old_document_state =
2493 DocumentState::FromDataSource(webview->mainFrame()->dataSource());
2494 if (old_document_state) {
2495 InternalDocumentStateData* internal_data =
2496 InternalDocumentStateData::FromDocumentState(document_state);
2497 InternalDocumentStateData* old_internal_data =
2498 InternalDocumentStateData::FromDocumentState(old_document_state);
2499 internal_data->set_is_overriding_user_agent(
2500 old_internal_data->is_overriding_user_agent());
2504 // The rest of RenderView assumes that a WebDataSource will always have a
2505 // non-null NavigationState.
2506 if (content_initiated) {
2507 document_state->set_navigation_state(
2508 NavigationStateImpl::CreateContentInitiated());
2509 } else {
2510 document_state->set_navigation_state(CreateNavigationStateFromPending());
2511 pending_navigation_params_.reset();
2514 // DocumentState::referred_by_prefetcher_ is true if we are
2515 // navigating from a page that used prefetching using a link on that
2516 // page. We are early enough in the request process here that we
2517 // can still see the DocumentState of the previous page and set
2518 // this value appropriately.
2519 // TODO(gavinp): catch the important case of navigation in a new
2520 // renderer process.
2521 if (webview) {
2522 if (WebFrame* old_frame = webview->mainFrame()) {
2523 const WebURLRequest& original_request = datasource->originalRequest();
2524 const GURL referrer(
2525 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2526 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2527 DocumentState::FromDataSource(old_frame->dataSource())
2528 ->was_prefetcher()) {
2529 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2530 WebDataSource* old_frame_datasource = old_frame->dataSource();
2531 if (old_frame_datasource &&
2532 referrer == GURL(old_frame_datasource->request().url())) {
2533 document_state->set_was_referred_by_prefetcher(true);
2534 break;
2541 if (content_initiated) {
2542 const WebURLRequest& request = datasource->request();
2543 switch (request.cachePolicy()) {
2544 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2545 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2546 break;
2547 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2548 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2549 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2550 break;
2551 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2552 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK);
2553 break;
2554 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2555 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2556 break;
2557 default:
2558 NOTREACHED();
2562 // Create the serviceworker's per-document network observing object if it
2563 // does not exist (When navigation happens within a page, the provider already
2564 // exists).
2565 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2566 DocumentState::FromDataSource(datasource))) {
2567 ServiceWorkerProviderType provider_type =
2568 SERVICE_WORKER_PROVIDER_FOR_WINDOW;
2569 if ((frame->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin) ==
2570 blink::WebSandboxFlags::Origin) {
2571 provider_type = SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME;
2573 scoped_ptr<ServiceWorkerNetworkProvider> network_provider(
2574 new ServiceWorkerNetworkProvider(routing_id_, provider_type));
2575 ServiceWorkerNetworkProvider::AttachToDocumentState(
2576 DocumentState::FromDataSource(datasource),
2577 network_provider.Pass());
2581 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2582 double triggering_event_time) {
2583 DCHECK(!frame_ || frame_ == frame);
2584 WebDataSource* ds = frame->provisionalDataSource();
2586 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2587 // callback is invoked.
2588 if (!ds)
2589 return;
2591 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2592 "id", routing_id_, "url", ds->request().url().string().utf8());
2593 DocumentState* document_state = DocumentState::FromDataSource(ds);
2595 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2596 CHECK_IMPLIES(ds->request().url() == GURL(kSwappedOutURL), is_swapped_out_)
2597 << "Heard swappedout:// when not swapped out.";
2599 // Update the request time if WebKit has better knowledge of it.
2600 if (document_state->request_time().is_null() &&
2601 triggering_event_time != 0.0) {
2602 document_state->set_request_time(Time::FromDoubleT(triggering_event_time));
2605 // Start time is only set after request time.
2606 document_state->set_start_load_time(Time::Now());
2608 bool is_top_most = !frame->parent();
2609 if (is_top_most) {
2610 render_view_->set_navigation_gesture(
2611 WebUserGestureIndicator::isProcessingUserGesture() ?
2612 NavigationGestureUser : NavigationGestureAuto);
2613 } else if (ds->replacesCurrentHistoryItem()) {
2614 // Subframe navigations that don't add session history items must be
2615 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2616 // handle loading of error pages.
2617 static_cast<NavigationStateImpl*>(document_state->navigation_state())
2618 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2621 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2622 DidStartProvisionalLoad(frame));
2623 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2625 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2626 routing_id_, ds->request().url()));
2629 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2630 blink::WebLocalFrame* frame) {
2631 DCHECK(!frame_ || frame_ == frame);
2632 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2635 void RenderFrameImpl::didFailProvisionalLoad(
2636 blink::WebLocalFrame* frame,
2637 const blink::WebURLError& error,
2638 blink::WebHistoryCommitType commit_type) {
2639 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2640 "id", routing_id_);
2641 DCHECK(!frame_ || frame_ == frame);
2642 WebDataSource* ds = frame->provisionalDataSource();
2643 DCHECK(ds);
2645 const WebURLRequest& failed_request = ds->request();
2647 // Notify the browser that we failed a provisional load with an error.
2649 // Note: It is important this notification occur before DidStopLoading so the
2650 // SSL manager can react to the provisional load failure before being
2651 // notified the load stopped.
2653 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2654 DidFailProvisionalLoad(frame, error));
2655 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2656 DidFailProvisionalLoad(error));
2658 SendFailedProvisionalLoad(failed_request, error, frame);
2660 if (!ShouldDisplayErrorPageForFailedLoad(error.reason, error.unreachableURL))
2661 return;
2663 // Make sure we never show errors in view source mode.
2664 frame->enableViewSourceMode(false);
2666 DocumentState* document_state = DocumentState::FromDataSource(ds);
2667 NavigationStateImpl* navigation_state =
2668 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2670 // If this is a failed back/forward/reload navigation, then we need to do a
2671 // 'replace' load. This is necessary to avoid messing up session history.
2672 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2673 // as session history is concerned.
2674 bool replace = commit_type != blink::WebStandardCommit;
2676 // If we failed on a browser initiated request, then make sure that our error
2677 // page load is regarded as the same browser initiated request.
2678 if (!navigation_state->IsContentInitiated()) {
2679 pending_navigation_params_.reset(new NavigationParams(
2680 navigation_state->common_params(), navigation_state->start_params(),
2681 navigation_state->request_params()));
2682 pending_navigation_params_->request_params.request_time =
2683 document_state->request_time();
2686 // Load an error page.
2687 LoadNavigationErrorPage(failed_request, error, replace);
2690 void RenderFrameImpl::didCommitProvisionalLoad(
2691 blink::WebLocalFrame* frame,
2692 const blink::WebHistoryItem& item,
2693 blink::WebHistoryCommitType commit_type) {
2694 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2695 "id", routing_id_,
2696 "url", GetLoadingUrl().possibly_invalid_spec());
2697 DCHECK(!frame_ || frame_ == frame);
2698 DocumentState* document_state =
2699 DocumentState::FromDataSource(frame->dataSource());
2700 NavigationStateImpl* navigation_state =
2701 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2703 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2704 RenderFrameProxy* proxy =
2705 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2706 CHECK(proxy);
2707 proxy->web_frame()->swap(frame_);
2708 proxy_routing_id_ = MSG_ROUTING_NONE;
2710 // If this is the main frame going from a remote frame to a local frame,
2711 // it needs to set RenderViewImpl's pointer for the main frame to itself
2712 // and ensure RenderWidget is no longer in swapped out mode.
2713 if (!is_subframe_) {
2714 CHECK(!render_view_->main_render_frame_);
2715 render_view_->main_render_frame_ = this;
2716 if (render_view_->is_swapped_out())
2717 render_view_->SetSwappedOut(false);
2721 // When we perform a new navigation, we need to update the last committed
2722 // session history entry with state for the page we are leaving. Do this
2723 // before updating the HistoryController state.
2724 render_view_->SendUpdateState();
2726 render_view_->history_controller()->UpdateForCommit(
2727 this, item, commit_type, navigation_state->WasWithinSamePage());
2729 InternalDocumentStateData* internal_data =
2730 InternalDocumentStateData::FromDocumentState(document_state);
2732 if (document_state->commit_load_time().is_null())
2733 document_state->set_commit_load_time(Time::Now());
2735 if (internal_data->must_reset_scroll_and_scale_state()) {
2736 render_view_->webview()->resetScrollAndScaleState();
2737 internal_data->set_must_reset_scroll_and_scale_state(false);
2740 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2741 if (is_new_navigation) {
2742 // We bump our Page ID to correspond with the new session history entry.
2743 render_view_->page_id_ = render_view_->next_page_id_++;
2745 // Don't update history list values for kSwappedOutURL, since
2746 // we don't want to forget the entry that was there, and since we will
2747 // never come back to kSwappedOutURL. Note that we have to call
2748 // SendUpdateState and update page_id_ even in this case, so that
2749 // the current entry gets a state update and so that we don't send a
2750 // state update to the wrong entry when we swap back in.
2751 DCHECK_IMPLIES(
2752 navigation_state->common_params().should_replace_current_entry,
2753 render_view_->history_list_length_ > 0);
2754 if (GetLoadingUrl() != GURL(kSwappedOutURL) &&
2755 !navigation_state->common_params().should_replace_current_entry) {
2756 // Advance our offset in session history, applying the length limit.
2757 // There is now no forward history.
2758 render_view_->history_list_offset_++;
2759 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2760 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2761 render_view_->history_list_length_ =
2762 render_view_->history_list_offset_ + 1;
2764 } else {
2765 const RequestNavigationParams& request_params =
2766 navigation_state->request_params();
2767 if (request_params.nav_entry_id != 0 &&
2768 !request_params.intended_as_new_entry) {
2769 // This is a successful session history navigation!
2770 render_view_->page_id_ = request_params.page_id;
2772 render_view_->history_list_offset_ =
2773 request_params.pending_history_list_offset;
2777 bool sent = Send(
2778 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2779 CHECK(sent); // http://crbug.com/407376
2781 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2782 DidCommitProvisionalLoad(frame, is_new_navigation));
2783 FOR_EACH_OBSERVER(
2784 RenderFrameObserver, observers_,
2785 DidCommitProvisionalLoad(is_new_navigation,
2786 navigation_state->WasWithinSamePage()));
2788 if (!frame->parent()) { // Only for top frames.
2789 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2790 if (render_thread_impl) { // Can be NULL in tests.
2791 render_thread_impl->histogram_customizer()->
2792 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2793 RenderView::GetRenderViewCount());
2797 // Remember that we've already processed this request, so we don't update
2798 // the session history again. We do this regardless of whether this is
2799 // a session history navigation, because if we attempted a session history
2800 // navigation without valid HistoryItem state, WebCore will think it is a
2801 // new navigation.
2802 navigation_state->set_request_committed(true);
2804 SendDidCommitProvisionalLoad(frame, commit_type, item);
2806 // Check whether we have new encoding name.
2807 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2810 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2811 DCHECK(!frame_ || frame_ == frame);
2813 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidCreateNewDocument());
2814 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2815 DidCreateNewDocument(frame));
2818 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2819 DCHECK(!frame_ || frame_ == frame);
2821 int enabled_bindings = render_view_->GetEnabledBindings();
2823 if (enabled_bindings & BINDINGS_POLICY_WEB_UI)
2824 WebUIExtension::Install(frame);
2826 if (enabled_bindings & BINDINGS_POLICY_DOM_AUTOMATION)
2827 DomAutomationController::Install(this, frame);
2829 if (enabled_bindings & BINDINGS_POLICY_STATS_COLLECTION)
2830 StatsCollectionController::Install(frame);
2832 const base::CommandLine& command_line =
2833 *base::CommandLine::ForCurrentProcess();
2835 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
2836 GpuBenchmarking::Install(frame);
2838 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2839 MemoryBenchmarkingExtension::Install(frame);
2841 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2842 SkiaBenchmarking::Install(frame);
2844 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2845 DidClearWindowObject(frame));
2846 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2849 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2850 DCHECK(!frame_ || frame_ == frame);
2852 // Notify the browser about non-blank documents loading in the top frame.
2853 GURL url = frame->document().url();
2854 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2855 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2856 // frame->tree()->top().
2857 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2858 if (frame == main_frame) {
2859 // For now, don't remember plugin zoom values. We don't want to mix them
2860 // with normal web content (i.e. a fixed layout plugin would usually want
2861 // them different).
2862 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2863 render_view_->GetRoutingID(),
2864 main_frame->document().isPluginDocument()));
2868 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2869 DidCreateDocumentElement());
2870 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2871 DidCreateDocumentElement(frame));
2874 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2875 const blink::WebString& title,
2876 blink::WebTextDirection direction) {
2877 DCHECK(!frame_ || frame_ == frame);
2878 // Ignore all but top level navigations.
2879 if (!frame->parent()) {
2880 base::string16 title16 = title;
2881 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2882 routing_id_, base::UTF16ToUTF8(title16));
2884 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2885 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2886 shortened_title, direction));
2889 // Also check whether we have new encoding name.
2890 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2893 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2894 blink::WebIconURL::Type icon_type) {
2895 DCHECK(!frame_ || frame_ == frame);
2896 // TODO(nasko): Investigate wheather implementation should move here.
2897 render_view_->didChangeIcon(frame, icon_type);
2900 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame,
2901 bool document_is_empty) {
2902 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2903 "id", routing_id_);
2904 DCHECK(!frame_ || frame_ == frame);
2905 WebDataSource* ds = frame->dataSource();
2906 DocumentState* document_state = DocumentState::FromDataSource(ds);
2907 document_state->set_finish_document_load_time(Time::Now());
2909 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2911 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2912 DidFinishDocumentLoad(frame));
2913 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2915 // Check whether we have new encoding name.
2916 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2918 // If this is an empty document with an http status code indicating an error,
2919 // we may want to display our own error page, so the user doesn't end up
2920 // with an unexplained blank page.
2921 if (!document_is_empty)
2922 return;
2924 // Do not show error page when DevTools is attached.
2925 RenderFrameImpl* localRoot = this;
2926 while (localRoot->frame_ && localRoot->frame_->parent() &&
2927 localRoot->frame_->parent()->isWebLocalFrame()) {
2928 localRoot = RenderFrameImpl::FromWebFrame(localRoot->frame_->parent());
2929 DCHECK(localRoot);
2931 if (localRoot->devtools_agent_ && localRoot->devtools_agent_->IsAttached())
2932 return;
2934 // Display error page instead of a blank page, if appropriate.
2935 std::string error_domain = "http";
2936 InternalDocumentStateData* internal_data =
2937 InternalDocumentStateData::FromDataSource(frame->dataSource());
2938 int http_status_code = internal_data->http_status_code();
2939 if (GetContentClient()->renderer()->HasErrorPage(http_status_code,
2940 &error_domain)) {
2941 WebURLError error;
2942 error.unreachableURL = frame->document().url();
2943 error.domain = WebString::fromUTF8(error_domain);
2944 error.reason = http_status_code;
2945 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
2949 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2950 DCHECK(!frame_ || frame_ == frame);
2951 if (!frame->parent()) {
2952 FrameMsg_UILoadMetricsReportType::Value report_type =
2953 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
2954 frame->dataSource()->request().inputPerfMetricReportPolicy());
2955 base::TimeTicks ui_timestamp = base::TimeTicks() +
2956 base::TimeDelta::FromSecondsD(
2957 frame->dataSource()->request().uiStartTime());
2959 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2960 routing_id_, report_type, ui_timestamp));
2964 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2965 const blink::WebURLError& error,
2966 blink::WebHistoryCommitType commit_type) {
2967 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2968 "id", routing_id_);
2969 DCHECK(!frame_ || frame_ == frame);
2970 // TODO(nasko): Move implementation here. No state needed.
2971 WebDataSource* ds = frame->dataSource();
2972 DCHECK(ds);
2974 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2975 DidFailLoad(frame, error));
2977 const WebURLRequest& failed_request = ds->request();
2978 base::string16 error_description;
2979 GetContentClient()->renderer()->GetNavigationErrorStrings(
2980 render_view_.get(),
2981 frame,
2982 failed_request,
2983 error,
2984 NULL,
2985 &error_description);
2986 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2987 failed_request.url(),
2988 error.reason,
2989 error_description,
2990 error.wasIgnoredByHandler));
2993 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2994 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2995 "id", routing_id_);
2996 DCHECK(!frame_ || frame_ == frame);
2997 WebDataSource* ds = frame->dataSource();
2998 DocumentState* document_state = DocumentState::FromDataSource(ds);
2999 if (document_state->finish_load_time().is_null()) {
3000 if (!frame->parent()) {
3001 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
3002 TRACE_EVENT_SCOPE_PROCESS);
3004 document_state->set_finish_load_time(Time::Now());
3007 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
3008 DidFinishLoad(frame));
3009 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
3011 // Don't send this message while the frame is swapped out.
3012 if (is_swapped_out())
3013 return;
3015 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
3016 ds->request().url()));
3019 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
3020 const blink::WebHistoryItem& item,
3021 blink::WebHistoryCommitType commit_type) {
3022 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
3023 "id", routing_id_);
3024 DCHECK(!frame_ || frame_ == frame);
3025 // If this was a reference fragment navigation that we initiated, then we
3026 // could end up having a non-null pending navigation params. We just need to
3027 // update the ExtraData on the datasource so that others who read the
3028 // ExtraData will get the new NavigationState. Similarly, if we did not
3029 // initiate this navigation, then we need to take care to reset any pre-
3030 // existing navigation state to a content-initiated navigation state.
3031 // didCreateDataSource conveniently takes care of this for us.
3032 didCreateDataSource(frame, frame->dataSource());
3034 DocumentState* document_state =
3035 DocumentState::FromDataSource(frame->dataSource());
3036 static_cast<NavigationStateImpl*>(document_state->navigation_state())
3037 ->set_was_within_same_page(true);
3039 didCommitProvisionalLoad(frame, item, commit_type);
3042 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
3043 DCHECK(!frame_ || frame_ == frame);
3044 // TODO(nasko): Move implementation here. Needed methods:
3045 // * StartNavStateSyncTimerIfNecessary
3046 render_view_->didUpdateCurrentHistoryItem(frame);
3049 void RenderFrameImpl::didChangeThemeColor() {
3050 if (frame_->parent())
3051 return;
3053 Send(new FrameHostMsg_DidChangeThemeColor(
3054 routing_id_, frame_->document().themeColor()));
3057 void RenderFrameImpl::dispatchLoad() {
3058 Send(new FrameHostMsg_DispatchLoad(routing_id_));
3061 void RenderFrameImpl::requestNotificationPermission(
3062 const blink::WebSecurityOrigin& origin,
3063 blink::WebNotificationPermissionCallback* callback) {
3064 if (!notification_permission_dispatcher_) {
3065 notification_permission_dispatcher_ =
3066 new NotificationPermissionDispatcher(this);
3069 notification_permission_dispatcher_->RequestPermission(origin, callback);
3072 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
3073 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
3074 return;
3076 if (is_empty_selection)
3077 selection_text_.clear();
3079 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3080 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3081 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3082 // to notify the selection was changed. Focus change should be notified
3083 // before selection change.
3084 GetRenderWidget()->UpdateTextInputState(
3085 RenderWidget::NO_SHOW_IME, RenderWidget::FROM_NON_IME);
3086 SyncSelectionIfRequired();
3089 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
3090 blink::WebColorChooserClient* client,
3091 const blink::WebColor& initial_color,
3092 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
3093 RendererWebColorChooserImpl* color_chooser =
3094 new RendererWebColorChooserImpl(this, client);
3095 std::vector<ColorSuggestion> color_suggestions;
3096 for (size_t i = 0; i < suggestions.size(); i++) {
3097 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
3099 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
3100 return color_chooser;
3103 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
3104 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
3105 message,
3106 base::string16(),
3107 frame_->document().url(),
3108 NULL);
3111 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
3112 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
3113 message,
3114 base::string16(),
3115 frame_->document().url(),
3116 NULL);
3119 bool RenderFrameImpl::runModalPromptDialog(
3120 const blink::WebString& message,
3121 const blink::WebString& default_value,
3122 blink::WebString* actual_value) {
3123 base::string16 result;
3124 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
3125 message,
3126 default_value,
3127 frame_->document().url(),
3128 &result);
3129 if (ok)
3130 actual_value->assign(result);
3131 return ok;
3134 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3135 bool is_reload,
3136 const blink::WebString& message) {
3137 // If we are swapping out, we have already run the beforeunload handler.
3138 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3139 // at all, to avoid running it twice.
3140 if (is_swapped_out_)
3141 return true;
3143 // Don't allow further dialogs if we are waiting to swap out, since the
3144 // PageGroupLoadDeferrer in our stack prevents it.
3145 if (render_view()->suppress_dialogs_until_swap_out_)
3146 return false;
3148 bool success = false;
3149 // This is an ignored return value, but is included so we can accept the same
3150 // response as RunJavaScriptMessage.
3151 base::string16 ignored_result;
3152 render_view()->SendAndRunNestedMessageLoop(
3153 new FrameHostMsg_RunBeforeUnloadConfirm(
3154 routing_id_, frame_->document().url(), message, is_reload,
3155 &success, &ignored_result));
3156 return success;
3159 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
3160 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
3161 params.source_type = GetRenderWidget()->context_menu_source_type();
3162 GetRenderWidget()->OnShowHostContextMenu(&params);
3163 if (GetRenderWidget()->has_host_context_menu_location()) {
3164 params.x = GetRenderWidget()->host_context_menu_location().x();
3165 params.y = GetRenderWidget()->host_context_menu_location().y();
3168 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3169 // it. We replace it with an empty GURL so the appropriate items are disabled
3170 // in the context menu.
3171 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3172 // data encoded images. We should have a way to save them.
3173 if (params.src_url.spec().size() > GetMaxURLChars())
3174 params.src_url = GURL();
3175 context_menu_node_ = data.node;
3177 #if defined(OS_ANDROID)
3178 gfx::Rect start_rect;
3179 gfx::Rect end_rect;
3180 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
3181 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
3182 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
3183 #endif
3185 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
3188 void RenderFrameImpl::clearContextMenu() {
3189 context_menu_node_.reset();
3192 void RenderFrameImpl::willSendRequest(
3193 blink::WebLocalFrame* frame,
3194 unsigned identifier,
3195 blink::WebURLRequest& request,
3196 const blink::WebURLResponse& redirect_response) {
3197 DCHECK(!frame_ || frame_ == frame);
3198 // The request my be empty during tests.
3199 if (request.url().isEmpty())
3200 return;
3202 // Set the first party for cookies url if it has not been set yet (new
3203 // requests). For redirects, it is updated by WebURLLoaderImpl.
3204 if (request.firstPartyForCookies().isEmpty()) {
3205 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
3206 request.setFirstPartyForCookies(request.url());
3207 } else {
3208 // TODO(nasko): When the top-level frame is remote, there is no document.
3209 // This is broken and should be fixed to propagate the first party.
3210 WebFrame* top = frame->top();
3211 if (top->isWebLocalFrame()) {
3212 request.setFirstPartyForCookies(
3213 frame->top()->document().firstPartyForCookies());
3218 WebDataSource* provisional_data_source = frame->provisionalDataSource();
3219 WebDataSource* data_source =
3220 provisional_data_source ? provisional_data_source : frame->dataSource();
3222 DocumentState* document_state = DocumentState::FromDataSource(data_source);
3223 DCHECK(document_state);
3224 InternalDocumentStateData* internal_data =
3225 InternalDocumentStateData::FromDocumentState(document_state);
3226 NavigationStateImpl* navigation_state =
3227 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3228 ui::PageTransition transition_type = navigation_state->GetTransitionType();
3229 if (provisional_data_source && provisional_data_source->isClientRedirect()) {
3230 transition_type = ui::PageTransitionFromInt(
3231 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3234 GURL request_url(request.url());
3235 GURL new_url;
3236 if (GetContentClient()->renderer()->WillSendRequest(
3237 frame,
3238 transition_type,
3239 request_url,
3240 request.firstPartyForCookies(),
3241 &new_url)) {
3242 request.setURL(WebURL(new_url));
3245 if (internal_data->is_cache_policy_override_set())
3246 request.setCachePolicy(internal_data->cache_policy_override());
3248 // The request's extra data may indicate that we should set a custom user
3249 // agent. This needs to be done here, after WebKit is through with setting the
3250 // user agent on its own. Similarly, it may indicate that we should set an
3251 // X-Requested-With header. This must be done here to avoid breaking CORS
3252 // checks.
3253 // PlzNavigate: there may also be a stream url associated with the request.
3254 WebString custom_user_agent;
3255 WebString requested_with;
3256 scoped_ptr<StreamOverrideParameters> stream_override;
3257 if (request.extraData()) {
3258 RequestExtraData* old_extra_data =
3259 static_cast<RequestExtraData*>(request.extraData());
3261 custom_user_agent = old_extra_data->custom_user_agent();
3262 if (!custom_user_agent.isNull()) {
3263 if (custom_user_agent.isEmpty())
3264 request.clearHTTPHeaderField("User-Agent");
3265 else
3266 request.setHTTPHeaderField("User-Agent", custom_user_agent);
3269 requested_with = old_extra_data->requested_with();
3270 if (!requested_with.isNull()) {
3271 if (requested_with.isEmpty())
3272 request.clearHTTPHeaderField("X-Requested-With");
3273 else
3274 request.setHTTPHeaderField("X-Requested-With", requested_with);
3276 stream_override = old_extra_data->TakeStreamOverrideOwnership();
3279 // Add the default accept header for frame request if it has not been set
3280 // already.
3281 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3282 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
3283 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
3284 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
3285 WebString::fromUTF8(kDefaultAcceptHeader));
3288 // Add an empty HTTP origin header for non GET methods if none is currently
3289 // present.
3290 request.addHTTPOriginIfNeeded(WebString());
3292 // Attach |should_replace_current_entry| state to requests so that, should
3293 // this navigation later require a request transfer, all state is preserved
3294 // when it is re-created in the new process.
3295 bool should_replace_current_entry = false;
3296 if (navigation_state->IsContentInitiated()) {
3297 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
3298 } else {
3299 // If the navigation is browser-initiated, the NavigationState contains the
3300 // correct value instead of the WebDataSource.
3302 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3303 // NavigationState::should_replace_current_entry().
3304 should_replace_current_entry =
3305 navigation_state->common_params().should_replace_current_entry;
3308 int provider_id = kInvalidServiceWorkerProviderId;
3309 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3310 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
3311 // |provisionalDataSource| may be null in some content::ResourceFetcher
3312 // use cases, we don't hook those requests.
3313 if (frame->provisionalDataSource()) {
3314 ServiceWorkerNetworkProvider* provider =
3315 ServiceWorkerNetworkProvider::FromDocumentState(
3316 DocumentState::FromDataSource(frame->provisionalDataSource()));
3317 provider_id = provider->provider_id();
3319 } else if (frame->dataSource()) {
3320 ServiceWorkerNetworkProvider* provider =
3321 ServiceWorkerNetworkProvider::FromDocumentState(
3322 DocumentState::FromDataSource(frame->dataSource()));
3323 provider_id = provider->provider_id();
3326 WebFrame* parent = frame->parent();
3327 int parent_routing_id = MSG_ROUTING_NONE;
3328 if (!parent) {
3329 parent_routing_id = -1;
3330 } else if (parent->isWebLocalFrame()) {
3331 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
3332 } else {
3333 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
3336 RequestExtraData* extra_data = new RequestExtraData();
3337 extra_data->set_visibility_state(render_view_->visibilityState());
3338 extra_data->set_custom_user_agent(custom_user_agent);
3339 extra_data->set_requested_with(requested_with);
3340 extra_data->set_render_frame_id(routing_id_);
3341 extra_data->set_is_main_frame(!parent);
3342 extra_data->set_frame_origin(
3343 GURL(frame->document().securityOrigin().toString()));
3344 extra_data->set_parent_is_main_frame(parent && !parent->parent());
3345 extra_data->set_parent_render_frame_id(parent_routing_id);
3346 extra_data->set_allow_download(
3347 navigation_state->common_params().allow_download);
3348 extra_data->set_transition_type(transition_type);
3349 extra_data->set_should_replace_current_entry(should_replace_current_entry);
3350 extra_data->set_transferred_request_child_id(
3351 navigation_state->start_params().transferred_request_child_id);
3352 extra_data->set_transferred_request_request_id(
3353 navigation_state->start_params().transferred_request_request_id);
3354 extra_data->set_service_worker_provider_id(provider_id);
3355 extra_data->set_stream_override(stream_override.Pass());
3356 request.setExtraData(extra_data);
3358 // TODO(creis): Update prefetching to work with out-of-process iframes.
3359 WebFrame* top_frame = frame->top();
3360 if (top_frame && top_frame->isWebLocalFrame()) {
3361 DocumentState* top_document_state =
3362 DocumentState::FromDataSource(top_frame->dataSource());
3363 if (top_document_state) {
3364 // TODO(gavinp): separate out prefetching and prerender field trials
3365 // if the rel=prerender rel type is sticking around.
3366 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
3367 top_document_state->set_was_prefetcher(true);
3371 // This is an instance where we embed a copy of the routing id
3372 // into the data portion of the message. This can cause problems if we
3373 // don't register this id on the browser side, since the download manager
3374 // expects to find a RenderViewHost based off the id.
3375 request.setRequestorID(render_view_->GetRoutingID());
3376 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3378 if (!navigation_state->start_params().extra_headers.empty()) {
3379 for (net::HttpUtil::HeadersIterator i(
3380 navigation_state->start_params().extra_headers.begin(),
3381 navigation_state->start_params().extra_headers.end(), "\n");
3382 i.GetNext();) {
3383 if (base::LowerCaseEqualsASCII(i.name(), "referer")) {
3384 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
3385 blink::WebReferrerPolicyDefault,
3386 request.url(),
3387 WebString::fromUTF8(i.values()));
3388 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
3389 } else {
3390 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
3391 WebString::fromUTF8(i.values()));
3396 if (!render_view_->renderer_preferences_.enable_referrers)
3397 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
3400 void RenderFrameImpl::didReceiveResponse(
3401 blink::WebLocalFrame* frame,
3402 unsigned identifier,
3403 const blink::WebURLResponse& response) {
3404 DCHECK(!frame_ || frame_ == frame);
3405 // Only do this for responses that correspond to a provisional data source
3406 // of the top-most frame. If we have a provisional data source, then we
3407 // can't have any sub-resources yet, so we know that this response must
3408 // correspond to a frame load.
3409 if (!frame->provisionalDataSource() || frame->parent())
3410 return;
3412 // If we are in view source mode, then just let the user see the source of
3413 // the server's error page.
3414 if (frame->isViewSourceModeEnabled())
3415 return;
3417 DocumentState* document_state =
3418 DocumentState::FromDataSource(frame->provisionalDataSource());
3419 int http_status_code = response.httpStatusCode();
3421 // Record page load flags.
3422 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3423 if (extra_data) {
3424 document_state->set_was_fetched_via_spdy(
3425 extra_data->was_fetched_via_spdy());
3426 document_state->set_was_npn_negotiated(
3427 extra_data->was_npn_negotiated());
3428 document_state->set_npn_negotiated_protocol(
3429 extra_data->npn_negotiated_protocol());
3430 document_state->set_was_alternate_protocol_available(
3431 extra_data->was_alternate_protocol_available());
3432 document_state->set_connection_info(
3433 extra_data->connection_info());
3434 document_state->set_was_fetched_via_proxy(
3435 extra_data->was_fetched_via_proxy());
3436 document_state->set_proxy_server(
3437 extra_data->proxy_server());
3439 InternalDocumentStateData* internal_data =
3440 InternalDocumentStateData::FromDocumentState(document_state);
3441 internal_data->set_http_status_code(http_status_code);
3444 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3445 blink::WebLocalFrame* frame,
3446 const blink::WebURLRequest& request,
3447 const blink::WebURLResponse& response) {
3448 DCHECK(!frame_ || frame_ == frame);
3449 // The recipients of this message have no use for data: URLs: they don't
3450 // affect the page's insecure content list and are not in the disk cache. To
3451 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3452 // filter them out here.
3453 GURL url(request.url());
3454 if (url.SchemeIs(url::kDataScheme))
3455 return;
3457 // Let the browser know we loaded a resource from the memory cache. This
3458 // message is needed to display the correct SSL indicators.
3459 Send(new FrameHostMsg_DidLoadResourceFromMemoryCache(
3460 routing_id_, url, response.securityInfo(), request.httpMethod().utf8(),
3461 response.mimeType().utf8(), WebURLRequestToResourceType(request)));
3464 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3465 DCHECK(!frame_ || frame_ == frame);
3466 Send(new FrameHostMsg_DidDisplayInsecureContent(routing_id_));
3469 void RenderFrameImpl::didRunInsecureContent(
3470 blink::WebLocalFrame* frame,
3471 const blink::WebSecurityOrigin& origin,
3472 const blink::WebURL& target) {
3473 DCHECK(!frame_ || frame_ == frame);
3474 Send(new FrameHostMsg_DidRunInsecureContent(
3475 routing_id_, origin.toString().utf8(), target));
3476 GetContentClient()->renderer()->RecordRapporURL(
3477 "ContentSettings.MixedScript.RanMixedScript",
3478 GURL(origin.toString().utf8()));
3481 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3482 DCHECK(!frame_ || frame_ == frame);
3483 #if defined(ENABLE_PLUGINS)
3484 if (frame != render_view_->webview()->mainFrame())
3485 return;
3486 PluginChannelHost::Broadcast(
3487 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3488 #endif
3491 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3492 v8::Local<v8::Context> context,
3493 int extension_group,
3494 int world_id) {
3495 DCHECK(!frame_ || frame_ == frame);
3497 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
3498 DidCreateScriptContext(context, extension_group, world_id));
3501 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3502 v8::Local<v8::Context> context,
3503 int world_id) {
3504 DCHECK(!frame_ || frame_ == frame);
3506 FOR_EACH_OBSERVER(RenderFrameObserver,
3507 observers_,
3508 WillReleaseScriptContext(context, world_id));
3511 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3512 DCHECK(!frame_ || frame_ == frame);
3513 // TODO(nasko): Move implementation here. Needed methods:
3514 // * StartNavStateSyncTimerIfNecessary
3515 render_view_->didChangeScrollOffset(frame);
3517 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeScrollOffset());
3520 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3521 DCHECK(!frame_ || frame_ == frame);
3522 if (!frame->parent()) {
3523 render_view_->Send(new ViewHostMsg_WillInsertBody(
3524 render_view_->GetRoutingID()));
3528 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3529 int count,
3530 bool final_update) {
3531 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3532 if (!count)
3533 active_match_ordinal = 0;
3535 render_view_->Send(new ViewHostMsg_Find_Reply(
3536 render_view_->GetRoutingID(), request_id, count,
3537 gfx::Rect(), active_match_ordinal, final_update));
3540 void RenderFrameImpl::reportFindInPageSelection(
3541 int request_id,
3542 int active_match_ordinal,
3543 const blink::WebRect& selection_rect) {
3544 render_view_->Send(new ViewHostMsg_Find_Reply(
3545 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3546 active_match_ordinal, false));
3549 void RenderFrameImpl::requestStorageQuota(
3550 blink::WebLocalFrame* frame,
3551 blink::WebStorageQuotaType type,
3552 unsigned long long requested_size,
3553 blink::WebStorageQuotaCallbacks callbacks) {
3554 DCHECK(!frame_ || frame_ == frame);
3555 WebSecurityOrigin origin = frame->document().securityOrigin();
3556 if (origin.isUnique()) {
3557 // Unique origins cannot store persistent state.
3558 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3559 return;
3561 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3562 render_view_->GetRoutingID(),
3563 GURL(origin.toString()),
3564 static_cast<storage::StorageType>(type),
3565 requested_size,
3566 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3569 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3570 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3571 impl->set_render_frame_id(routing_id_);
3574 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3575 if (!geolocation_dispatcher_)
3576 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3577 return geolocation_dispatcher_;
3580 blink::WebPresentationClient* RenderFrameImpl::presentationClient() {
3581 if (!presentation_dispatcher_)
3582 presentation_dispatcher_ = new PresentationDispatcher(this);
3583 return presentation_dispatcher_;
3586 blink::WebPushClient* RenderFrameImpl::pushClient() {
3587 if (!push_messaging_dispatcher_)
3588 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3589 return push_messaging_dispatcher_;
3592 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3593 blink::WebLocalFrame* frame,
3594 blink::WebRTCPeerConnectionHandler* handler) {
3595 DCHECK(!frame_ || frame_ == frame);
3596 #if defined(ENABLE_WEBRTC)
3597 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3598 #endif
3601 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3602 if (!web_user_media_client_)
3603 InitializeUserMediaClient();
3604 return web_user_media_client_;
3607 blink::WebEncryptedMediaClient* RenderFrameImpl::encryptedMediaClient() {
3608 if (!web_encrypted_media_client_) {
3609 web_encrypted_media_client_.reset(new media::WebEncryptedMediaClientImpl(
3610 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3611 // is destructed before |this|, and does not give away ownership of the
3612 // callback.
3613 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported,
3614 base::Unretained(this)),
3615 GetCdmFactory(), GetMediaPermission()));
3617 return web_encrypted_media_client_.get();
3620 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3621 if (!midi_dispatcher_)
3622 midi_dispatcher_ = new MidiDispatcher(this);
3623 return midi_dispatcher_;
3626 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3627 blink::WebLocalFrame* source_frame,
3628 blink::WebFrame* target_frame,
3629 blink::WebSecurityOrigin target_origin,
3630 blink::WebDOMMessageEvent event) {
3631 DCHECK(!frame_ || frame_ == target_frame);
3633 // Currently, a postMessage that targets a cross-process frame can be plumbed
3634 // either through this function or RenderFrameProxy::postMessageEvent. This
3635 // function is used when the target cross-process frame is a top-level frame
3636 // which has been swapped out. In that case, the corresponding WebLocalFrame
3637 // currently remains in the frame tree even in site-per-process mode (see
3638 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3639 // --site-per-process mode for all other cases.
3641 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3642 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3643 // cross-process postMessages.
3644 if (!is_swapped_out_)
3645 return false;
3647 // It is possible to get here on a swapped-out frame without a
3648 // |render_frame_proxy_|. This happens when:
3649 // - This process only has one active RenderView and is about to go away
3650 // (e.g., due to cross-process navigation).
3651 // - The top frame has a subframe with an unload handler.
3652 // - The subframe sends a postMessage to the top-level frame in its unload
3653 // handler.
3654 // See https://crbug.com/475651 for details. We return false here, since we
3655 // don't want to deliver the message to the new process in this case.
3656 if (!render_frame_proxy_)
3657 return false;
3659 render_frame_proxy_->postMessageEvent(
3660 source_frame, render_frame_proxy_->web_frame(), target_origin, event);
3661 return true;
3664 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3665 const blink::WebURL& url) {
3666 DCHECK(!frame_ || frame_ == frame);
3667 std::string user_agent_override_for_url =
3668 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3669 if (!user_agent_override_for_url.empty())
3670 return WebString::fromUTF8(user_agent_override_for_url);
3672 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3673 render_view_->renderer_preferences_.user_agent_override.empty()) {
3674 return blink::WebString();
3677 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3678 // associated with it, so the checks below are not valid. Temporarily
3679 // return early and fix properly as part of https://crbug.com/426555.
3680 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3681 return blink::WebString();
3683 // If we're in the middle of committing a load, the data source we need
3684 // will still be provisional.
3685 WebFrame* main_frame = render_view_->webview()->mainFrame();
3686 WebDataSource* data_source = NULL;
3687 if (main_frame->provisionalDataSource())
3688 data_source = main_frame->provisionalDataSource();
3689 else
3690 data_source = main_frame->dataSource();
3692 InternalDocumentStateData* internal_data = data_source ?
3693 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3694 if (internal_data && internal_data->is_overriding_user_agent())
3695 return WebString::fromUTF8(
3696 render_view_->renderer_preferences_.user_agent_override);
3697 return blink::WebString();
3700 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3701 DCHECK(!frame_ || frame_ == frame);
3702 if (render_view_->renderer_preferences_.enable_do_not_track)
3703 return WebString::fromUTF8("1");
3704 return WebString();
3707 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3708 bool default_value) {
3709 DCHECK(!frame_ || frame_ == frame);
3710 if (!default_value)
3711 return false;
3713 bool blocked = true;
3714 Send(new FrameHostMsg_Are3DAPIsBlocked(
3715 routing_id_,
3716 GURL(frame->top()->securityOrigin().toString()),
3717 THREE_D_API_TYPE_WEBGL,
3718 &blocked));
3719 return !blocked;
3722 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3723 int arb_robustness_status_code) {
3724 DCHECK(!frame_ || frame_ == frame);
3725 Send(new FrameHostMsg_DidLose3DContext(
3726 GURL(frame->top()->securityOrigin().toString()),
3727 THREE_D_API_TYPE_WEBGL,
3728 arb_robustness_status_code));
3731 blink::WebScreenOrientationClient*
3732 RenderFrameImpl::webScreenOrientationClient() {
3733 if (!screen_orientation_dispatcher_)
3734 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3735 return screen_orientation_dispatcher_;
3738 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3739 ServiceWorkerNetworkProvider* provider =
3740 ServiceWorkerNetworkProvider::FromDocumentState(
3741 DocumentState::FromDataSource(&data_source));
3742 if (!provider->context())
3743 return false;
3744 return provider->context()->controller_handle_id() !=
3745 kInvalidServiceWorkerHandleId;
3748 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3749 ServiceWorkerNetworkProvider* provider =
3750 ServiceWorkerNetworkProvider::FromDocumentState(
3751 DocumentState::FromDataSource(&data_source));
3752 if (provider->context() && provider->context()->controller())
3753 return provider->context()->controller()->version_id();
3754 return kInvalidServiceWorkerVersionId;
3757 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3758 blink::WebAXEvent event) {
3759 HandleWebAccessibilityEvent(obj, event);
3762 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3763 int identifier,
3764 int match_index,
3765 const blink::WebAXObject& start_object,
3766 int start_offset,
3767 const blink::WebAXObject& end_object,
3768 int end_offset) {
3769 if (renderer_accessibility_) {
3770 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3771 identifier, match_index, start_object, start_offset,
3772 end_object, end_offset);
3776 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame) {
3777 DCHECK(!frame_ || frame_ == frame);
3779 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3782 bool RenderFrameImpl::enterFullscreen() {
3783 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, true));
3784 return true;
3787 bool RenderFrameImpl::exitFullscreen() {
3788 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, false));
3789 return true;
3792 blink::WebPermissionClient* RenderFrameImpl::permissionClient() {
3793 if (!permission_client_)
3794 permission_client_.reset(new PermissionDispatcher(GetServiceRegistry()));
3796 return permission_client_.get();
3799 blink::WebAppBannerClient* RenderFrameImpl::appBannerClient() {
3800 if (!app_banner_client_) {
3801 app_banner_client_ =
3802 GetContentClient()->renderer()->CreateAppBannerClient(this);
3805 return app_banner_client_.get();
3808 void RenderFrameImpl::registerProtocolHandler(const WebString& scheme,
3809 const WebURL& url,
3810 const WebString& title) {
3811 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3812 Send(new FrameHostMsg_RegisterProtocolHandler(
3813 routing_id_,
3814 base::UTF16ToUTF8(base::StringPiece16(scheme)),
3815 url,
3816 title,
3817 user_gesture));
3820 void RenderFrameImpl::unregisterProtocolHandler(const WebString& scheme,
3821 const WebURL& url) {
3822 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3823 Send(new FrameHostMsg_UnregisterProtocolHandler(
3824 routing_id_,
3825 base::UTF16ToUTF8(base::StringPiece16(scheme)),
3826 url,
3827 user_gesture));
3830 blink::WebBluetooth* RenderFrameImpl::bluetooth() {
3831 if (!bluetooth_) {
3832 bluetooth_.reset(new WebBluetoothImpl(
3833 ChildThreadImpl::current()->thread_safe_sender(), routing_id_));
3836 return bluetooth_.get();
3839 blink::WebUSBClient* RenderFrameImpl::usbClient() {
3840 #if !defined(OS_ANDROID)
3841 if (!usb_client_) {
3842 mojo::ServiceProviderPtr device_services =
3843 ConnectToApplication(GURL(device::kDevicesMojoAppUrl));
3844 usb_client_.reset(new WebUSBClientImpl(device_services.Pass()));
3846 #endif
3847 return usb_client_.get();
3850 #if defined(ENABLE_WEBVR)
3851 blink::WebVRClient* RenderFrameImpl::webVRClient() {
3852 if (!vr_dispatcher_)
3853 vr_dispatcher_.reset(new VRDispatcher(GetServiceRegistry()));
3855 return vr_dispatcher_.get();
3857 #endif
3859 void RenderFrameImpl::DidPlay(WebMediaPlayer* player) {
3860 has_played_media_ = true;
3861 Send(new FrameHostMsg_MediaPlayingNotification(
3862 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3863 player->hasAudio(), player->isRemote()));
3866 void RenderFrameImpl::DidPause(WebMediaPlayer* player) {
3867 Send(new FrameHostMsg_MediaPausedNotification(
3868 routing_id_, reinterpret_cast<int64>(player)));
3871 void RenderFrameImpl::PlayerGone(WebMediaPlayer* player) {
3872 DidPause(player);
3875 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3876 observers_.AddObserver(observer);
3879 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3880 observer->RenderFrameGone();
3881 observers_.RemoveObserver(observer);
3884 void RenderFrameImpl::OnStop() {
3885 DCHECK(frame_);
3886 frame_->stopLoading();
3887 if (!frame_->parent())
3888 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3890 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3893 void RenderFrameImpl::WasHidden() {
3894 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3897 void RenderFrameImpl::WasShown() {
3898 // TODO(kenrb): Need to figure out how to do this better. Should
3899 // VisibilityState remain a page-level concept or move to frames?
3900 // The semantics of 'Show' might have to change here.
3901 if (render_widget_) {
3902 static_cast<blink::WebFrameWidget*>(render_widget_->webwidget())->
3903 setVisibilityState(blink::WebPageVisibilityStateVisible, false);
3905 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3908 void RenderFrameImpl::WidgetWillClose() {
3909 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WidgetWillClose());
3912 bool RenderFrameImpl::IsHidden() {
3913 return GetRenderWidget()->is_hidden();
3916 // Tell the embedding application that the URL of the active page has changed.
3917 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3918 blink::WebFrame* frame,
3919 blink::WebHistoryCommitType commit_type,
3920 const blink::WebHistoryItem& item) {
3921 DCHECK(!frame_ || frame_ == frame);
3922 WebDataSource* ds = frame->dataSource();
3923 DCHECK(ds);
3925 const WebURLRequest& request = ds->request();
3926 const WebURLResponse& response = ds->response();
3928 DocumentState* document_state = DocumentState::FromDataSource(ds);
3929 NavigationStateImpl* navigation_state =
3930 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3931 InternalDocumentStateData* internal_data =
3932 InternalDocumentStateData::FromDocumentState(document_state);
3934 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3935 params.http_status_code = response.httpStatusCode();
3936 params.url_is_unreachable = ds->hasUnreachableURL();
3937 params.is_post = false;
3938 params.intended_as_new_entry =
3939 navigation_state->request_params().intended_as_new_entry;
3940 params.did_create_new_entry = commit_type == blink::WebStandardCommit;
3941 params.post_id = -1;
3942 params.page_id = render_view_->page_id_;
3943 params.nav_entry_id = navigation_state->request_params().nav_entry_id;
3944 // We need to track the RenderViewHost routing_id because of downstream
3945 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3946 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3947 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3948 // based on the ID stored in the resource requests. Once those dependencies
3949 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3950 // client to be based on the routing_id of the RenderFrameHost.
3951 params.render_view_routing_id = render_view_->routing_id();
3952 params.socket_address.set_host(response.remoteIPAddress().utf8());
3953 params.socket_address.set_port(response.remotePort());
3954 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3955 if (extra_data)
3956 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3957 params.was_within_same_page = navigation_state->WasWithinSamePage();
3958 params.security_info = response.securityInfo();
3960 // Set the URL to be displayed in the browser UI to the user.
3961 params.url = GetLoadingUrl();
3962 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3964 // Set the origin of the frame. This will be replicated to the corresponding
3965 // RenderFrameProxies in other processes.
3966 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3967 // to https://crbug.com/439608 and will be replicated as unique origins.
3968 if (!is_swapped_out_) {
3969 std::string scheme = frame->document().securityOrigin().protocol().utf8();
3970 if (url::IsStandard(scheme.c_str(),
3971 url::Component(0, static_cast<int>(scheme.length())))) {
3972 params.origin = frame->document().securityOrigin();
3976 if (frame->document().baseURL() != params.url)
3977 params.base_url = frame->document().baseURL();
3979 GetRedirectChain(ds, &params.redirects);
3980 params.should_update_history = !ds->hasUnreachableURL() &&
3981 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3983 params.searchable_form_url = internal_data->searchable_form_url();
3984 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3986 params.gesture = render_view_->navigation_gesture_;
3987 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3989 // Make navigation state a part of the DidCommitProvisionalLoad message so
3990 // that committed entry has it at all times.
3991 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3992 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3993 if (entry)
3994 params.page_state = HistoryEntryToPageState(entry);
3995 else
3996 params.page_state = PageState::CreateFromURL(request.url());
3997 } else {
3998 // In --site-per-process, just send a single HistoryItem for this frame,
3999 // rather than the whole tree. It will be stored in the corresponding
4000 // FrameNavigationEntry.
4001 params.page_state = SingleHistoryItemToPageState(item);
4003 params.item_sequence_number = item.itemSequenceNumber();
4004 params.document_sequence_number = item.documentSequenceNumber();
4006 if (!frame->parent()) {
4007 // Top-level navigation.
4009 // Reset the zoom limits in case a plugin had changed them previously. This
4010 // will also call us back which will cause us to send a message to
4011 // update WebContentsImpl.
4012 render_view_->webview()->zoomLimitsChanged(
4013 ZoomFactorToZoomLevel(kMinimumZoomFactor),
4014 ZoomFactorToZoomLevel(kMaximumZoomFactor));
4016 // Set zoom level, but don't do it for full-page plugin since they don't use
4017 // the same zoom settings.
4018 HostZoomLevels::iterator host_zoom =
4019 render_view_->host_zoom_levels_.find(GURL(request.url()));
4020 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
4021 // Reset the zoom levels for plugins.
4022 render_view_->webview()->setZoomLevel(0);
4023 } else {
4024 // If the zoom level is not found, then do nothing. In-page navigation
4025 // relies on not changing the zoom level in this case.
4026 if (host_zoom != render_view_->host_zoom_levels_.end())
4027 render_view_->webview()->setZoomLevel(host_zoom->second);
4030 if (host_zoom != render_view_->host_zoom_levels_.end()) {
4031 // This zoom level was merely recorded transiently for this load. We can
4032 // erase it now. If at some point we reload this page, the browser will
4033 // send us a new, up-to-date zoom level.
4034 render_view_->host_zoom_levels_.erase(host_zoom);
4037 // Update contents MIME type for main frame.
4038 params.contents_mime_type = ds->response().mimeType().utf8();
4040 params.transition = navigation_state->GetTransitionType();
4041 if (!ui::PageTransitionIsMainFrame(params.transition)) {
4042 // If the main frame does a load, it should not be reported as a subframe
4043 // navigation. This can occur in the following case:
4044 // 1. You're on a site with frames.
4045 // 2. You do a subframe navigation. This is stored with transition type
4046 // MANUAL_SUBFRAME.
4047 // 3. You navigate to some non-frame site, say, google.com.
4048 // 4. You navigate back to the page from step 2. Since it was initially
4049 // MANUAL_SUBFRAME, it will be that same transition type here.
4050 // We don't want that, because any navigation that changes the toplevel
4051 // frame should be tracked as a toplevel navigation (this allows us to
4052 // update the URL bar, etc).
4053 params.transition = ui::PAGE_TRANSITION_LINK;
4056 // If the page contained a client redirect (meta refresh, document.loc...),
4057 // set the referrer and transition appropriately.
4058 if (ds->isClientRedirect()) {
4059 params.referrer =
4060 Referrer(params.redirects[0], ds->request().referrerPolicy());
4061 params.transition = ui::PageTransitionFromInt(
4062 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
4063 } else {
4064 params.referrer = RenderViewImpl::GetReferrerFromRequest(
4065 frame, ds->request());
4068 base::string16 method = request.httpMethod();
4069 if (base::EqualsASCII(method, "POST")) {
4070 params.is_post = true;
4071 params.post_id = ExtractPostId(entry);
4074 // Send the user agent override back.
4075 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
4077 // Track the URL of the original request. We use the first entry of the
4078 // redirect chain if it exists because the chain may have started in another
4079 // process.
4080 params.original_request_url = GetOriginalRequestURL(ds);
4082 params.history_list_was_cleared =
4083 navigation_state->request_params().should_clear_history_list;
4085 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
4086 frame->dataSource()->request().inputPerfMetricReportPolicy());
4087 params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD(
4088 frame->dataSource()->request().uiStartTime());
4090 // Save some histogram data so we can compute the average memory used per
4091 // page load of the glyphs.
4092 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4093 blink::WebGlyphCache::pageCount());
4095 // This message needs to be sent before any of allowScripts(),
4096 // allowImages(), allowPlugins() is called for the new page, so that when
4097 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4098 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4099 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4100 } else {
4101 // Subframe navigation: the type depends on whether this navigation
4102 // generated a new session history entry. When they do generate a session
4103 // history entry, it means the user initiated the navigation and we should
4104 // mark it as such.
4105 if (commit_type == blink::WebStandardCommit)
4106 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
4107 else
4108 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
4110 DCHECK(!navigation_state->request_params().should_clear_history_list);
4111 params.history_list_was_cleared = false;
4112 params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT;
4114 // Don't send this message while the subframe is swapped out.
4115 if (!is_swapped_out())
4116 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4119 // If we end up reusing this WebRequest (for example, due to a #ref click),
4120 // we don't want the transition type to persist. Just clear it.
4121 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
4124 void RenderFrameImpl::didStartLoading(bool to_different_document) {
4125 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4126 "id", routing_id_);
4127 render_view_->FrameDidStartLoading(frame_);
4128 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
4131 void RenderFrameImpl::didStopLoading() {
4132 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4133 "id", routing_id_);
4134 render_view_->FrameDidStopLoading(frame_);
4135 Send(new FrameHostMsg_DidStopLoading(routing_id_));
4138 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
4139 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
4142 void RenderFrameImpl::HandleWebAccessibilityEvent(
4143 const blink::WebAXObject& obj, blink::WebAXEvent event) {
4144 if (renderer_accessibility_)
4145 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
4148 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
4149 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FocusedNodeChanged(node));
4152 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) {
4153 if (renderer_accessibility())
4154 renderer_accessibility()->AccessibilityFocusedNodeChanged(node);
4157 // PlzNavigate
4158 void RenderFrameImpl::OnCommitNavigation(
4159 const ResourceResponseHead& response,
4160 const GURL& stream_url,
4161 const CommonNavigationParams& common_params,
4162 const RequestNavigationParams& request_params) {
4163 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4164 switches::kEnableBrowserSideNavigation));
4165 // This will override the url requested by the WebURLLoader, as well as
4166 // provide it with the response to the request.
4167 scoped_ptr<StreamOverrideParameters> stream_override(
4168 new StreamOverrideParameters());
4169 stream_override->stream_url = stream_url;
4170 stream_override->response = response;
4172 NavigateInternal(common_params, StartNavigationParams(), request_params,
4173 stream_override.Pass());
4176 void RenderFrameImpl::OnFailedNavigation(
4177 const CommonNavigationParams& common_params,
4178 const RequestNavigationParams& request_params,
4179 bool has_stale_copy_in_cache,
4180 int error_code) {
4181 bool is_reload = IsReload(common_params.navigation_type);
4182 bool is_history_navigation = request_params.page_state.IsValid();
4183 WebURLRequest::CachePolicy cache_policy =
4184 WebURLRequest::UseProtocolCachePolicy;
4185 RenderFrameImpl::PrepareRenderViewForNavigation(
4186 common_params.url, request_params, &is_reload, &cache_policy);
4188 GetContentClient()->SetActiveURL(common_params.url);
4190 pending_navigation_params_.reset(new NavigationParams(
4191 common_params, StartNavigationParams(), request_params));
4193 // Inform the browser of the start of the provisional load. This is needed so
4194 // that the load is properly tracked by the WebNavigation API.
4195 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4196 routing_id_, common_params.url));
4198 // Send the provisional load failure.
4199 blink::WebURLError error =
4200 CreateWebURLError(common_params.url, has_stale_copy_in_cache, error_code);
4201 WebURLRequest failed_request = CreateURLRequestForNavigation(
4202 common_params, scoped_ptr<StreamOverrideParameters>(),
4203 frame_->isViewSourceModeEnabled());
4204 SendFailedProvisionalLoad(failed_request, error, frame_);
4206 if (!ShouldDisplayErrorPageForFailedLoad(error_code, common_params.url)) {
4207 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4208 // http://crbug.com/501960
4209 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4210 return;
4213 // Make sure errors are not shown in view source mode.
4214 frame_->enableViewSourceMode(false);
4216 // Replace the current history entry in reloads, history navigations and loads
4217 // of the same url. This corresponds to Blink's notion of a standard
4218 // commit.
4219 // TODO(clamy): see if initial commits in subframes should be handled
4220 // separately.
4221 bool replace = is_reload || is_history_navigation ||
4222 common_params.url == GetLoadingUrl();
4223 LoadNavigationErrorPage(failed_request, error, replace);
4226 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
4227 RenderFrame* render_frame,
4228 const NavigationPolicyInfo& info) {
4229 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
4230 info.urlRequest));
4232 // TODO(nick): Is consulting |is_subframe_| here correct?
4233 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_) {
4234 // There's no reason to ignore navigations on subframes, since the swap out
4235 // logic no longer applies.
4236 } else {
4237 if (is_swapped_out_) {
4238 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
4239 // Targeted links may try to navigate a swapped out frame. Allow the
4240 // browser process to navigate the tab instead. Note that it is also
4241 // possible for non-targeted navigations (from this view) to arrive
4242 // here just after we are swapped out. It's ok to send them to the
4243 // browser, as long as they're for the top level frame.
4244 // TODO(creis): Ensure this supports targeted form submissions when
4245 // fixing http://crbug.com/101395.
4246 if (info.frame->parent() == NULL) {
4247 OpenURL(info.frame, info.urlRequest.url(), referrer,
4248 info.defaultPolicy);
4249 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4252 // We should otherwise ignore in-process iframe navigations, if they
4253 // arrive just after we are swapped out.
4254 return blink::WebNavigationPolicyIgnore;
4257 // Allow kSwappedOutURL to complete.
4258 return info.defaultPolicy;
4262 // Webkit is asking whether to navigate to a new URL.
4263 // This is fine normally, except if we're showing UI from one security
4264 // context and they're trying to navigate to a different context.
4265 const GURL& url = info.urlRequest.url();
4267 // A content initiated navigation may have originated from a link-click,
4268 // script, drag-n-drop operation, etc.
4269 DocumentState* document_state = static_cast<DocumentState*>(info.extraData);
4270 bool is_content_initiated =
4271 document_state->navigation_state()->IsContentInitiated();
4273 // If the browser is interested, then give it a chance to look at the request.
4274 if (is_content_initiated) {
4275 bool is_form_post =
4276 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
4277 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
4278 base::EqualsASCII(base::StringPiece16(info.urlRequest.httpMethod()),
4279 "POST");
4280 bool browser_handles_request =
4281 render_view_->renderer_preferences_
4282 .browser_handles_non_local_top_level_requests
4283 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
4284 is_form_post);
4285 if (!browser_handles_request) {
4286 browser_handles_request = IsTopLevelNavigation(info.frame) &&
4287 render_view_->renderer_preferences_
4288 .browser_handles_all_top_level_requests;
4291 if (browser_handles_request) {
4292 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4293 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4297 // Use the frame's original request's URL rather than the document's URL for
4298 // subsequent checks. For a popup, the document's URL may become the opener
4299 // window's URL if the opener has called document.write().
4300 // See http://crbug.com/93517.
4301 GURL old_url(info.frame->dataSource()->request().url());
4303 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4304 // an extension or app origin, leaving a WebUI page, etc). We only care about
4305 // top-level navigations (not iframes). But we sometimes navigate to
4306 // about:blank to clear a tab, and we want to still allow that.
4308 // Note: this is known to break POST submissions when crossing process
4309 // boundaries until http://crbug.com/101395 is fixed. This is better for
4310 // security than loading a WebUI, extension or app page in the wrong process.
4311 // POST requests don't work because this mechanism does not preserve form
4312 // POST data. We will need to send the request's httpBody data up to the
4313 // browser process, and issue a special POST navigation in WebKit (via
4314 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4315 // for examples of how to send the httpBody data.
4316 if (!info.frame->parent() && is_content_initiated &&
4317 !url.SchemeIs(url::kAboutScheme)) {
4318 bool send_referrer = false;
4320 // All navigations to or from WebUI URLs or within WebUI-enabled
4321 // RenderProcesses must be handled by the browser process so that the
4322 // correct bindings and data sources can be registered.
4323 // Similarly, navigations to view-source URLs or within ViewSource mode
4324 // must be handled by the browser process (except for reloads - those are
4325 // safe to leave within the renderer).
4326 // Lastly, access to file:// URLs from non-file:// URL pages must be
4327 // handled by the browser so that ordinary renderer processes don't get
4328 // blessed with file permissions.
4329 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
4330 bool is_initial_navigation = render_view_->history_list_length_ == 0;
4331 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
4332 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
4333 url.SchemeIs(kViewSourceScheme) ||
4334 (info.frame->isViewSourceModeEnabled() &&
4335 info.navigationType != blink::WebNavigationTypeReload);
4337 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
4338 // Fork non-file to file opens. Check the opener URL if this is the
4339 // initial navigation in a newly opened window.
4340 GURL source_url(old_url);
4341 if (is_initial_navigation && source_url.is_empty() &&
4342 info.frame->opener())
4343 source_url = info.frame->opener()->top()->document().url();
4344 DCHECK(!source_url.is_empty());
4345 should_fork = !source_url.SchemeIs(url::kFileScheme);
4348 if (!should_fork) {
4349 // Give the embedder a chance.
4350 should_fork = GetContentClient()->renderer()->ShouldFork(
4351 info.frame, url, info.urlRequest.httpMethod().utf8(),
4352 is_initial_navigation, info.isRedirect, &send_referrer);
4355 if (should_fork) {
4356 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
4357 info.defaultPolicy);
4358 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4362 // Detect when a page is "forking" a new tab that can be safely rendered in
4363 // its own process. This is done by sites like Gmail that try to open links
4364 // in new windows without script connections back to the original page. We
4365 // treat such cases as browser navigations (in which we will create a new
4366 // renderer for a cross-site navigation), rather than WebKit navigations.
4368 // We use the following heuristic to decide whether to fork a new page in its
4369 // own process:
4370 // The parent page must open a new tab to about:blank, set the new tab's
4371 // window.opener to null, and then redirect the tab to a cross-site URL using
4372 // JavaScript.
4374 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4375 // (see below).
4376 bool is_fork =
4377 // Must start from a tab showing about:blank, which is later redirected.
4378 old_url == GURL(url::kAboutBlankURL) &&
4379 // Must be the first real navigation of the tab.
4380 render_view_->historyBackListCount() < 1 &&
4381 render_view_->historyForwardListCount() < 1 &&
4382 // The parent page must have set the child's window.opener to null before
4383 // redirecting to the desired URL.
4384 info.frame->opener() == NULL &&
4385 // Must be a top-level frame.
4386 info.frame->parent() == NULL &&
4387 // Must not have issued the request from this page.
4388 is_content_initiated &&
4389 // Must be targeted at the current tab.
4390 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
4391 // Must be a JavaScript navigation, which appears as "other".
4392 info.navigationType == blink::WebNavigationTypeOther;
4394 if (is_fork) {
4395 // Open the URL via the browser, not via WebKit.
4396 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
4397 return blink::WebNavigationPolicyIgnore;
4400 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4401 // This includes navigations with no request being sent to the network stack.
4402 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4403 switches::kEnableBrowserSideNavigation) &&
4404 info.urlRequest.checkForBrowserSideNavigation() &&
4405 ShouldMakeNetworkRequestForURL(url)) {
4406 BeginNavigation(&info.urlRequest);
4407 return blink::WebNavigationPolicyIgnore;
4410 return info.defaultPolicy;
4413 void RenderFrameImpl::OpenURL(WebFrame* frame,
4414 const GURL& url,
4415 const Referrer& referrer,
4416 WebNavigationPolicy policy) {
4417 DCHECK_EQ(frame_, frame);
4419 FrameHostMsg_OpenURL_Params params;
4420 params.url = url;
4421 params.referrer = referrer;
4422 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
4423 WebDataSource* ds = frame->provisionalDataSource();
4424 if (ds) {
4425 DocumentState* document_state = DocumentState::FromDataSource(ds);
4426 NavigationStateImpl* navigation_state =
4427 static_cast<NavigationStateImpl*>(document_state->navigation_state());
4428 if (navigation_state->IsContentInitiated()) {
4429 params.should_replace_current_entry =
4430 ds->replacesCurrentHistoryItem() &&
4431 render_view_->history_list_length_;
4432 } else {
4433 // This is necessary to preserve the should_replace_current_entry value on
4434 // cross-process redirects, in the event it was set by a previous process.
4436 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4437 // NavigationState::should_replace_current_entry().
4438 params.should_replace_current_entry =
4439 navigation_state->common_params().should_replace_current_entry;
4441 } else {
4442 params.should_replace_current_entry = false;
4444 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
4445 if (GetContentClient()->renderer()->AllowPopup())
4446 params.user_gesture = true;
4448 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
4449 policy == blink::WebNavigationPolicyNewForegroundTab ||
4450 policy == blink::WebNavigationPolicyNewWindow ||
4451 policy == blink::WebNavigationPolicyNewPopup) {
4452 WebUserGestureIndicator::consumeUserGesture();
4455 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4458 void RenderFrameImpl::NavigateInternal(
4459 const CommonNavigationParams& common_params,
4460 const StartNavigationParams& start_params,
4461 const RequestNavigationParams& request_params,
4462 scoped_ptr<StreamOverrideParameters> stream_params) {
4463 bool browser_side_navigation =
4464 base::CommandLine::ForCurrentProcess()->HasSwitch(
4465 switches::kEnableBrowserSideNavigation);
4466 bool is_reload = IsReload(common_params.navigation_type);
4467 bool is_history_navigation = request_params.page_state.IsValid();
4468 WebURLRequest::CachePolicy cache_policy =
4469 WebURLRequest::UseProtocolCachePolicy;
4470 RenderFrameImpl::PrepareRenderViewForNavigation(
4471 common_params.url, request_params, &is_reload, &cache_policy);
4473 GetContentClient()->SetActiveURL(common_params.url);
4475 // If this frame isn't in the same process as the main frame, it may naively
4476 // assume that this is the first navigation in the iframe, but this may not
4477 // actually be the case. Inform the frame's state machine if this frame has
4478 // already committed other loads.
4479 if (request_params.has_committed_real_load && frame_->parent())
4480 frame_->setCommittedFirstRealLoad();
4482 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
4483 // We cannot reload if we do not have any history state. This happens, for
4484 // example, when recovering from a crash.
4485 is_reload = false;
4486 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4489 pending_navigation_params_.reset(
4490 new NavigationParams(common_params, start_params, request_params));
4492 // Create parameters for a standard navigation.
4493 blink::WebFrameLoadType load_type = blink::WebFrameLoadType::Standard;
4494 bool should_load_request = false;
4495 WebHistoryItem item_for_history_navigation;
4496 WebURLRequest request = CreateURLRequestForNavigation(
4497 common_params, stream_params.Pass(), frame_->isViewSourceModeEnabled());
4498 #if defined(OS_ANDROID)
4499 request.setHasUserGesture(start_params.has_user_gesture);
4500 #endif
4502 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4503 // navigation for this request (since it already went to the browser).
4504 if (browser_side_navigation)
4505 request.setCheckForBrowserSideNavigation(false);
4507 // If we are reloading, then use the history state of the current frame.
4508 // Otherwise, if we have history state, then we need to navigate to it, which
4509 // corresponds to a back/forward navigation event. Update the parameters
4510 // depending on the navigation type.
4511 if (is_reload) {
4512 bool ignore_cache = (common_params.navigation_type ==
4513 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
4514 load_type = ignore_cache ? blink::WebFrameLoadType::ReloadFromOrigin
4515 : blink::WebFrameLoadType::Reload;
4517 if (!browser_side_navigation) {
4518 const GURL override_url =
4519 (common_params.navigation_type ==
4520 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL)
4521 ? common_params.url
4522 : GURL();
4523 request = frame_->requestForReload(load_type, override_url);
4525 should_load_request = true;
4526 } else if (is_history_navigation) {
4527 // We must know the page ID of the page we are navigating back to.
4528 DCHECK_NE(request_params.page_id, -1);
4529 // We must know the nav entry ID of the page we are navigating back to,
4530 // which should be the case because history navigations are routed via the
4531 // browser.
4532 DCHECK_NE(0, request_params.nav_entry_id);
4533 scoped_ptr<HistoryEntry> entry =
4534 PageStateToHistoryEntry(request_params.page_state);
4535 if (entry) {
4536 // Ensure we didn't save the swapped out URL in UpdateState, since the
4537 // browser should never be telling us to navigate to swappedout://.
4538 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
4540 if (!browser_side_navigation) {
4541 scoped_ptr<NavigationParams> navigation_params(
4542 new NavigationParams(*pending_navigation_params_.get()));
4543 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4544 // By default, tell the HistoryController to go the deserialized
4545 // HistoryEntry. This only works if all frames are in the same
4546 // process.
4547 DCHECK(!frame_->parent());
4548 render_view_->history_controller()->GoToEntry(
4549 frame_, entry.Pass(), navigation_params.Pass(), cache_policy);
4550 } else {
4551 // In --site-per-process, the browser process sends a single
4552 // WebHistoryItem destined for this frame.
4553 // TODO(creis): Change PageState to FrameState. In the meantime, we
4554 // store the relevant frame's WebHistoryItem in the root of the
4555 // PageState.
4556 SetPendingNavigationParams(navigation_params.Pass());
4557 blink::WebHistoryItem history_item = entry->root();
4558 blink::WebHistoryLoadType load_type =
4559 request_params.is_same_document_history_load
4560 ? blink::WebHistorySameDocumentLoad
4561 : blink::WebHistoryDifferentDocumentLoad;
4563 // Let the history controller know the provisional entry, since it is
4564 // used at commit time. Otherwise skip GoToEntry and navigate the
4565 // frame directly.
4566 // TODO(creis): Consider cloning the current entry to handle subframe
4567 // cases. Changes to SendUpdateState might affect this.
4568 render_view_->history_controller()->set_provisional_entry(
4569 entry.Pass());
4570 WebURLRequest request =
4571 frame_->requestFromHistoryItem(history_item, cache_policy);
4572 frame_->load(request, blink::WebFrameLoadType::BackForward,
4573 history_item, load_type);
4575 } else {
4576 // TODO(clamy): this should be set to the HistoryItem sent by the
4577 // browser once the HistoryController has moved to the browser.
4578 // TODO(clamy): distinguish between different document and same document
4579 // loads.
4580 // TODO(clamy): update this for subframes history loads.
4581 item_for_history_navigation =
4582 entry->GetHistoryNodeForFrame(this)->item();
4583 load_type = blink::WebFrameLoadType::BackForward;
4584 should_load_request = true;
4587 } else {
4588 // Navigate to the given URL.
4589 if (!start_params.extra_headers.empty() && !browser_side_navigation) {
4590 for (net::HttpUtil::HeadersIterator i(start_params.extra_headers.begin(),
4591 start_params.extra_headers.end(),
4592 "\n");
4593 i.GetNext();) {
4594 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
4595 WebString::fromUTF8(i.values()));
4599 if (start_params.is_post && !browser_side_navigation) {
4600 request.setHTTPMethod(WebString::fromUTF8("POST"));
4602 // Set post data.
4603 WebHTTPBody http_body;
4604 http_body.initialize();
4605 const char* data = nullptr;
4606 if (start_params.browser_initiated_post_data.size()) {
4607 data = reinterpret_cast<const char*>(
4608 &start_params.browser_initiated_post_data.front());
4610 http_body.appendData(
4611 WebData(data, start_params.browser_initiated_post_data.size()));
4612 request.setHTTPBody(http_body);
4615 // A session history navigation should have been accompanied by state.
4616 CHECK_EQ(request_params.page_id, -1);
4618 should_load_request = true;
4621 if (should_load_request) {
4622 // Record this before starting the load. We need a lower bound of this
4623 // time to sanitize the navigationStart override set below.
4624 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
4626 // Perform a navigation to a data url if needed.
4627 if (!common_params.base_url_for_data_url.is_empty() ||
4628 (browser_side_navigation &&
4629 common_params.url.SchemeIs(url::kDataScheme))) {
4630 LoadDataURL(common_params, frame_);
4631 } else {
4632 // Load the request.
4633 frame_->toWebLocalFrame()->load(request, load_type,
4634 item_for_history_navigation);
4637 if (load_type == blink::WebFrameLoadType::Standard) {
4638 UpdateFrameNavigationTiming(frame_,
4639 request_params.browser_navigation_start,
4640 renderer_navigation_start);
4644 // In case LoadRequest failed before didCreateDataSource was called.
4645 pending_navigation_params_.reset();
4648 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4649 const std::string& encoding_name) {
4650 // Only update main frame's encoding_name.
4651 if (!frame->parent())
4652 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4655 void RenderFrameImpl::SyncSelectionIfRequired() {
4656 base::string16 text;
4657 size_t offset;
4658 gfx::Range range;
4659 #if defined(ENABLE_PLUGINS)
4660 if (render_view_->focused_pepper_plugin_) {
4661 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4662 offset = 0; // Pepper API does not support offset reporting.
4663 // TODO(kinaba): cut as needed.
4664 } else
4665 #endif
4667 size_t location, length;
4668 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4669 &location, &length)) {
4670 return;
4673 range = gfx::Range(location, location + length);
4675 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4676 blink::WebTextInputTypeNone) {
4677 // If current focused element is editable, we will send 100 more chars
4678 // before and after selection. It is for input method surrounding text
4679 // feature.
4680 if (location > kExtraCharsBeforeAndAfterSelection)
4681 offset = location - kExtraCharsBeforeAndAfterSelection;
4682 else
4683 offset = 0;
4684 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4685 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4686 if (!webrange.isNull())
4687 text = webrange.toPlainText();
4688 } else {
4689 offset = location;
4690 text = frame_->selectionAsText();
4691 // http://crbug.com/101435
4692 // In some case, frame->selectionAsText() returned text's length is not
4693 // equal to the length returned from webwidget()->caretOrSelectionRange().
4694 // So we have to set the range according to text.length().
4695 range.set_end(range.start() + text.length());
4699 // Sometimes we get repeated didChangeSelection calls from webkit when
4700 // the selection hasn't actually changed. We don't want to report these
4701 // because it will cause us to continually claim the X clipboard.
4702 if (selection_text_offset_ != offset ||
4703 selection_range_ != range ||
4704 selection_text_ != text) {
4705 selection_text_ = text;
4706 selection_text_offset_ = offset;
4707 selection_range_ = range;
4708 SetSelectedText(text, offset, range);
4710 GetRenderWidget()->UpdateSelectionBounds();
4713 void RenderFrameImpl::InitializeUserMediaClient() {
4714 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4715 return;
4717 #if defined(ENABLE_WEBRTC)
4718 DCHECK(!web_user_media_client_);
4719 web_user_media_client_ = new UserMediaClientImpl(
4720 this,
4721 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4722 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4723 #endif
4726 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4727 WebMediaPlayerClient* client) {
4728 #if defined(ENABLE_WEBRTC)
4729 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4730 bool found_neon =
4731 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4732 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4733 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4734 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4735 new RenderMediaLog(),
4736 CreateRendererFactory());
4737 #else
4738 return NULL;
4739 #endif // defined(ENABLE_WEBRTC)
4742 scoped_ptr<MediaStreamRendererFactory>
4743 RenderFrameImpl::CreateRendererFactory() {
4744 scoped_ptr<MediaStreamRendererFactory> factory =
4745 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4746 if (factory.get())
4747 return factory.Pass();
4748 #if defined(ENABLE_WEBRTC)
4749 return scoped_ptr<MediaStreamRendererFactory>(
4750 new MediaStreamRendererFactoryImpl());
4751 #else
4752 return scoped_ptr<MediaStreamRendererFactory>(
4753 static_cast<MediaStreamRendererFactory*>(NULL));
4754 #endif
4757 void RenderFrameImpl::PrepareRenderViewForNavigation(
4758 const GURL& url,
4759 const RequestNavigationParams& request_params,
4760 bool* is_reload,
4761 WebURLRequest::CachePolicy* cache_policy) {
4762 DCHECK(render_view_->webview());
4764 MaybeHandleDebugURL(url);
4766 FOR_EACH_OBSERVER(
4767 RenderViewObserver, render_view_->observers_, Navigate(url));
4769 render_view_->history_list_offset_ =
4770 request_params.current_history_list_offset;
4771 render_view_->history_list_length_ =
4772 request_params.current_history_list_length;
4773 if (request_params.should_clear_history_list) {
4774 CHECK_EQ(-1, render_view_->history_list_offset_);
4775 CHECK_EQ(0, render_view_->history_list_length_);
4778 if (!is_swapped_out_ || frame_->parent())
4779 return;
4781 // This is a swapped out main frame, so swap the renderer back in.
4782 // We marked the view as hidden when swapping the view out, so be sure to
4783 // reset the visibility state before navigating to the new URL.
4784 render_view_->webview()->setVisibilityState(
4785 render_view_->visibilityState(), false);
4787 // If this is an attempt to reload while we are swapped out, we should not
4788 // reload swappedout://, but the previous page, which is stored in
4789 // params.state. Setting is_reload to false will treat this like a back
4790 // navigation to accomplish that.
4791 *is_reload = false;
4792 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4794 // We refresh timezone when a view is swapped in since timezone
4795 // can get out of sync when the system timezone is updated while
4796 // the view is swapped out.
4797 RenderThreadImpl::NotifyTimezoneChange();
4799 render_view_->SetSwappedOut(false);
4800 is_swapped_out_ = false;
4801 return;
4804 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4805 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4806 switches::kEnableBrowserSideNavigation));
4807 DCHECK(request);
4808 // TODO(clamy): Execute the beforeunload event.
4810 // Note: At this stage, the goal is to apply all the modifications the
4811 // renderer wants to make to the request, and then send it to the browser, so
4812 // that the actual network request can be started. Ideally, all such
4813 // modifications should take place in willSendRequest, and in the
4814 // implementation of willSendRequest for the various InspectorAgents
4815 // (devtools).
4817 // TODO(clamy): Apply devtools override.
4818 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4819 // else in blink.
4820 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4822 // TODO(clamy): Same-document navigations should not be sent back to the
4823 // browser.
4824 // TODO(clamy): Data urls should not be sent back to the browser either.
4825 bool should_replace_current_entry = false;
4826 WebDataSource* provisional_data_source = frame_->provisionalDataSource();
4827 WebDataSource* current_data_source = frame_->dataSource();
4828 WebDataSource* data_source =
4829 provisional_data_source ? provisional_data_source : current_data_source;
4831 // The current entry can only be replaced if there already is an entry in the
4832 // history list.
4833 if (data_source && render_view_->history_list_length_ > 0) {
4834 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
4836 Send(new FrameHostMsg_BeginNavigation(
4837 routing_id_,
4838 MakeCommonNavigationParams(request, should_replace_current_entry),
4839 BeginNavigationParams(
4840 request->httpMethod().latin1(), GetWebURLRequestHeaders(*request),
4841 GetLoadFlagsForWebURLRequest(*request), request->hasUserGesture()),
4842 GetRequestBodyForWebURLRequest(*request)));
4845 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams& params,
4846 WebFrame* frame) {
4847 // A loadData request with a specified base URL.
4848 std::string mime_type, charset, data;
4849 if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) {
4850 const GURL base_url = params.base_url_for_data_url.is_empty() ?
4851 params.url : params.base_url_for_data_url;
4852 frame->loadData(
4853 WebData(data.c_str(), data.length()),
4854 WebString::fromUTF8(mime_type),
4855 WebString::fromUTF8(charset),
4856 base_url,
4857 params.history_url_for_data_url,
4858 false);
4859 } else {
4860 CHECK(false) << "Invalid URL passed: "
4861 << params.url.possibly_invalid_spec();
4865 void RenderFrameImpl::SendFailedProvisionalLoad(
4866 const blink::WebURLRequest& request,
4867 const blink::WebURLError& error,
4868 blink::WebLocalFrame* frame) {
4869 bool show_repost_interstitial =
4870 (error.reason == net::ERR_CACHE_MISS &&
4871 base::EqualsASCII(base::StringPiece16(request.httpMethod()), "POST"));
4873 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
4874 params.error_code = error.reason;
4875 GetContentClient()->renderer()->GetNavigationErrorStrings(
4876 render_view_.get(), frame, request, error, NULL,
4877 &params.error_description);
4878 params.url = error.unreachableURL;
4879 params.showing_repost_interstitial = show_repost_interstitial;
4880 params.was_ignored_by_handler = error.wasIgnoredByHandler;
4881 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_, params));
4884 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4885 int error_code,
4886 const GURL& unreachable_url) {
4887 // Don't display an error page if this is simply a cancelled load. Aside
4888 // from being dumb, Blink doesn't expect it and it will cause a crash.
4889 if (error_code == net::ERR_ABORTED)
4890 return false;
4892 // Don't display "client blocked" error page if browser has asked us not to.
4893 if (error_code == net::ERR_BLOCKED_BY_CLIENT &&
4894 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
4895 return false;
4898 // Allow the embedder to suppress an error page.
4899 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4900 this, unreachable_url)) {
4901 return false;
4904 if (RenderThreadImpl::current() &&
4905 RenderThreadImpl::current()->layout_test_mode()) {
4906 return false;
4909 return true;
4912 GURL RenderFrameImpl::GetLoadingUrl() const {
4913 WebDataSource* ds = frame_->dataSource();
4914 if (ds->hasUnreachableURL())
4915 return ds->unreachableURL();
4917 const WebURLRequest& request = ds->request();
4918 return request.url();
4921 void RenderFrameImpl::PopulateDocumentStateFromPending(
4922 DocumentState* document_state) {
4923 document_state->set_request_time(
4924 pending_navigation_params_->request_params.request_time);
4926 InternalDocumentStateData* internal_data =
4927 InternalDocumentStateData::FromDocumentState(document_state);
4929 if (!pending_navigation_params_->common_params.url.SchemeIs(
4930 url::kJavaScriptScheme) &&
4931 pending_navigation_params_->common_params.navigation_type ==
4932 FrameMsg_Navigate_Type::RESTORE) {
4933 // We're doing a load of a page that was restored from the last session. By
4934 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4935 // can result in stale data for pages that are set to expire. We explicitly
4936 // override that by setting the policy here so that as necessary we load
4937 // from the network.
4939 // TODO(davidben): Remove this in favor of passing a cache policy to the
4940 // loadHistoryItem call in OnNavigate. That requires not overloading
4941 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4942 // policy based on load type, etc".
4943 internal_data->set_cache_policy_override(
4944 WebURLRequest::UseProtocolCachePolicy);
4947 if (IsReload(pending_navigation_params_->common_params.navigation_type))
4948 document_state->set_load_type(DocumentState::RELOAD);
4949 else if (pending_navigation_params_->request_params.page_state.IsValid())
4950 document_state->set_load_type(DocumentState::HISTORY_LOAD);
4951 else
4952 document_state->set_load_type(DocumentState::NORMAL_LOAD);
4954 internal_data->set_is_overriding_user_agent(
4955 pending_navigation_params_->request_params.is_overriding_user_agent);
4956 internal_data->set_must_reset_scroll_and_scale_state(
4957 pending_navigation_params_->common_params.navigation_type ==
4958 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
4959 document_state->set_can_load_local_resources(
4960 pending_navigation_params_->request_params.can_load_local_resources);
4963 NavigationState* RenderFrameImpl::CreateNavigationStateFromPending() {
4964 // A navigation resulting from loading a javascript URL should not be treated
4965 // as a browser initiated event. Instead, we want it to look as if the page
4966 // initiated any load resulting from JS execution.
4967 if (!pending_navigation_params_->common_params.url.SchemeIs(
4968 url::kJavaScriptScheme)) {
4969 return NavigationStateImpl::CreateBrowserInitiated(
4970 pending_navigation_params_->common_params,
4971 pending_navigation_params_->start_params,
4972 pending_navigation_params_->request_params);
4974 return NavigationStateImpl::CreateContentInitiated();
4977 #if defined(OS_ANDROID)
4978 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4979 WebMediaPlayerClient* client,
4980 WebMediaPlayerEncryptedMediaClient* encrypted_client,
4981 const media::WebMediaPlayerParams& params) {
4982 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4983 if (SynchronousCompositorFactory* factory =
4984 SynchronousCompositorFactory::GetInstance()) {
4985 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4986 } else {
4987 GpuChannelHost* gpu_channel_host =
4988 RenderThreadImpl::current()->EstablishGpuChannelSync(
4989 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4991 if (!gpu_channel_host) {
4992 LOG(ERROR) << "Failed to establish GPU channel for media player";
4993 return NULL;
4996 scoped_refptr<cc_blink::ContextProviderWebContext> context_provider =
4997 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4999 if (!context_provider.get()) {
5000 LOG(ERROR) << "Failed to get context3d for media player";
5001 return NULL;
5004 stream_texture_factory = StreamTextureFactoryImpl::Create(
5005 context_provider, gpu_channel_host, routing_id_);
5008 return new WebMediaPlayerAndroid(
5009 frame_, client, encrypted_client, weak_factory_.GetWeakPtr(),
5010 GetMediaPlayerManager(), GetCdmFactory(), stream_texture_factory, params);
5013 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
5014 if (!media_player_manager_)
5015 media_player_manager_ = new RendererMediaPlayerManager(this);
5016 return media_player_manager_;
5018 #endif // defined(OS_ANDROID)
5020 media::MediaPermission* RenderFrameImpl::GetMediaPermission() {
5021 if (!media_permission_dispatcher_)
5022 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
5023 return media_permission_dispatcher_;
5026 #if defined(ENABLE_MOJO_MEDIA)
5027 media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() {
5028 if (!media_service_factory_) {
5029 mojo::ServiceProviderPtr service_provider =
5030 ConnectToApplication(GURL("mojo:media"));
5031 mojo::ConnectToService(service_provider.get(), &media_service_factory_);
5032 media_service_factory_.set_connection_error_handler(
5033 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError,
5034 base::Unretained(this)));
5037 return media_service_factory_.get();
5040 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5041 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5042 // violation on the old |media_service_factory_| by outstanding
5043 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5044 // this.
5045 // media_service_factory_.reset();
5047 #endif
5049 bool RenderFrameImpl::AreSecureCodecsSupported() {
5050 #if defined(OS_ANDROID)
5051 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5052 return render_view_->renderer_preferences_
5053 .use_video_overlay_for_embedded_encrypted_video;
5054 #else
5055 return false;
5056 #endif // defined(OS_ANDROID)
5059 media::CdmFactory* RenderFrameImpl::GetCdmFactory() {
5060 #if defined(ENABLE_BROWSER_CDMS)
5061 if (!cdm_manager_)
5062 cdm_manager_ = new RendererCdmManager(this);
5063 #endif // defined(ENABLE_BROWSER_CDMS)
5065 if (!cdm_factory_) {
5066 DCHECK(frame_);
5068 #if defined(ENABLE_MOJO_MEDIA)
5069 cdm_factory_.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5070 #else
5071 cdm_factory_.reset(new RenderCdmFactory(
5072 #if defined(ENABLE_PEPPER_CDMS)
5073 base::Bind(&PepperCdmWrapperImpl::Create, frame_)
5074 #elif defined(ENABLE_BROWSER_CDMS)
5075 cdm_manager_
5076 #endif
5078 #endif // defined(ENABLE_MOJO_MEDIA)
5081 return cdm_factory_.get();
5084 void RenderFrameImpl::RegisterMojoServices() {
5085 // Only main frame have ImageDownloader service.
5086 if (!frame_->parent()) {
5087 GetServiceRegistry()->AddService<image_downloader::ImageDownloader>(
5088 base::Bind(&ImageDownloaderImpl::CreateMojoService,
5089 base::Unretained(this)));
5093 mojo::ServiceProviderPtr RenderFrameImpl::ConnectToApplication(
5094 const GURL& url) {
5095 DCHECK(mojo_shell_);
5096 mojo::ServiceProviderPtr service_provider;
5097 mojo::URLRequestPtr request(mojo::URLRequest::New());
5098 request->url = mojo::String::From(url);
5099 mojo_shell_->ConnectToApplication(request.Pass(), GetProxy(&service_provider),
5100 nullptr, nullptr,
5101 base::Bind(&OnGotContentHandlerID));
5102 return service_provider.Pass();
5105 } // namespace content