Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blobce8141951a33d01c60ae6ff4b320cd437e6a992f
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 "components/scheduler/renderer/renderer_scheduler.h"
24 #include "content/child/appcache/appcache_dispatcher.h"
25 #include "content/child/permissions/permission_dispatcher.h"
26 #include "content/child/plugin_messages.h"
27 #include "content/child/quota_dispatcher.h"
28 #include "content/child/request_extra_data.h"
29 #include "content/child/service_worker/service_worker_handle_reference.h"
30 #include "content/child/service_worker/service_worker_network_provider.h"
31 #include "content/child/service_worker/service_worker_provider_context.h"
32 #include "content/child/service_worker/web_service_worker_provider_impl.h"
33 #include "content/child/v8_value_converter_impl.h"
34 #include "content/child/web_url_loader_impl.h"
35 #include "content/child/web_url_request_util.h"
36 #include "content/child/webmessageportchannel_impl.h"
37 #include "content/child/websocket_bridge.h"
38 #include "content/child/weburlresponse_extradata_impl.h"
39 #include "content/common/accessibility_messages.h"
40 #include "content/common/clipboard_messages.h"
41 #include "content/common/frame_messages.h"
42 #include "content/common/frame_replication_state.h"
43 #include "content/common/input_messages.h"
44 #include "content/common/navigation_params.h"
45 #include "content/common/service_worker/service_worker_types.h"
46 #include "content/common/site_isolation_policy.h"
47 #include "content/common/swapped_out_messages.h"
48 #include "content/common/view_messages.h"
49 #include "content/public/common/bindings_policy.h"
50 #include "content/public/common/content_constants.h"
51 #include "content/public/common/content_switches.h"
52 #include "content/public/common/context_menu_params.h"
53 #include "content/public/common/isolated_world_ids.h"
54 #include "content/public/common/page_state.h"
55 #include "content/public/common/resource_response.h"
56 #include "content/public/common/url_constants.h"
57 #include "content/public/common/url_utils.h"
58 #include "content/public/renderer/browser_plugin_delegate.h"
59 #include "content/public/renderer/content_renderer_client.h"
60 #include "content/public/renderer/context_menu_client.h"
61 #include "content/public/renderer/document_state.h"
62 #include "content/public/renderer/navigation_state.h"
63 #include "content/public/renderer/render_frame_observer.h"
64 #include "content/public/renderer/renderer_ppapi_host.h"
65 #include "content/renderer/accessibility/renderer_accessibility.h"
66 #include "content/renderer/bluetooth/web_bluetooth_impl.h"
67 #include "content/renderer/browser_plugin/browser_plugin.h"
68 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
69 #include "content/renderer/child_frame_compositing_helper.h"
70 #include "content/renderer/context_menu_params_builder.h"
71 #include "content/renderer/devtools/devtools_agent.h"
72 #include "content/renderer/dom_automation_controller.h"
73 #include "content/renderer/external_popup_menu.h"
74 #include "content/renderer/geolocation_dispatcher.h"
75 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
76 #include "content/renderer/history_controller.h"
77 #include "content/renderer/history_serialization.h"
78 #include "content/renderer/image_downloader/image_downloader_impl.h"
79 #include "content/renderer/ime_event_guard.h"
80 #include "content/renderer/internal_document_state_data.h"
81 #include "content/renderer/manifest/manifest_manager.h"
82 #include "content/renderer/media/audio_renderer_mixer_manager.h"
83 #include "content/renderer/media/crypto/render_cdm_factory.h"
84 #include "content/renderer/media/media_permission_dispatcher.h"
85 #include "content/renderer/media/media_stream_dispatcher.h"
86 #include "content/renderer/media/media_stream_renderer_factory_impl.h"
87 #include "content/renderer/media/midi_dispatcher.h"
88 #include "content/renderer/media/render_media_log.h"
89 #include "content/renderer/media/user_media_client_impl.h"
90 #include "content/renderer/media/webmediaplayer_ms.h"
91 #include "content/renderer/memory_benchmarking_extension.h"
92 #include "content/renderer/mojo/service_registry_js_wrapper.h"
93 #include "content/renderer/navigation_state_impl.h"
94 #include "content/renderer/notification_permission_dispatcher.h"
95 #include "content/renderer/npapi/plugin_channel_host.h"
96 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
97 #include "content/renderer/presentation/presentation_dispatcher.h"
98 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
99 #include "content/renderer/render_frame_proxy.h"
100 #include "content/renderer/render_process.h"
101 #include "content/renderer/render_thread_impl.h"
102 #include "content/renderer/render_view_impl.h"
103 #include "content/renderer/render_widget_fullscreen_pepper.h"
104 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
105 #include "content/renderer/renderer_webcolorchooser_impl.h"
106 #include "content/renderer/savable_resources.h"
107 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
108 #include "content/renderer/shared_worker_repository.h"
109 #include "content/renderer/skia_benchmarking_extension.h"
110 #include "content/renderer/stats_collection_controller.h"
111 #include "content/renderer/web_ui_extension.h"
112 #include "content/renderer/websharedworker_proxy.h"
113 #include "gin/modules/module_registry.h"
114 #include "media/base/audio_renderer_mixer_input.h"
115 #include "media/base/media_log.h"
116 #include "media/blink/webencryptedmediaclient_impl.h"
117 #include "media/blink/webmediaplayer_impl.h"
118 #include "media/renderers/gpu_video_accelerator_factories.h"
119 #include "mojo/common/url_type_converters.h"
120 #include "net/base/data_url.h"
121 #include "net/base/net_errors.h"
122 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
123 #include "net/http/http_util.h"
124 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
125 #include "third_party/WebKit/public/platform/WebString.h"
126 #include "third_party/WebKit/public/platform/WebURL.h"
127 #include "third_party/WebKit/public/platform/WebURLError.h"
128 #include "third_party/WebKit/public/platform/WebURLResponse.h"
129 #include "third_party/WebKit/public/platform/WebVector.h"
130 #include "third_party/WebKit/public/platform/modules/webusb/WebUSBClient.h"
131 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
132 #include "third_party/WebKit/public/web/WebDocument.h"
133 #include "third_party/WebKit/public/web/WebFrameWidget.h"
134 #include "third_party/WebKit/public/web/WebGlyphCache.h"
135 #include "third_party/WebKit/public/web/WebKit.h"
136 #include "third_party/WebKit/public/web/WebLocalFrame.h"
137 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
138 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
139 #include "third_party/WebKit/public/web/WebPlugin.h"
140 #include "third_party/WebKit/public/web/WebPluginParams.h"
141 #include "third_party/WebKit/public/web/WebRange.h"
142 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
143 #include "third_party/WebKit/public/web/WebScriptSource.h"
144 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
145 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
146 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
147 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
148 #include "third_party/WebKit/public/web/WebSettings.h"
149 #include "third_party/WebKit/public/web/WebSurroundingText.h"
150 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
151 #include "third_party/WebKit/public/web/WebView.h"
152 #include "third_party/mojo/src/mojo/edk/js/core.h"
153 #include "third_party/mojo/src/mojo/edk/js/support.h"
154 #include "url/url_util.h"
156 #if defined(ENABLE_PLUGINS)
157 #include "content/renderer/npapi/webplugin_impl.h"
158 #include "content/renderer/pepper/pepper_browser_connection.h"
159 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
160 #include "content/renderer/pepper/pepper_webplugin_impl.h"
161 #include "content/renderer/pepper/plugin_module.h"
162 #endif
164 #if defined(ENABLE_WEBRTC)
165 #include "content/renderer/media/rtc_peer_connection_handler.h"
166 #endif
168 #if defined(OS_ANDROID)
169 #include <cpu-features.h>
171 #include "content/common/gpu/client/context_provider_command_buffer.h"
172 #include "content/renderer/android/synchronous_compositor_factory.h"
173 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
174 #include "content/renderer/media/android/renderer_media_player_manager.h"
175 #include "content/renderer/media/android/stream_texture_factory_impl.h"
176 #include "content/renderer/media/android/webmediaplayer_android.h"
177 #else
178 #include "cc/blink/context_provider_web_context.h"
179 #include "content/renderer/usb/web_usb_client_impl.h"
180 #include "device/devices_app/public/cpp/constants.h"
181 #endif
183 #if defined(ENABLE_PEPPER_CDMS)
184 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
185 #elif defined(ENABLE_BROWSER_CDMS)
186 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
187 #endif
189 #if defined(ENABLE_MOJO_MEDIA)
190 #include "media/mojo/services/mojo_cdm_factory.h"
191 #include "media/mojo/services/mojo_renderer_factory.h"
192 #include "mojo/application/public/cpp/connect.h"
193 #include "mojo/application/public/interfaces/shell.mojom.h"
194 #include "third_party/mojo/src/mojo/public/cpp/bindings/interface_request.h"
195 #else
196 #include "media/renderers/default_renderer_factory.h"
197 #endif
199 #if defined(ENABLE_WEBVR)
200 #include "content/renderer/vr/vr_dispatcher.h"
201 #endif
203 using blink::WebContentDecryptionModule;
204 using blink::WebContextMenuData;
205 using blink::WebData;
206 using blink::WebDataSource;
207 using blink::WebDocument;
208 using blink::WebDOMEvent;
209 using blink::WebDOMMessageEvent;
210 using blink::WebElement;
211 using blink::WebExternalPopupMenu;
212 using blink::WebExternalPopupMenuClient;
213 using blink::WebFrame;
214 using blink::WebHistoryItem;
215 using blink::WebHTTPBody;
216 using blink::WebLocalFrame;
217 using blink::WebMediaPlayer;
218 using blink::WebMediaPlayerClient;
219 using blink::WebMediaPlayerEncryptedMediaClient;
220 using blink::WebNavigationPolicy;
221 using blink::WebNavigationType;
222 using blink::WebNode;
223 using blink::WebPluginParams;
224 using blink::WebPopupMenuInfo;
225 using blink::WebRange;
226 using blink::WebReferrerPolicy;
227 using blink::WebScriptSource;
228 using blink::WebSearchableFormData;
229 using blink::WebSecurityOrigin;
230 using blink::WebSecurityPolicy;
231 using blink::WebSerializedScriptValue;
232 using blink::WebServiceWorkerProvider;
233 using blink::WebSettings;
234 using blink::WebStorageQuotaCallbacks;
235 using blink::WebString;
236 using blink::WebURL;
237 using blink::WebURLError;
238 using blink::WebURLRequest;
239 using blink::WebURLResponse;
240 using blink::WebUserGestureIndicator;
241 using blink::WebVector;
242 using blink::WebView;
243 using base::Time;
244 using base::TimeDelta;
246 namespace content {
248 namespace {
250 const char kDefaultAcceptHeader[] =
251 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
252 "*;q=0.8";
253 const char kAcceptHeader[] = "Accept";
255 const size_t kExtraCharsBeforeAndAfterSelection = 100;
257 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
258 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
259 LAZY_INSTANCE_INITIALIZER;
261 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
262 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
264 int64 ExtractPostId(HistoryEntry* entry) {
265 if (!entry)
266 return -1;
268 const WebHistoryItem& item = entry->root();
269 if (item.isNull() || item.httpBody().isNull())
270 return -1;
272 return item.httpBody().identifier();
275 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
276 const WebURLResponse& response) {
277 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
280 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
281 // Replace any occurrences of swappedout:// with about:blank.
282 const WebURL& blank_url = GURL(url::kAboutBlankURL);
283 WebVector<WebURL> urls;
284 ds->redirectChain(urls);
285 result->reserve(urls.size());
286 for (size_t i = 0; i < urls.size(); ++i) {
287 if (urls[i] != GURL(kSwappedOutURL))
288 result->push_back(urls[i]);
289 else
290 result->push_back(blank_url);
294 // Returns the original request url. If there is no redirect, the original
295 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
296 // frame was loaded by loadData, the original url will be ds->unreachableURL()
297 GURL GetOriginalRequestURL(WebDataSource* ds) {
298 // WebDataSource has unreachable URL means that the frame is loaded through
299 // blink::WebFrame::loadData(), and the base URL will be in the redirect
300 // chain. However, we never visited the baseURL. So in this case, we should
301 // use the unreachable URL as the original URL.
302 if (ds->hasUnreachableURL())
303 return ds->unreachableURL();
305 std::vector<GURL> redirects;
306 GetRedirectChain(ds, &redirects);
307 if (!redirects.empty())
308 return redirects.at(0);
310 return ds->originalRequest().url();
313 NOINLINE void CrashIntentionally() {
314 // NOTE(shess): Crash directly rather than using NOTREACHED() so
315 // that the signature is easier to triage in crash reports.
317 // Linker's ICF feature may merge this function with other functions with the
318 // same definition and it may confuse the crash report processing system.
319 static int static_variable_to_make_this_function_unique = 0;
320 base::debug::Alias(&static_variable_to_make_this_function_unique);
322 volatile int* zero = nullptr;
323 *zero = 0;
326 NOINLINE void BadCastCrashIntentionally() {
327 class A {
328 virtual void f() {}
331 class B {
332 virtual void f() {}
335 A a;
336 (void)(B*)&a;
339 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
340 NOINLINE void MaybeTriggerAsanError(const GURL& url) {
341 // NOTE(rogerm): We intentionally perform an invalid heap access here in
342 // order to trigger an Address Sanitizer (ASAN) error report.
343 const char kCrashDomain[] = "crash";
344 const char kHeapOverflow[] = "/heap-overflow";
345 const char kHeapUnderflow[] = "/heap-underflow";
346 const char kUseAfterFree[] = "/use-after-free";
347 #if defined(SYZYASAN)
348 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
349 const char kCorruptHeap[] = "/corrupt-heap";
350 #endif
352 if (!url.DomainIs(kCrashDomain))
353 return;
355 if (!url.has_path())
356 return;
358 std::string crash_type(url.path());
359 if (crash_type == kHeapOverflow) {
360 base::debug::AsanHeapOverflow();
361 } else if (crash_type == kHeapUnderflow) {
362 base::debug::AsanHeapUnderflow();
363 } else if (crash_type == kUseAfterFree) {
364 base::debug::AsanHeapUseAfterFree();
365 #if defined(SYZYASAN)
366 } else if (crash_type == kCorruptHeapBlock) {
367 base::debug::AsanCorruptHeapBlock();
368 } else if (crash_type == kCorruptHeap) {
369 base::debug::AsanCorruptHeap();
370 #endif
373 #endif // ADDRESS_SANITIZER || SYZYASAN
375 void MaybeHandleDebugURL(const GURL& url) {
376 if (!url.SchemeIs(kChromeUIScheme))
377 return;
378 if (url == GURL(kChromeUIBadCastCrashURL)) {
379 BadCastCrashIntentionally();
380 } else if (url == GURL(kChromeUICrashURL)) {
381 CrashIntentionally();
382 } else if (url == GURL(kChromeUIDumpURL)) {
383 // This URL will only correctly create a crash dump file if content is
384 // hosted in a process that has correctly called
385 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
386 // of base::debug::DumpWithoutCrashing for more details.
387 base::debug::DumpWithoutCrashing();
388 } else if (url == GURL(kChromeUIKillURL)) {
389 base::Process::Current().Terminate(1, false);
390 } else if (url == GURL(kChromeUIHangURL)) {
391 for (;;) {
392 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
394 } else if (url == GURL(kChromeUIShorthangURL)) {
395 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
398 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
399 MaybeTriggerAsanError(url);
400 #endif // ADDRESS_SANITIZER || SYZYASAN
403 // Returns false unless this is a top-level navigation.
404 bool IsTopLevelNavigation(WebFrame* frame) {
405 return frame->parent() == NULL;
408 WebURLRequest CreateURLRequestForNavigation(
409 const CommonNavigationParams& common_params,
410 scoped_ptr<StreamOverrideParameters> stream_override,
411 bool is_view_source_mode_enabled) {
412 WebURLRequest request(common_params.url);
413 if (is_view_source_mode_enabled)
414 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
416 if (common_params.referrer.url.is_valid()) {
417 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
418 common_params.referrer.policy,
419 common_params.url,
420 WebString::fromUTF8(common_params.referrer.url.spec()));
421 if (!web_referrer.isEmpty())
422 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
425 RequestExtraData* extra_data = new RequestExtraData();
426 extra_data->set_stream_override(stream_override.Pass());
427 request.setExtraData(extra_data);
429 // Set the ui timestamp for this navigation. Currently the timestamp here is
430 // only non empty when the navigation was triggered by an Android intent. The
431 // timestamp is converted to a double version supported by blink. It will be
432 // passed back to the browser in the DidCommitProvisionalLoad and the
433 // DocumentLoadComplete IPCs.
434 base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
435 request.setUiStartTime(ui_timestamp.InSecondsF());
436 request.setInputPerfMetricReportPolicy(
437 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
438 common_params.report_type));
439 return request;
442 void UpdateFrameNavigationTiming(WebFrame* frame,
443 base::TimeTicks browser_navigation_start,
444 base::TimeTicks renderer_navigation_start) {
445 // The browser provides the navigation_start time to bootstrap the
446 // Navigation Timing information for the browser-initiated navigations. In
447 // case of cross-process navigations, this carries over the time of
448 // finishing the onbeforeunload handler of the previous page.
449 DCHECK(!browser_navigation_start.is_null());
450 if (frame->provisionalDataSource()) {
451 // |browser_navigation_start| is likely before this process existed, so we
452 // can't use InterProcessTimeTicksConverter. We need at least to ensure
453 // that the browser-side navigation start we set is not later than the one
454 // on the renderer side.
455 base::TimeTicks navigation_start = std::min(
456 browser_navigation_start, renderer_navigation_start);
457 double navigation_start_seconds =
458 (navigation_start - base::TimeTicks()).InSecondsF();
459 frame->provisionalDataSource()->setNavigationStartTime(
460 navigation_start_seconds);
461 // TODO(clamy): We need to provide additional timing values for the
462 // Navigation Timing API to work with browser-side navigations.
466 // PlzNavigate
467 CommonNavigationParams MakeCommonNavigationParams(
468 blink::WebURLRequest* request,
469 bool should_replace_current_entry) {
470 const RequestExtraData kEmptyData;
471 const RequestExtraData* extra_data =
472 static_cast<RequestExtraData*>(request->extraData());
473 if (!extra_data)
474 extra_data = &kEmptyData;
475 Referrer referrer(
476 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
477 request->referrerPolicy());
479 // Set the ui timestamp for this navigation. Currently the timestamp here is
480 // only non empty when the navigation was triggered by an Android intent, or
481 // by the user clicking on a link. The timestamp is converted from a double
482 // version supported by blink. It will be passed back to the renderer in the
483 // CommitNavigation IPC, and then back to the browser again in the
484 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
485 base::TimeTicks ui_timestamp =
486 base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
487 FrameMsg_UILoadMetricsReportType::Value report_type =
488 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
489 request->inputPerfMetricReportPolicy());
490 return CommonNavigationParams(
491 request->url(), referrer, extra_data->transition_type(),
492 FrameMsg_Navigate_Type::NORMAL, true, should_replace_current_entry,
493 ui_timestamp, report_type, GURL(), GURL());
496 #if !defined(OS_ANDROID) || defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
497 media::Context3D GetSharedMainThreadContext3D() {
498 cc::ContextProvider* provider =
499 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
500 if (!provider)
501 return media::Context3D();
502 return media::Context3D(provider->ContextGL(), provider->GrContext());
504 #endif
506 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
507 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
508 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
509 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
512 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
513 nullptr;
515 void OnGotContentHandlerID(uint32_t content_handler_id) {}
517 } // namespace
519 // static
520 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
521 int32 routing_id) {
522 DCHECK(routing_id != MSG_ROUTING_NONE);
523 CreateParams params(render_view, routing_id);
525 if (g_create_render_frame_impl)
526 return g_create_render_frame_impl(params);
527 else
528 return new RenderFrameImpl(params);
531 // static
532 RenderFrame* RenderFrame::FromRoutingID(int routing_id) {
533 return RenderFrameImpl::FromRoutingID(routing_id);
536 // static
537 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int routing_id) {
538 RoutingIDFrameMap::iterator iter =
539 g_routing_id_frame_map.Get().find(routing_id);
540 if (iter != g_routing_id_frame_map.Get().end())
541 return iter->second;
542 return NULL;
545 // static
546 RenderFrameImpl* RenderFrameImpl::CreateMainFrame(RenderViewImpl* render_view,
547 int32 routing_id) {
548 RenderFrameImpl* render_frame =
549 RenderFrameImpl::Create(render_view, routing_id);
550 WebLocalFrame* web_frame =
551 WebLocalFrame::create(blink::WebTreeScopeType::Document, render_frame);
552 render_frame->SetWebFrame(web_frame);
553 render_view->webview()->setMainFrame(web_frame);
554 return render_frame;
557 // static
558 void RenderFrameImpl::CreateFrame(
559 int routing_id,
560 int proxy_routing_id,
561 int opener_routing_id,
562 int parent_routing_id,
563 int previous_sibling_routing_id,
564 const FrameReplicationState& replicated_state,
565 CompositorDependencies* compositor_deps,
566 const FrameMsg_NewFrame_WidgetParams& widget_params) {
567 blink::WebLocalFrame* web_frame;
568 RenderFrameImpl* render_frame;
569 if (proxy_routing_id == MSG_ROUTING_NONE) {
570 RenderFrameProxy* parent_proxy =
571 RenderFrameProxy::FromRoutingID(parent_routing_id);
572 // If the browser is sending a valid parent routing id, it should already
573 // be created and registered.
574 CHECK(parent_proxy);
575 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
577 blink::WebFrame* previous_sibling_web_frame = nullptr;
578 RenderFrameProxy* previous_sibling_proxy =
579 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id);
580 if (previous_sibling_proxy)
581 previous_sibling_web_frame = previous_sibling_proxy->web_frame();
583 // Create the RenderFrame and WebLocalFrame, linking the two.
584 render_frame =
585 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
586 web_frame = parent_web_frame->createLocalChild(
587 replicated_state.scope, WebString::fromUTF8(replicated_state.name),
588 replicated_state.sandbox_flags, render_frame,
589 previous_sibling_web_frame);
590 } else {
591 RenderFrameProxy* proxy =
592 RenderFrameProxy::FromRoutingID(proxy_routing_id);
593 CHECK(proxy);
594 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
595 web_frame =
596 blink::WebLocalFrame::create(replicated_state.scope, render_frame);
597 render_frame->proxy_routing_id_ = proxy_routing_id;
598 web_frame->initializeToReplaceRemoteFrame(
599 proxy->web_frame(), WebString::fromUTF8(replicated_state.name),
600 replicated_state.sandbox_flags);
602 render_frame->SetWebFrame(web_frame);
603 CHECK_IMPLIES(parent_routing_id == MSG_ROUTING_NONE, !web_frame->parent());
605 WebFrame* opener = ResolveOpener(opener_routing_id, nullptr);
606 web_frame->setOpener(opener);
608 if (widget_params.routing_id != MSG_ROUTING_NONE) {
609 CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());
610 render_frame->render_widget_ = RenderWidget::CreateForFrame(
611 widget_params.routing_id, widget_params.surface_id,
612 widget_params.hidden, render_frame->render_view_->screen_info(),
613 compositor_deps, web_frame);
614 // TODO(kenrb): Observing shouldn't be necessary when we sort out
615 // WasShown and WasHidden, separating page-level visibility from
616 // frame-level visibility.
617 render_frame->render_widget_->RegisterRenderFrame(render_frame);
620 render_frame->Initialize();
623 // static
624 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
625 return RenderFrameImpl::FromWebFrame(web_frame);
628 // static
629 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
630 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
631 if (iter != g_frame_map.Get().end())
632 return iter->second;
633 return NULL;
636 // static
637 void RenderFrameImpl::InstallCreateHook(
638 CreateRenderFrameImplFunction create_render_frame_impl) {
639 CHECK(!g_create_render_frame_impl);
640 g_create_render_frame_impl = create_render_frame_impl;
643 // static
644 blink::WebFrame* RenderFrameImpl::ResolveOpener(int opener_frame_routing_id,
645 int* opener_view_routing_id) {
646 if (opener_view_routing_id)
647 *opener_view_routing_id = MSG_ROUTING_NONE;
649 if (opener_frame_routing_id == MSG_ROUTING_NONE)
650 return nullptr;
652 // Opener routing ID could refer to either a RenderFrameProxy or a
653 // RenderFrame, so need to check both.
654 RenderFrameProxy* opener_proxy =
655 RenderFrameProxy::FromRoutingID(opener_frame_routing_id);
656 if (opener_proxy) {
657 if (opener_view_routing_id)
658 *opener_view_routing_id = opener_proxy->render_view()->GetRoutingID();
660 // TODO(nasko,alexmos): This check won't be needed once swappedout:// is
661 // gone.
662 if (opener_proxy->IsMainFrameDetachedFromTree()) {
663 DCHECK(!SiteIsolationPolicy::IsSwappedOutStateForbidden());
664 return opener_proxy->render_view()->webview()->mainFrame();
665 } else {
666 return opener_proxy->web_frame();
670 RenderFrameImpl* opener_frame =
671 RenderFrameImpl::FromRoutingID(opener_frame_routing_id);
672 if (opener_frame) {
673 if (opener_view_routing_id)
674 *opener_view_routing_id = opener_frame->render_view()->GetRoutingID();
675 return opener_frame->GetWebFrame();
678 return nullptr;
681 // RenderFrameImpl ----------------------------------------------------------
682 RenderFrameImpl::RenderFrameImpl(const CreateParams& params)
683 : frame_(NULL),
684 is_subframe_(false),
685 is_local_root_(false),
686 render_view_(params.render_view->AsWeakPtr()),
687 routing_id_(params.routing_id),
688 is_swapped_out_(false),
689 render_frame_proxy_(NULL),
690 is_detaching_(false),
691 proxy_routing_id_(MSG_ROUTING_NONE),
692 #if defined(ENABLE_PLUGINS)
693 plugin_power_saver_helper_(nullptr),
694 #endif
695 cookie_jar_(this),
696 selection_text_offset_(0),
697 selection_range_(gfx::Range::InvalidRange()),
698 handling_select_range_(false),
699 notification_permission_dispatcher_(NULL),
700 web_user_media_client_(NULL),
701 media_permission_dispatcher_(NULL),
702 midi_dispatcher_(NULL),
703 #if defined(OS_ANDROID)
704 media_player_manager_(NULL),
705 #endif
706 #if defined(ENABLE_BROWSER_CDMS)
707 cdm_manager_(NULL),
708 #endif
709 #if defined(VIDEO_HOLE)
710 contains_media_player_(false),
711 #endif
712 has_played_media_(false),
713 devtools_agent_(nullptr),
714 geolocation_dispatcher_(NULL),
715 push_messaging_dispatcher_(NULL),
716 presentation_dispatcher_(NULL),
717 screen_orientation_dispatcher_(NULL),
718 manifest_manager_(NULL),
719 accessibility_mode_(AccessibilityModeOff),
720 renderer_accessibility_(NULL),
721 weak_factory_(this) {
722 std::pair<RoutingIDFrameMap::iterator, bool> result =
723 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
724 CHECK(result.second) << "Inserting a duplicate item.";
726 RenderThread::Get()->AddRoute(routing_id_, this);
728 render_view_->RegisterRenderFrame(this);
730 // Everything below subclasses RenderFrameObserver and is automatically
731 // deleted when the RenderFrame gets deleted.
732 #if defined(OS_ANDROID)
733 new GinJavaBridgeDispatcher(this);
734 #endif
736 #if defined(ENABLE_PLUGINS)
737 // Manages its own lifetime.
738 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
739 #endif
741 manifest_manager_ = new ManifestManager(this);
743 GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_));
746 RenderFrameImpl::~RenderFrameImpl() {
747 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
748 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
750 base::trace_event::TraceLog::GetInstance()->RemoveProcessLabel(routing_id_);
752 #if defined(VIDEO_HOLE)
753 if (contains_media_player_)
754 render_view_->UnregisterVideoHoleFrame(this);
755 #endif
757 if (!is_subframe_) {
758 // When using swapped out frames, RenderFrameProxy is owned by
759 // RenderFrameImpl in the case it is the main frame. Ensure it is deleted
760 // along with this object.
761 if (render_frame_proxy_ &&
762 !SiteIsolationPolicy::IsSwappedOutStateForbidden()) {
763 // The following method calls back into this object and clears
764 // |render_frame_proxy_|.
765 render_frame_proxy_->frameDetached(
766 blink::WebRemoteFrameClient::DetachType::Remove);
769 // Ensure the RenderView doesn't point to this object, once it is destroyed.
770 // TODO(nasko): Add a check that the |main_render_frame_| of |render_view_|
771 // is |this|, once the object is no longer leaked.
772 // See https://crbug.com/464764.
773 render_view_->main_render_frame_ = nullptr;
776 render_view_->UnregisterRenderFrame(this);
777 g_routing_id_frame_map.Get().erase(routing_id_);
778 RenderThread::Get()->RemoveRoute(routing_id_);
781 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
782 DCHECK(!frame_);
784 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
785 std::make_pair(web_frame, this));
786 CHECK(result.second) << "Inserting a duplicate item.";
788 frame_ = web_frame;
791 void RenderFrameImpl::Initialize() {
792 is_subframe_ = !!frame_->parent();
793 is_local_root_ = !frame_->parent() || frame_->parent()->isWebRemoteFrame();
795 #if defined(ENABLE_PLUGINS)
796 new PepperBrowserConnection(this);
797 #endif
798 new SharedWorkerRepository(this);
800 if (is_local_root_ && !render_frame_proxy_) {
801 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
802 // when |this| is deleted.
803 devtools_agent_ = new DevToolsAgent(this);
806 RegisterMojoServices();
808 // We delay calling this until we have the WebFrame so that any observer or
809 // embedder can call GetWebFrame on any RenderFrame.
810 GetContentClient()->renderer()->RenderFrameCreated(this);
813 RenderWidget* RenderFrameImpl::GetRenderWidget() {
814 return render_view_.get();
817 #if defined(ENABLE_PLUGINS)
818 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
819 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
820 DidCreatePepperPlugin(host));
821 if (host->GetPluginName() == kFlashPluginName) {
822 RenderThread::Get()->RecordAction(
823 base::UserMetricsAction("FrameLoadWithFlash"));
827 void RenderFrameImpl::PepperDidChangeCursor(
828 PepperPluginInstanceImpl* instance,
829 const blink::WebCursorInfo& cursor) {
830 // Update the cursor appearance immediately if the requesting plugin is the
831 // one which receives the last mouse event. Otherwise, the new cursor won't be
832 // picked up until the plugin gets the next input event. That is bad if, e.g.,
833 // the plugin would like to set an invisible cursor when there isn't any user
834 // input for a while.
835 if (instance == render_view_->pepper_last_mouse_event_target())
836 GetRenderWidget()->didChangeCursor(cursor);
839 void RenderFrameImpl::PepperDidReceiveMouseEvent(
840 PepperPluginInstanceImpl* instance) {
841 render_view_->set_pepper_last_mouse_event_target(instance);
844 void RenderFrameImpl::PepperTextInputTypeChanged(
845 PepperPluginInstanceImpl* instance) {
846 if (instance != render_view_->focused_pepper_plugin())
847 return;
849 GetRenderWidget()->UpdateTextInputState(
850 RenderWidget::NO_SHOW_IME, RenderWidget::FROM_NON_IME);
852 FocusedNodeChangedForAccessibility(WebNode());
855 void RenderFrameImpl::PepperCaretPositionChanged(
856 PepperPluginInstanceImpl* instance) {
857 if (instance != render_view_->focused_pepper_plugin())
858 return;
859 GetRenderWidget()->UpdateSelectionBounds();
862 void RenderFrameImpl::PepperCancelComposition(
863 PepperPluginInstanceImpl* instance) {
864 if (instance != render_view_->focused_pepper_plugin())
865 return;
866 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
867 #if defined(OS_MACOSX) || defined(USE_AURA)
868 GetRenderWidget()->UpdateCompositionInfo(true);
869 #endif
872 void RenderFrameImpl::PepperSelectionChanged(
873 PepperPluginInstanceImpl* instance) {
874 if (instance != render_view_->focused_pepper_plugin())
875 return;
876 SyncSelectionIfRequired();
879 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
880 PepperPluginInstanceImpl* plugin) {
881 GURL active_url;
882 if (render_view_->webview() && render_view_->webview()->mainFrame())
883 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
884 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
885 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
886 plugin, active_url, GetRenderWidget()->screenInfo());
887 widget->show(blink::WebNavigationPolicyIgnore);
888 return widget;
891 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
892 if (!render_view_->focused_pepper_plugin())
893 return false;
894 return render_view_->focused_pepper_plugin()->
895 IsPluginAcceptingCompositionEvents();
898 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
899 base::ProcessId plugin_pid) {
900 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
901 // routing_id_ as a result.
902 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
905 void RenderFrameImpl::SimulateImeSetComposition(
906 const base::string16& text,
907 const std::vector<blink::WebCompositionUnderline>& underlines,
908 int selection_start,
909 int selection_end) {
910 render_view_->OnImeSetComposition(
911 text, underlines, selection_start, selection_end);
914 void RenderFrameImpl::SimulateImeConfirmComposition(
915 const base::string16& text,
916 const gfx::Range& replacement_range) {
917 render_view_->OnImeConfirmComposition(text, replacement_range, false);
920 void RenderFrameImpl::OnImeSetComposition(
921 const base::string16& text,
922 const std::vector<blink::WebCompositionUnderline>& underlines,
923 int selection_start,
924 int selection_end) {
925 // When a PPAPI plugin has focus, we bypass WebKit.
926 if (!IsPepperAcceptingCompositionEvents()) {
927 pepper_composition_text_ = text;
928 } else {
929 // TODO(kinaba) currently all composition events are sent directly to
930 // plugins. Use DOM event mechanism after WebKit is made aware about
931 // plugins that support composition.
932 // The code below mimics the behavior of WebCore::Editor::setComposition.
934 // Empty -> nonempty: composition started.
935 if (pepper_composition_text_.empty() && !text.empty()) {
936 render_view_->focused_pepper_plugin()->HandleCompositionStart(
937 base::string16());
939 // Nonempty -> empty: composition canceled.
940 if (!pepper_composition_text_.empty() && text.empty()) {
941 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
942 base::string16());
944 pepper_composition_text_ = text;
945 // Nonempty: composition is ongoing.
946 if (!pepper_composition_text_.empty()) {
947 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
948 pepper_composition_text_, underlines, selection_start,
949 selection_end);
954 void RenderFrameImpl::OnImeConfirmComposition(
955 const base::string16& text,
956 const gfx::Range& replacement_range,
957 bool keep_selection) {
958 // When a PPAPI plugin has focus, we bypass WebKit.
959 // Here, text.empty() has a special meaning. It means to commit the last
960 // update of composition text (see
961 // RenderWidgetHost::ImeConfirmComposition()).
962 const base::string16& last_text = text.empty() ? pepper_composition_text_
963 : text;
965 // last_text is empty only when both text and pepper_composition_text_ is.
966 // Ignore it.
967 if (last_text.empty())
968 return;
970 if (!IsPepperAcceptingCompositionEvents()) {
971 base::i18n::UTF16CharIterator iterator(&last_text);
972 int32 i = 0;
973 while (iterator.Advance()) {
974 blink::WebKeyboardEvent char_event;
975 char_event.type = blink::WebInputEvent::Char;
976 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
977 char_event.modifiers = 0;
978 char_event.windowsKeyCode = last_text[i];
979 char_event.nativeKeyCode = last_text[i];
981 const int32 char_start = i;
982 for (; i < iterator.array_pos(); ++i) {
983 char_event.text[i - char_start] = last_text[i];
984 char_event.unmodifiedText[i - char_start] = last_text[i];
987 if (GetRenderWidget()->webwidget())
988 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
990 } else {
991 // Mimics the order of events sent by WebKit.
992 // See WebCore::Editor::setComposition() for the corresponding code.
993 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
994 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
996 pepper_composition_text_.clear();
998 #endif // defined(ENABLE_PLUGINS)
1000 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
1001 if (!web_user_media_client_)
1002 InitializeUserMediaClient();
1003 return web_user_media_client_ ?
1004 web_user_media_client_->media_stream_dispatcher() : NULL;
1007 bool RenderFrameImpl::Send(IPC::Message* message) {
1008 if (is_detaching_) {
1009 delete message;
1010 return false;
1012 if (is_swapped_out_) {
1013 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
1014 delete message;
1015 return false;
1019 return RenderThread::Get()->Send(message);
1022 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1023 void RenderFrameImpl::DidHideExternalPopupMenu() {
1024 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
1025 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
1026 external_popup_menu_.reset();
1028 #endif
1030 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
1031 // We may get here while detaching, when the WebFrame has been deleted. Do
1032 // not process any messages in this state.
1033 if (!frame_)
1034 return false;
1036 // TODO(kenrb): document() should not be null, but as a transitional step
1037 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1038 // to this method. This happens for a top-level remote frame, where a
1039 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1040 // around and is still able to receive messages.
1041 if (!frame_->document().isNull())
1042 GetContentClient()->SetActiveURL(frame_->document().url());
1044 base::ObserverListBase<RenderFrameObserver>::Iterator it(&observers_);
1045 RenderFrameObserver* observer;
1046 while ((observer = it.GetNext()) != NULL) {
1047 if (observer->OnMessageReceived(msg))
1048 return true;
1051 bool handled = true;
1052 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
1053 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
1054 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
1055 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
1056 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
1057 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
1058 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
1059 OnCustomContextMenuAction)
1060 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
1061 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
1062 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
1063 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
1064 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
1065 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
1066 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
1067 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
1068 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1069 IPC_MESSAGE_HANDLER(InputMsg_AdjustSelectionByCharacterOffset,
1070 OnAdjustSelectionByCharacterOffset)
1071 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1072 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
1073 OnMoveRangeSelectionExtent)
1074 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1075 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1076 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
1077 OnExtendSelectionAndDelete)
1078 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
1079 OnSetCompositionFromExistingText)
1080 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
1081 OnExecuteNoValueEditCommand)
1082 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
1083 IPC_MESSAGE_HANDLER(FrameMsg_AddMessageToConsole, OnAddMessageToConsole)
1084 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
1085 OnJavaScriptExecuteRequest)
1086 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
1087 OnJavaScriptExecuteRequestForTests)
1088 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld,
1089 OnJavaScriptExecuteRequestInIsolatedWorld)
1090 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
1091 OnVisualStateRequest)
1092 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
1093 OnSetEditableSelectionOffsets)
1094 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
1095 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
1096 OnTextSurroundingSelectionRequest)
1097 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
1098 OnSetAccessibilityMode)
1099 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree,
1100 OnSnapshotAccessibilityTree)
1101 IPC_MESSAGE_HANDLER(FrameMsg_UpdateOpener, OnUpdateOpener)
1102 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
1103 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags, OnDidUpdateSandboxFlags)
1104 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings,
1105 OnTextTrackSettingsChanged)
1106 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent, OnPostMessageEvent)
1107 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation, OnFailedNavigation)
1108 IPC_MESSAGE_HANDLER(FrameMsg_GetSavableResourceLinks,
1109 OnGetSavableResourceLinks)
1110 #if defined(OS_ANDROID)
1111 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1112 #elif defined(OS_MACOSX)
1113 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1114 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1115 #endif
1116 IPC_END_MESSAGE_MAP()
1118 return handled;
1121 void RenderFrameImpl::OnNavigate(
1122 const CommonNavigationParams& common_params,
1123 const StartNavigationParams& start_params,
1124 const RequestNavigationParams& request_params) {
1125 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
1126 // Can be NULL in tests.
1127 if (render_thread_impl)
1128 render_thread_impl->GetRendererScheduler()->OnPageLoadStarted();
1129 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1130 switches::kEnableBrowserSideNavigation));
1131 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_,
1132 "url", common_params.url.possibly_invalid_spec());
1133 NavigateInternal(common_params, start_params, request_params,
1134 scoped_ptr<StreamOverrideParameters>());
1137 void RenderFrameImpl::NavigateToSwappedOutURL() {
1138 // We use loadRequest instead of loadHTMLString because the former commits
1139 // synchronously. Otherwise a new navigation can interrupt the navigation
1140 // to kSwappedOutURL. If that happens to be to the page we had been
1141 // showing, then WebKit will never send a commit and we'll be left spinning.
1142 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1143 // the navigation to swappedout:// is not announced to the browser side.
1144 is_swapped_out_ = true;
1145 GURL swappedOutURL(kSwappedOutURL);
1146 WebURLRequest request(swappedOutURL);
1147 frame_->loadRequest(request);
1150 void RenderFrameImpl::BindServiceRegistry(
1151 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1152 mojo::ServiceProviderPtr exposed_services) {
1153 service_registry_.Bind(services.Pass());
1154 service_registry_.BindRemoteServiceProvider(exposed_services.Pass());
1157 ManifestManager* RenderFrameImpl::manifest_manager() {
1158 return manifest_manager_;
1161 void RenderFrameImpl::SetPendingNavigationParams(
1162 scoped_ptr<NavigationParams> navigation_params) {
1163 pending_navigation_params_ = navigation_params.Pass();
1166 void RenderFrameImpl::OnBeforeUnload() {
1167 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1168 "id", routing_id_);
1169 // TODO(creis): Right now, this is only called on the main frame. Make the
1170 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1171 // it.
1172 CHECK(!frame_->parent());
1174 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1175 bool proceed = frame_->dispatchBeforeUnloadEvent();
1176 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1177 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1178 before_unload_start_time,
1179 before_unload_end_time));
1182 void RenderFrameImpl::OnSwapOut(
1183 int proxy_routing_id,
1184 bool is_loading,
1185 const FrameReplicationState& replicated_frame_state) {
1186 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1187 RenderFrameProxy* proxy = NULL;
1188 bool swapped_out_forbidden =
1189 SiteIsolationPolicy::IsSwappedOutStateForbidden();
1190 bool is_main_frame = !frame_->parent();
1192 // This codepath should only be hit for subframes when in --site-per-process.
1193 CHECK_IMPLIES(!is_main_frame,
1194 SiteIsolationPolicy::AreCrossProcessFramesPossible());
1196 // Only run unload if we're not swapped out yet, but send the ack either way.
1197 if (!is_swapped_out_) {
1198 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1199 // a different process. This involves running the unload handler and
1200 // clearing the page. We also allow this process to exit if there are no
1201 // other active RenderFrames in it.
1203 // Send an UpdateState message before we get swapped out.
1204 render_view_->SendUpdateState();
1206 // If we need a proxy to replace this, create it now so its routing id is
1207 // registered for receiving IPC messages.
1208 if (proxy_routing_id != MSG_ROUTING_NONE) {
1209 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(
1210 this, proxy_routing_id, replicated_frame_state.scope);
1213 // Synchronously run the unload handler before sending the ACK.
1214 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1215 // unload on subframes as well.
1216 if (is_main_frame)
1217 frame_->dispatchUnloadEvent();
1219 // Swap out and stop sending any IPC messages that are not ACKs.
1220 if (is_main_frame)
1221 render_view_->SetSwappedOut(true);
1222 is_swapped_out_ = true;
1224 // Set the proxy here, since OnStop() below could cause an onload event
1225 // handler to execute, which could trigger code such as
1226 // willCheckAndDispatchMessageEvent() that needs the proxy.
1227 if (proxy)
1228 set_render_frame_proxy(proxy);
1230 // Now that we're swapped out and filtering IPC messages, stop loading to
1231 // ensure that no other in-progress navigation continues. We do this here
1232 // to avoid sending a DidStopLoading message to the browser process.
1233 // TODO(creis): Should we be stopping all frames here and using
1234 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1235 // frame?
1236 if (!swapped_out_forbidden)
1237 OnStop();
1239 // Transfer settings such as initial drawing parameters to the remote frame,
1240 // if one is created, that will replace this frame.
1241 if (!is_main_frame && proxy)
1242 proxy->web_frame()->initializeFromFrame(frame_);
1244 // Replace the page with a blank dummy URL. The unload handler will not be
1245 // run a second time, thanks to a check in FrameLoader::stopLoading.
1246 // TODO(creis): Need to add a better way to do this that avoids running the
1247 // beforeunload handler. For now, we just run it a second time silently.
1248 if (!swapped_out_forbidden)
1249 NavigateToSwappedOutURL();
1251 // Let WebKit know that this view is hidden so it can drop resources and
1252 // stop compositing.
1253 // TODO(creis): Support this for subframes as well.
1254 if (is_main_frame) {
1255 render_view_->webview()->setVisibilityState(
1256 blink::WebPageVisibilityStateHidden, false);
1260 // It is now safe to show modal dialogs again.
1261 // TODO(creis): Deal with modal dialogs from subframes.
1262 if (is_main_frame)
1263 render_view_->suppress_dialogs_until_swap_out_ = false;
1265 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1267 RenderViewImpl* render_view = render_view_.get();
1269 // Now that all of the cleanup is complete and the browser side is notified,
1270 // start using the RenderFrameProxy, if one is created.
1271 if (proxy && swapped_out_forbidden) {
1272 frame_->swap(proxy->web_frame());
1274 if (is_loading)
1275 proxy->OnDidStartLoading();
1278 // In --site-per-process, initialize the WebRemoteFrame with the replication
1279 // state passed by the process that is now rendering the frame.
1280 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1281 // in that case we leave the LocalFrame as the main frame visible to Blink
1282 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1283 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1284 // When we do an unconditional swap for all frames, we can remove
1285 // !is_main_frame below.
1286 if (proxy && swapped_out_forbidden)
1287 proxy->SetReplicatedState(replicated_frame_state);
1289 // Safe to exit if no one else is using the process.
1290 // TODO(nasko): Remove the dependency on RenderViewImpl here and ref count
1291 // the process based on the lifetime of this RenderFrameImpl object.
1292 if (is_main_frame) {
1293 render_view->WasSwappedOut();
1297 void RenderFrameImpl::OnContextMenuClosed(
1298 const CustomContextMenuContext& custom_context) {
1299 if (custom_context.request_id) {
1300 // External request, should be in our map.
1301 ContextMenuClient* client =
1302 pending_context_menus_.Lookup(custom_context.request_id);
1303 if (client) {
1304 client->OnMenuClosed(custom_context.request_id);
1305 pending_context_menus_.Remove(custom_context.request_id);
1307 } else {
1308 if (custom_context.link_followed.is_valid())
1309 frame_->sendPings(context_menu_node_, custom_context.link_followed);
1310 // Internal request, forward to WebKit.
1311 context_menu_node_.reset();
1315 void RenderFrameImpl::OnCustomContextMenuAction(
1316 const CustomContextMenuContext& custom_context,
1317 unsigned action) {
1318 if (custom_context.request_id) {
1319 // External context menu request, look in our map.
1320 ContextMenuClient* client =
1321 pending_context_menus_.Lookup(custom_context.request_id);
1322 if (client)
1323 client->OnMenuAction(custom_context.request_id, action);
1324 } else {
1325 // Internal request, forward to WebKit.
1326 render_view_->webview()->performCustomContextMenuAction(action);
1330 void RenderFrameImpl::OnUndo() {
1331 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1334 void RenderFrameImpl::OnRedo() {
1335 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1338 void RenderFrameImpl::OnCut() {
1339 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1340 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1343 void RenderFrameImpl::OnCopy() {
1344 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1345 WebNode current_node = context_menu_node_.isNull() ?
1346 GetFocusedElement() : context_menu_node_;
1347 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1350 void RenderFrameImpl::OnPaste() {
1351 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1352 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1355 void RenderFrameImpl::OnPasteAndMatchStyle() {
1356 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1357 frame_->executeCommand(
1358 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1361 #if defined(OS_MACOSX)
1362 void RenderFrameImpl::OnCopyToFindPboard() {
1363 // Since the find pasteboard supports only plain text, this can be simpler
1364 // than the |OnCopy()| case.
1365 if (frame_->hasSelection()) {
1366 base::string16 selection = frame_->selectionAsText();
1367 RenderThread::Get()->Send(
1368 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1371 #endif
1373 void RenderFrameImpl::OnDelete() {
1374 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1377 void RenderFrameImpl::OnSelectAll() {
1378 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1379 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1382 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1383 const gfx::Point& extent) {
1384 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1385 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1387 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1388 frame_->selectRange(base, extent);
1391 void RenderFrameImpl::OnAdjustSelectionByCharacterOffset(int start_adjust,
1392 int end_adjust) {
1393 size_t start, length;
1394 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
1395 &start, &length)) {
1396 return;
1399 // Sanity checks to disallow empty and out of range selections.
1400 if (start_adjust - end_adjust > static_cast<int>(length)
1401 || static_cast<int>(start) + start_adjust < 0) {
1402 return;
1405 // A negative adjust amount moves the selection towards the beginning of
1406 // the document, a positive amount moves the selection towards the end of
1407 // the document.
1408 start += start_adjust;
1409 length += end_adjust - start_adjust;
1411 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1412 frame_->selectRange(WebRange::fromDocumentRange(frame_, start, length));
1415 void RenderFrameImpl::OnUnselect() {
1416 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1417 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1420 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1421 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1422 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1423 GetRenderWidget()->routing_id()));
1425 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1426 frame_->moveRangeSelectionExtent(point);
1429 void RenderFrameImpl::OnReplace(const base::string16& text) {
1430 if (!frame_->hasSelection())
1431 frame_->selectWordAroundCaret();
1433 frame_->replaceSelection(text);
1436 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1437 if (!frame_->hasSelection())
1438 return;
1440 frame_->replaceMisspelledRange(text);
1443 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1444 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1447 void RenderFrameImpl::OnAddMessageToConsole(ConsoleMessageLevel level,
1448 const std::string& message) {
1449 AddMessageToConsole(level, message);
1452 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1453 const base::string16& jscript,
1454 int id,
1455 bool notify_result) {
1456 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1457 TRACE_EVENT_SCOPE_THREAD);
1459 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1460 v8::Local<v8::Value> result =
1461 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1463 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1466 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1467 const base::string16& jscript,
1468 int id,
1469 bool notify_result,
1470 bool has_user_gesture) {
1471 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1472 TRACE_EVENT_SCOPE_THREAD);
1474 // A bunch of tests expect to run code in the context of a user gesture, which
1475 // can grant additional privileges (e.g. the ability to create popups).
1476 scoped_ptr<blink::WebScopedUserGesture> gesture(
1477 has_user_gesture ? new blink::WebScopedUserGesture : nullptr);
1478 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1479 v8::Local<v8::Value> result =
1480 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1482 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1485 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1486 const base::string16& jscript,
1487 int id,
1488 bool notify_result,
1489 int world_id) {
1490 TRACE_EVENT_INSTANT0("test_tracing",
1491 "OnJavaScriptExecuteRequestInIsolatedWorld",
1492 TRACE_EVENT_SCOPE_THREAD);
1494 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
1495 world_id > ISOLATED_WORLD_ID_MAX) {
1496 // Return if the world_id is not valid. world_id is passed as a plain int
1497 // over IPC and needs to be verified here, in the IPC endpoint.
1498 NOTREACHED();
1499 return;
1502 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1503 WebScriptSource script = WebScriptSource(jscript);
1504 JavaScriptIsolatedWorldRequest* request = new JavaScriptIsolatedWorldRequest(
1505 id, notify_result, routing_id_, weak_factory_.GetWeakPtr());
1506 frame_->requestExecuteScriptInIsolatedWorld(world_id, &script, 1, 0, false,
1507 request);
1510 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1511 int id,
1512 bool notify_result,
1513 int routing_id,
1514 base::WeakPtr<RenderFrameImpl> render_frame_impl)
1515 : id_(id),
1516 notify_result_(notify_result),
1517 routing_id_(routing_id),
1518 render_frame_impl_(render_frame_impl) {
1521 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1522 ~JavaScriptIsolatedWorldRequest() {
1525 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1526 const blink::WebVector<v8::Local<v8::Value>>& result) {
1527 if (!render_frame_impl_.get()) {
1528 return;
1531 if (notify_result_) {
1532 base::ListValue list;
1533 if (!result.isEmpty()) {
1534 // It's safe to always use the main world context when converting
1535 // here. V8ValueConverterImpl shouldn't actually care about the
1536 // context scope, and it switches to v8::Object's creation context
1537 // when encountered. (from extensions/renderer/script_injection.cc)
1538 v8::Local<v8::Context> context =
1539 render_frame_impl_.get()->frame_->mainWorldScriptContext();
1540 v8::Context::Scope context_scope(context);
1541 V8ValueConverterImpl converter;
1542 converter.SetDateAllowed(true);
1543 converter.SetRegExpAllowed(true);
1544 for (const auto& value : result) {
1545 scoped_ptr<base::Value> result_value(
1546 converter.FromV8Value(value, context));
1547 list.Append(result_value ? result_value.Pass()
1548 : base::Value::CreateNullValue());
1550 } else {
1551 list.Set(0, base::Value::CreateNullValue());
1553 render_frame_impl_.get()->Send(
1554 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id_, list));
1557 delete this;
1560 void RenderFrameImpl::HandleJavascriptExecutionResult(
1561 const base::string16& jscript,
1562 int id,
1563 bool notify_result,
1564 v8::Local<v8::Value> result) {
1565 if (notify_result) {
1566 base::ListValue list;
1567 if (!result.IsEmpty()) {
1568 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1569 v8::Context::Scope context_scope(context);
1570 V8ValueConverterImpl converter;
1571 converter.SetDateAllowed(true);
1572 converter.SetRegExpAllowed(true);
1573 scoped_ptr<base::Value> result_value(
1574 converter.FromV8Value(result, context));
1575 list.Set(0, result_value ? result_value.Pass()
1576 : base::Value::CreateNullValue());
1577 } else {
1578 list.Set(0, base::Value::CreateNullValue());
1580 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1584 void RenderFrameImpl::OnVisualStateRequest(uint64 id) {
1585 GetRenderWidget()->QueueMessage(
1586 new FrameHostMsg_VisualStateResponse(routing_id_, id),
1587 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1590 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1591 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1592 if (!GetRenderWidget()->ShouldHandleImeEvent())
1593 return;
1594 ImeEventGuard guard(GetRenderWidget());
1595 frame_->setEditableSelectionOffsets(start, end);
1598 void RenderFrameImpl::OnSetCompositionFromExistingText(
1599 int start, int end,
1600 const std::vector<blink::WebCompositionUnderline>& underlines) {
1601 if (!GetRenderWidget()->ShouldHandleImeEvent())
1602 return;
1603 ImeEventGuard guard(GetRenderWidget());
1604 frame_->setCompositionFromExistingText(start, end, underlines);
1607 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
1608 frame_->executeCommand(WebString::fromUTF8(name), GetFocusedElement());
1611 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1612 if (!GetRenderWidget()->ShouldHandleImeEvent())
1613 return;
1615 DCHECK(!WebUserGestureIndicator::isProcessingUserGesture());
1617 ImeEventGuard guard(GetRenderWidget());
1618 blink::WebScopedUserGesture gesture_indicator;
1619 frame_->extendSelectionAndDelete(before, after);
1622 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1623 if (accessibility_mode_ == new_mode)
1624 return;
1625 accessibility_mode_ = new_mode;
1626 if (renderer_accessibility_) {
1627 // Note: this isn't called automatically by the destructor because
1628 // there'd be no point in calling it in frame teardown, only if there's
1629 // an accessibility mode change but the frame is persisting.
1630 renderer_accessibility_->DisableAccessibility();
1632 delete renderer_accessibility_;
1633 renderer_accessibility_ = NULL;
1635 if (accessibility_mode_ == AccessibilityModeOff)
1636 return;
1638 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1639 renderer_accessibility_ = new RendererAccessibility(this);
1642 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) {
1643 ui::AXTreeUpdate<AXContentNodeData> response;
1644 RendererAccessibility::SnapshotAccessibilityTree(this, &response);
1645 Send(new AccessibilityHostMsg_SnapshotResponse(
1646 routing_id_, callback_id, response));
1649 void RenderFrameImpl::OnUpdateOpener(int opener_routing_id) {
1650 WebFrame* opener = ResolveOpener(opener_routing_id, nullptr);
1651 frame_->setOpener(opener);
1654 void RenderFrameImpl::OnDidUpdateSandboxFlags(blink::WebSandboxFlags flags) {
1655 frame_->setFrameOwnerSandboxFlags(flags);
1658 void RenderFrameImpl::OnTextTrackSettingsChanged(
1659 const FrameMsg_TextTrackSettings_Params& params) {
1660 DCHECK(!frame_->parent());
1661 if (!render_view_->webview())
1662 return;
1664 if (params.text_tracks_enabled) {
1665 render_view_->webview()->settings()->setTextTrackKindUserPreference(
1666 WebSettings::TextTrackKindUserPreference::Captions);
1667 } else {
1668 render_view_->webview()->settings()->setTextTrackKindUserPreference(
1669 WebSettings::TextTrackKindUserPreference::Default);
1671 render_view_->webview()->settings()->setTextTrackBackgroundColor(
1672 WebString::fromUTF8(params.text_track_background_color));
1673 render_view_->webview()->settings()->setTextTrackFontFamily(
1674 WebString::fromUTF8(params.text_track_font_family));
1675 render_view_->webview()->settings()->setTextTrackFontStyle(
1676 WebString::fromUTF8(params.text_track_font_style));
1677 render_view_->webview()->settings()->setTextTrackFontVariant(
1678 WebString::fromUTF8(params.text_track_font_variant));
1679 render_view_->webview()->settings()->setTextTrackTextColor(
1680 WebString::fromUTF8(params.text_track_text_color));
1681 render_view_->webview()->settings()->setTextTrackTextShadow(
1682 WebString::fromUTF8(params.text_track_text_shadow));
1683 render_view_->webview()->settings()->setTextTrackTextSize(
1684 WebString::fromUTF8(params.text_track_text_size));
1687 void RenderFrameImpl::OnPostMessageEvent(
1688 const FrameMsg_PostMessage_Params& params) {
1689 // Find the source frame if it exists.
1690 WebFrame* source_frame = NULL;
1691 if (params.source_routing_id != MSG_ROUTING_NONE) {
1692 RenderFrameProxy* source_proxy =
1693 RenderFrameProxy::FromRoutingID(params.source_routing_id);
1694 if (source_proxy) {
1695 // Currently, navigating a top-level frame cross-process does not swap
1696 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1697 // WebRemoteFrame will not have an associated blink::Frame. If this is
1698 // the case for |source_proxy|, use the corresponding (swapped-out)
1699 // WebLocalFrame instead, so that event.source for this message can be
1700 // set and used properly.
1701 if (source_proxy->IsMainFrameDetachedFromTree())
1702 source_frame = source_proxy->render_view()->webview()->mainFrame();
1703 else
1704 source_frame = source_proxy->web_frame();
1708 // If the message contained MessagePorts, create the corresponding endpoints.
1709 blink::WebMessagePortChannelArray channels =
1710 WebMessagePortChannelImpl::CreatePorts(
1711 params.message_ports, params.new_routing_ids,
1712 base::ThreadTaskRunnerHandle::Get().get());
1714 WebSerializedScriptValue serialized_script_value;
1715 if (params.is_data_raw_string) {
1716 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1717 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1718 v8::Context::Scope context_scope(context);
1719 V8ValueConverterImpl converter;
1720 converter.SetDateAllowed(true);
1721 converter.SetRegExpAllowed(true);
1722 scoped_ptr<base::Value> value(new base::StringValue(params.data));
1723 v8::Local<v8::Value> result_value = converter.ToV8Value(value.get(),
1724 context);
1725 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
1726 } else {
1727 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
1730 // Create an event with the message. The next-to-last parameter to
1731 // initMessageEvent is the last event ID, which is not used with postMessage.
1732 WebDOMEvent event = frame_->document().createEvent("MessageEvent");
1733 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
1734 msg_event.initMessageEvent("message",
1735 // |canBubble| and |cancellable| are always false
1736 false, false,
1737 serialized_script_value,
1738 params.source_origin, source_frame,
1739 frame_->document(), "", channels);
1741 // We must pass in the target_origin to do the security check on this side,
1742 // since it may have changed since the original postMessage call was made.
1743 WebSecurityOrigin target_origin;
1744 if (!params.target_origin.empty()) {
1745 target_origin =
1746 WebSecurityOrigin::createFromString(WebString(params.target_origin));
1748 frame_->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
1751 #if defined(OS_ANDROID)
1752 void RenderFrameImpl::OnSelectPopupMenuItems(
1753 bool canceled,
1754 const std::vector<int>& selected_indices) {
1755 // It is possible to receive more than one of these calls if the user presses
1756 // a select faster than it takes for the show-select-popup IPC message to make
1757 // it to the browser UI thread. Ignore the extra-messages.
1758 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1759 if (!external_popup_menu_)
1760 return;
1762 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1763 external_popup_menu_.reset();
1765 #endif
1767 #if defined(OS_MACOSX)
1768 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1769 if (external_popup_menu_ == NULL)
1770 return;
1771 external_popup_menu_->DidSelectItem(selected_index);
1772 external_popup_menu_.reset();
1774 #endif
1776 void RenderFrameImpl::OnReload(bool ignore_cache) {
1777 frame_->reload(ignore_cache);
1780 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1781 blink::WebSurroundingText surroundingText;
1782 surroundingText.initialize(frame_->selectionRange(), max_length);
1784 if (surroundingText.isNull()) {
1785 // |surroundingText| might not be correctly initialized, for example if
1786 // |frame_->selectionRange().isNull()|, in other words, if there was no
1787 // selection.
1788 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1789 routing_id_, base::string16(), 0, 0));
1790 return;
1793 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1794 routing_id_,
1795 surroundingText.textContent(),
1796 surroundingText.startOffsetInTextContent(),
1797 surroundingText.endOffsetInTextContent()));
1800 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1801 const base::string16& message,
1802 const base::string16& default_value,
1803 const GURL& frame_url,
1804 base::string16* result) {
1805 // Don't allow further dialogs if we are waiting to swap out, since the
1806 // PageGroupLoadDeferrer in our stack prevents it.
1807 if (render_view()->suppress_dialogs_until_swap_out_)
1808 return false;
1810 bool success = false;
1811 base::string16 result_temp;
1812 if (!result)
1813 result = &result_temp;
1815 render_view()->SendAndRunNestedMessageLoop(
1816 new FrameHostMsg_RunJavaScriptMessage(
1817 routing_id_, message, default_value, frame_url, type, &success,
1818 result));
1819 return success;
1822 void RenderFrameImpl::LoadNavigationErrorPage(
1823 const WebURLRequest& failed_request,
1824 const WebURLError& error,
1825 bool replace) {
1826 std::string error_html;
1827 GetContentClient()->renderer()->GetNavigationErrorStrings(
1828 render_view(), frame_, failed_request, error, &error_html, NULL);
1830 frame_->loadHTMLString(error_html,
1831 GURL(kUnreachableWebDataURL),
1832 error.unreachableURL,
1833 replace);
1836 void RenderFrameImpl::DidCommitCompositorFrame() {
1837 if (BrowserPluginManager::Get())
1838 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1839 FOR_EACH_OBSERVER(
1840 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1843 RenderView* RenderFrameImpl::GetRenderView() {
1844 return render_view_.get();
1847 int RenderFrameImpl::GetRoutingID() {
1848 return routing_id_;
1851 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1852 DCHECK(frame_);
1853 return frame_;
1856 WebElement RenderFrameImpl::GetFocusedElement() const {
1857 WebDocument doc = frame_->document();
1858 if (!doc.isNull())
1859 return doc.focusedElement();
1861 return WebElement();
1864 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1865 return render_view_->GetWebkitPreferences();
1868 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1869 const ContextMenuParams& params) {
1870 DCHECK(client); // A null client means "internal" when we issue callbacks.
1871 ContextMenuParams our_params(params);
1872 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1873 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1874 return our_params.custom_context.request_id;
1877 void RenderFrameImpl::CancelContextMenu(int request_id) {
1878 DCHECK(pending_context_menus_.Lookup(request_id));
1879 pending_context_menus_.Remove(request_id);
1882 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1883 return context_menu_node_;
1886 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1887 blink::WebFrame* frame,
1888 const WebPluginInfo& info,
1889 const blink::WebPluginParams& params,
1890 scoped_ptr<content::PluginInstanceThrottler> throttler) {
1891 DCHECK_EQ(frame_, frame);
1892 #if defined(ENABLE_PLUGINS)
1893 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1894 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1895 this, GetContentClient()
1896 ->renderer()
1897 ->CreateBrowserPluginDelegate(this, params.mimeType.utf8(),
1898 GURL(params.url))
1899 ->GetWeakPtr());
1902 bool pepper_plugin_was_registered = false;
1903 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1904 this, info, &pepper_plugin_was_registered));
1905 if (pepper_plugin_was_registered) {
1906 if (pepper_module.get()) {
1907 return new PepperWebPluginImpl(
1908 pepper_module.get(), params, this,
1909 make_scoped_ptr(
1910 static_cast<PluginInstanceThrottlerImpl*>(throttler.release())));
1913 #if defined(OS_CHROMEOS)
1914 LOG(WARNING) << "Pepper module/plugin creation failed.";
1915 #else
1916 if (info.type == WebPluginInfo::PLUGIN_TYPE_NPAPI) {
1917 // TODO(jam): change to take RenderFrame.
1918 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1920 #endif
1921 #endif
1922 return NULL;
1925 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1926 const blink::WebURLRequest& request,
1927 blink::WebNavigationPolicy policy) {
1928 DCHECK(!frame_ || frame_ == frame);
1929 loadURLExternally(frame, request, policy, WebString());
1932 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1933 OnJavaScriptExecuteRequest(javascript, 0, false);
1936 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1937 return &service_registry_;
1940 #if defined(ENABLE_PLUGINS)
1941 void RenderFrameImpl::RegisterPeripheralPlugin(
1942 const url::Origin& content_origin,
1943 const base::Closure& unthrottle_callback) {
1944 return plugin_power_saver_helper_->RegisterPeripheralPlugin(
1945 content_origin, unthrottle_callback);
1947 #endif // defined(ENABLE_PLUGINS)
1949 bool RenderFrameImpl::IsFTPDirectoryListing() {
1950 WebURLResponseExtraDataImpl* extra_data =
1951 GetExtraDataFromResponse(frame_->dataSource()->response());
1952 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1955 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1956 BrowserPluginManager::Get()->Attach(element_instance_id);
1959 void RenderFrameImpl::DetachGuest(int element_instance_id) {
1960 BrowserPluginManager::Get()->Detach(element_instance_id);
1963 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1964 size_t offset,
1965 const gfx::Range& range) {
1966 // Use the routing id of Render Widget Host.
1967 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1968 selection_text,
1969 offset,
1970 range));
1973 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1974 v8::Isolate* isolate,
1975 v8::Local<v8::Context> context) {
1976 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1977 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1978 return;
1980 v8::HandleScope handle_scope(isolate);
1981 registry->AddBuiltinModule(
1982 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1983 registry->AddBuiltinModule(isolate,
1984 mojo::js::Support::kModuleName,
1985 mojo::js::Support::GetModule(isolate));
1986 registry->AddBuiltinModule(
1987 isolate,
1988 ServiceRegistryJsWrapper::kModuleName,
1989 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1992 void RenderFrameImpl::AddMessageToConsole(ConsoleMessageLevel level,
1993 const std::string& message) {
1994 if (devtools_agent_)
1995 devtools_agent_->AddMessageToConsole(level, message);
1998 // blink::WebFrameClient implementation ----------------------------------------
2000 blink::WebPlugin* RenderFrameImpl::createPlugin(
2001 blink::WebLocalFrame* frame,
2002 const blink::WebPluginParams& params) {
2003 DCHECK_EQ(frame_, frame);
2004 blink::WebPlugin* plugin = NULL;
2005 if (GetContentClient()->renderer()->OverrideCreatePlugin(
2006 this, frame, params, &plugin)) {
2007 return plugin;
2010 if (base::UTF16ToUTF8(base::StringPiece16(params.mimeType)) ==
2011 kBrowserPluginMimeType) {
2012 return BrowserPluginManager::Get()->CreateBrowserPlugin(
2013 this, GetContentClient()
2014 ->renderer()
2015 ->CreateBrowserPluginDelegate(this, kBrowserPluginMimeType,
2016 GURL(params.url))
2017 ->GetWeakPtr());
2020 #if defined(ENABLE_PLUGINS)
2021 WebPluginInfo info;
2022 std::string mime_type;
2023 bool found = false;
2024 WebString top_origin = frame->top()->securityOrigin().toString();
2025 Send(new FrameHostMsg_GetPluginInfo(routing_id_, params.url, GURL(top_origin),
2026 params.mimeType.utf8(), &found, &info,
2027 &mime_type));
2028 if (!found)
2029 return NULL;
2031 WebPluginParams params_to_use = params;
2032 params_to_use.mimeType = WebString::fromUTF8(mime_type);
2033 return CreatePlugin(frame, info, params_to_use, nullptr /* throttler */);
2034 #else
2035 return NULL;
2036 #endif // defined(ENABLE_PLUGINS)
2039 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
2040 blink::WebLocalFrame* frame,
2041 const blink::WebURL& url,
2042 WebMediaPlayerClient* client,
2043 WebMediaPlayerEncryptedMediaClient* encrypted_client,
2044 WebContentDecryptionModule* initial_cdm) {
2045 #if defined(VIDEO_HOLE)
2046 if (!contains_media_player_) {
2047 render_view_->RegisterVideoHoleFrame(this);
2048 contains_media_player_ = true;
2050 #endif // defined(VIDEO_HOLE)
2052 blink::WebMediaStream web_stream(
2053 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
2054 if (!web_stream.isNull())
2055 return CreateWebMediaPlayerForMediaStream(client);
2057 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2059 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2060 scoped_refptr<media::AudioRendererSink> audio_renderer_sink;
2061 media::WebMediaPlayerParams::Context3DCB context_3d_cb;
2062 #else
2063 scoped_refptr<media::AudioRendererSink> audio_renderer_sink =
2064 render_thread->GetAudioRendererMixerManager()->CreateInput(routing_id_);
2065 media::WebMediaPlayerParams::Context3DCB context_3d_cb =
2066 base::Bind(&GetSharedMainThreadContext3D);
2067 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2069 scoped_refptr<media::MediaLog> media_log(new RenderMediaLog());
2070 media::WebMediaPlayerParams params(
2071 base::Bind(&ContentRendererClient::DeferMediaLoad,
2072 base::Unretained(GetContentClient()->renderer()),
2073 static_cast<RenderFrame*>(this), has_played_media_),
2074 audio_renderer_sink, media_log, render_thread->GetMediaThreadTaskRunner(),
2075 render_thread->GetWorkerTaskRunner(),
2076 render_thread->compositor_task_runner(), context_3d_cb,
2077 GetMediaPermission(), initial_cdm);
2079 #if defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2080 return CreateAndroidWebMediaPlayer(client, encrypted_client, params);
2081 #else
2082 #if defined(ENABLE_MOJO_MEDIA)
2083 scoped_ptr<media::RendererFactory> media_renderer_factory(
2084 new media::MojoRendererFactory(GetMediaServiceFactory()));
2085 #else
2086 scoped_ptr<media::RendererFactory> media_renderer_factory =
2087 GetContentClient()->renderer()->CreateMediaRendererFactory(
2088 this, render_thread->GetGpuFactories(), media_log);
2090 if (!media_renderer_factory.get()) {
2091 media_renderer_factory.reset(new media::DefaultRendererFactory(
2092 media_log, render_thread->GetGpuFactories(),
2093 *render_thread->GetAudioHardwareConfig()));
2095 #endif // defined(ENABLE_MOJO_MEDIA)
2097 return new media::WebMediaPlayerImpl(
2098 frame, client, encrypted_client, weak_factory_.GetWeakPtr(),
2099 media_renderer_factory.Pass(), GetCdmFactory(), params);
2100 #endif // defined(OS_ANDROID) && !defined(ENABLE_MEDIA_PIPELINE_ON_ANDROID)
2103 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
2104 blink::WebLocalFrame* frame,
2105 blink::WebApplicationCacheHostClient* client) {
2106 if (!frame || !frame->view())
2107 return NULL;
2108 DCHECK(!frame_ || frame_ == frame);
2109 return new RendererWebApplicationCacheHostImpl(
2110 RenderViewImpl::FromWebView(frame->view()), client,
2111 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2114 blink::WebWorkerContentSettingsClientProxy*
2115 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2116 blink::WebLocalFrame* frame) {
2117 if (!frame || !frame->view())
2118 return NULL;
2119 DCHECK(!frame_ || frame_ == frame);
2120 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2121 this, frame);
2124 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
2125 const WebPopupMenuInfo& popup_menu_info,
2126 WebExternalPopupMenuClient* popup_menu_client) {
2127 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2128 // An IPC message is sent to the browser to build and display the actual
2129 // popup. The user could have time to click a different select by the time
2130 // the popup is shown. In that case external_popup_menu_ is non NULL.
2131 // By returning NULL in that case, we instruct Blink to cancel that new
2132 // popup. So from the user perspective, only the first one will show, and
2133 // will have to close the first one before another one can be shown.
2134 if (external_popup_menu_)
2135 return NULL;
2136 external_popup_menu_.reset(
2137 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
2138 if (render_view_->screen_metrics_emulator_) {
2139 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
2140 external_popup_menu_.get(),
2141 render_view_->screen_metrics_emulator_.get());
2143 return external_popup_menu_.get();
2144 #else
2145 return NULL;
2146 #endif
2149 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
2150 DCHECK(!frame_ || frame_ == frame);
2151 return &cookie_jar_;
2154 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
2155 blink::WebLocalFrame* frame) {
2156 DCHECK(!frame_ || frame_ == frame);
2157 // At this point we should have non-null data source.
2158 DCHECK(frame->dataSource());
2159 if (!ChildThreadImpl::current())
2160 return NULL; // May be null in some tests.
2161 ServiceWorkerNetworkProvider* provider =
2162 ServiceWorkerNetworkProvider::FromDocumentState(
2163 DocumentState::FromDataSource(frame->dataSource()));
2164 DCHECK(provider);
2165 return new WebServiceWorkerProviderImpl(
2166 ChildThreadImpl::current()->thread_safe_sender(),
2167 provider->context());
2170 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
2171 DCHECK(!frame_ || frame_ == frame);
2172 // If the request hasn't yet committed, notify the browser process that it is
2173 // no longer safe to show the pending URL of the main frame, since a URL spoof
2174 // is now possible. (If the request has committed, the browser already knows.)
2175 if (!frame->parent()) {
2176 DocumentState* document_state =
2177 DocumentState::FromDataSource(frame->dataSource());
2178 NavigationStateImpl* navigation_state =
2179 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2181 if (!navigation_state->request_committed()) {
2182 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
2187 blink::WebFrame* RenderFrameImpl::createChildFrame(
2188 blink::WebLocalFrame* parent,
2189 blink::WebTreeScopeType scope,
2190 const blink::WebString& name,
2191 blink::WebSandboxFlags sandbox_flags) {
2192 // Synchronously notify the browser of a child frame creation to get the
2193 // routing_id for the RenderFrame.
2194 int child_routing_id = MSG_ROUTING_NONE;
2195 Send(new FrameHostMsg_CreateChildFrame(
2196 routing_id_, scope,
2197 base::UTF16ToUTF8(base::StringPiece16(name)), sandbox_flags,
2198 &child_routing_id));
2200 // Allocation of routing id failed, so we can't create a child frame. This can
2201 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2202 // out state or synchronous IPC message above has failed.
2203 if (child_routing_id == MSG_ROUTING_NONE) {
2204 NOTREACHED() << "Failed to allocate routing id for child frame.";
2205 return nullptr;
2208 // Create the RenderFrame and WebLocalFrame, linking the two.
2209 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
2210 render_view_.get(), child_routing_id);
2211 blink::WebLocalFrame* web_frame =
2212 WebLocalFrame::create(scope, child_render_frame);
2213 child_render_frame->SetWebFrame(web_frame);
2215 // Add the frame to the frame tree and initialize it.
2216 parent->appendChild(web_frame);
2217 child_render_frame->Initialize();
2219 return web_frame;
2222 void RenderFrameImpl::didChangeOpener(blink::WebFrame* opener) {
2223 // Only active frames are able to disown their opener.
2224 if (!opener && is_swapped_out_)
2225 return;
2227 // Only a local frame should be able to update another frame's opener.
2228 DCHECK(!opener || opener->isWebLocalFrame());
2230 int opener_routing_id = opener ?
2231 RenderFrameImpl::FromWebFrame(opener->toWebLocalFrame())->GetRoutingID() :
2232 MSG_ROUTING_NONE;
2233 Send(new FrameHostMsg_DidChangeOpener(routing_id_, opener_routing_id));
2236 void RenderFrameImpl::frameDetached(blink::WebFrame* frame, DetachType type) {
2237 // NOTE: This function is called on the frame that is being detached and not
2238 // the parent frame. This is different from createChildFrame() which is
2239 // called on the parent frame.
2240 CHECK(!is_detaching_);
2241 DCHECK(!frame_ || frame_ == frame);
2243 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameDetached());
2244 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2245 FrameDetached(frame));
2247 // We only notify the browser process when the frame is being detached for
2248 // removal. If the frame is being detached for swap, we don't need to do this
2249 // since we are not modifiying the frame tree.
2250 if (type == DetachType::Remove)
2251 Send(new FrameHostMsg_Detach(routing_id_));
2253 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2254 // sent before setting |is_detaching_| to true.
2255 is_detaching_ = true;
2257 // Clean up the associated RenderWidget for the frame, if there is one.
2258 if (render_widget_) {
2259 render_widget_->UnregisterRenderFrame(this);
2260 render_widget_->CloseForFrame();
2263 // We need to clean up subframes by removing them from the map and deleting
2264 // the RenderFrameImpl. In contrast, the main frame is owned by its
2265 // containing RenderViewHost (so that they have the same lifetime), so only
2266 // removal from the map is needed and no deletion.
2267 FrameMap::iterator it = g_frame_map.Get().find(frame);
2268 CHECK(it != g_frame_map.Get().end());
2269 CHECK_EQ(it->second, this);
2270 g_frame_map.Get().erase(it);
2272 // Only remove the frame from the renderer's frame tree if the frame is
2273 // being detached for removal. In the case of a swap, the frame needs to
2274 // remain in the tree so WebFrame::swap() can replace it with the new frame.
2275 if (is_subframe_ && type == DetachType::Remove)
2276 frame->parent()->removeChild(frame);
2278 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2279 // object may not be deleted immediately and other methods may try to access
2280 // it.
2281 frame->close();
2282 frame_ = nullptr;
2284 delete this;
2285 // Object is invalid after this point.
2288 void RenderFrameImpl::frameFocused() {
2289 Send(new FrameHostMsg_FrameFocused(routing_id_));
2292 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
2293 DCHECK(!frame_ || frame_ == frame);
2295 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
2296 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2297 FrameWillClose(frame));
2300 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
2301 const blink::WebString& name) {
2302 DCHECK(!frame_ || frame_ == frame);
2304 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2305 // updates may have performance implications for benchmarks like SunSpider.
2306 // For now, send these updates only for --site-per-process, which needs to
2307 // replicate frame names to frame proxies, and when
2308 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2309 // can be optimized further by only sending the update if there are any
2310 // remote frames in the frame tree, or delaying and batching up IPCs if
2311 // updates are happening too frequently.
2312 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() ||
2313 render_view_->renderer_preferences_.report_frame_name_changes) {
2314 Send(new FrameHostMsg_DidChangeName(
2315 routing_id_, base::UTF16ToUTF8(base::StringPiece16(name))));
2319 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame* child_frame,
2320 blink::WebSandboxFlags flags) {
2321 int frame_routing_id = MSG_ROUTING_NONE;
2322 if (child_frame->isWebRemoteFrame()) {
2323 frame_routing_id =
2324 RenderFrameProxy::FromWebFrame(child_frame)->routing_id();
2325 } else {
2326 frame_routing_id =
2327 RenderFrameImpl::FromWebFrame(child_frame)->GetRoutingID();
2330 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_, frame_routing_id,
2331 flags));
2334 void RenderFrameImpl::didMatchCSS(
2335 blink::WebLocalFrame* frame,
2336 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2337 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2338 DCHECK(!frame_ || frame_ == frame);
2340 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2341 DidMatchCSS(newly_matching_selectors,
2342 stopped_matching_selectors));
2345 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2346 const blink::WebString& source) {
2347 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2348 source);
2351 void RenderFrameImpl::didAddMessageToConsole(
2352 const blink::WebConsoleMessage& message,
2353 const blink::WebString& source_name,
2354 unsigned source_line,
2355 const blink::WebString& stack_trace) {
2356 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2357 switch (message.level) {
2358 case blink::WebConsoleMessage::LevelDebug:
2359 log_severity = logging::LOG_VERBOSE;
2360 break;
2361 case blink::WebConsoleMessage::LevelLog:
2362 case blink::WebConsoleMessage::LevelInfo:
2363 log_severity = logging::LOG_INFO;
2364 break;
2365 case blink::WebConsoleMessage::LevelWarning:
2366 log_severity = logging::LOG_WARNING;
2367 break;
2368 case blink::WebConsoleMessage::LevelError:
2369 log_severity = logging::LOG_ERROR;
2370 break;
2371 default:
2372 log_severity = logging::LOG_VERBOSE;
2375 if (shouldReportDetailedMessageForSource(source_name)) {
2376 FOR_EACH_OBSERVER(
2377 RenderFrameObserver, observers_,
2378 DetailedConsoleMessageAdded(message.text,
2379 source_name,
2380 stack_trace,
2381 source_line,
2382 static_cast<int32>(log_severity)));
2385 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2386 static_cast<int32>(log_severity),
2387 message.text,
2388 static_cast<int32>(source_line),
2389 source_name));
2392 void RenderFrameImpl::loadURLExternally(
2393 blink::WebLocalFrame* frame,
2394 const blink::WebURLRequest& request,
2395 blink::WebNavigationPolicy policy,
2396 const blink::WebString& suggested_name) {
2397 DCHECK(!frame_ || frame_ == frame);
2398 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2399 if (policy == blink::WebNavigationPolicyDownload) {
2400 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2401 GetRoutingID(),
2402 request.url(), referrer,
2403 suggested_name));
2404 } else {
2405 OpenURL(frame, request.url(), referrer, policy);
2409 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2410 const NavigationPolicyInfo& info) {
2411 DCHECK(!frame_ || frame_ == info.frame);
2412 return DecidePolicyForNavigation(this, info);
2415 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2416 blink::WebFrame* frame) {
2417 DCHECK(!frame_ || frame_ == frame);
2418 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2421 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2422 const blink::WebFormElement& form) {
2423 DCHECK(!frame_ || frame_ == frame);
2425 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSendSubmitEvent(form));
2428 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2429 const blink::WebFormElement& form) {
2430 DCHECK(!frame_ || frame_ == frame);
2431 DocumentState* document_state =
2432 DocumentState::FromDataSource(frame->provisionalDataSource());
2433 NavigationStateImpl* navigation_state =
2434 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2435 InternalDocumentStateData* internal_data =
2436 InternalDocumentStateData::FromDocumentState(document_state);
2438 if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(),
2439 ui::PAGE_TRANSITION_LINK)) {
2440 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2443 // Save these to be processed when the ensuing navigation is committed.
2444 WebSearchableFormData web_searchable_form_data(form);
2445 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2446 internal_data->set_searchable_form_encoding(
2447 web_searchable_form_data.encoding().utf8());
2449 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form));
2452 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2453 blink::WebDataSource* datasource) {
2454 DCHECK(!frame_ || frame_ == frame);
2456 bool content_initiated = !pending_navigation_params_.get();
2458 // Make sure any previous redirect URLs end up in our new data source.
2459 if (pending_navigation_params_.get()) {
2460 for (const auto& i :
2461 pending_navigation_params_->request_params.redirects) {
2462 datasource->appendRedirect(i);
2466 DocumentState* document_state = DocumentState::FromDataSource(datasource);
2467 if (!document_state) {
2468 document_state = new DocumentState;
2469 datasource->setExtraData(document_state);
2470 if (!content_initiated)
2471 PopulateDocumentStateFromPending(document_state);
2474 // Carry over the user agent override flag, if it exists.
2475 blink::WebView* webview = render_view_->webview();
2476 if (content_initiated && webview && webview->mainFrame() &&
2477 webview->mainFrame()->isWebLocalFrame() &&
2478 webview->mainFrame()->dataSource()) {
2479 DocumentState* old_document_state =
2480 DocumentState::FromDataSource(webview->mainFrame()->dataSource());
2481 if (old_document_state) {
2482 InternalDocumentStateData* internal_data =
2483 InternalDocumentStateData::FromDocumentState(document_state);
2484 InternalDocumentStateData* old_internal_data =
2485 InternalDocumentStateData::FromDocumentState(old_document_state);
2486 internal_data->set_is_overriding_user_agent(
2487 old_internal_data->is_overriding_user_agent());
2491 // The rest of RenderView assumes that a WebDataSource will always have a
2492 // non-null NavigationState.
2493 if (content_initiated) {
2494 document_state->set_navigation_state(
2495 NavigationStateImpl::CreateContentInitiated());
2496 } else {
2497 document_state->set_navigation_state(CreateNavigationStateFromPending());
2498 pending_navigation_params_.reset();
2501 // DocumentState::referred_by_prefetcher_ is true if we are
2502 // navigating from a page that used prefetching using a link on that
2503 // page. We are early enough in the request process here that we
2504 // can still see the DocumentState of the previous page and set
2505 // this value appropriately.
2506 // TODO(gavinp): catch the important case of navigation in a new
2507 // renderer process.
2508 if (webview) {
2509 if (WebFrame* old_frame = webview->mainFrame()) {
2510 const WebURLRequest& original_request = datasource->originalRequest();
2511 const GURL referrer(
2512 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2513 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2514 DocumentState::FromDataSource(old_frame->dataSource())
2515 ->was_prefetcher()) {
2516 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2517 WebDataSource* old_frame_datasource = old_frame->dataSource();
2518 if (old_frame_datasource &&
2519 referrer == GURL(old_frame_datasource->request().url())) {
2520 document_state->set_was_referred_by_prefetcher(true);
2521 break;
2528 if (content_initiated) {
2529 const WebURLRequest& request = datasource->request();
2530 switch (request.cachePolicy()) {
2531 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2532 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2533 break;
2534 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2535 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2536 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2537 break;
2538 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2539 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK);
2540 break;
2541 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2542 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2543 break;
2544 default:
2545 NOTREACHED();
2549 // Create the serviceworker's per-document network observing object if it
2550 // does not exist (When navigation happens within a page, the provider already
2551 // exists).
2552 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2553 DocumentState::FromDataSource(datasource))) {
2554 ServiceWorkerProviderType provider_type =
2555 SERVICE_WORKER_PROVIDER_FOR_WINDOW;
2556 if ((frame->effectiveSandboxFlags() & blink::WebSandboxFlags::Origin) ==
2557 blink::WebSandboxFlags::Origin) {
2558 provider_type = SERVICE_WORKER_PROVIDER_FOR_SANDBOXED_FRAME;
2560 scoped_ptr<ServiceWorkerNetworkProvider> network_provider(
2561 new ServiceWorkerNetworkProvider(routing_id_, provider_type));
2562 ServiceWorkerNetworkProvider::AttachToDocumentState(
2563 DocumentState::FromDataSource(datasource),
2564 network_provider.Pass());
2568 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2569 double triggering_event_time) {
2570 DCHECK(!frame_ || frame_ == frame);
2571 WebDataSource* ds = frame->provisionalDataSource();
2573 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2574 // callback is invoked.
2575 if (!ds)
2576 return;
2578 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2579 "id", routing_id_, "url", ds->request().url().string().utf8());
2580 DocumentState* document_state = DocumentState::FromDataSource(ds);
2582 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2583 CHECK_IMPLIES(ds->request().url() == GURL(kSwappedOutURL), is_swapped_out_)
2584 << "Heard swappedout:// when not swapped out.";
2586 // Update the request time if WebKit has better knowledge of it.
2587 if (document_state->request_time().is_null() &&
2588 triggering_event_time != 0.0) {
2589 document_state->set_request_time(Time::FromDoubleT(triggering_event_time));
2592 // Start time is only set after request time.
2593 document_state->set_start_load_time(Time::Now());
2595 bool is_top_most = !frame->parent();
2596 if (is_top_most) {
2597 render_view_->set_navigation_gesture(
2598 WebUserGestureIndicator::isProcessingUserGesture() ?
2599 NavigationGestureUser : NavigationGestureAuto);
2600 } else if (ds->replacesCurrentHistoryItem()) {
2601 // Subframe navigations that don't add session history items must be
2602 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2603 // handle loading of error pages.
2604 static_cast<NavigationStateImpl*>(document_state->navigation_state())
2605 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2608 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2609 DidStartProvisionalLoad(frame));
2610 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2612 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2613 routing_id_, ds->request().url()));
2616 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2617 blink::WebLocalFrame* frame) {
2618 DCHECK(!frame_ || frame_ == frame);
2619 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2622 void RenderFrameImpl::didFailProvisionalLoad(
2623 blink::WebLocalFrame* frame,
2624 const blink::WebURLError& error,
2625 blink::WebHistoryCommitType commit_type) {
2626 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2627 "id", routing_id_);
2628 DCHECK(!frame_ || frame_ == frame);
2629 WebDataSource* ds = frame->provisionalDataSource();
2630 DCHECK(ds);
2632 const WebURLRequest& failed_request = ds->request();
2634 // Notify the browser that we failed a provisional load with an error.
2636 // Note: It is important this notification occur before DidStopLoading so the
2637 // SSL manager can react to the provisional load failure before being
2638 // notified the load stopped.
2640 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2641 DidFailProvisionalLoad(frame, error));
2642 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2643 DidFailProvisionalLoad(error));
2645 SendFailedProvisionalLoad(failed_request, error, frame);
2647 if (!ShouldDisplayErrorPageForFailedLoad(error.reason, error.unreachableURL))
2648 return;
2650 // Make sure we never show errors in view source mode.
2651 frame->enableViewSourceMode(false);
2653 DocumentState* document_state = DocumentState::FromDataSource(ds);
2654 NavigationStateImpl* navigation_state =
2655 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2657 // If this is a failed back/forward/reload navigation, then we need to do a
2658 // 'replace' load. This is necessary to avoid messing up session history.
2659 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2660 // as session history is concerned.
2661 bool replace = commit_type != blink::WebStandardCommit;
2663 // If we failed on a browser initiated request, then make sure that our error
2664 // page load is regarded as the same browser initiated request.
2665 if (!navigation_state->IsContentInitiated()) {
2666 pending_navigation_params_.reset(new NavigationParams(
2667 navigation_state->common_params(), navigation_state->start_params(),
2668 navigation_state->request_params()));
2669 pending_navigation_params_->request_params.request_time =
2670 document_state->request_time();
2673 // Load an error page.
2674 LoadNavigationErrorPage(failed_request, error, replace);
2677 void RenderFrameImpl::didCommitProvisionalLoad(
2678 blink::WebLocalFrame* frame,
2679 const blink::WebHistoryItem& item,
2680 blink::WebHistoryCommitType commit_type) {
2681 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2682 "id", routing_id_,
2683 "url", GetLoadingUrl().possibly_invalid_spec());
2684 DCHECK(!frame_ || frame_ == frame);
2685 DocumentState* document_state =
2686 DocumentState::FromDataSource(frame->dataSource());
2687 NavigationStateImpl* navigation_state =
2688 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2690 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2691 RenderFrameProxy* proxy =
2692 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2693 CHECK(proxy);
2694 proxy->web_frame()->swap(frame_);
2695 proxy_routing_id_ = MSG_ROUTING_NONE;
2697 // If this is the main frame going from a remote frame to a local frame,
2698 // it needs to set RenderViewImpl's pointer for the main frame to itself
2699 // and ensure RenderWidget is no longer in swapped out mode.
2700 if (!is_subframe_) {
2701 CHECK(!render_view_->main_render_frame_);
2702 render_view_->main_render_frame_ = this;
2703 if (render_view_->is_swapped_out())
2704 render_view_->SetSwappedOut(false);
2708 // When we perform a new navigation, we need to update the last committed
2709 // session history entry with state for the page we are leaving. Do this
2710 // before updating the HistoryController state.
2711 render_view_->SendUpdateState();
2713 render_view_->history_controller()->UpdateForCommit(
2714 this, item, commit_type, navigation_state->WasWithinSamePage());
2716 InternalDocumentStateData* internal_data =
2717 InternalDocumentStateData::FromDocumentState(document_state);
2719 if (document_state->commit_load_time().is_null())
2720 document_state->set_commit_load_time(Time::Now());
2722 if (internal_data->must_reset_scroll_and_scale_state()) {
2723 render_view_->webview()->resetScrollAndScaleState();
2724 internal_data->set_must_reset_scroll_and_scale_state(false);
2727 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2728 if (is_new_navigation) {
2729 // We bump our Page ID to correspond with the new session history entry.
2730 render_view_->page_id_ = render_view_->next_page_id_++;
2732 // Don't update history list values for kSwappedOutURL, since
2733 // we don't want to forget the entry that was there, and since we will
2734 // never come back to kSwappedOutURL. Note that we have to call
2735 // SendUpdateState and update page_id_ even in this case, so that
2736 // the current entry gets a state update and so that we don't send a
2737 // state update to the wrong entry when we swap back in.
2738 DCHECK_IMPLIES(
2739 navigation_state->common_params().should_replace_current_entry,
2740 render_view_->history_list_length_ > 0);
2741 if (GetLoadingUrl() != GURL(kSwappedOutURL) &&
2742 !navigation_state->common_params().should_replace_current_entry) {
2743 // Advance our offset in session history, applying the length limit.
2744 // There is now no forward history.
2745 render_view_->history_list_offset_++;
2746 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2747 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2748 render_view_->history_list_length_ =
2749 render_view_->history_list_offset_ + 1;
2751 } else {
2752 const RequestNavigationParams& request_params =
2753 navigation_state->request_params();
2754 if (request_params.nav_entry_id != 0 &&
2755 !request_params.intended_as_new_entry) {
2756 // This is a successful session history navigation!
2757 render_view_->page_id_ = request_params.page_id;
2759 render_view_->history_list_offset_ =
2760 request_params.pending_history_list_offset;
2764 bool sent = Send(
2765 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2766 CHECK(sent); // http://crbug.com/407376
2768 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2769 DidCommitProvisionalLoad(frame, is_new_navigation));
2770 FOR_EACH_OBSERVER(
2771 RenderFrameObserver, observers_,
2772 DidCommitProvisionalLoad(is_new_navigation,
2773 navigation_state->WasWithinSamePage()));
2775 if (!frame->parent()) { // Only for top frames.
2776 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2777 if (render_thread_impl) { // Can be NULL in tests.
2778 render_thread_impl->histogram_customizer()->
2779 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2780 RenderView::GetRenderViewCount());
2781 render_thread_impl->GetRendererScheduler()->OnPageLoadStarted();
2785 // Remember that we've already processed this request, so we don't update
2786 // the session history again. We do this regardless of whether this is
2787 // a session history navigation, because if we attempted a session history
2788 // navigation without valid HistoryItem state, WebCore will think it is a
2789 // new navigation.
2790 navigation_state->set_request_committed(true);
2792 SendDidCommitProvisionalLoad(frame, commit_type, item);
2794 // Check whether we have new encoding name.
2795 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2798 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2799 DCHECK(!frame_ || frame_ == frame);
2801 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidCreateNewDocument());
2802 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2803 DidCreateNewDocument(frame));
2806 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2807 DCHECK(!frame_ || frame_ == frame);
2809 int enabled_bindings = render_view_->GetEnabledBindings();
2811 if (enabled_bindings & BINDINGS_POLICY_WEB_UI)
2812 WebUIExtension::Install(frame);
2814 if (enabled_bindings & BINDINGS_POLICY_DOM_AUTOMATION)
2815 DomAutomationController::Install(this, frame);
2817 if (enabled_bindings & BINDINGS_POLICY_STATS_COLLECTION)
2818 StatsCollectionController::Install(frame);
2820 const base::CommandLine& command_line =
2821 *base::CommandLine::ForCurrentProcess();
2823 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
2824 GpuBenchmarking::Install(frame);
2826 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2827 MemoryBenchmarkingExtension::Install(frame);
2829 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2830 SkiaBenchmarking::Install(frame);
2832 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2833 DidClearWindowObject(frame));
2834 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2837 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2838 DCHECK(!frame_ || frame_ == frame);
2840 // Notify the browser about non-blank documents loading in the top frame.
2841 GURL url = frame->document().url();
2842 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2843 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2844 // frame->tree()->top().
2845 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2846 if (frame == main_frame) {
2847 // For now, don't remember plugin zoom values. We don't want to mix them
2848 // with normal web content (i.e. a fixed layout plugin would usually want
2849 // them different).
2850 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2851 render_view_->GetRoutingID(),
2852 main_frame->document().isPluginDocument()));
2856 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2857 DidCreateDocumentElement());
2858 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2859 DidCreateDocumentElement(frame));
2862 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2863 const blink::WebString& title,
2864 blink::WebTextDirection direction) {
2865 DCHECK(!frame_ || frame_ == frame);
2866 // Ignore all but top level navigations.
2867 if (!frame->parent()) {
2868 base::string16 title16 = title;
2869 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2870 routing_id_, base::UTF16ToUTF8(title16));
2872 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2873 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2874 shortened_title, direction));
2877 // Also check whether we have new encoding name.
2878 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2881 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2882 blink::WebIconURL::Type icon_type) {
2883 DCHECK(!frame_ || frame_ == frame);
2884 // TODO(nasko): Investigate wheather implementation should move here.
2885 render_view_->didChangeIcon(frame, icon_type);
2888 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame,
2889 bool document_is_empty) {
2890 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2891 "id", routing_id_);
2892 DCHECK(!frame_ || frame_ == frame);
2893 WebDataSource* ds = frame->dataSource();
2894 DocumentState* document_state = DocumentState::FromDataSource(ds);
2895 document_state->set_finish_document_load_time(Time::Now());
2897 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2899 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2900 DidFinishDocumentLoad(frame));
2901 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2903 // Check whether we have new encoding name.
2904 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2906 // If this is an empty document with an http status code indicating an error,
2907 // we may want to display our own error page, so the user doesn't end up
2908 // with an unexplained blank page.
2909 if (!document_is_empty)
2910 return;
2912 // Do not show error page when DevTools is attached.
2913 RenderFrameImpl* localRoot = this;
2914 while (localRoot->frame_ && localRoot->frame_->parent() &&
2915 localRoot->frame_->parent()->isWebLocalFrame()) {
2916 localRoot = RenderFrameImpl::FromWebFrame(localRoot->frame_->parent());
2917 DCHECK(localRoot);
2919 if (localRoot->devtools_agent_ && localRoot->devtools_agent_->IsAttached())
2920 return;
2922 // Display error page instead of a blank page, if appropriate.
2923 std::string error_domain = "http";
2924 InternalDocumentStateData* internal_data =
2925 InternalDocumentStateData::FromDataSource(frame->dataSource());
2926 int http_status_code = internal_data->http_status_code();
2927 if (GetContentClient()->renderer()->HasErrorPage(http_status_code,
2928 &error_domain)) {
2929 WebURLError error;
2930 error.unreachableURL = frame->document().url();
2931 error.domain = WebString::fromUTF8(error_domain);
2932 error.reason = http_status_code;
2933 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
2937 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2938 DCHECK(!frame_ || frame_ == frame);
2939 if (!frame->parent()) {
2940 FrameMsg_UILoadMetricsReportType::Value report_type =
2941 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
2942 frame->dataSource()->request().inputPerfMetricReportPolicy());
2943 base::TimeTicks ui_timestamp = base::TimeTicks() +
2944 base::TimeDelta::FromSecondsD(
2945 frame->dataSource()->request().uiStartTime());
2947 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2948 routing_id_, report_type, ui_timestamp));
2952 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2953 const blink::WebURLError& error,
2954 blink::WebHistoryCommitType commit_type) {
2955 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2956 "id", routing_id_);
2957 DCHECK(!frame_ || frame_ == frame);
2958 // TODO(nasko): Move implementation here. No state needed.
2959 WebDataSource* ds = frame->dataSource();
2960 DCHECK(ds);
2962 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2963 DidFailLoad(frame, error));
2965 const WebURLRequest& failed_request = ds->request();
2966 base::string16 error_description;
2967 GetContentClient()->renderer()->GetNavigationErrorStrings(
2968 render_view_.get(),
2969 frame,
2970 failed_request,
2971 error,
2972 NULL,
2973 &error_description);
2974 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2975 failed_request.url(),
2976 error.reason,
2977 error_description,
2978 error.wasIgnoredByHandler));
2981 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2982 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2983 "id", routing_id_);
2984 DCHECK(!frame_ || frame_ == frame);
2985 WebDataSource* ds = frame->dataSource();
2986 DocumentState* document_state = DocumentState::FromDataSource(ds);
2987 if (document_state->finish_load_time().is_null()) {
2988 if (!frame->parent()) {
2989 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2990 TRACE_EVENT_SCOPE_PROCESS);
2992 document_state->set_finish_load_time(Time::Now());
2995 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2996 DidFinishLoad(frame));
2997 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2999 // Don't send this message while the frame is swapped out.
3000 if (is_swapped_out())
3001 return;
3003 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
3004 ds->request().url()));
3007 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
3008 const blink::WebHistoryItem& item,
3009 blink::WebHistoryCommitType commit_type) {
3010 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
3011 "id", routing_id_);
3012 DCHECK(!frame_ || frame_ == frame);
3013 // If this was a reference fragment navigation that we initiated, then we
3014 // could end up having a non-null pending navigation params. We just need to
3015 // update the ExtraData on the datasource so that others who read the
3016 // ExtraData will get the new NavigationState. Similarly, if we did not
3017 // initiate this navigation, then we need to take care to reset any pre-
3018 // existing navigation state to a content-initiated navigation state.
3019 // didCreateDataSource conveniently takes care of this for us.
3020 didCreateDataSource(frame, frame->dataSource());
3022 DocumentState* document_state =
3023 DocumentState::FromDataSource(frame->dataSource());
3024 static_cast<NavigationStateImpl*>(document_state->navigation_state())
3025 ->set_was_within_same_page(true);
3027 didCommitProvisionalLoad(frame, item, commit_type);
3030 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
3031 DCHECK(!frame_ || frame_ == frame);
3032 // TODO(nasko): Move implementation here. Needed methods:
3033 // * StartNavStateSyncTimerIfNecessary
3034 render_view_->didUpdateCurrentHistoryItem(frame);
3037 void RenderFrameImpl::didChangeThemeColor() {
3038 if (frame_->parent())
3039 return;
3041 Send(new FrameHostMsg_DidChangeThemeColor(
3042 routing_id_, frame_->document().themeColor()));
3045 void RenderFrameImpl::dispatchLoad() {
3046 Send(new FrameHostMsg_DispatchLoad(routing_id_));
3049 void RenderFrameImpl::requestNotificationPermission(
3050 const blink::WebSecurityOrigin& origin,
3051 blink::WebNotificationPermissionCallback* callback) {
3052 if (!notification_permission_dispatcher_) {
3053 notification_permission_dispatcher_ =
3054 new NotificationPermissionDispatcher(this);
3057 notification_permission_dispatcher_->RequestPermission(origin, callback);
3060 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
3061 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
3062 return;
3064 if (is_empty_selection)
3065 selection_text_.clear();
3067 // UpdateTextInputState should be called before SyncSelectionIfRequired.
3068 // UpdateTextInputState may send TextInputStateChanged to notify the focus
3069 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3070 // to notify the selection was changed. Focus change should be notified
3071 // before selection change.
3072 GetRenderWidget()->UpdateTextInputState(
3073 RenderWidget::NO_SHOW_IME, RenderWidget::FROM_NON_IME);
3074 SyncSelectionIfRequired();
3077 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
3078 blink::WebColorChooserClient* client,
3079 const blink::WebColor& initial_color,
3080 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
3081 RendererWebColorChooserImpl* color_chooser =
3082 new RendererWebColorChooserImpl(this, client);
3083 std::vector<ColorSuggestion> color_suggestions;
3084 for (size_t i = 0; i < suggestions.size(); i++) {
3085 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
3087 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
3088 return color_chooser;
3091 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
3092 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
3093 message,
3094 base::string16(),
3095 frame_->document().url(),
3096 NULL);
3099 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
3100 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
3101 message,
3102 base::string16(),
3103 frame_->document().url(),
3104 NULL);
3107 bool RenderFrameImpl::runModalPromptDialog(
3108 const blink::WebString& message,
3109 const blink::WebString& default_value,
3110 blink::WebString* actual_value) {
3111 base::string16 result;
3112 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
3113 message,
3114 default_value,
3115 frame_->document().url(),
3116 &result);
3117 if (ok)
3118 actual_value->assign(result);
3119 return ok;
3122 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3123 bool is_reload,
3124 const blink::WebString& message) {
3125 // If we are swapping out, we have already run the beforeunload handler.
3126 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3127 // at all, to avoid running it twice.
3128 if (is_swapped_out_)
3129 return true;
3131 // Don't allow further dialogs if we are waiting to swap out, since the
3132 // PageGroupLoadDeferrer in our stack prevents it.
3133 if (render_view()->suppress_dialogs_until_swap_out_)
3134 return false;
3136 bool success = false;
3137 // This is an ignored return value, but is included so we can accept the same
3138 // response as RunJavaScriptMessage.
3139 base::string16 ignored_result;
3140 render_view()->SendAndRunNestedMessageLoop(
3141 new FrameHostMsg_RunBeforeUnloadConfirm(
3142 routing_id_, frame_->document().url(), message, is_reload,
3143 &success, &ignored_result));
3144 return success;
3147 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
3148 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
3149 params.source_type = GetRenderWidget()->context_menu_source_type();
3150 GetRenderWidget()->OnShowHostContextMenu(&params);
3151 if (GetRenderWidget()->has_host_context_menu_location()) {
3152 params.x = GetRenderWidget()->host_context_menu_location().x();
3153 params.y = GetRenderWidget()->host_context_menu_location().y();
3156 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3157 // it. We replace it with an empty GURL so the appropriate items are disabled
3158 // in the context menu.
3159 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3160 // data encoded images. We should have a way to save them.
3161 if (params.src_url.spec().size() > GetMaxURLChars())
3162 params.src_url = GURL();
3163 context_menu_node_ = data.node;
3165 #if defined(OS_ANDROID)
3166 gfx::Rect start_rect;
3167 gfx::Rect end_rect;
3168 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
3169 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
3170 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
3171 #endif
3173 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
3176 void RenderFrameImpl::clearContextMenu() {
3177 context_menu_node_.reset();
3180 void RenderFrameImpl::willSendRequest(
3181 blink::WebLocalFrame* frame,
3182 unsigned identifier,
3183 blink::WebURLRequest& request,
3184 const blink::WebURLResponse& redirect_response) {
3185 DCHECK(!frame_ || frame_ == frame);
3186 // The request my be empty during tests.
3187 if (request.url().isEmpty())
3188 return;
3190 // Set the first party for cookies url if it has not been set yet (new
3191 // requests). For redirects, it is updated by WebURLLoaderImpl.
3192 if (request.firstPartyForCookies().isEmpty()) {
3193 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
3194 request.setFirstPartyForCookies(request.url());
3195 } else {
3196 // TODO(nasko): When the top-level frame is remote, there is no document.
3197 // This is broken and should be fixed to propagate the first party.
3198 WebFrame* top = frame->top();
3199 if (top->isWebLocalFrame()) {
3200 request.setFirstPartyForCookies(
3201 frame->top()->document().firstPartyForCookies());
3206 WebDataSource* provisional_data_source = frame->provisionalDataSource();
3207 WebDataSource* data_source =
3208 provisional_data_source ? provisional_data_source : frame->dataSource();
3210 DocumentState* document_state = DocumentState::FromDataSource(data_source);
3211 DCHECK(document_state);
3212 InternalDocumentStateData* internal_data =
3213 InternalDocumentStateData::FromDocumentState(document_state);
3214 NavigationStateImpl* navigation_state =
3215 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3216 ui::PageTransition transition_type = navigation_state->GetTransitionType();
3217 if (provisional_data_source && provisional_data_source->isClientRedirect()) {
3218 transition_type = ui::PageTransitionFromInt(
3219 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3222 GURL request_url(request.url());
3223 GURL new_url;
3224 if (GetContentClient()->renderer()->WillSendRequest(
3225 frame,
3226 transition_type,
3227 request_url,
3228 request.firstPartyForCookies(),
3229 &new_url)) {
3230 request.setURL(WebURL(new_url));
3233 if (internal_data->is_cache_policy_override_set())
3234 request.setCachePolicy(internal_data->cache_policy_override());
3236 // The request's extra data may indicate that we should set a custom user
3237 // agent. This needs to be done here, after WebKit is through with setting the
3238 // user agent on its own. Similarly, it may indicate that we should set an
3239 // X-Requested-With header. This must be done here to avoid breaking CORS
3240 // checks.
3241 // PlzNavigate: there may also be a stream url associated with the request.
3242 WebString custom_user_agent;
3243 WebString requested_with;
3244 scoped_ptr<StreamOverrideParameters> stream_override;
3245 if (request.extraData()) {
3246 RequestExtraData* old_extra_data =
3247 static_cast<RequestExtraData*>(request.extraData());
3249 custom_user_agent = old_extra_data->custom_user_agent();
3250 if (!custom_user_agent.isNull()) {
3251 if (custom_user_agent.isEmpty())
3252 request.clearHTTPHeaderField("User-Agent");
3253 else
3254 request.setHTTPHeaderField("User-Agent", custom_user_agent);
3257 requested_with = old_extra_data->requested_with();
3258 if (!requested_with.isNull()) {
3259 if (requested_with.isEmpty())
3260 request.clearHTTPHeaderField("X-Requested-With");
3261 else
3262 request.setHTTPHeaderField("X-Requested-With", requested_with);
3264 stream_override = old_extra_data->TakeStreamOverrideOwnership();
3267 // Add the default accept header for frame request if it has not been set
3268 // already.
3269 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3270 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
3271 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
3272 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
3273 WebString::fromUTF8(kDefaultAcceptHeader));
3276 // Add an empty HTTP origin header for non GET methods if none is currently
3277 // present.
3278 request.addHTTPOriginIfNeeded(WebString());
3280 // Attach |should_replace_current_entry| state to requests so that, should
3281 // this navigation later require a request transfer, all state is preserved
3282 // when it is re-created in the new process.
3283 bool should_replace_current_entry = false;
3284 if (navigation_state->IsContentInitiated()) {
3285 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
3286 } else {
3287 // If the navigation is browser-initiated, the NavigationState contains the
3288 // correct value instead of the WebDataSource.
3290 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3291 // NavigationState::should_replace_current_entry().
3292 should_replace_current_entry =
3293 navigation_state->common_params().should_replace_current_entry;
3296 int provider_id = kInvalidServiceWorkerProviderId;
3297 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3298 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
3299 // |provisionalDataSource| may be null in some content::ResourceFetcher
3300 // use cases, we don't hook those requests.
3301 if (frame->provisionalDataSource()) {
3302 ServiceWorkerNetworkProvider* provider =
3303 ServiceWorkerNetworkProvider::FromDocumentState(
3304 DocumentState::FromDataSource(frame->provisionalDataSource()));
3305 provider_id = provider->provider_id();
3307 } else if (frame->dataSource()) {
3308 ServiceWorkerNetworkProvider* provider =
3309 ServiceWorkerNetworkProvider::FromDocumentState(
3310 DocumentState::FromDataSource(frame->dataSource()));
3311 provider_id = provider->provider_id();
3312 // Explicitly set the SkipServiceWorker flag here if the renderer process
3313 // hasn't received SetControllerServiceWorker message.
3314 if (!provider->IsControlledByServiceWorker())
3315 request.setSkipServiceWorker(true);
3318 WebFrame* parent = frame->parent();
3319 int parent_routing_id = MSG_ROUTING_NONE;
3320 if (!parent) {
3321 parent_routing_id = -1;
3322 } else if (parent->isWebLocalFrame()) {
3323 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
3324 } else {
3325 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
3328 RequestExtraData* extra_data = new RequestExtraData();
3329 extra_data->set_visibility_state(render_view_->visibilityState());
3330 extra_data->set_custom_user_agent(custom_user_agent);
3331 extra_data->set_requested_with(requested_with);
3332 extra_data->set_render_frame_id(routing_id_);
3333 extra_data->set_is_main_frame(!parent);
3334 extra_data->set_frame_origin(
3335 GURL(frame->document().securityOrigin().toString()));
3336 extra_data->set_parent_is_main_frame(parent && !parent->parent());
3337 extra_data->set_parent_render_frame_id(parent_routing_id);
3338 extra_data->set_allow_download(
3339 navigation_state->common_params().allow_download);
3340 extra_data->set_transition_type(transition_type);
3341 extra_data->set_should_replace_current_entry(should_replace_current_entry);
3342 extra_data->set_transferred_request_child_id(
3343 navigation_state->start_params().transferred_request_child_id);
3344 extra_data->set_transferred_request_request_id(
3345 navigation_state->start_params().transferred_request_request_id);
3346 extra_data->set_service_worker_provider_id(provider_id);
3347 extra_data->set_stream_override(stream_override.Pass());
3348 request.setExtraData(extra_data);
3350 // TODO(creis): Update prefetching to work with out-of-process iframes.
3351 WebFrame* top_frame = frame->top();
3352 if (top_frame && top_frame->isWebLocalFrame()) {
3353 DocumentState* top_document_state =
3354 DocumentState::FromDataSource(top_frame->dataSource());
3355 if (top_document_state) {
3356 // TODO(gavinp): separate out prefetching and prerender field trials
3357 // if the rel=prerender rel type is sticking around.
3358 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
3359 top_document_state->set_was_prefetcher(true);
3363 // This is an instance where we embed a copy of the routing id
3364 // into the data portion of the message. This can cause problems if we
3365 // don't register this id on the browser side, since the download manager
3366 // expects to find a RenderViewHost based off the id.
3367 request.setRequestorID(render_view_->GetRoutingID());
3368 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3370 if (!navigation_state->start_params().extra_headers.empty()) {
3371 for (net::HttpUtil::HeadersIterator i(
3372 navigation_state->start_params().extra_headers.begin(),
3373 navigation_state->start_params().extra_headers.end(), "\n");
3374 i.GetNext();) {
3375 if (base::LowerCaseEqualsASCII(i.name(), "referer")) {
3376 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
3377 blink::WebReferrerPolicyDefault,
3378 request.url(),
3379 WebString::fromUTF8(i.values()));
3380 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
3381 } else {
3382 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
3383 WebString::fromUTF8(i.values()));
3388 if (!render_view_->renderer_preferences_.enable_referrers)
3389 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
3392 void RenderFrameImpl::didReceiveResponse(
3393 blink::WebLocalFrame* frame,
3394 unsigned identifier,
3395 const blink::WebURLResponse& response) {
3396 DCHECK(!frame_ || frame_ == frame);
3397 // Only do this for responses that correspond to a provisional data source
3398 // of the top-most frame. If we have a provisional data source, then we
3399 // can't have any sub-resources yet, so we know that this response must
3400 // correspond to a frame load.
3401 if (!frame->provisionalDataSource() || frame->parent())
3402 return;
3404 // If we are in view source mode, then just let the user see the source of
3405 // the server's error page.
3406 if (frame->isViewSourceModeEnabled())
3407 return;
3409 DocumentState* document_state =
3410 DocumentState::FromDataSource(frame->provisionalDataSource());
3411 int http_status_code = response.httpStatusCode();
3413 // Record page load flags.
3414 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3415 if (extra_data) {
3416 document_state->set_was_fetched_via_spdy(
3417 extra_data->was_fetched_via_spdy());
3418 document_state->set_was_npn_negotiated(
3419 extra_data->was_npn_negotiated());
3420 document_state->set_npn_negotiated_protocol(
3421 extra_data->npn_negotiated_protocol());
3422 document_state->set_was_alternate_protocol_available(
3423 extra_data->was_alternate_protocol_available());
3424 document_state->set_connection_info(
3425 extra_data->connection_info());
3426 document_state->set_was_fetched_via_proxy(
3427 extra_data->was_fetched_via_proxy());
3428 document_state->set_proxy_server(
3429 extra_data->proxy_server());
3431 InternalDocumentStateData* internal_data =
3432 InternalDocumentStateData::FromDocumentState(document_state);
3433 internal_data->set_http_status_code(http_status_code);
3436 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3437 blink::WebLocalFrame* frame,
3438 const blink::WebURLRequest& request,
3439 const blink::WebURLResponse& response) {
3440 DCHECK(!frame_ || frame_ == frame);
3441 // The recipients of this message have no use for data: URLs: they don't
3442 // affect the page's insecure content list and are not in the disk cache. To
3443 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3444 // filter them out here.
3445 GURL url(request.url());
3446 if (url.SchemeIs(url::kDataScheme))
3447 return;
3449 // Let the browser know we loaded a resource from the memory cache. This
3450 // message is needed to display the correct SSL indicators.
3451 Send(new FrameHostMsg_DidLoadResourceFromMemoryCache(
3452 routing_id_, url, response.securityInfo(), request.httpMethod().utf8(),
3453 response.mimeType().utf8(), WebURLRequestToResourceType(request)));
3456 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3457 DCHECK(!frame_ || frame_ == frame);
3458 Send(new FrameHostMsg_DidDisplayInsecureContent(routing_id_));
3461 void RenderFrameImpl::didRunInsecureContent(
3462 blink::WebLocalFrame* frame,
3463 const blink::WebSecurityOrigin& origin,
3464 const blink::WebURL& target) {
3465 DCHECK(!frame_ || frame_ == frame);
3466 Send(new FrameHostMsg_DidRunInsecureContent(
3467 routing_id_, origin.toString().utf8(), target));
3468 GetContentClient()->renderer()->RecordRapporURL(
3469 "ContentSettings.MixedScript.RanMixedScript",
3470 GURL(origin.toString().utf8()));
3473 void RenderFrameImpl::didChangePerformanceTiming() {
3474 FOR_EACH_OBSERVER(RenderFrameObserver,
3475 observers_,
3476 DidChangePerformanceTiming());
3479 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3480 DCHECK(!frame_ || frame_ == frame);
3481 #if defined(ENABLE_PLUGINS)
3482 if (frame != render_view_->webview()->mainFrame())
3483 return;
3484 PluginChannelHost::Broadcast(
3485 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3486 #endif
3489 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3490 v8::Local<v8::Context> context,
3491 int extension_group,
3492 int world_id) {
3493 DCHECK(!frame_ || frame_ == frame);
3495 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
3496 DidCreateScriptContext(context, extension_group, world_id));
3499 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3500 v8::Local<v8::Context> context,
3501 int world_id) {
3502 DCHECK(!frame_ || frame_ == frame);
3504 FOR_EACH_OBSERVER(RenderFrameObserver,
3505 observers_,
3506 WillReleaseScriptContext(context, world_id));
3509 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3510 DCHECK(!frame_ || frame_ == frame);
3511 // TODO(nasko): Move implementation here. Needed methods:
3512 // * StartNavStateSyncTimerIfNecessary
3513 render_view_->didChangeScrollOffset(frame);
3515 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeScrollOffset());
3518 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3519 DCHECK(!frame_ || frame_ == frame);
3520 if (!frame->parent()) {
3521 render_view_->Send(new ViewHostMsg_WillInsertBody(
3522 render_view_->GetRoutingID()));
3526 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3527 int count,
3528 bool final_update) {
3529 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3530 if (!count)
3531 active_match_ordinal = 0;
3533 render_view_->Send(new ViewHostMsg_Find_Reply(
3534 render_view_->GetRoutingID(), request_id, count,
3535 gfx::Rect(), active_match_ordinal, final_update));
3538 void RenderFrameImpl::reportFindInPageSelection(
3539 int request_id,
3540 int active_match_ordinal,
3541 const blink::WebRect& selection_rect) {
3542 render_view_->Send(new ViewHostMsg_Find_Reply(
3543 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3544 active_match_ordinal, false));
3547 void RenderFrameImpl::requestStorageQuota(
3548 blink::WebLocalFrame* frame,
3549 blink::WebStorageQuotaType type,
3550 unsigned long long requested_size,
3551 blink::WebStorageQuotaCallbacks callbacks) {
3552 DCHECK(!frame_ || frame_ == frame);
3553 WebSecurityOrigin origin = frame->document().securityOrigin();
3554 if (origin.isUnique()) {
3555 // Unique origins cannot store persistent state.
3556 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3557 return;
3559 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3560 render_view_->GetRoutingID(),
3561 GURL(origin.toString()),
3562 static_cast<storage::StorageType>(type),
3563 requested_size,
3564 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3567 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3568 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3569 impl->set_render_frame_id(routing_id_);
3572 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3573 if (!geolocation_dispatcher_)
3574 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3575 return geolocation_dispatcher_;
3578 blink::WebPresentationClient* RenderFrameImpl::presentationClient() {
3579 if (!presentation_dispatcher_)
3580 presentation_dispatcher_ = new PresentationDispatcher(this);
3581 return presentation_dispatcher_;
3584 blink::WebPushClient* RenderFrameImpl::pushClient() {
3585 if (!push_messaging_dispatcher_)
3586 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3587 return push_messaging_dispatcher_;
3590 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3591 blink::WebLocalFrame* frame,
3592 blink::WebRTCPeerConnectionHandler* handler) {
3593 DCHECK(!frame_ || frame_ == frame);
3594 #if defined(ENABLE_WEBRTC)
3595 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3596 #endif
3599 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3600 if (!web_user_media_client_)
3601 InitializeUserMediaClient();
3602 return web_user_media_client_;
3605 blink::WebEncryptedMediaClient* RenderFrameImpl::encryptedMediaClient() {
3606 if (!web_encrypted_media_client_) {
3607 web_encrypted_media_client_.reset(new media::WebEncryptedMediaClientImpl(
3608 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3609 // is destructed before |this|, and does not give away ownership of the
3610 // callback.
3611 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported,
3612 base::Unretained(this)),
3613 GetCdmFactory(), GetMediaPermission()));
3615 return web_encrypted_media_client_.get();
3618 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3619 if (!midi_dispatcher_)
3620 midi_dispatcher_ = new MidiDispatcher(this);
3621 return midi_dispatcher_;
3624 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3625 blink::WebLocalFrame* source_frame,
3626 blink::WebFrame* target_frame,
3627 blink::WebSecurityOrigin target_origin,
3628 blink::WebDOMMessageEvent event) {
3629 DCHECK(!frame_ || frame_ == target_frame);
3631 // Currently, a postMessage that targets a cross-process frame can be plumbed
3632 // either through this function or RenderFrameProxy::postMessageEvent. This
3633 // function is used when the target cross-process frame is a top-level frame
3634 // which has been swapped out. In that case, the corresponding WebLocalFrame
3635 // currently remains in the frame tree even in site-per-process mode (see
3636 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3637 // --site-per-process mode for all other cases.
3639 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3640 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3641 // cross-process postMessages.
3642 if (!is_swapped_out_)
3643 return false;
3645 // It is possible to get here on a swapped-out frame without a
3646 // |render_frame_proxy_|. This happens when:
3647 // - This process only has one active RenderView and is about to go away
3648 // (e.g., due to cross-process navigation).
3649 // - The top frame has a subframe with an unload handler.
3650 // - The subframe sends a postMessage to the top-level frame in its unload
3651 // handler.
3652 // See https://crbug.com/475651 for details. We return false here, since we
3653 // don't want to deliver the message to the new process in this case.
3654 if (!render_frame_proxy_)
3655 return false;
3657 render_frame_proxy_->postMessageEvent(
3658 source_frame, render_frame_proxy_->web_frame(), target_origin, event);
3659 return true;
3662 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3663 const blink::WebURL& url) {
3664 DCHECK(!frame_ || frame_ == frame);
3665 std::string user_agent_override_for_url =
3666 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3667 if (!user_agent_override_for_url.empty())
3668 return WebString::fromUTF8(user_agent_override_for_url);
3670 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3671 render_view_->renderer_preferences_.user_agent_override.empty()) {
3672 return blink::WebString();
3675 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3676 // associated with it, so the checks below are not valid. Temporarily
3677 // return early and fix properly as part of https://crbug.com/426555.
3678 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3679 return blink::WebString();
3681 // If we're in the middle of committing a load, the data source we need
3682 // will still be provisional.
3683 WebFrame* main_frame = render_view_->webview()->mainFrame();
3684 WebDataSource* data_source = NULL;
3685 if (main_frame->provisionalDataSource())
3686 data_source = main_frame->provisionalDataSource();
3687 else
3688 data_source = main_frame->dataSource();
3690 InternalDocumentStateData* internal_data = data_source ?
3691 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3692 if (internal_data && internal_data->is_overriding_user_agent())
3693 return WebString::fromUTF8(
3694 render_view_->renderer_preferences_.user_agent_override);
3695 return blink::WebString();
3698 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3699 DCHECK(!frame_ || frame_ == frame);
3700 if (render_view_->renderer_preferences_.enable_do_not_track)
3701 return WebString::fromUTF8("1");
3702 return WebString();
3705 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3706 bool default_value) {
3707 DCHECK(!frame_ || frame_ == frame);
3708 if (!default_value)
3709 return false;
3711 bool blocked = true;
3712 Send(new FrameHostMsg_Are3DAPIsBlocked(
3713 routing_id_,
3714 GURL(frame->top()->securityOrigin().toString()),
3715 THREE_D_API_TYPE_WEBGL,
3716 &blocked));
3717 return !blocked;
3720 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3721 int arb_robustness_status_code) {
3722 DCHECK(!frame_ || frame_ == frame);
3723 Send(new FrameHostMsg_DidLose3DContext(
3724 GURL(frame->top()->securityOrigin().toString()),
3725 THREE_D_API_TYPE_WEBGL,
3726 arb_robustness_status_code));
3729 blink::WebScreenOrientationClient*
3730 RenderFrameImpl::webScreenOrientationClient() {
3731 if (!screen_orientation_dispatcher_)
3732 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3733 return screen_orientation_dispatcher_;
3736 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3737 ServiceWorkerNetworkProvider* provider =
3738 ServiceWorkerNetworkProvider::FromDocumentState(
3739 DocumentState::FromDataSource(&data_source));
3740 return provider->IsControlledByServiceWorker();
3743 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3744 ServiceWorkerNetworkProvider* provider =
3745 ServiceWorkerNetworkProvider::FromDocumentState(
3746 DocumentState::FromDataSource(&data_source));
3747 if (provider->context() && provider->context()->controller())
3748 return provider->context()->controller()->version_id();
3749 return kInvalidServiceWorkerVersionId;
3752 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3753 blink::WebAXEvent event) {
3754 HandleWebAccessibilityEvent(obj, event);
3757 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3758 int identifier,
3759 int match_index,
3760 const blink::WebAXObject& start_object,
3761 int start_offset,
3762 const blink::WebAXObject& end_object,
3763 int end_offset) {
3764 if (renderer_accessibility_) {
3765 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3766 identifier, match_index, start_object, start_offset,
3767 end_object, end_offset);
3771 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame) {
3772 DCHECK(!frame_ || frame_ == frame);
3774 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3777 bool RenderFrameImpl::enterFullscreen() {
3778 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, true));
3779 return true;
3782 bool RenderFrameImpl::exitFullscreen() {
3783 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, false));
3784 return true;
3787 blink::WebPermissionClient* RenderFrameImpl::permissionClient() {
3788 if (!permission_client_)
3789 permission_client_.reset(new PermissionDispatcher(GetServiceRegistry()));
3791 return permission_client_.get();
3794 blink::WebAppBannerClient* RenderFrameImpl::appBannerClient() {
3795 if (!app_banner_client_) {
3796 app_banner_client_ =
3797 GetContentClient()->renderer()->CreateAppBannerClient(this);
3800 return app_banner_client_.get();
3803 void RenderFrameImpl::registerProtocolHandler(const WebString& scheme,
3804 const WebURL& url,
3805 const WebString& title) {
3806 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3807 Send(new FrameHostMsg_RegisterProtocolHandler(
3808 routing_id_,
3809 base::UTF16ToUTF8(base::StringPiece16(scheme)),
3810 url,
3811 title,
3812 user_gesture));
3815 void RenderFrameImpl::unregisterProtocolHandler(const WebString& scheme,
3816 const WebURL& url) {
3817 bool user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
3818 Send(new FrameHostMsg_UnregisterProtocolHandler(
3819 routing_id_,
3820 base::UTF16ToUTF8(base::StringPiece16(scheme)),
3821 url,
3822 user_gesture));
3825 blink::WebBluetooth* RenderFrameImpl::bluetooth() {
3826 if (!bluetooth_) {
3827 bluetooth_.reset(new WebBluetoothImpl(
3828 ChildThreadImpl::current()->thread_safe_sender(), routing_id_));
3831 return bluetooth_.get();
3834 blink::WebUSBClient* RenderFrameImpl::usbClient() {
3835 #if !defined(OS_ANDROID)
3836 if (!usb_client_) {
3837 mojo::ServiceProviderPtr device_services =
3838 ConnectToApplication(GURL(device::kDevicesMojoAppUrl));
3839 usb_client_.reset(new WebUSBClientImpl(device_services.Pass()));
3841 #endif
3842 return usb_client_.get();
3845 #if defined(ENABLE_WEBVR)
3846 blink::WebVRClient* RenderFrameImpl::webVRClient() {
3847 if (!vr_dispatcher_)
3848 vr_dispatcher_.reset(new VRDispatcher(GetServiceRegistry()));
3850 return vr_dispatcher_.get();
3852 #endif
3854 void RenderFrameImpl::DidPlay(WebMediaPlayer* player) {
3855 has_played_media_ = true;
3856 Send(new FrameHostMsg_MediaPlayingNotification(
3857 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3858 player->hasAudio(), player->isRemote()));
3861 void RenderFrameImpl::DidPause(WebMediaPlayer* player) {
3862 Send(new FrameHostMsg_MediaPausedNotification(
3863 routing_id_, reinterpret_cast<int64>(player)));
3866 void RenderFrameImpl::PlayerGone(WebMediaPlayer* player) {
3867 DidPause(player);
3870 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3871 observers_.AddObserver(observer);
3874 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3875 observer->RenderFrameGone();
3876 observers_.RemoveObserver(observer);
3879 void RenderFrameImpl::OnStop() {
3880 DCHECK(frame_);
3881 frame_->stopLoading();
3882 if (!frame_->parent())
3883 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3885 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3888 void RenderFrameImpl::WasHidden() {
3889 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3892 void RenderFrameImpl::WasShown() {
3893 // TODO(kenrb): Need to figure out how to do this better. Should
3894 // VisibilityState remain a page-level concept or move to frames?
3895 // The semantics of 'Show' might have to change here.
3896 if (render_widget_) {
3897 static_cast<blink::WebFrameWidget*>(render_widget_->webwidget())->
3898 setVisibilityState(blink::WebPageVisibilityStateVisible, false);
3900 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3903 void RenderFrameImpl::WidgetWillClose() {
3904 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WidgetWillClose());
3907 bool RenderFrameImpl::IsHidden() {
3908 return GetRenderWidget()->is_hidden();
3911 // Tell the embedding application that the URL of the active page has changed.
3912 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3913 blink::WebFrame* frame,
3914 blink::WebHistoryCommitType commit_type,
3915 const blink::WebHistoryItem& item) {
3916 DCHECK(!frame_ || frame_ == frame);
3917 WebDataSource* ds = frame->dataSource();
3918 DCHECK(ds);
3920 const WebURLRequest& request = ds->request();
3921 const WebURLResponse& response = ds->response();
3923 DocumentState* document_state = DocumentState::FromDataSource(ds);
3924 NavigationStateImpl* navigation_state =
3925 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3926 InternalDocumentStateData* internal_data =
3927 InternalDocumentStateData::FromDocumentState(document_state);
3929 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3930 params.http_status_code = response.httpStatusCode();
3931 params.url_is_unreachable = ds->hasUnreachableURL();
3932 params.is_post = false;
3933 params.intended_as_new_entry =
3934 navigation_state->request_params().intended_as_new_entry;
3935 params.did_create_new_entry = commit_type == blink::WebStandardCommit;
3936 params.post_id = -1;
3937 params.page_id = render_view_->page_id_;
3938 params.nav_entry_id = navigation_state->request_params().nav_entry_id;
3939 // We need to track the RenderViewHost routing_id because of downstream
3940 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3941 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3942 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3943 // based on the ID stored in the resource requests. Once those dependencies
3944 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3945 // client to be based on the routing_id of the RenderFrameHost.
3946 params.render_view_routing_id = render_view_->routing_id();
3947 params.socket_address.set_host(response.remoteIPAddress().utf8());
3948 params.socket_address.set_port(response.remotePort());
3949 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3950 if (extra_data)
3951 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3952 params.was_within_same_page = navigation_state->WasWithinSamePage();
3953 params.security_info = response.securityInfo();
3955 // Set the URL to be displayed in the browser UI to the user.
3956 params.url = GetLoadingUrl();
3957 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3959 // Set the origin of the frame. This will be replicated to the corresponding
3960 // RenderFrameProxies in other processes.
3961 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3962 // to https://crbug.com/439608 and will be replicated as unique origins.
3963 if (!is_swapped_out_) {
3964 std::string scheme = frame->document().securityOrigin().protocol().utf8();
3965 if (url::IsStandard(scheme.c_str(),
3966 url::Component(0, static_cast<int>(scheme.length())))) {
3967 params.origin = frame->document().securityOrigin();
3971 if (frame->document().baseURL() != params.url)
3972 params.base_url = frame->document().baseURL();
3974 GetRedirectChain(ds, &params.redirects);
3975 params.should_update_history = !ds->hasUnreachableURL() &&
3976 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3978 params.searchable_form_url = internal_data->searchable_form_url();
3979 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3981 params.gesture = render_view_->navigation_gesture_;
3982 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3984 // Make navigation state a part of the DidCommitProvisionalLoad message so
3985 // that committed entry has it at all times.
3986 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3987 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
3988 if (entry)
3989 params.page_state = HistoryEntryToPageState(entry);
3990 else
3991 params.page_state = PageState::CreateFromURL(request.url());
3992 } else {
3993 // In --site-per-process, just send a single HistoryItem for this frame,
3994 // rather than the whole tree. It will be stored in the corresponding
3995 // FrameNavigationEntry.
3996 params.page_state = SingleHistoryItemToPageState(item);
3998 params.item_sequence_number = item.itemSequenceNumber();
3999 params.document_sequence_number = item.documentSequenceNumber();
4001 if (!frame->parent()) {
4002 // Top-level navigation.
4004 // Reset the zoom limits in case a plugin had changed them previously. This
4005 // will also call us back which will cause us to send a message to
4006 // update WebContentsImpl.
4007 render_view_->webview()->zoomLimitsChanged(
4008 ZoomFactorToZoomLevel(kMinimumZoomFactor),
4009 ZoomFactorToZoomLevel(kMaximumZoomFactor));
4011 // Set zoom level, but don't do it for full-page plugin since they don't use
4012 // the same zoom settings.
4013 HostZoomLevels::iterator host_zoom =
4014 render_view_->host_zoom_levels_.find(GURL(request.url()));
4015 if (render_view_->webview()->mainFrame()->isWebLocalFrame() &&
4016 render_view_->webview()->mainFrame()->document().isPluginDocument()) {
4017 // Reset the zoom levels for plugins.
4018 render_view_->webview()->setZoomLevel(0);
4019 } else {
4020 // If the zoom level is not found, then do nothing. In-page navigation
4021 // relies on not changing the zoom level in this case.
4022 if (host_zoom != render_view_->host_zoom_levels_.end())
4023 render_view_->webview()->setZoomLevel(host_zoom->second);
4026 if (host_zoom != render_view_->host_zoom_levels_.end()) {
4027 // This zoom level was merely recorded transiently for this load. We can
4028 // erase it now. If at some point we reload this page, the browser will
4029 // send us a new, up-to-date zoom level.
4030 render_view_->host_zoom_levels_.erase(host_zoom);
4033 // Update contents MIME type for main frame.
4034 params.contents_mime_type = ds->response().mimeType().utf8();
4036 params.transition = navigation_state->GetTransitionType();
4037 if (!ui::PageTransitionIsMainFrame(params.transition)) {
4038 // If the main frame does a load, it should not be reported as a subframe
4039 // navigation. This can occur in the following case:
4040 // 1. You're on a site with frames.
4041 // 2. You do a subframe navigation. This is stored with transition type
4042 // MANUAL_SUBFRAME.
4043 // 3. You navigate to some non-frame site, say, google.com.
4044 // 4. You navigate back to the page from step 2. Since it was initially
4045 // MANUAL_SUBFRAME, it will be that same transition type here.
4046 // We don't want that, because any navigation that changes the toplevel
4047 // frame should be tracked as a toplevel navigation (this allows us to
4048 // update the URL bar, etc).
4049 params.transition = ui::PAGE_TRANSITION_LINK;
4052 // If the page contained a client redirect (meta refresh, document.loc...),
4053 // set the referrer and transition appropriately.
4054 if (ds->isClientRedirect()) {
4055 params.referrer =
4056 Referrer(params.redirects[0], ds->request().referrerPolicy());
4057 params.transition = ui::PageTransitionFromInt(
4058 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
4059 } else {
4060 params.referrer = RenderViewImpl::GetReferrerFromRequest(
4061 frame, ds->request());
4064 base::string16 method = request.httpMethod();
4065 if (base::EqualsASCII(method, "POST")) {
4066 params.is_post = true;
4067 params.post_id = ExtractPostId(entry);
4070 // Send the user agent override back.
4071 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
4073 // Track the URL of the original request. We use the first entry of the
4074 // redirect chain if it exists because the chain may have started in another
4075 // process.
4076 params.original_request_url = GetOriginalRequestURL(ds);
4078 params.history_list_was_cleared =
4079 navigation_state->request_params().should_clear_history_list;
4081 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
4082 frame->dataSource()->request().inputPerfMetricReportPolicy());
4083 params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD(
4084 frame->dataSource()->request().uiStartTime());
4086 // Save some histogram data so we can compute the average memory used per
4087 // page load of the glyphs.
4088 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4089 blink::WebGlyphCache::pageCount());
4091 // This message needs to be sent before any of allowScripts(),
4092 // allowImages(), allowPlugins() is called for the new page, so that when
4093 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4094 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4095 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4096 } else {
4097 // Subframe navigation: the type depends on whether this navigation
4098 // generated a new session history entry. When they do generate a session
4099 // history entry, it means the user initiated the navigation and we should
4100 // mark it as such.
4101 if (commit_type == blink::WebStandardCommit)
4102 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
4103 else
4104 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
4106 DCHECK(!navigation_state->request_params().should_clear_history_list);
4107 params.history_list_was_cleared = false;
4108 params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT;
4110 // Don't send this message while the subframe is swapped out.
4111 if (!is_swapped_out())
4112 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4115 // If we end up reusing this WebRequest (for example, due to a #ref click),
4116 // we don't want the transition type to persist. Just clear it.
4117 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
4120 void RenderFrameImpl::didStartLoading(bool to_different_document) {
4121 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4122 "id", routing_id_);
4123 render_view_->FrameDidStartLoading(frame_);
4124 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
4127 void RenderFrameImpl::didStopLoading() {
4128 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4129 "id", routing_id_);
4130 render_view_->FrameDidStopLoading(frame_);
4131 Send(new FrameHostMsg_DidStopLoading(routing_id_));
4134 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
4135 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
4138 void RenderFrameImpl::HandleWebAccessibilityEvent(
4139 const blink::WebAXObject& obj, blink::WebAXEvent event) {
4140 if (renderer_accessibility_)
4141 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
4144 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
4145 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FocusedNodeChanged(node));
4148 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) {
4149 if (renderer_accessibility())
4150 renderer_accessibility()->AccessibilityFocusedNodeChanged(node);
4153 // PlzNavigate
4154 void RenderFrameImpl::OnCommitNavigation(
4155 const ResourceResponseHead& response,
4156 const GURL& stream_url,
4157 const CommonNavigationParams& common_params,
4158 const RequestNavigationParams& request_params) {
4159 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4160 switches::kEnableBrowserSideNavigation));
4161 // This will override the url requested by the WebURLLoader, as well as
4162 // provide it with the response to the request.
4163 scoped_ptr<StreamOverrideParameters> stream_override(
4164 new StreamOverrideParameters());
4165 stream_override->stream_url = stream_url;
4166 stream_override->response = response;
4168 NavigateInternal(common_params, StartNavigationParams(), request_params,
4169 stream_override.Pass());
4172 void RenderFrameImpl::OnFailedNavigation(
4173 const CommonNavigationParams& common_params,
4174 const RequestNavigationParams& request_params,
4175 bool has_stale_copy_in_cache,
4176 int error_code) {
4177 bool is_reload = IsReload(common_params.navigation_type);
4178 bool is_history_navigation = request_params.page_state.IsValid();
4179 WebURLRequest::CachePolicy cache_policy =
4180 WebURLRequest::UseProtocolCachePolicy;
4181 RenderFrameImpl::PrepareRenderViewForNavigation(
4182 common_params.url, request_params, &is_reload, &cache_policy);
4184 GetContentClient()->SetActiveURL(common_params.url);
4186 pending_navigation_params_.reset(new NavigationParams(
4187 common_params, StartNavigationParams(), request_params));
4189 // Inform the browser of the start of the provisional load. This is needed so
4190 // that the load is properly tracked by the WebNavigation API.
4191 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4192 routing_id_, common_params.url));
4194 // Send the provisional load failure.
4195 blink::WebURLError error =
4196 CreateWebURLError(common_params.url, has_stale_copy_in_cache, error_code);
4197 WebURLRequest failed_request = CreateURLRequestForNavigation(
4198 common_params, scoped_ptr<StreamOverrideParameters>(),
4199 frame_->isViewSourceModeEnabled());
4200 SendFailedProvisionalLoad(failed_request, error, frame_);
4202 if (!ShouldDisplayErrorPageForFailedLoad(error_code, common_params.url)) {
4203 // TODO(avi): Remove this; we shouldn't ever be dropping navigations.
4204 // http://crbug.com/501960
4205 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4206 return;
4209 // Make sure errors are not shown in view source mode.
4210 frame_->enableViewSourceMode(false);
4212 // Replace the current history entry in reloads, history navigations and loads
4213 // of the same url. This corresponds to Blink's notion of a standard
4214 // commit.
4215 // TODO(clamy): see if initial commits in subframes should be handled
4216 // separately.
4217 bool replace = is_reload || is_history_navigation ||
4218 common_params.url == GetLoadingUrl();
4219 LoadNavigationErrorPage(failed_request, error, replace);
4222 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
4223 RenderFrame* render_frame,
4224 const NavigationPolicyInfo& info) {
4225 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
4226 info.urlRequest));
4228 // TODO(nick): Is consulting |is_subframe_| here correct?
4229 if (SiteIsolationPolicy::IsSwappedOutStateForbidden() && is_subframe_) {
4230 // There's no reason to ignore navigations on subframes, since the swap out
4231 // logic no longer applies.
4232 } else {
4233 if (is_swapped_out_) {
4234 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
4235 // Targeted links may try to navigate a swapped out frame. Allow the
4236 // browser process to navigate the tab instead. Note that it is also
4237 // possible for non-targeted navigations (from this view) to arrive
4238 // here just after we are swapped out. It's ok to send them to the
4239 // browser, as long as they're for the top level frame.
4240 // TODO(creis): Ensure this supports targeted form submissions when
4241 // fixing http://crbug.com/101395.
4242 if (info.frame->parent() == NULL) {
4243 OpenURL(info.frame, info.urlRequest.url(), referrer,
4244 info.defaultPolicy);
4245 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4248 // We should otherwise ignore in-process iframe navigations, if they
4249 // arrive just after we are swapped out.
4250 return blink::WebNavigationPolicyIgnore;
4253 // Allow kSwappedOutURL to complete.
4254 return info.defaultPolicy;
4258 // Webkit is asking whether to navigate to a new URL.
4259 // This is fine normally, except if we're showing UI from one security
4260 // context and they're trying to navigate to a different context.
4261 const GURL& url = info.urlRequest.url();
4263 // A content initiated navigation may have originated from a link-click,
4264 // script, drag-n-drop operation, etc.
4265 DocumentState* document_state = static_cast<DocumentState*>(info.extraData);
4266 bool is_content_initiated =
4267 document_state->navigation_state()->IsContentInitiated();
4269 // If the browser is interested, then give it a chance to look at the request.
4270 if (is_content_initiated && IsTopLevelNavigation(info.frame) &&
4271 render_view_->renderer_preferences_
4272 .browser_handles_all_top_level_requests) {
4273 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4274 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4277 // Use the frame's original request's URL rather than the document's URL for
4278 // subsequent checks. For a popup, the document's URL may become the opener
4279 // window's URL if the opener has called document.write().
4280 // See http://crbug.com/93517.
4281 GURL old_url(info.frame->dataSource()->request().url());
4283 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4284 // an extension or app origin, leaving a WebUI page, etc). We only care about
4285 // top-level navigations (not iframes). But we sometimes navigate to
4286 // about:blank to clear a tab, and we want to still allow that.
4288 // Note: this is known to break POST submissions when crossing process
4289 // boundaries until http://crbug.com/101395 is fixed. This is better for
4290 // security than loading a WebUI, extension or app page in the wrong process.
4291 // POST requests don't work because this mechanism does not preserve form
4292 // POST data. We will need to send the request's httpBody data up to the
4293 // browser process, and issue a special POST navigation in WebKit (via
4294 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4295 // for examples of how to send the httpBody data.
4296 if (!info.frame->parent() && is_content_initiated &&
4297 !url.SchemeIs(url::kAboutScheme)) {
4298 bool send_referrer = false;
4300 // All navigations to or from WebUI URLs or within WebUI-enabled
4301 // RenderProcesses must be handled by the browser process so that the
4302 // correct bindings and data sources can be registered.
4303 // Similarly, navigations to view-source URLs or within ViewSource mode
4304 // must be handled by the browser process (except for reloads - those are
4305 // safe to leave within the renderer).
4306 // Lastly, access to file:// URLs from non-file:// URL pages must be
4307 // handled by the browser so that ordinary renderer processes don't get
4308 // blessed with file permissions.
4309 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
4310 bool is_initial_navigation = render_view_->history_list_length_ == 0;
4311 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
4312 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
4313 url.SchemeIs(kViewSourceScheme) ||
4314 (info.frame->isViewSourceModeEnabled() &&
4315 info.navigationType != blink::WebNavigationTypeReload);
4317 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
4318 // Fork non-file to file opens. Check the opener URL if this is the
4319 // initial navigation in a newly opened window.
4320 GURL source_url(old_url);
4321 if (is_initial_navigation && source_url.is_empty() &&
4322 info.frame->opener())
4323 source_url = info.frame->opener()->top()->document().url();
4324 DCHECK(!source_url.is_empty());
4325 should_fork = !source_url.SchemeIs(url::kFileScheme);
4328 if (!should_fork) {
4329 // Give the embedder a chance.
4330 should_fork = GetContentClient()->renderer()->ShouldFork(
4331 info.frame, url, info.urlRequest.httpMethod().utf8(),
4332 is_initial_navigation, info.isRedirect, &send_referrer);
4335 if (should_fork) {
4336 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
4337 info.defaultPolicy);
4338 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4342 // Detect when a page is "forking" a new tab that can be safely rendered in
4343 // its own process. This is done by sites like Gmail that try to open links
4344 // in new windows without script connections back to the original page. We
4345 // treat such cases as browser navigations (in which we will create a new
4346 // renderer for a cross-site navigation), rather than WebKit navigations.
4348 // We use the following heuristic to decide whether to fork a new page in its
4349 // own process:
4350 // The parent page must open a new tab to about:blank, set the new tab's
4351 // window.opener to null, and then redirect the tab to a cross-site URL using
4352 // JavaScript.
4354 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4355 // (see below).
4356 bool is_fork =
4357 // Must start from a tab showing about:blank, which is later redirected.
4358 old_url == GURL(url::kAboutBlankURL) &&
4359 // Must be the first real navigation of the tab.
4360 render_view_->historyBackListCount() < 1 &&
4361 render_view_->historyForwardListCount() < 1 &&
4362 // The parent page must have set the child's window.opener to null before
4363 // redirecting to the desired URL.
4364 info.frame->opener() == NULL &&
4365 // Must be a top-level frame.
4366 info.frame->parent() == NULL &&
4367 // Must not have issued the request from this page.
4368 is_content_initiated &&
4369 // Must be targeted at the current tab.
4370 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
4371 // Must be a JavaScript navigation, which appears as "other".
4372 info.navigationType == blink::WebNavigationTypeOther;
4374 if (is_fork) {
4375 // Open the URL via the browser, not via WebKit.
4376 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
4377 return blink::WebNavigationPolicyIgnore;
4380 // PlzNavigate: if the navigation is not synchronous, send it to the browser.
4381 // This includes navigations with no request being sent to the network stack.
4382 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4383 switches::kEnableBrowserSideNavigation) &&
4384 info.urlRequest.checkForBrowserSideNavigation() &&
4385 ShouldMakeNetworkRequestForURL(url)) {
4386 BeginNavigation(&info.urlRequest);
4387 return blink::WebNavigationPolicyIgnore;
4390 return info.defaultPolicy;
4393 void RenderFrameImpl::OnGetSavableResourceLinks() {
4394 std::vector<GURL> resources_list;
4395 std::vector<GURL> referrer_urls_list;
4396 std::vector<blink::WebReferrerPolicy> referrer_policies_list;
4397 SavableResourcesResult result(&resources_list, &referrer_urls_list,
4398 &referrer_policies_list);
4400 if (!GetSavableResourceLinksForFrame(
4401 frame_, &result, const_cast<const char**>(GetSavableSchemes()))) {
4402 Send(new FrameHostMsg_SavableResourceLinksError(routing_id_));
4403 return;
4406 std::vector<Referrer> referrers_list;
4407 CHECK_EQ(referrer_urls_list.size(), referrer_policies_list.size());
4408 for (unsigned i = 0; i < referrer_urls_list.size(); ++i) {
4409 referrers_list.push_back(
4410 Referrer(referrer_urls_list[i], referrer_policies_list[i]));
4413 Send(new FrameHostMsg_SavableResourceLinksResponse(
4414 routing_id_, frame_->document().url(), resources_list, referrers_list));
4417 void RenderFrameImpl::OpenURL(WebFrame* frame,
4418 const GURL& url,
4419 const Referrer& referrer,
4420 WebNavigationPolicy policy) {
4421 DCHECK_EQ(frame_, frame);
4423 FrameHostMsg_OpenURL_Params params;
4424 params.url = url;
4425 params.referrer = referrer;
4426 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
4427 WebDataSource* ds = frame->provisionalDataSource();
4428 if (ds) {
4429 DocumentState* document_state = DocumentState::FromDataSource(ds);
4430 NavigationStateImpl* navigation_state =
4431 static_cast<NavigationStateImpl*>(document_state->navigation_state());
4432 if (navigation_state->IsContentInitiated()) {
4433 params.should_replace_current_entry =
4434 ds->replacesCurrentHistoryItem() &&
4435 render_view_->history_list_length_;
4436 } else {
4437 // This is necessary to preserve the should_replace_current_entry value on
4438 // cross-process redirects, in the event it was set by a previous process.
4440 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4441 // NavigationState::should_replace_current_entry().
4442 params.should_replace_current_entry =
4443 navigation_state->common_params().should_replace_current_entry;
4445 } else {
4446 params.should_replace_current_entry = false;
4448 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
4449 if (GetContentClient()->renderer()->AllowPopup())
4450 params.user_gesture = true;
4452 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
4453 policy == blink::WebNavigationPolicyNewForegroundTab ||
4454 policy == blink::WebNavigationPolicyNewWindow ||
4455 policy == blink::WebNavigationPolicyNewPopup) {
4456 WebUserGestureIndicator::consumeUserGesture();
4459 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4462 void RenderFrameImpl::NavigateInternal(
4463 const CommonNavigationParams& common_params,
4464 const StartNavigationParams& start_params,
4465 const RequestNavigationParams& request_params,
4466 scoped_ptr<StreamOverrideParameters> stream_params) {
4467 bool browser_side_navigation =
4468 base::CommandLine::ForCurrentProcess()->HasSwitch(
4469 switches::kEnableBrowserSideNavigation);
4470 bool is_reload = IsReload(common_params.navigation_type);
4471 bool is_history_navigation = request_params.page_state.IsValid();
4472 WebURLRequest::CachePolicy cache_policy =
4473 WebURLRequest::UseProtocolCachePolicy;
4474 RenderFrameImpl::PrepareRenderViewForNavigation(
4475 common_params.url, request_params, &is_reload, &cache_policy);
4477 GetContentClient()->SetActiveURL(common_params.url);
4479 // If this frame isn't in the same process as the main frame, it may naively
4480 // assume that this is the first navigation in the iframe, but this may not
4481 // actually be the case. Inform the frame's state machine if this frame has
4482 // already committed other loads.
4483 if (request_params.has_committed_real_load && frame_->parent())
4484 frame_->setCommittedFirstRealLoad();
4486 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
4487 // We cannot reload if we do not have any history state. This happens, for
4488 // example, when recovering from a crash.
4489 is_reload = false;
4490 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4493 pending_navigation_params_.reset(
4494 new NavigationParams(common_params, start_params, request_params));
4496 // Create parameters for a standard navigation.
4497 blink::WebFrameLoadType load_type = blink::WebFrameLoadType::Standard;
4498 bool should_load_request = false;
4499 WebHistoryItem item_for_history_navigation;
4500 WebURLRequest request = CreateURLRequestForNavigation(
4501 common_params, stream_params.Pass(), frame_->isViewSourceModeEnabled());
4502 #if defined(OS_ANDROID)
4503 request.setHasUserGesture(start_params.has_user_gesture);
4504 #endif
4506 // PlzNavigate: Make sure that Blink's loader will not try to use browser side
4507 // navigation for this request (since it already went to the browser).
4508 if (browser_side_navigation)
4509 request.setCheckForBrowserSideNavigation(false);
4511 // If we are reloading, then use the history state of the current frame.
4512 // Otherwise, if we have history state, then we need to navigate to it, which
4513 // corresponds to a back/forward navigation event. Update the parameters
4514 // depending on the navigation type.
4515 if (is_reload) {
4516 bool ignore_cache = (common_params.navigation_type ==
4517 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
4518 load_type = ignore_cache ? blink::WebFrameLoadType::ReloadFromOrigin
4519 : blink::WebFrameLoadType::Reload;
4521 if (!browser_side_navigation) {
4522 const GURL override_url =
4523 (common_params.navigation_type ==
4524 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL)
4525 ? common_params.url
4526 : GURL();
4527 request = frame_->requestForReload(load_type, override_url);
4529 should_load_request = true;
4530 } else if (is_history_navigation) {
4531 // We must know the page ID of the page we are navigating back to.
4532 DCHECK_NE(request_params.page_id, -1);
4533 // We must know the nav entry ID of the page we are navigating back to,
4534 // which should be the case because history navigations are routed via the
4535 // browser.
4536 DCHECK_NE(0, request_params.nav_entry_id);
4537 scoped_ptr<HistoryEntry> entry =
4538 PageStateToHistoryEntry(request_params.page_state);
4539 if (entry) {
4540 // Ensure we didn't save the swapped out URL in UpdateState, since the
4541 // browser should never be telling us to navigate to swappedout://.
4542 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
4544 if (!browser_side_navigation) {
4545 scoped_ptr<NavigationParams> navigation_params(
4546 new NavigationParams(*pending_navigation_params_.get()));
4547 if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) {
4548 // By default, tell the HistoryController to go the deserialized
4549 // HistoryEntry. This only works if all frames are in the same
4550 // process.
4551 DCHECK(!frame_->parent());
4552 render_view_->history_controller()->GoToEntry(
4553 frame_, entry.Pass(), navigation_params.Pass(), cache_policy);
4554 } else {
4555 // In --site-per-process, the browser process sends a single
4556 // WebHistoryItem destined for this frame.
4557 // TODO(creis): Change PageState to FrameState. In the meantime, we
4558 // store the relevant frame's WebHistoryItem in the root of the
4559 // PageState.
4560 SetPendingNavigationParams(navigation_params.Pass());
4561 blink::WebHistoryItem history_item = entry->root();
4562 blink::WebHistoryLoadType load_type =
4563 request_params.is_same_document_history_load
4564 ? blink::WebHistorySameDocumentLoad
4565 : blink::WebHistoryDifferentDocumentLoad;
4567 // Let the history controller know the provisional entry, since it is
4568 // used at commit time. Otherwise skip GoToEntry and navigate the
4569 // frame directly.
4570 // TODO(creis): Consider cloning the current entry to handle subframe
4571 // cases. Changes to SendUpdateState might affect this.
4572 render_view_->history_controller()->set_provisional_entry(
4573 entry.Pass());
4574 WebURLRequest request =
4575 frame_->requestFromHistoryItem(history_item, cache_policy);
4576 frame_->load(request, blink::WebFrameLoadType::BackForward,
4577 history_item, load_type);
4579 } else {
4580 // TODO(clamy): this should be set to the HistoryItem sent by the
4581 // browser once the HistoryController has moved to the browser.
4582 // TODO(clamy): distinguish between different document and same document
4583 // loads.
4584 // TODO(clamy): update this for subframes history loads.
4585 item_for_history_navigation =
4586 entry->GetHistoryNodeForFrame(this)->item();
4587 load_type = blink::WebFrameLoadType::BackForward;
4588 should_load_request = true;
4591 } else {
4592 // Navigate to the given URL.
4593 if (!start_params.extra_headers.empty() && !browser_side_navigation) {
4594 for (net::HttpUtil::HeadersIterator i(start_params.extra_headers.begin(),
4595 start_params.extra_headers.end(),
4596 "\n");
4597 i.GetNext();) {
4598 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
4599 WebString::fromUTF8(i.values()));
4603 if (start_params.is_post && !browser_side_navigation) {
4604 request.setHTTPMethod(WebString::fromUTF8("POST"));
4606 // Set post data.
4607 WebHTTPBody http_body;
4608 http_body.initialize();
4609 const char* data = nullptr;
4610 if (start_params.browser_initiated_post_data.size()) {
4611 data = reinterpret_cast<const char*>(
4612 &start_params.browser_initiated_post_data.front());
4614 http_body.appendData(
4615 WebData(data, start_params.browser_initiated_post_data.size()));
4616 request.setHTTPBody(http_body);
4619 // A session history navigation should have been accompanied by state.
4620 CHECK_EQ(request_params.page_id, -1);
4622 should_load_request = true;
4625 if (should_load_request) {
4626 // Record this before starting the load. We need a lower bound of this
4627 // time to sanitize the navigationStart override set below.
4628 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
4630 // Perform a navigation to a data url if needed.
4631 if (!common_params.base_url_for_data_url.is_empty() ||
4632 (browser_side_navigation &&
4633 common_params.url.SchemeIs(url::kDataScheme))) {
4634 LoadDataURL(common_params, frame_);
4635 } else {
4636 // Load the request.
4637 frame_->toWebLocalFrame()->load(request, load_type,
4638 item_for_history_navigation);
4641 if (load_type == blink::WebFrameLoadType::Standard) {
4642 UpdateFrameNavigationTiming(frame_,
4643 request_params.browser_navigation_start,
4644 renderer_navigation_start);
4648 // In case LoadRequest failed before didCreateDataSource was called.
4649 pending_navigation_params_.reset();
4652 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4653 const std::string& encoding_name) {
4654 // Only update main frame's encoding_name.
4655 if (!frame->parent())
4656 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4659 void RenderFrameImpl::SyncSelectionIfRequired() {
4660 base::string16 text;
4661 size_t offset;
4662 gfx::Range range;
4663 #if defined(ENABLE_PLUGINS)
4664 if (render_view_->focused_pepper_plugin_) {
4665 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4666 offset = 0; // Pepper API does not support offset reporting.
4667 // TODO(kinaba): cut as needed.
4668 } else
4669 #endif
4671 size_t location, length;
4672 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4673 &location, &length)) {
4674 return;
4677 range = gfx::Range(location, location + length);
4679 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4680 blink::WebTextInputTypeNone) {
4681 // If current focused element is editable, we will send 100 more chars
4682 // before and after selection. It is for input method surrounding text
4683 // feature.
4684 if (location > kExtraCharsBeforeAndAfterSelection)
4685 offset = location - kExtraCharsBeforeAndAfterSelection;
4686 else
4687 offset = 0;
4688 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4689 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4690 if (!webrange.isNull())
4691 text = webrange.toPlainText();
4692 } else {
4693 offset = location;
4694 text = frame_->selectionAsText();
4695 // http://crbug.com/101435
4696 // In some case, frame->selectionAsText() returned text's length is not
4697 // equal to the length returned from webwidget()->caretOrSelectionRange().
4698 // So we have to set the range according to text.length().
4699 range.set_end(range.start() + text.length());
4703 // Sometimes we get repeated didChangeSelection calls from webkit when
4704 // the selection hasn't actually changed. We don't want to report these
4705 // because it will cause us to continually claim the X clipboard.
4706 if (selection_text_offset_ != offset ||
4707 selection_range_ != range ||
4708 selection_text_ != text) {
4709 selection_text_ = text;
4710 selection_text_offset_ = offset;
4711 selection_range_ = range;
4712 SetSelectedText(text, offset, range);
4714 GetRenderWidget()->UpdateSelectionBounds();
4717 void RenderFrameImpl::InitializeUserMediaClient() {
4718 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4719 return;
4721 #if defined(ENABLE_WEBRTC)
4722 DCHECK(!web_user_media_client_);
4723 web_user_media_client_ = new UserMediaClientImpl(
4724 this,
4725 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4726 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4727 #endif
4730 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4731 WebMediaPlayerClient* client) {
4732 #if defined(ENABLE_WEBRTC)
4733 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4734 bool found_neon =
4735 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4736 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4737 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4738 scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner =
4739 RenderThreadImpl::current()->compositor_task_runner();
4740 if (!compositor_task_runner.get())
4741 compositor_task_runner = base::MessageLoop::current()->task_runner();
4742 return new WebMediaPlayerMS(
4743 frame_, client, weak_factory_.GetWeakPtr(), new RenderMediaLog(),
4744 CreateRendererFactory(),
4745 compositor_task_runner);
4746 #else
4747 return NULL;
4748 #endif // defined(ENABLE_WEBRTC)
4751 scoped_ptr<MediaStreamRendererFactory>
4752 RenderFrameImpl::CreateRendererFactory() {
4753 scoped_ptr<MediaStreamRendererFactory> factory =
4754 GetContentClient()->renderer()->CreateMediaStreamRendererFactory();
4755 if (factory.get())
4756 return factory.Pass();
4757 #if defined(ENABLE_WEBRTC)
4758 return scoped_ptr<MediaStreamRendererFactory>(
4759 new MediaStreamRendererFactoryImpl());
4760 #else
4761 return scoped_ptr<MediaStreamRendererFactory>(
4762 static_cast<MediaStreamRendererFactory*>(NULL));
4763 #endif
4766 void RenderFrameImpl::PrepareRenderViewForNavigation(
4767 const GURL& url,
4768 const RequestNavigationParams& request_params,
4769 bool* is_reload,
4770 WebURLRequest::CachePolicy* cache_policy) {
4771 DCHECK(render_view_->webview());
4773 MaybeHandleDebugURL(url);
4775 FOR_EACH_OBSERVER(
4776 RenderViewObserver, render_view_->observers_, Navigate(url));
4778 render_view_->history_list_offset_ =
4779 request_params.current_history_list_offset;
4780 render_view_->history_list_length_ =
4781 request_params.current_history_list_length;
4782 if (request_params.should_clear_history_list) {
4783 CHECK_EQ(-1, render_view_->history_list_offset_);
4784 CHECK_EQ(0, render_view_->history_list_length_);
4787 if (!is_swapped_out_ || frame_->parent())
4788 return;
4790 // This is a swapped out main frame, so swap the renderer back in.
4791 // We marked the view as hidden when swapping the view out, so be sure to
4792 // reset the visibility state before navigating to the new URL.
4793 render_view_->webview()->setVisibilityState(
4794 render_view_->visibilityState(), false);
4796 // If this is an attempt to reload while we are swapped out, we should not
4797 // reload swappedout://, but the previous page, which is stored in
4798 // params.state. Setting is_reload to false will treat this like a back
4799 // navigation to accomplish that.
4800 *is_reload = false;
4801 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4803 // We refresh timezone when a view is swapped in since timezone
4804 // can get out of sync when the system timezone is updated while
4805 // the view is swapped out.
4806 RenderThreadImpl::NotifyTimezoneChange();
4808 render_view_->SetSwappedOut(false);
4809 is_swapped_out_ = false;
4810 return;
4813 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4814 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4815 switches::kEnableBrowserSideNavigation));
4816 DCHECK(request);
4817 // TODO(clamy): Execute the beforeunload event.
4819 // Note: At this stage, the goal is to apply all the modifications the
4820 // renderer wants to make to the request, and then send it to the browser, so
4821 // that the actual network request can be started. Ideally, all such
4822 // modifications should take place in willSendRequest, and in the
4823 // implementation of willSendRequest for the various InspectorAgents
4824 // (devtools).
4826 // TODO(clamy): Apply devtools override.
4827 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4828 // else in blink.
4829 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4831 // TODO(clamy): Same-document navigations should not be sent back to the
4832 // browser.
4833 // TODO(clamy): Data urls should not be sent back to the browser either.
4834 bool should_replace_current_entry = false;
4835 WebDataSource* provisional_data_source = frame_->provisionalDataSource();
4836 WebDataSource* current_data_source = frame_->dataSource();
4837 WebDataSource* data_source =
4838 provisional_data_source ? provisional_data_source : current_data_source;
4840 // The current entry can only be replaced if there already is an entry in the
4841 // history list.
4842 if (data_source && render_view_->history_list_length_ > 0) {
4843 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
4845 Send(new FrameHostMsg_BeginNavigation(
4846 routing_id_,
4847 MakeCommonNavigationParams(request, should_replace_current_entry),
4848 BeginNavigationParams(
4849 request->httpMethod().latin1(), GetWebURLRequestHeaders(*request),
4850 GetLoadFlagsForWebURLRequest(*request), request->hasUserGesture()),
4851 GetRequestBodyForWebURLRequest(*request)));
4854 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams& params,
4855 WebFrame* frame) {
4856 // A loadData request with a specified base URL.
4857 std::string mime_type, charset, data;
4858 if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) {
4859 const GURL base_url = params.base_url_for_data_url.is_empty() ?
4860 params.url : params.base_url_for_data_url;
4861 frame->loadData(
4862 WebData(data.c_str(), data.length()),
4863 WebString::fromUTF8(mime_type),
4864 WebString::fromUTF8(charset),
4865 base_url,
4866 params.history_url_for_data_url,
4867 false);
4868 } else {
4869 CHECK(false) << "Invalid URL passed: "
4870 << params.url.possibly_invalid_spec();
4874 void RenderFrameImpl::SendFailedProvisionalLoad(
4875 const blink::WebURLRequest& request,
4876 const blink::WebURLError& error,
4877 blink::WebLocalFrame* frame) {
4878 bool show_repost_interstitial =
4879 (error.reason == net::ERR_CACHE_MISS &&
4880 base::EqualsASCII(base::StringPiece16(request.httpMethod()), "POST"));
4882 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
4883 params.error_code = error.reason;
4884 GetContentClient()->renderer()->GetNavigationErrorStrings(
4885 render_view_.get(), frame, request, error, NULL,
4886 &params.error_description);
4887 params.url = error.unreachableURL;
4888 params.showing_repost_interstitial = show_repost_interstitial;
4889 params.was_ignored_by_handler = error.wasIgnoredByHandler;
4890 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_, params));
4893 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4894 int error_code,
4895 const GURL& unreachable_url) {
4896 // Don't display an error page if this is simply a cancelled load. Aside
4897 // from being dumb, Blink doesn't expect it and it will cause a crash.
4898 if (error_code == net::ERR_ABORTED)
4899 return false;
4901 // Don't display "client blocked" error page if browser has asked us not to.
4902 if (error_code == net::ERR_BLOCKED_BY_CLIENT &&
4903 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
4904 return false;
4907 // Allow the embedder to suppress an error page.
4908 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4909 this, unreachable_url)) {
4910 return false;
4913 if (RenderThreadImpl::current() &&
4914 RenderThreadImpl::current()->layout_test_mode()) {
4915 return false;
4918 return true;
4921 GURL RenderFrameImpl::GetLoadingUrl() const {
4922 WebDataSource* ds = frame_->dataSource();
4923 if (ds->hasUnreachableURL())
4924 return ds->unreachableURL();
4926 const WebURLRequest& request = ds->request();
4927 return request.url();
4930 void RenderFrameImpl::PopulateDocumentStateFromPending(
4931 DocumentState* document_state) {
4932 document_state->set_request_time(
4933 pending_navigation_params_->request_params.request_time);
4935 InternalDocumentStateData* internal_data =
4936 InternalDocumentStateData::FromDocumentState(document_state);
4938 if (!pending_navigation_params_->common_params.url.SchemeIs(
4939 url::kJavaScriptScheme) &&
4940 pending_navigation_params_->common_params.navigation_type ==
4941 FrameMsg_Navigate_Type::RESTORE) {
4942 // We're doing a load of a page that was restored from the last session. By
4943 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4944 // can result in stale data for pages that are set to expire. We explicitly
4945 // override that by setting the policy here so that as necessary we load
4946 // from the network.
4948 // TODO(davidben): Remove this in favor of passing a cache policy to the
4949 // loadHistoryItem call in OnNavigate. That requires not overloading
4950 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4951 // policy based on load type, etc".
4952 internal_data->set_cache_policy_override(
4953 WebURLRequest::UseProtocolCachePolicy);
4956 if (IsReload(pending_navigation_params_->common_params.navigation_type))
4957 document_state->set_load_type(DocumentState::RELOAD);
4958 else if (pending_navigation_params_->request_params.page_state.IsValid())
4959 document_state->set_load_type(DocumentState::HISTORY_LOAD);
4960 else
4961 document_state->set_load_type(DocumentState::NORMAL_LOAD);
4963 internal_data->set_is_overriding_user_agent(
4964 pending_navigation_params_->request_params.is_overriding_user_agent);
4965 internal_data->set_must_reset_scroll_and_scale_state(
4966 pending_navigation_params_->common_params.navigation_type ==
4967 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
4968 document_state->set_can_load_local_resources(
4969 pending_navigation_params_->request_params.can_load_local_resources);
4972 NavigationState* RenderFrameImpl::CreateNavigationStateFromPending() {
4973 // A navigation resulting from loading a javascript URL should not be treated
4974 // as a browser initiated event. Instead, we want it to look as if the page
4975 // initiated any load resulting from JS execution.
4976 if (!pending_navigation_params_->common_params.url.SchemeIs(
4977 url::kJavaScriptScheme)) {
4978 return NavigationStateImpl::CreateBrowserInitiated(
4979 pending_navigation_params_->common_params,
4980 pending_navigation_params_->start_params,
4981 pending_navigation_params_->request_params);
4983 return NavigationStateImpl::CreateContentInitiated();
4986 #if defined(OS_ANDROID)
4987 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4988 WebMediaPlayerClient* client,
4989 WebMediaPlayerEncryptedMediaClient* encrypted_client,
4990 const media::WebMediaPlayerParams& params) {
4991 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4992 if (SynchronousCompositorFactory* factory =
4993 SynchronousCompositorFactory::GetInstance()) {
4994 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4995 } else {
4996 GpuChannelHost* gpu_channel_host =
4997 RenderThreadImpl::current()->EstablishGpuChannelSync(
4998 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
5000 if (!gpu_channel_host) {
5001 LOG(ERROR) << "Failed to establish GPU channel for media player";
5002 return NULL;
5005 scoped_refptr<cc_blink::ContextProviderWebContext> context_provider =
5006 RenderThreadImpl::current()->SharedMainThreadContextProvider();
5008 if (!context_provider.get()) {
5009 LOG(ERROR) << "Failed to get context3d for media player";
5010 return NULL;
5013 stream_texture_factory = StreamTextureFactoryImpl::Create(
5014 context_provider, gpu_channel_host, routing_id_);
5017 return new WebMediaPlayerAndroid(
5018 frame_, client, encrypted_client, weak_factory_.GetWeakPtr(),
5019 GetMediaPlayerManager(), GetCdmFactory(), stream_texture_factory, params);
5022 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
5023 if (!media_player_manager_)
5024 media_player_manager_ = new RendererMediaPlayerManager(this);
5025 return media_player_manager_;
5027 #endif // defined(OS_ANDROID)
5029 media::MediaPermission* RenderFrameImpl::GetMediaPermission() {
5030 if (!media_permission_dispatcher_)
5031 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
5032 return media_permission_dispatcher_;
5035 #if defined(ENABLE_MOJO_MEDIA)
5036 media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() {
5037 if (!media_service_factory_) {
5038 mojo::ServiceProviderPtr service_provider =
5039 ConnectToApplication(GURL("mojo:media"));
5040 mojo::ConnectToService(service_provider.get(), &media_service_factory_);
5041 media_service_factory_.set_connection_error_handler(
5042 base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError,
5043 base::Unretained(this)));
5046 return media_service_factory_.get();
5049 void RenderFrameImpl::OnMediaServiceFactoryConnectionError() {
5050 // TODO(xhwang): Resetting |media_service_factory_| could cause access
5051 // violation on the old |media_service_factory_| by outstanding
5052 // media::CdmFactory or media::RendererFactory. Find a better way to handle
5053 // this.
5054 // media_service_factory_.reset();
5056 #endif
5058 bool RenderFrameImpl::AreSecureCodecsSupported() {
5059 #if defined(OS_ANDROID)
5060 // Hardware-secure codecs are only supported if secure surfaces are enabled.
5061 return render_view_->renderer_preferences_
5062 .use_video_overlay_for_embedded_encrypted_video;
5063 #else
5064 return false;
5065 #endif // defined(OS_ANDROID)
5068 media::CdmFactory* RenderFrameImpl::GetCdmFactory() {
5069 #if defined(ENABLE_BROWSER_CDMS)
5070 if (!cdm_manager_)
5071 cdm_manager_ = new RendererCdmManager(this);
5072 #endif // defined(ENABLE_BROWSER_CDMS)
5074 if (!cdm_factory_) {
5075 DCHECK(frame_);
5077 #if defined(ENABLE_MOJO_MEDIA)
5078 cdm_factory_.reset(new media::MojoCdmFactory(GetMediaServiceFactory()));
5079 #else
5080 cdm_factory_.reset(new RenderCdmFactory(
5081 #if defined(ENABLE_PEPPER_CDMS)
5082 base::Bind(&PepperCdmWrapperImpl::Create, frame_)
5083 #elif defined(ENABLE_BROWSER_CDMS)
5084 cdm_manager_
5085 #endif
5087 #endif // defined(ENABLE_MOJO_MEDIA)
5090 return cdm_factory_.get();
5093 void RenderFrameImpl::RegisterMojoServices() {
5094 // Only main frame have ImageDownloader service.
5095 if (!frame_->parent()) {
5096 GetServiceRegistry()->AddService<image_downloader::ImageDownloader>(
5097 base::Bind(&ImageDownloaderImpl::CreateMojoService,
5098 base::Unretained(this)));
5102 mojo::ServiceProviderPtr RenderFrameImpl::ConnectToApplication(
5103 const GURL& url) {
5104 DCHECK(mojo_shell_);
5105 mojo::ServiceProviderPtr service_provider;
5106 mojo::URLRequestPtr request(mojo::URLRequest::New());
5107 request->url = mojo::String::From(url);
5108 mojo_shell_->ConnectToApplication(request.Pass(), GetProxy(&service_provider),
5109 nullptr, nullptr,
5110 base::Bind(&OnGotContentHandlerID));
5111 return service_provider.Pass();
5114 } // namespace content