Re-enable blink_perf.canvas on Windows
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blobd21b492c09ef014f99480f2a81c0edf3dd7bed23
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/time/time.h"
21 #include "cc/base/switches.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/permissions/permission_dispatcher.h"
24 #include "content/child/plugin_messages.h"
25 #include "content/child/quota_dispatcher.h"
26 #include "content/child/request_extra_data.h"
27 #include "content/child/service_worker/service_worker_handle_reference.h"
28 #include "content/child/service_worker/service_worker_network_provider.h"
29 #include "content/child/service_worker/service_worker_provider_context.h"
30 #include "content/child/service_worker/web_service_worker_provider_impl.h"
31 #include "content/child/v8_value_converter_impl.h"
32 #include "content/child/web_url_loader_impl.h"
33 #include "content/child/web_url_request_util.h"
34 #include "content/child/webmessageportchannel_impl.h"
35 #include "content/child/websocket_bridge.h"
36 #include "content/child/weburlresponse_extradata_impl.h"
37 #include "content/common/clipboard_messages.h"
38 #include "content/common/frame_messages.h"
39 #include "content/common/frame_replication_state.h"
40 #include "content/common/input_messages.h"
41 #include "content/common/navigation_params.h"
42 #include "content/common/service_worker/service_worker_types.h"
43 #include "content/common/swapped_out_messages.h"
44 #include "content/common/view_messages.h"
45 #include "content/public/common/bindings_policy.h"
46 #include "content/public/common/content_constants.h"
47 #include "content/public/common/content_switches.h"
48 #include "content/public/common/context_menu_params.h"
49 #include "content/public/common/page_state.h"
50 #include "content/public/common/resource_response.h"
51 #include "content/public/common/url_constants.h"
52 #include "content/public/common/url_utils.h"
53 #include "content/public/renderer/browser_plugin_delegate.h"
54 #include "content/public/renderer/content_renderer_client.h"
55 #include "content/public/renderer/context_menu_client.h"
56 #include "content/public/renderer/document_state.h"
57 #include "content/public/renderer/isolated_world_ids.h"
58 #include "content/public/renderer/navigation_state.h"
59 #include "content/public/renderer/render_frame_observer.h"
60 #include "content/public/renderer/renderer_ppapi_host.h"
61 #include "content/renderer/accessibility/renderer_accessibility.h"
62 #include "content/renderer/browser_plugin/browser_plugin.h"
63 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
64 #include "content/renderer/child_frame_compositing_helper.h"
65 #include "content/renderer/context_menu_params_builder.h"
66 #include "content/renderer/devtools/devtools_agent.h"
67 #include "content/renderer/dom_automation_controller.h"
68 #include "content/renderer/dom_utils.h"
69 #include "content/renderer/external_popup_menu.h"
70 #include "content/renderer/geolocation_dispatcher.h"
71 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
72 #include "content/renderer/history_controller.h"
73 #include "content/renderer/history_serialization.h"
74 #include "content/renderer/image_loading_helper.h"
75 #include "content/renderer/ime_event_guard.h"
76 #include "content/renderer/internal_document_state_data.h"
77 #include "content/renderer/manifest/manifest_manager.h"
78 #include "content/renderer/media/audio_renderer_mixer_manager.h"
79 #include "content/renderer/media/crypto/render_cdm_factory.h"
80 #include "content/renderer/media/media_permission_dispatcher.h"
81 #include "content/renderer/media/media_stream_dispatcher.h"
82 #include "content/renderer/media/media_stream_renderer_factory.h"
83 #include "content/renderer/media/midi_dispatcher.h"
84 #include "content/renderer/media/render_media_log.h"
85 #include "content/renderer/media/user_media_client_impl.h"
86 #include "content/renderer/media/webmediaplayer_ms.h"
87 #include "content/renderer/memory_benchmarking_extension.h"
88 #include "content/renderer/mojo/service_registry_js_wrapper.h"
89 #include "content/renderer/navigation_state_impl.h"
90 #include "content/renderer/notification_permission_dispatcher.h"
91 #include "content/renderer/npapi/plugin_channel_host.h"
92 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
93 #include "content/renderer/presentation/presentation_dispatcher.h"
94 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
95 #include "content/renderer/render_frame_proxy.h"
96 #include "content/renderer/render_process.h"
97 #include "content/renderer/render_thread_impl.h"
98 #include "content/renderer/render_view_impl.h"
99 #include "content/renderer/render_widget_fullscreen_pepper.h"
100 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
101 #include "content/renderer/renderer_webcolorchooser_impl.h"
102 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
103 #include "content/renderer/shared_worker_repository.h"
104 #include "content/renderer/skia_benchmarking_extension.h"
105 #include "content/renderer/stats_collection_controller.h"
106 #include "content/renderer/web_ui_extension.h"
107 #include "content/renderer/websharedworker_proxy.h"
108 #include "gin/modules/module_registry.h"
109 #include "media/base/audio_renderer_mixer_input.h"
110 #include "media/base/media_log.h"
111 #include "media/blink/webencryptedmediaclient_impl.h"
112 #include "media/blink/webmediaplayer_impl.h"
113 #include "media/blink/webmediaplayer_params.h"
114 #include "media/renderers/gpu_video_accelerator_factories.h"
115 #include "net/base/data_url.h"
116 #include "net/base/net_errors.h"
117 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
118 #include "net/http/http_util.h"
119 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
120 #include "third_party/WebKit/public/platform/WebString.h"
121 #include "third_party/WebKit/public/platform/WebURL.h"
122 #include "third_party/WebKit/public/platform/WebURLError.h"
123 #include "third_party/WebKit/public/platform/WebURLResponse.h"
124 #include "third_party/WebKit/public/platform/WebVector.h"
125 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
126 #include "third_party/WebKit/public/web/WebDocument.h"
127 #include "third_party/WebKit/public/web/WebFrameWidget.h"
128 #include "third_party/WebKit/public/web/WebGlyphCache.h"
129 #include "third_party/WebKit/public/web/WebKit.h"
130 #include "third_party/WebKit/public/web/WebLocalFrame.h"
131 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
132 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
133 #include "third_party/WebKit/public/web/WebPlugin.h"
134 #include "third_party/WebKit/public/web/WebPluginParams.h"
135 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
136 #include "third_party/WebKit/public/web/WebRange.h"
137 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
138 #include "third_party/WebKit/public/web/WebScriptSource.h"
139 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
140 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
141 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
142 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
143 #include "third_party/WebKit/public/web/WebSettings.h"
144 #include "third_party/WebKit/public/web/WebSurroundingText.h"
145 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
146 #include "third_party/WebKit/public/web/WebView.h"
147 #include "third_party/mojo/src/mojo/edk/js/core.h"
148 #include "third_party/mojo/src/mojo/edk/js/support.h"
150 #if defined(ENABLE_PLUGINS)
151 #include "content/renderer/npapi/webplugin_impl.h"
152 #include "content/renderer/pepper/pepper_browser_connection.h"
153 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
154 #include "content/renderer/pepper/pepper_webplugin_impl.h"
155 #include "content/renderer/pepper/plugin_module.h"
156 #endif
158 #if defined(ENABLE_WEBRTC)
159 #include "content/renderer/media/rtc_peer_connection_handler.h"
160 #endif
162 #if defined(OS_ANDROID)
163 #include <cpu-features.h>
165 #include "content/common/gpu/client/context_provider_command_buffer.h"
166 #include "content/renderer/android/synchronous_compositor_factory.h"
167 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
168 #include "content/renderer/media/android/renderer_media_player_manager.h"
169 #include "content/renderer/media/android/stream_texture_factory_impl.h"
170 #include "content/renderer/media/android/webmediaplayer_android.h"
171 #else
172 #include "cc/blink/context_provider_web_context.h"
173 #endif
175 #if defined(ENABLE_PEPPER_CDMS)
176 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
177 #elif defined(ENABLE_BROWSER_CDMS)
178 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
179 #endif
181 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
182 #include "content/renderer/media/media_renderer_service_provider.h"
183 #include "media/mojo/services/mojo_renderer_factory.h"
184 #else
185 #include "media/renderers/default_renderer_factory.h"
186 #endif
188 using blink::WebContextMenuData;
189 using blink::WebData;
190 using blink::WebDataSource;
191 using blink::WebDocument;
192 using blink::WebDOMEvent;
193 using blink::WebDOMMessageEvent;
194 using blink::WebElement;
195 using blink::WebExternalPopupMenu;
196 using blink::WebExternalPopupMenuClient;
197 using blink::WebFrame;
198 using blink::WebHistoryItem;
199 using blink::WebHTTPBody;
200 using blink::WebLocalFrame;
201 using blink::WebMediaPlayer;
202 using blink::WebMediaPlayerClient;
203 using blink::WebNavigationPolicy;
204 using blink::WebNavigationType;
205 using blink::WebNode;
206 using blink::WebPluginParams;
207 using blink::WebPopupMenuInfo;
208 using blink::WebRange;
209 using blink::WebReferrerPolicy;
210 using blink::WebScriptSource;
211 using blink::WebSearchableFormData;
212 using blink::WebSecurityOrigin;
213 using blink::WebSecurityPolicy;
214 using blink::WebSerializedScriptValue;
215 using blink::WebServiceWorkerProvider;
216 using blink::WebStorageQuotaCallbacks;
217 using blink::WebString;
218 using blink::WebURL;
219 using blink::WebURLError;
220 using blink::WebURLRequest;
221 using blink::WebURLResponse;
222 using blink::WebUserGestureIndicator;
223 using blink::WebVector;
224 using blink::WebView;
225 using base::Time;
226 using base::TimeDelta;
228 namespace content {
230 namespace {
232 const char kDefaultAcceptHeader[] =
233 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
234 "*;q=0.8";
235 const char kAcceptHeader[] = "Accept";
237 const size_t kExtraCharsBeforeAndAfterSelection = 100;
239 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
240 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
241 LAZY_INSTANCE_INITIALIZER;
243 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
244 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
246 int64 ExtractPostId(HistoryEntry* entry) {
247 if (!entry)
248 return -1;
250 const WebHistoryItem& item = entry->root();
251 if (item.isNull() || item.httpBody().isNull())
252 return -1;
254 return item.httpBody().identifier();
257 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
258 const WebURLResponse& response) {
259 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
262 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
263 // Replace any occurrences of swappedout:// with about:blank.
264 const WebURL& blank_url = GURL(url::kAboutBlankURL);
265 WebVector<WebURL> urls;
266 ds->redirectChain(urls);
267 result->reserve(urls.size());
268 for (size_t i = 0; i < urls.size(); ++i) {
269 if (urls[i] != GURL(kSwappedOutURL))
270 result->push_back(urls[i]);
271 else
272 result->push_back(blank_url);
276 // Returns the original request url. If there is no redirect, the original
277 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
278 // frame was loaded by loadData, the original url will be ds->unreachableURL()
279 GURL GetOriginalRequestURL(WebDataSource* ds) {
280 // WebDataSource has unreachable URL means that the frame is loaded through
281 // blink::WebFrame::loadData(), and the base URL will be in the redirect
282 // chain. However, we never visited the baseURL. So in this case, we should
283 // use the unreachable URL as the original URL.
284 if (ds->hasUnreachableURL())
285 return ds->unreachableURL();
287 std::vector<GURL> redirects;
288 GetRedirectChain(ds, &redirects);
289 if (!redirects.empty())
290 return redirects.at(0);
292 return ds->originalRequest().url();
295 NOINLINE void CrashIntentionally() {
296 // NOTE(shess): Crash directly rather than using NOTREACHED() so
297 // that the signature is easier to triage in crash reports.
298 volatile int* zero = NULL;
299 *zero = 0;
302 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
303 NOINLINE void MaybeTriggerAsanError(const GURL& url) {
304 // NOTE(rogerm): We intentionally perform an invalid heap access here in
305 // order to trigger an Address Sanitizer (ASAN) error report.
306 const char kCrashDomain[] = "crash";
307 const char kHeapOverflow[] = "/heap-overflow";
308 const char kHeapUnderflow[] = "/heap-underflow";
309 const char kUseAfterFree[] = "/use-after-free";
310 #if defined(SYZYASAN)
311 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
312 const char kCorruptHeap[] = "/corrupt-heap";
313 #endif
315 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
316 return;
318 if (!url.has_path())
319 return;
321 std::string crash_type(url.path());
322 if (crash_type == kHeapOverflow) {
323 base::debug::AsanHeapOverflow();
324 } else if (crash_type == kHeapUnderflow ) {
325 base::debug::AsanHeapUnderflow();
326 } else if (crash_type == kUseAfterFree) {
327 base::debug::AsanHeapUseAfterFree();
328 #if defined(SYZYASAN)
329 } else if (crash_type == kCorruptHeapBlock) {
330 base::debug::AsanCorruptHeapBlock();
331 } else if (crash_type == kCorruptHeap) {
332 base::debug::AsanCorruptHeap();
333 #endif
336 #endif // ADDRESS_SANITIZER || SYZYASAN
338 void MaybeHandleDebugURL(const GURL& url) {
339 if (!url.SchemeIs(kChromeUIScheme))
340 return;
341 if (url == GURL(kChromeUICrashURL)) {
342 CrashIntentionally();
343 } else if (url == GURL(kChromeUIDumpURL)) {
344 // This URL will only correctly create a crash dump file if content is
345 // hosted in a process that has correctly called
346 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
347 // of base::debug::DumpWithoutCrashing for more details.
348 base::debug::DumpWithoutCrashing();
349 } else if (url == GURL(kChromeUIKillURL)) {
350 base::Process::Current().Terminate(1, false);
351 } else if (url == GURL(kChromeUIHangURL)) {
352 for (;;) {
353 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
355 } else if (url == GURL(kChromeUIShorthangURL)) {
356 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
359 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
360 MaybeTriggerAsanError(url);
361 #endif // ADDRESS_SANITIZER || SYZYASAN
364 // Returns false unless this is a top-level navigation.
365 bool IsTopLevelNavigation(WebFrame* frame) {
366 return frame->parent() == NULL;
369 // Returns false unless this is a top-level navigation that crosses origins.
370 bool IsNonLocalTopLevelNavigation(const GURL& url,
371 WebFrame* frame,
372 WebNavigationType type,
373 bool is_form_post) {
374 if (!IsTopLevelNavigation(frame))
375 return false;
377 // Navigations initiated within Webkit are not sent out to the external host
378 // in the following cases.
379 // 1. The url scheme is not http/https
380 // 2. The origin of the url and the opener is the same in which case the
381 // opener relationship is maintained.
382 // 3. Reloads/form submits/back forward navigations
383 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
384 return false;
386 if (type != blink::WebNavigationTypeReload &&
387 type != blink::WebNavigationTypeBackForward && !is_form_post) {
388 // The opener relationship between the new window and the parent allows the
389 // new window to script the parent and vice versa. This is not allowed if
390 // the origins of the two domains are different. This can be treated as a
391 // top level navigation and routed back to the host.
392 blink::WebFrame* opener = frame->opener();
393 if (!opener)
394 return true;
396 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
397 return true;
399 return false;
402 WebURLRequest CreateURLRequestForNavigation(
403 const CommonNavigationParams& common_params,
404 scoped_ptr<StreamOverrideParameters> stream_override,
405 bool is_view_source_mode_enabled) {
406 WebURLRequest request(common_params.url);
407 if (is_view_source_mode_enabled)
408 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
410 if (common_params.referrer.url.is_valid()) {
411 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
412 common_params.referrer.policy,
413 common_params.url,
414 WebString::fromUTF8(common_params.referrer.url.spec()));
415 if (!web_referrer.isEmpty())
416 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
419 RequestExtraData* extra_data = new RequestExtraData();
420 extra_data->set_stream_override(stream_override.Pass());
421 request.setExtraData(extra_data);
423 // Set the ui timestamp for this navigation. Currently the timestamp here is
424 // only non empty when the navigation was triggered by an Android intent. The
425 // timestamp is converted to a double version supported by blink. It will be
426 // passed back to the browser in the DidCommitProvisionalLoad and the
427 // DocumentLoadComplete IPCs.
428 base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
429 request.setUiStartTime(ui_timestamp.InSecondsF());
430 request.setInputPerfMetricReportPolicy(
431 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
432 common_params.report_type));
433 return request;
436 void UpdateFrameNavigationTiming(WebFrame* frame,
437 base::TimeTicks browser_navigation_start,
438 base::TimeTicks renderer_navigation_start) {
439 // The browser provides the navigation_start time to bootstrap the
440 // Navigation Timing information for the browser-initiated navigations. In
441 // case of cross-process navigations, this carries over the time of
442 // finishing the onbeforeunload handler of the previous page.
443 DCHECK(!browser_navigation_start.is_null());
444 if (frame->provisionalDataSource()) {
445 // |browser_navigation_start| is likely before this process existed, so we
446 // can't use InterProcessTimeTicksConverter. We need at least to ensure
447 // that the browser-side navigation start we set is not later than the one
448 // on the renderer side.
449 base::TimeTicks navigation_start = std::min(
450 browser_navigation_start, renderer_navigation_start);
451 double navigation_start_seconds =
452 (navigation_start - base::TimeTicks()).InSecondsF();
453 frame->provisionalDataSource()->setNavigationStartTime(
454 navigation_start_seconds);
455 // TODO(clamy): We need to provide additional timing values for the
456 // Navigation Timing API to work with browser-side navigations.
460 // PlzNavigate
461 CommonNavigationParams MakeCommonNavigationParams(
462 blink::WebURLRequest* request) {
463 const RequestExtraData kEmptyData;
464 const RequestExtraData* extra_data =
465 static_cast<RequestExtraData*>(request->extraData());
466 if (!extra_data)
467 extra_data = &kEmptyData;
468 Referrer referrer(
469 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
470 request->referrerPolicy());
472 // Set the ui timestamp for this navigation. Currently the timestamp here is
473 // only non empty when the navigation was triggered by an Android intent, or
474 // by the user clicking on a link. The timestamp is converted from a double
475 // version supported by blink. It will be passed back to the renderer in the
476 // CommitNavigation IPC, and then back to the browser again in the
477 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
478 base::TimeTicks ui_timestamp =
479 base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
480 FrameMsg_UILoadMetricsReportType::Value report_type =
481 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
482 request->inputPerfMetricReportPolicy());
483 return CommonNavigationParams(request->url(), referrer,
484 extra_data->transition_type(),
485 FrameMsg_Navigate_Type::NORMAL, true,
486 ui_timestamp, report_type, GURL(), GURL());
489 #if !defined(OS_ANDROID)
490 media::Context3D GetSharedMainThreadContext3D() {
491 cc::ContextProvider* provider =
492 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
493 if (!provider)
494 return media::Context3D();
495 return media::Context3D(provider->ContextGL(), provider->GrContext());
497 #endif
499 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
500 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
501 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
502 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
505 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
506 nullptr;
508 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
509 static_assert( \
510 static_cast<int>(content_name) == static_cast<int>(blink_name), \
511 "enum values must match")
513 // Check that blink::WebSandboxFlags is kept in sync with
514 // content::SandboxFlags.
515 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE,
516 blink::WebSandboxFlags::None);
517 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION,
518 blink::WebSandboxFlags::Navigation);
519 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS,
520 blink::WebSandboxFlags::Plugins);
521 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN,
522 blink::WebSandboxFlags::Origin);
523 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS,
524 blink::WebSandboxFlags::Forms);
525 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS,
526 blink::WebSandboxFlags::Scripts);
527 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION,
528 blink::WebSandboxFlags::TopNavigation);
529 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS,
530 blink::WebSandboxFlags::Popups);
531 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES,
532 blink::WebSandboxFlags::AutomaticFeatures);
533 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK,
534 blink::WebSandboxFlags::PointerLock);
535 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN,
536 blink::WebSandboxFlags::DocumentDomain);
537 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK,
538 blink::WebSandboxFlags::OrientationLock);
539 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL,
540 blink::WebSandboxFlags::All);
542 } // namespace
544 // static
545 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
546 int32 routing_id) {
547 DCHECK(routing_id != MSG_ROUTING_NONE);
549 if (g_create_render_frame_impl)
550 return g_create_render_frame_impl(render_view, routing_id);
551 else
552 return new RenderFrameImpl(render_view, routing_id);
555 // static
556 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
557 RoutingIDFrameMap::iterator iter =
558 g_routing_id_frame_map.Get().find(routing_id);
559 if (iter != g_routing_id_frame_map.Get().end())
560 return iter->second;
561 return NULL;
564 // static
565 void RenderFrameImpl::CreateFrame(
566 int routing_id,
567 int parent_routing_id,
568 int previous_sibling_routing_id,
569 int proxy_routing_id,
570 const FrameReplicationState& replicated_state,
571 CompositorDependencies* compositor_deps,
572 const FrameMsg_NewFrame_WidgetParams& widget_params) {
573 // TODO(nasko): For now, this message is only sent for subframes, as the
574 // top level frame is created when the RenderView is created through the
575 // ViewMsg_New IPC.
576 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
578 blink::WebLocalFrame* web_frame;
579 RenderFrameImpl* render_frame;
580 if (proxy_routing_id == MSG_ROUTING_NONE) {
581 RenderFrameProxy* parent_proxy =
582 RenderFrameProxy::FromRoutingID(parent_routing_id);
583 // If the browser is sending a valid parent routing id, it should already
584 // be created and registered.
585 CHECK(parent_proxy);
586 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
588 blink::WebFrame* previous_sibling_web_frame = nullptr;
589 RenderFrameProxy* previous_sibling_proxy =
590 RenderFrameProxy::FromRoutingID(previous_sibling_routing_id);
591 if (previous_sibling_proxy)
592 previous_sibling_web_frame = previous_sibling_proxy->web_frame();
594 // Create the RenderFrame and WebLocalFrame, linking the two.
595 render_frame =
596 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
597 web_frame = parent_web_frame->createLocalChild(
598 WebString::fromUTF8(replicated_state.name),
599 ContentToWebSandboxFlags(replicated_state.sandbox_flags), render_frame,
600 previous_sibling_web_frame);
601 } else {
602 RenderFrameProxy* proxy =
603 RenderFrameProxy::FromRoutingID(proxy_routing_id);
604 CHECK(proxy);
605 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
606 web_frame = blink::WebLocalFrame::create(render_frame);
607 render_frame->proxy_routing_id_ = proxy_routing_id;
608 web_frame->initializeToReplaceRemoteFrame(
609 proxy->web_frame(), WebString::fromUTF8(replicated_state.name),
610 ContentToWebSandboxFlags(replicated_state.sandbox_flags));
612 render_frame->SetWebFrame(web_frame);
614 if (widget_params.routing_id != MSG_ROUTING_NONE) {
615 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
616 switches::kSitePerProcess));
617 render_frame->render_widget_ = RenderWidget::CreateForFrame(
618 widget_params.routing_id, widget_params.surface_id,
619 widget_params.hidden, render_frame->render_view_->screen_info(),
620 compositor_deps, web_frame);
621 // TODO(kenrb): Observing shouldn't be necessary when we sort out
622 // WasShown and WasHidden, separating page-level visibility from
623 // frame-level visibility.
624 render_frame->render_widget_->RegisterRenderFrame(render_frame);
627 render_frame->Initialize();
630 // static
631 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
632 return RenderFrameImpl::FromWebFrame(web_frame);
635 // static
636 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
637 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
638 if (iter != g_frame_map.Get().end())
639 return iter->second;
640 return NULL;
643 // static
644 void RenderFrameImpl::InstallCreateHook(
645 CreateRenderFrameImplFunction create_render_frame_impl) {
646 CHECK(!g_create_render_frame_impl);
647 g_create_render_frame_impl = create_render_frame_impl;
650 // static
651 content::SandboxFlags RenderFrameImpl::WebToContentSandboxFlags(
652 blink::WebSandboxFlags flags) {
653 return static_cast<content::SandboxFlags>(flags);
656 // static
657 blink::WebSandboxFlags RenderFrameImpl::ContentToWebSandboxFlags(
658 content::SandboxFlags flags) {
659 return static_cast<blink::WebSandboxFlags>(flags);
662 // RenderFrameImpl ----------------------------------------------------------
663 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
664 : frame_(NULL),
665 is_subframe_(false),
666 is_local_root_(false),
667 render_view_(render_view->AsWeakPtr()),
668 routing_id_(routing_id),
669 is_swapped_out_(false),
670 render_frame_proxy_(NULL),
671 is_detaching_(false),
672 proxy_routing_id_(MSG_ROUTING_NONE),
673 #if defined(ENABLE_PLUGINS)
674 plugin_power_saver_helper_(NULL),
675 #endif
676 cookie_jar_(this),
677 selection_text_offset_(0),
678 selection_range_(gfx::Range::InvalidRange()),
679 handling_select_range_(false),
680 notification_permission_dispatcher_(NULL),
681 web_user_media_client_(NULL),
682 media_permission_dispatcher_(NULL),
683 midi_dispatcher_(NULL),
684 #if defined(OS_ANDROID)
685 media_player_manager_(NULL),
686 #endif
687 #if defined(ENABLE_BROWSER_CDMS)
688 cdm_manager_(NULL),
689 #endif
690 cdm_factory_(NULL),
691 #if defined(VIDEO_HOLE)
692 contains_media_player_(false),
693 #endif
694 devtools_agent_(nullptr),
695 geolocation_dispatcher_(NULL),
696 push_messaging_dispatcher_(NULL),
697 presentation_dispatcher_(NULL),
698 screen_orientation_dispatcher_(NULL),
699 manifest_manager_(NULL),
700 accessibility_mode_(AccessibilityModeOff),
701 renderer_accessibility_(NULL),
702 weak_factory_(this) {
703 std::pair<RoutingIDFrameMap::iterator, bool> result =
704 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
705 CHECK(result.second) << "Inserting a duplicate item.";
707 RenderThread::Get()->AddRoute(routing_id_, this);
709 render_view_->RegisterRenderFrame(this);
711 // Everything below subclasses RenderFrameObserver and is automatically
712 // deleted when the RenderFrame gets deleted.
713 #if defined(OS_ANDROID)
714 new GinJavaBridgeDispatcher(this);
715 #endif
717 #if defined(ENABLE_PLUGINS)
718 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
719 #endif
721 manifest_manager_ = new ManifestManager(this);
724 RenderFrameImpl::~RenderFrameImpl() {
725 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
726 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
728 #if defined(VIDEO_HOLE)
729 if (contains_media_player_)
730 render_view_->UnregisterVideoHoleFrame(this);
731 #endif
733 if (!is_subframe_) {
734 // RenderFrameProxy is "owned" by RenderFrameImpl in the case it is
735 // the main frame. Ensure it is deleted along with this object.
736 if (render_frame_proxy_) {
737 // The following method calls back into this object and clears
738 // |render_frame_proxy_|.
739 render_frame_proxy_->frameDetached();
742 // Ensure the RenderView doesn't point to this object, once it is destroyed.
743 CHECK_EQ(render_view_->main_render_frame_, this);
744 render_view_->main_render_frame_ = nullptr;
747 render_view_->UnregisterRenderFrame(this);
748 g_routing_id_frame_map.Get().erase(routing_id_);
749 RenderThread::Get()->RemoveRoute(routing_id_);
752 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
753 DCHECK(!frame_);
755 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
756 std::make_pair(web_frame, this));
757 CHECK(result.second) << "Inserting a duplicate item.";
759 frame_ = web_frame;
762 void RenderFrameImpl::Initialize() {
763 is_subframe_ = !!frame_->parent();
764 is_local_root_ = !frame_->parent() || frame_->parent()->isWebRemoteFrame();
766 #if defined(ENABLE_PLUGINS)
767 new PepperBrowserConnection(this);
768 #endif
769 new SharedWorkerRepository(this);
771 if (!frame_->parent())
772 new ImageLoadingHelper(this);
774 if (is_local_root_ && !render_frame_proxy_) {
775 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
776 // when |this| is deleted.
777 devtools_agent_ = new DevToolsAgent(this);
780 // We delay calling this until we have the WebFrame so that any observer or
781 // embedder can call GetWebFrame on any RenderFrame.
782 GetContentClient()->renderer()->RenderFrameCreated(this);
785 RenderWidget* RenderFrameImpl::GetRenderWidget() {
786 return render_view_.get();
789 #if defined(ENABLE_PLUGINS)
790 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
791 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
792 DidCreatePepperPlugin(host));
793 if (host->GetPluginName() == kFlashPluginName) {
794 RenderThread::Get()->RecordAction(
795 base::UserMetricsAction("FrameLoadWithFlash"));
799 void RenderFrameImpl::PepperDidChangeCursor(
800 PepperPluginInstanceImpl* instance,
801 const blink::WebCursorInfo& cursor) {
802 // Update the cursor appearance immediately if the requesting plugin is the
803 // one which receives the last mouse event. Otherwise, the new cursor won't be
804 // picked up until the plugin gets the next input event. That is bad if, e.g.,
805 // the plugin would like to set an invisible cursor when there isn't any user
806 // input for a while.
807 if (instance == render_view_->pepper_last_mouse_event_target())
808 GetRenderWidget()->didChangeCursor(cursor);
811 void RenderFrameImpl::PepperDidReceiveMouseEvent(
812 PepperPluginInstanceImpl* instance) {
813 render_view_->set_pepper_last_mouse_event_target(instance);
816 void RenderFrameImpl::PepperTextInputTypeChanged(
817 PepperPluginInstanceImpl* instance) {
818 if (instance != render_view_->focused_pepper_plugin())
819 return;
821 GetRenderWidget()->UpdateTextInputType();
823 FocusedNodeChangedForAccessibility(WebNode());
826 void RenderFrameImpl::PepperCaretPositionChanged(
827 PepperPluginInstanceImpl* instance) {
828 if (instance != render_view_->focused_pepper_plugin())
829 return;
830 GetRenderWidget()->UpdateSelectionBounds();
833 void RenderFrameImpl::PepperCancelComposition(
834 PepperPluginInstanceImpl* instance) {
835 if (instance != render_view_->focused_pepper_plugin())
836 return;
837 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
838 #if defined(OS_MACOSX) || defined(USE_AURA)
839 GetRenderWidget()->UpdateCompositionInfo(true);
840 #endif
843 void RenderFrameImpl::PepperSelectionChanged(
844 PepperPluginInstanceImpl* instance) {
845 if (instance != render_view_->focused_pepper_plugin())
846 return;
847 SyncSelectionIfRequired();
850 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
851 PepperPluginInstanceImpl* plugin) {
852 GURL active_url;
853 if (render_view_->webview() && render_view_->webview()->mainFrame())
854 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
855 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
856 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
857 plugin, active_url, GetRenderWidget()->screenInfo());
858 widget->show(blink::WebNavigationPolicyIgnore);
859 return widget;
862 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
863 if (!render_view_->focused_pepper_plugin())
864 return false;
865 return render_view_->focused_pepper_plugin()->
866 IsPluginAcceptingCompositionEvents();
869 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
870 base::ProcessId plugin_pid) {
871 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
872 // routing_id_ as a result.
873 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
876 void RenderFrameImpl::SimulateImeSetComposition(
877 const base::string16& text,
878 const std::vector<blink::WebCompositionUnderline>& underlines,
879 int selection_start,
880 int selection_end) {
881 render_view_->OnImeSetComposition(
882 text, underlines, selection_start, selection_end);
885 void RenderFrameImpl::SimulateImeConfirmComposition(
886 const base::string16& text,
887 const gfx::Range& replacement_range) {
888 render_view_->OnImeConfirmComposition(text, replacement_range, false);
891 void RenderFrameImpl::OnImeSetComposition(
892 const base::string16& text,
893 const std::vector<blink::WebCompositionUnderline>& underlines,
894 int selection_start,
895 int selection_end) {
896 // When a PPAPI plugin has focus, we bypass WebKit.
897 if (!IsPepperAcceptingCompositionEvents()) {
898 pepper_composition_text_ = text;
899 } else {
900 // TODO(kinaba) currently all composition events are sent directly to
901 // plugins. Use DOM event mechanism after WebKit is made aware about
902 // plugins that support composition.
903 // The code below mimics the behavior of WebCore::Editor::setComposition.
905 // Empty -> nonempty: composition started.
906 if (pepper_composition_text_.empty() && !text.empty()) {
907 render_view_->focused_pepper_plugin()->HandleCompositionStart(
908 base::string16());
910 // Nonempty -> empty: composition canceled.
911 if (!pepper_composition_text_.empty() && text.empty()) {
912 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
913 base::string16());
915 pepper_composition_text_ = text;
916 // Nonempty: composition is ongoing.
917 if (!pepper_composition_text_.empty()) {
918 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
919 pepper_composition_text_, underlines, selection_start,
920 selection_end);
925 void RenderFrameImpl::OnImeConfirmComposition(
926 const base::string16& text,
927 const gfx::Range& replacement_range,
928 bool keep_selection) {
929 // When a PPAPI plugin has focus, we bypass WebKit.
930 // Here, text.empty() has a special meaning. It means to commit the last
931 // update of composition text (see
932 // RenderWidgetHost::ImeConfirmComposition()).
933 const base::string16& last_text = text.empty() ? pepper_composition_text_
934 : text;
936 // last_text is empty only when both text and pepper_composition_text_ is.
937 // Ignore it.
938 if (last_text.empty())
939 return;
941 if (!IsPepperAcceptingCompositionEvents()) {
942 base::i18n::UTF16CharIterator iterator(&last_text);
943 int32 i = 0;
944 while (iterator.Advance()) {
945 blink::WebKeyboardEvent char_event;
946 char_event.type = blink::WebInputEvent::Char;
947 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
948 char_event.modifiers = 0;
949 char_event.windowsKeyCode = last_text[i];
950 char_event.nativeKeyCode = last_text[i];
952 const int32 char_start = i;
953 for (; i < iterator.array_pos(); ++i) {
954 char_event.text[i - char_start] = last_text[i];
955 char_event.unmodifiedText[i - char_start] = last_text[i];
958 if (GetRenderWidget()->webwidget())
959 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
961 } else {
962 // Mimics the order of events sent by WebKit.
963 // See WebCore::Editor::setComposition() for the corresponding code.
964 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
965 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
967 pepper_composition_text_.clear();
969 #endif // defined(ENABLE_PLUGINS)
971 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
972 if (!web_user_media_client_)
973 InitializeUserMediaClient();
974 return web_user_media_client_ ?
975 web_user_media_client_->media_stream_dispatcher() : NULL;
978 bool RenderFrameImpl::Send(IPC::Message* message) {
979 if (is_detaching_) {
980 delete message;
981 return false;
983 if (is_swapped_out_) {
984 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
985 delete message;
986 return false;
990 return RenderThread::Get()->Send(message);
993 #if defined(OS_MACOSX) || defined(OS_ANDROID)
994 void RenderFrameImpl::DidHideExternalPopupMenu() {
995 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
996 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
997 external_popup_menu_.reset();
999 #endif
1001 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
1002 // We may get here while detaching, when the WebFrame has been deleted. Do
1003 // not process any messages in this state.
1004 if (!frame_)
1005 return false;
1007 // TODO(kenrb): document() should not be null, but as a transitional step
1008 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
1009 // to this method. This happens for a top-level remote frame, where a
1010 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
1011 // around and is still able to receive messages.
1012 if (!frame_->document().isNull())
1013 GetContentClient()->SetActiveURL(frame_->document().url());
1015 ObserverListBase<RenderFrameObserver>::Iterator it(&observers_);
1016 RenderFrameObserver* observer;
1017 while ((observer = it.GetNext()) != NULL) {
1018 if (observer->OnMessageReceived(msg))
1019 return true;
1022 bool handled = true;
1023 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
1024 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
1025 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
1026 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
1027 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
1028 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
1029 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
1030 OnCustomContextMenuAction)
1031 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
1032 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
1033 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
1034 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
1035 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
1036 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
1037 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
1038 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
1039 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1040 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1041 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
1042 OnMoveRangeSelectionExtent)
1043 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1044 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1045 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
1046 OnExtendSelectionAndDelete)
1047 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
1048 OnSetCompositionFromExistingText)
1049 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
1050 OnExecuteNoValueEditCommand)
1051 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
1052 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
1053 OnJavaScriptExecuteRequest)
1054 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
1055 OnJavaScriptExecuteRequestForTests)
1056 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestInIsolatedWorld,
1057 OnJavaScriptExecuteRequestInIsolatedWorld)
1058 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
1059 OnVisualStateRequest)
1060 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
1061 OnSetEditableSelectionOffsets)
1062 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
1063 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
1064 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition, OnRevertExitTransition)
1065 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements,
1066 OnHideTransitionElements)
1067 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements,
1068 OnShowTransitionElements)
1069 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
1070 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
1071 OnTextSurroundingSelectionRequest)
1072 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
1073 OnAddStyleSheetByURL)
1074 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
1075 OnSetAccessibilityMode)
1076 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree,
1077 OnSnapshotAccessibilityTree)
1078 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
1079 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
1080 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags, OnDidUpdateSandboxFlags)
1081 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings,
1082 OnTextTrackSettingsChanged)
1083 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent, OnPostMessageEvent)
1084 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation, OnFailedNavigation)
1085 #if defined(OS_ANDROID)
1086 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1087 #elif defined(OS_MACOSX)
1088 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1089 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1090 #endif
1091 IPC_END_MESSAGE_MAP()
1093 return handled;
1096 void RenderFrameImpl::OnNavigate(
1097 const CommonNavigationParams& common_params,
1098 const StartNavigationParams& start_params,
1099 const RequestNavigationParams& request_params) {
1100 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1101 switches::kEnableBrowserSideNavigation));
1102 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_,
1103 "url", common_params.url.possibly_invalid_spec());
1104 NavigateInternal(common_params, start_params, request_params,
1105 scoped_ptr<StreamOverrideParameters>());
1108 void RenderFrameImpl::NavigateToSwappedOutURL() {
1109 // We use loadRequest instead of loadHTMLString because the former commits
1110 // synchronously. Otherwise a new navigation can interrupt the navigation
1111 // to kSwappedOutURL. If that happens to be to the page we had been
1112 // showing, then WebKit will never send a commit and we'll be left spinning.
1113 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1114 // the navigation to swappedout:// is not announced to the browser side.
1115 is_swapped_out_ = true;
1116 GURL swappedOutURL(kSwappedOutURL);
1117 WebURLRequest request(swappedOutURL);
1118 frame_->loadRequest(request);
1121 void RenderFrameImpl::BindServiceRegistry(
1122 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1123 mojo::ServiceProviderPtr exposed_services) {
1124 service_registry_.Bind(services.Pass());
1125 service_registry_.BindRemoteServiceProvider(exposed_services.Pass());
1128 ManifestManager* RenderFrameImpl::manifest_manager() {
1129 return manifest_manager_;
1132 void RenderFrameImpl::SetPendingNavigationParams(
1133 scoped_ptr<NavigationParams> navigation_params) {
1134 pending_navigation_params_ = navigation_params.Pass();
1137 void RenderFrameImpl::OnBeforeUnload() {
1138 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1139 "id", routing_id_);
1140 // TODO(creis): Right now, this is only called on the main frame. Make the
1141 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1142 // it.
1143 CHECK(!frame_->parent());
1145 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1146 bool proceed = frame_->dispatchBeforeUnloadEvent();
1147 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1148 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1149 before_unload_start_time,
1150 before_unload_end_time));
1153 void RenderFrameImpl::OnSwapOut(
1154 int proxy_routing_id,
1155 bool is_loading,
1156 const FrameReplicationState& replicated_frame_state) {
1157 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1158 RenderFrameProxy* proxy = NULL;
1159 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
1160 switches::kSitePerProcess);
1161 bool is_main_frame = !frame_->parent();
1163 // Only run unload if we're not swapped out yet, but send the ack either way.
1164 if (!is_swapped_out_) {
1165 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1166 // a different process. This involves running the unload handler and
1167 // clearing the page. We also allow this process to exit if there are no
1168 // other active RenderFrames in it.
1170 // Send an UpdateState message before we get swapped out.
1171 render_view_->SyncNavigationState();
1173 // If we need a proxy to replace this, create it now so its routing id is
1174 // registered for receiving IPC messages.
1175 if (proxy_routing_id != MSG_ROUTING_NONE) {
1176 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1177 proxy_routing_id);
1180 // Synchronously run the unload handler before sending the ACK.
1181 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1182 // unload on subframes as well.
1183 if (is_main_frame)
1184 frame_->dispatchUnloadEvent();
1186 // Swap out and stop sending any IPC messages that are not ACKs.
1187 if (is_main_frame)
1188 render_view_->SetSwappedOut(true);
1189 is_swapped_out_ = true;
1191 // Set the proxy here, since OnStop() below could cause an onload event
1192 // handler to execute, which could trigger code such as
1193 // willCheckAndDispatchMessageEvent() that needs the proxy.
1194 if (proxy)
1195 set_render_frame_proxy(proxy);
1197 // Now that we're swapped out and filtering IPC messages, stop loading to
1198 // ensure that no other in-progress navigation continues. We do this here
1199 // to avoid sending a DidStopLoading message to the browser process.
1200 // TODO(creis): Should we be stopping all frames here and using
1201 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1202 // frame?
1203 OnStop();
1205 // Transfer settings such as initial drawing parameters to the remote frame,
1206 // if one is created, that will replace this frame.
1207 if (!is_main_frame && proxy)
1208 proxy->web_frame()->initializeFromFrame(frame_);
1210 // Replace the page with a blank dummy URL. The unload handler will not be
1211 // run a second time, thanks to a check in FrameLoader::stopLoading.
1212 // TODO(creis): Need to add a better way to do this that avoids running the
1213 // beforeunload handler. For now, we just run it a second time silently.
1214 if (!is_site_per_process || is_main_frame)
1215 NavigateToSwappedOutURL();
1217 // Let WebKit know that this view is hidden so it can drop resources and
1218 // stop compositing.
1219 // TODO(creis): Support this for subframes as well.
1220 if (is_main_frame) {
1221 render_view_->webview()->setVisibilityState(
1222 blink::WebPageVisibilityStateHidden, false);
1226 // It is now safe to show modal dialogs again.
1227 // TODO(creis): Deal with modal dialogs from subframes.
1228 if (is_main_frame)
1229 render_view_->suppress_dialogs_until_swap_out_ = false;
1231 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1233 // Now that all of the cleanup is complete and the browser side is notified,
1234 // start using the RenderFrameProxy, if one is created.
1235 if (proxy) {
1236 if (!is_main_frame) {
1237 frame_->swap(proxy->web_frame());
1239 if (is_loading)
1240 proxy->OnDidStartLoading();
1242 if (is_site_per_process) {
1243 // TODO(nasko): delete the frame here, since we've replaced it with a
1244 // proxy.
1249 // In --site-per-process, initialize the WebRemoteFrame with the replication
1250 // state passed by the process that is now rendering the frame.
1251 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1252 // in that case we leave the LocalFrame as the main frame visible to Blink
1253 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1254 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1255 // When we do an unconditional swap for all frames, we can remove
1256 // !is_main_frame below.
1257 if (is_site_per_process && proxy && !is_main_frame)
1258 proxy->SetReplicatedState(replicated_frame_state);
1260 // Safe to exit if no one else is using the process.
1261 if (is_main_frame)
1262 render_view_->WasSwappedOut();
1265 void RenderFrameImpl::OnContextMenuClosed(
1266 const CustomContextMenuContext& custom_context) {
1267 if (custom_context.request_id) {
1268 // External request, should be in our map.
1269 ContextMenuClient* client =
1270 pending_context_menus_.Lookup(custom_context.request_id);
1271 if (client) {
1272 client->OnMenuClosed(custom_context.request_id);
1273 pending_context_menus_.Remove(custom_context.request_id);
1275 } else {
1276 if (custom_context.link_followed.is_valid()) {
1277 frame_->sendPings(
1278 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1279 custom_context.link_followed);
1281 // Internal request, forward to WebKit.
1282 context_menu_node_.reset();
1286 void RenderFrameImpl::OnCustomContextMenuAction(
1287 const CustomContextMenuContext& custom_context,
1288 unsigned action) {
1289 if (custom_context.request_id) {
1290 // External context menu request, look in our map.
1291 ContextMenuClient* client =
1292 pending_context_menus_.Lookup(custom_context.request_id);
1293 if (client)
1294 client->OnMenuAction(custom_context.request_id, action);
1295 } else {
1296 // Internal request, forward to WebKit.
1297 render_view_->webview()->performCustomContextMenuAction(action);
1301 void RenderFrameImpl::OnUndo() {
1302 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1305 void RenderFrameImpl::OnRedo() {
1306 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1309 void RenderFrameImpl::OnCut() {
1310 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1311 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1314 void RenderFrameImpl::OnCopy() {
1315 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1316 WebNode current_node = context_menu_node_.isNull() ?
1317 GetFocusedElement() : context_menu_node_;
1318 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1321 void RenderFrameImpl::OnPaste() {
1322 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1323 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1326 void RenderFrameImpl::OnPasteAndMatchStyle() {
1327 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1328 frame_->executeCommand(
1329 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1332 #if defined(OS_MACOSX)
1333 void RenderFrameImpl::OnCopyToFindPboard() {
1334 // Since the find pasteboard supports only plain text, this can be simpler
1335 // than the |OnCopy()| case.
1336 if (frame_->hasSelection()) {
1337 base::string16 selection = frame_->selectionAsText();
1338 RenderThread::Get()->Send(
1339 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1342 #endif
1344 void RenderFrameImpl::OnDelete() {
1345 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1348 void RenderFrameImpl::OnSelectAll() {
1349 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1350 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1353 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1354 const gfx::Point& extent) {
1355 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1356 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1358 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1359 frame_->selectRange(base, extent);
1362 void RenderFrameImpl::OnUnselect() {
1363 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1364 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1367 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1368 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1369 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1370 GetRenderWidget()->routing_id()));
1372 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1373 frame_->moveRangeSelectionExtent(point);
1376 void RenderFrameImpl::OnReplace(const base::string16& text) {
1377 if (!frame_->hasSelection())
1378 frame_->selectWordAroundCaret();
1380 frame_->replaceSelection(text);
1383 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1384 if (!frame_->hasSelection())
1385 return;
1387 frame_->replaceMisspelledRange(text);
1390 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1391 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1394 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1395 const base::string16& jscript,
1396 int id,
1397 bool notify_result) {
1398 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1399 TRACE_EVENT_SCOPE_THREAD);
1401 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1402 v8::Local<v8::Value> result =
1403 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1405 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1408 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1409 const base::string16& jscript,
1410 int id,
1411 bool notify_result,
1412 bool has_user_gesture) {
1413 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1414 TRACE_EVENT_SCOPE_THREAD);
1416 // A bunch of tests expect to run code in the context of a user gesture, which
1417 // can grant additional privileges (e.g. the ability to create popups).
1418 scoped_ptr<blink::WebScopedUserGesture> gesture(
1419 has_user_gesture ? new blink::WebScopedUserGesture : nullptr);
1420 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1421 v8::Local<v8::Value> result =
1422 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1424 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1427 void RenderFrameImpl::OnJavaScriptExecuteRequestInIsolatedWorld(
1428 const base::string16& jscript,
1429 int id,
1430 bool notify_result,
1431 int world_id) {
1432 TRACE_EVENT_INSTANT0("test_tracing",
1433 "OnJavaScriptExecuteRequestInIsolatedWorld",
1434 TRACE_EVENT_SCOPE_THREAD);
1436 if (world_id <= ISOLATED_WORLD_ID_GLOBAL ||
1437 world_id > ISOLATED_WORLD_ID_MAX) {
1438 // Return if the world_id is not valid. world_id is passed as a plain int
1439 // over IPC and needs to be verified here, in the IPC endpoint.
1440 NOTREACHED();
1441 return;
1444 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1445 WebScriptSource script = WebScriptSource(jscript);
1446 JavaScriptIsolatedWorldRequest* request = new JavaScriptIsolatedWorldRequest(
1447 id, notify_result, routing_id_, weak_factory_.GetWeakPtr());
1448 frame_->requestExecuteScriptInIsolatedWorld(world_id, &script, 1, 0, false,
1449 request);
1452 RenderFrameImpl::JavaScriptIsolatedWorldRequest::JavaScriptIsolatedWorldRequest(
1453 int id,
1454 bool notify_result,
1455 int routing_id,
1456 base::WeakPtr<RenderFrameImpl> render_frame_impl)
1457 : id_(id),
1458 notify_result_(notify_result),
1459 routing_id_(routing_id),
1460 render_frame_impl_(render_frame_impl) {
1463 RenderFrameImpl::JavaScriptIsolatedWorldRequest::
1464 ~JavaScriptIsolatedWorldRequest() {
1467 void RenderFrameImpl::JavaScriptIsolatedWorldRequest::completed(
1468 const blink::WebVector<v8::Local<v8::Value>>& result) {
1469 if (!render_frame_impl_.get()) {
1470 return;
1473 if (notify_result_) {
1474 base::ListValue list;
1475 if (!result.isEmpty()) {
1476 // It's safe to always use the main world context when converting
1477 // here. V8ValueConverterImpl shouldn't actually care about the
1478 // context scope, and it switches to v8::Object's creation context
1479 // when encountered. (from extensions/renderer/script_injection.cc)
1480 v8::Local<v8::Context> context =
1481 render_frame_impl_.get()->frame_->mainWorldScriptContext();
1482 v8::Context::Scope context_scope(context);
1483 V8ValueConverterImpl converter;
1484 converter.SetDateAllowed(true);
1485 converter.SetRegExpAllowed(true);
1486 for (const auto& value : result) {
1487 scoped_ptr<base::Value> result_value(
1488 converter.FromV8Value(value, context));
1489 list.Append(result_value ? result_value.Pass()
1490 : base::Value::CreateNullValue());
1492 } else {
1493 list.Set(0, base::Value::CreateNullValue());
1495 render_frame_impl_.get()->Send(
1496 new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id_, list));
1499 delete this;
1502 void RenderFrameImpl::HandleJavascriptExecutionResult(
1503 const base::string16& jscript,
1504 int id,
1505 bool notify_result,
1506 v8::Local<v8::Value> result) {
1507 if (notify_result) {
1508 base::ListValue list;
1509 if (!result.IsEmpty()) {
1510 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1511 v8::Context::Scope context_scope(context);
1512 V8ValueConverterImpl converter;
1513 converter.SetDateAllowed(true);
1514 converter.SetRegExpAllowed(true);
1515 scoped_ptr<base::Value> result_value(
1516 converter.FromV8Value(result, context));
1517 list.Set(0, result_value ? result_value.Pass()
1518 : base::Value::CreateNullValue());
1519 } else {
1520 list.Set(0, base::Value::CreateNullValue());
1522 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1526 void RenderFrameImpl::OnVisualStateRequest(uint64 id) {
1527 GetRenderWidget()->QueueMessage(
1528 new FrameHostMsg_VisualStateResponse(routing_id_, id),
1529 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1532 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1533 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1534 if (!GetRenderWidget()->ShouldHandleImeEvent())
1535 return;
1536 ImeEventGuard guard(GetRenderWidget());
1537 frame_->setEditableSelectionOffsets(start, end);
1540 void RenderFrameImpl::OnSetCompositionFromExistingText(
1541 int start, int end,
1542 const std::vector<blink::WebCompositionUnderline>& underlines) {
1543 if (!GetRenderWidget()->ShouldHandleImeEvent())
1544 return;
1545 ImeEventGuard guard(GetRenderWidget());
1546 frame_->setCompositionFromExistingText(start, end, underlines);
1549 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
1550 frame_->executeCommand(WebString::fromUTF8(name), GetFocusedElement());
1553 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1554 if (!GetRenderWidget()->ShouldHandleImeEvent())
1555 return;
1556 ImeEventGuard guard(GetRenderWidget());
1557 frame_->extendSelectionAndDelete(before, after);
1560 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1561 if (accessibility_mode_ == new_mode)
1562 return;
1563 accessibility_mode_ = new_mode;
1564 if (renderer_accessibility_) {
1565 // Note: this isn't called automatically by the destructor because
1566 // there'd be no point in calling it in frame teardown, only if there's
1567 // an accessibility mode change but the frame is persisting.
1568 renderer_accessibility_->DisableAccessibility();
1570 delete renderer_accessibility_;
1571 renderer_accessibility_ = NULL;
1573 if (accessibility_mode_ == AccessibilityModeOff)
1574 return;
1576 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1577 renderer_accessibility_ = new RendererAccessibility(this);
1580 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) {
1581 ui::AXTreeUpdate response;
1582 RendererAccessibility::SnapshotAccessibilityTree(this, &response);
1583 Send(new AccessibilityHostMsg_SnapshotResponse(
1584 routing_id_, callback_id, response));
1587 void RenderFrameImpl::OnDisownOpener() {
1588 // TODO(creis): We should only see this for main frames for now. To support
1589 // disowning the opener on subframes, we will need to move WebContentsImpl's
1590 // opener_ to FrameTreeNode.
1591 CHECK(!frame_->parent());
1593 if (frame_->opener())
1594 frame_->setOpener(NULL);
1597 void RenderFrameImpl::OnDidUpdateSandboxFlags(SandboxFlags flags) {
1598 frame_->setFrameOwnerSandboxFlags(ContentToWebSandboxFlags(flags));
1601 void RenderFrameImpl::OnTextTrackSettingsChanged(
1602 const FrameMsg_TextTrackSettings_Params& params) {
1603 DCHECK(!frame_->parent());
1604 if (!render_view_->webview())
1605 return;
1606 render_view_->webview()->settings()->setTextTrackBackgroundColor(
1607 WebString::fromUTF8(params.text_track_background_color));
1608 render_view_->webview()->settings()->setTextTrackFontFamily(
1609 WebString::fromUTF8(params.text_track_font_family));
1610 render_view_->webview()->settings()->setTextTrackFontStyle(
1611 WebString::fromUTF8(params.text_track_font_style));
1612 render_view_->webview()->settings()->setTextTrackFontVariant(
1613 WebString::fromUTF8(params.text_track_font_variant));
1614 render_view_->webview()->settings()->setTextTrackTextColor(
1615 WebString::fromUTF8(params.text_track_text_color));
1616 render_view_->webview()->settings()->setTextTrackTextShadow(
1617 WebString::fromUTF8(params.text_track_text_shadow));
1618 render_view_->webview()->settings()->setTextTrackTextSize(
1619 WebString::fromUTF8(params.text_track_text_size));
1622 void RenderFrameImpl::OnPostMessageEvent(
1623 const FrameMsg_PostMessage_Params& params) {
1624 // Find the source frame if it exists.
1625 WebFrame* source_frame = NULL;
1626 if (params.source_view_routing_id != MSG_ROUTING_NONE) {
1627 // Support a legacy postMessage path for specifying a source RenderView;
1628 // this is currently used when sending messages to Android WebView.
1629 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1630 RenderViewImpl* source_view =
1631 RenderViewImpl::FromRoutingID(params.source_view_routing_id);
1632 if (source_view)
1633 source_frame = source_view->webview()->mainFrame();
1634 } else if (params.source_routing_id != MSG_ROUTING_NONE) {
1635 RenderFrameProxy* source_proxy =
1636 RenderFrameProxy::FromRoutingID(params.source_routing_id);
1637 if (source_proxy) {
1638 // Currently, navigating a top-level frame cross-process does not swap
1639 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1640 // WebRemoteFrame will not have an associated blink::Frame. If this is
1641 // the case for |source_proxy|, use the corresponding (swapped-out)
1642 // WebLocalFrame instead, so that event.source for this message can be
1643 // set and used properly.
1644 if (source_proxy->IsMainFrameDetachedFromTree())
1645 source_frame = source_proxy->render_view()->webview()->mainFrame();
1646 else
1647 source_frame = source_proxy->web_frame();
1651 // If the message contained MessagePorts, create the corresponding endpoints.
1652 blink::WebMessagePortChannelArray channels =
1653 WebMessagePortChannelImpl::CreatePorts(
1654 params.message_ports, params.new_routing_ids,
1655 base::MessageLoopProxy::current().get());
1657 WebSerializedScriptValue serialized_script_value;
1658 if (params.is_data_raw_string) {
1659 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1660 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1661 v8::Context::Scope context_scope(context);
1662 V8ValueConverterImpl converter;
1663 converter.SetDateAllowed(true);
1664 converter.SetRegExpAllowed(true);
1665 scoped_ptr<base::Value> value(new base::StringValue(params.data));
1666 v8::Local<v8::Value> result_value = converter.ToV8Value(value.get(),
1667 context);
1668 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
1669 } else {
1670 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
1673 // Create an event with the message. The next-to-last parameter to
1674 // initMessageEvent is the last event ID, which is not used with postMessage.
1675 WebDOMEvent event = frame_->document().createEvent("MessageEvent");
1676 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
1677 msg_event.initMessageEvent("message",
1678 // |canBubble| and |cancellable| are always false
1679 false, false,
1680 serialized_script_value,
1681 params.source_origin, source_frame, "", channels);
1683 // We must pass in the target_origin to do the security check on this side,
1684 // since it may have changed since the original postMessage call was made.
1685 WebSecurityOrigin target_origin;
1686 if (!params.target_origin.empty()) {
1687 target_origin =
1688 WebSecurityOrigin::createFromString(WebString(params.target_origin));
1690 frame_->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
1693 #if defined(OS_ANDROID)
1694 void RenderFrameImpl::OnSelectPopupMenuItems(
1695 bool canceled,
1696 const std::vector<int>& selected_indices) {
1697 // It is possible to receive more than one of these calls if the user presses
1698 // a select faster than it takes for the show-select-popup IPC message to make
1699 // it to the browser UI thread. Ignore the extra-messages.
1700 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1701 if (!external_popup_menu_)
1702 return;
1704 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1705 external_popup_menu_.reset();
1707 #endif
1709 #if defined(OS_MACOSX)
1710 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1711 if (external_popup_menu_ == NULL)
1712 return;
1713 external_popup_menu_->DidSelectItem(selected_index);
1714 external_popup_menu_.reset();
1716 #endif
1718 void RenderFrameImpl::OnReload(bool ignore_cache) {
1719 frame_->reload(ignore_cache);
1722 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1723 blink::WebSurroundingText surroundingText;
1724 surroundingText.initialize(frame_->selectionRange(), max_length);
1726 if (surroundingText.isNull()) {
1727 // |surroundingText| might not be correctly initialized, for example if
1728 // |frame_->selectionRange().isNull()|, in other words, if there was no
1729 // selection.
1730 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1731 routing_id_, base::string16(), 0, 0));
1732 return;
1735 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1736 routing_id_,
1737 surroundingText.textContent(),
1738 surroundingText.startOffsetInTextContent(),
1739 surroundingText.endOffsetInTextContent()));
1742 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1743 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1746 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1747 frame_->document().setIsTransitionDocument(true);
1748 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1751 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector,
1752 bool exit_to_native_app) {
1753 frame_->document().setIsTransitionDocument(true);
1754 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector),
1755 exit_to_native_app);
1758 void RenderFrameImpl::OnRevertExitTransition() {
1759 frame_->document().setIsTransitionDocument(false);
1760 frame_->document().revertExitTransition();
1763 void RenderFrameImpl::OnHideTransitionElements(
1764 const std::string& css_selector) {
1765 frame_->document().hideTransitionElements(WebString::fromUTF8(css_selector));
1768 void RenderFrameImpl::OnShowTransitionElements(
1769 const std::string& css_selector) {
1770 frame_->document().showTransitionElements(WebString::fromUTF8(css_selector));
1773 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1774 const base::string16& message,
1775 const base::string16& default_value,
1776 const GURL& frame_url,
1777 base::string16* result) {
1778 // Don't allow further dialogs if we are waiting to swap out, since the
1779 // PageGroupLoadDeferrer in our stack prevents it.
1780 if (render_view()->suppress_dialogs_until_swap_out_)
1781 return false;
1783 bool success = false;
1784 base::string16 result_temp;
1785 if (!result)
1786 result = &result_temp;
1788 render_view()->SendAndRunNestedMessageLoop(
1789 new FrameHostMsg_RunJavaScriptMessage(
1790 routing_id_, message, default_value, frame_url, type, &success,
1791 result));
1792 return success;
1795 void RenderFrameImpl::LoadNavigationErrorPage(
1796 const WebURLRequest& failed_request,
1797 const WebURLError& error,
1798 bool replace) {
1799 std::string error_html;
1800 GetContentClient()->renderer()->GetNavigationErrorStrings(
1801 render_view(), frame_, failed_request, error, &error_html, NULL);
1803 frame_->loadHTMLString(error_html,
1804 GURL(kUnreachableWebDataURL),
1805 error.unreachableURL,
1806 replace);
1809 void RenderFrameImpl::DidCommitCompositorFrame() {
1810 if (BrowserPluginManager::Get())
1811 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1812 FOR_EACH_OBSERVER(
1813 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1816 RenderView* RenderFrameImpl::GetRenderView() {
1817 return render_view_.get();
1820 int RenderFrameImpl::GetRoutingID() {
1821 return routing_id_;
1824 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1825 DCHECK(frame_);
1826 return frame_;
1829 WebElement RenderFrameImpl::GetFocusedElement() const {
1830 WebDocument doc = frame_->document();
1831 if (!doc.isNull())
1832 return doc.focusedElement();
1834 return WebElement();
1837 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1838 return render_view_->GetWebkitPreferences();
1841 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1842 const ContextMenuParams& params) {
1843 DCHECK(client); // A null client means "internal" when we issue callbacks.
1844 ContextMenuParams our_params(params);
1845 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1846 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1847 return our_params.custom_context.request_id;
1850 void RenderFrameImpl::CancelContextMenu(int request_id) {
1851 DCHECK(pending_context_menus_.Lookup(request_id));
1852 pending_context_menus_.Remove(request_id);
1855 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1856 return context_menu_node_;
1859 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1860 blink::WebFrame* frame,
1861 const WebPluginInfo& info,
1862 const blink::WebPluginParams& params,
1863 scoped_ptr<content::PluginInstanceThrottler> throttler) {
1864 DCHECK_EQ(frame_, frame);
1865 #if defined(ENABLE_PLUGINS)
1866 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1867 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1868 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1869 this, params.mimeType.utf8(), GURL(params.url)));
1870 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1871 this, browser_plugin_delegate.Pass());
1874 bool pepper_plugin_was_registered = false;
1875 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1876 this, info, &pepper_plugin_was_registered));
1877 if (pepper_plugin_was_registered) {
1878 if (pepper_module.get()) {
1879 return new PepperWebPluginImpl(
1880 pepper_module.get(), params, this,
1881 make_scoped_ptr(
1882 static_cast<PluginInstanceThrottlerImpl*>(throttler.release())));
1885 #if defined(OS_CHROMEOS)
1886 LOG(WARNING) << "Pepper module/plugin creation failed.";
1887 return NULL;
1888 #else
1889 // TODO(jam): change to take RenderFrame.
1890 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1891 #endif
1892 #else
1893 return NULL;
1894 #endif
1897 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1898 const blink::WebURLRequest& request,
1899 blink::WebNavigationPolicy policy) {
1900 DCHECK(!frame_ || frame_ == frame);
1901 loadURLExternally(frame, request, policy, WebString());
1904 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1905 OnJavaScriptExecuteRequest(javascript, 0, false);
1908 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1909 return &service_registry_;
1912 #if defined(ENABLE_PLUGINS)
1913 void RenderFrameImpl::RegisterPeripheralPlugin(
1914 const GURL& content_origin,
1915 const base::Closure& unthrottle_callback) {
1916 return plugin_power_saver_helper_->RegisterPeripheralPlugin(
1917 content_origin, unthrottle_callback);
1919 #endif // defined(ENABLE_PLUGINS)
1921 bool RenderFrameImpl::IsFTPDirectoryListing() {
1922 WebURLResponseExtraDataImpl* extra_data =
1923 GetExtraDataFromResponse(frame_->dataSource()->response());
1924 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1927 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1928 BrowserPluginManager::Get()->Attach(element_instance_id);
1931 void RenderFrameImpl::DetachGuest(int element_instance_id) {
1932 BrowserPluginManager::Get()->Detach(element_instance_id);
1935 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1936 size_t offset,
1937 const gfx::Range& range) {
1938 // Use the routing id of Render Widget Host.
1939 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1940 selection_text,
1941 offset,
1942 range));
1945 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1946 v8::Isolate* isolate,
1947 v8::Local<v8::Context> context) {
1948 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1949 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1950 return;
1952 v8::HandleScope handle_scope(isolate);
1953 registry->AddBuiltinModule(
1954 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1955 registry->AddBuiltinModule(isolate,
1956 mojo::js::Support::kModuleName,
1957 mojo::js::Support::GetModule(isolate));
1958 registry->AddBuiltinModule(
1959 isolate,
1960 ServiceRegistryJsWrapper::kModuleName,
1961 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1964 // blink::WebFrameClient implementation ----------------------------------------
1966 blink::WebPluginPlaceholder* RenderFrameImpl::createPluginPlaceholder(
1967 blink::WebLocalFrame* frame,
1968 const blink::WebPluginParams& params) {
1969 DCHECK_EQ(frame_, frame);
1970 return GetContentClient()
1971 ->renderer()
1972 ->CreatePluginPlaceholder(this, frame, params)
1973 .release();
1976 blink::WebPlugin* RenderFrameImpl::createPlugin(
1977 blink::WebLocalFrame* frame,
1978 const blink::WebPluginParams& params) {
1979 DCHECK_EQ(frame_, frame);
1980 blink::WebPlugin* plugin = NULL;
1981 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1982 this, frame, params, &plugin)) {
1983 return plugin;
1986 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1987 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1988 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1989 kBrowserPluginMimeType, GURL(params.url)));
1990 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1991 this, browser_plugin_delegate.Pass());
1994 #if defined(ENABLE_PLUGINS)
1995 WebPluginInfo info;
1996 std::string mime_type;
1997 bool found = false;
1998 Send(new FrameHostMsg_GetPluginInfo(
1999 routing_id_, params.url, frame->top()->document().url(),
2000 params.mimeType.utf8(), &found, &info, &mime_type));
2001 if (!found)
2002 return NULL;
2004 WebPluginParams params_to_use = params;
2005 params_to_use.mimeType = WebString::fromUTF8(mime_type);
2006 return CreatePlugin(frame, info, params_to_use, nullptr /* throttler */);
2007 #else
2008 return NULL;
2009 #endif // defined(ENABLE_PLUGINS)
2012 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
2013 blink::WebLocalFrame* frame,
2014 const blink::WebURL& url,
2015 blink::WebMediaPlayerClient* client) {
2016 return createMediaPlayer(frame, url, client, nullptr);
2019 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
2020 blink::WebLocalFrame* frame,
2021 const blink::WebURL& url,
2022 blink::WebMediaPlayerClient* client,
2023 blink::WebContentDecryptionModule* initial_cdm) {
2024 #if defined(VIDEO_HOLE)
2025 if (!contains_media_player_) {
2026 render_view_->RegisterVideoHoleFrame(this);
2027 contains_media_player_ = true;
2029 #endif // defined(VIDEO_HOLE)
2031 blink::WebMediaStream web_stream(
2032 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
2033 if (!web_stream.isNull())
2034 return CreateWebMediaPlayerForMediaStream(url, client);
2036 #if defined(OS_ANDROID)
2037 return CreateAndroidWebMediaPlayer(url, client, GetMediaPermission(),
2038 initial_cdm);
2039 #else
2040 scoped_refptr<media::MediaLog> media_log(new RenderMediaLog());
2042 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2043 media::WebMediaPlayerParams params(
2044 base::Bind(&ContentRendererClient::DeferMediaLoad,
2045 base::Unretained(GetContentClient()->renderer()),
2046 static_cast<RenderFrame*>(this)),
2047 render_thread->GetAudioRendererMixerManager()->CreateInput(routing_id_),
2048 media_log, render_thread->GetMediaThreadTaskRunner(),
2049 render_thread->compositor_message_loop_proxy(),
2050 base::Bind(&GetSharedMainThreadContext3D), GetMediaPermission(),
2051 initial_cdm);
2053 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
2054 scoped_ptr<media::RendererFactory> media_renderer_factory(
2055 new media::MojoRendererFactory(make_scoped_ptr(
2056 new MediaRendererServiceProvider(GetServiceRegistry()))));
2057 #else
2058 scoped_ptr<media::RendererFactory> media_renderer_factory =
2059 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
2060 media_log);
2062 if (!media_renderer_factory.get()) {
2063 media_renderer_factory.reset(new media::DefaultRendererFactory(
2064 media_log, render_thread->GetGpuFactories(),
2065 *render_thread->GetAudioHardwareConfig()));
2067 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
2069 return new media::WebMediaPlayerImpl(
2070 frame, client, weak_factory_.GetWeakPtr(), media_renderer_factory.Pass(),
2071 GetCdmFactory(), params);
2072 #endif // defined(OS_ANDROID)
2075 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
2076 blink::WebLocalFrame* frame,
2077 blink::WebApplicationCacheHostClient* client) {
2078 if (!frame || !frame->view())
2079 return NULL;
2080 DCHECK(!frame_ || frame_ == frame);
2081 return new RendererWebApplicationCacheHostImpl(
2082 RenderViewImpl::FromWebView(frame->view()), client,
2083 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2086 blink::WebWorkerContentSettingsClientProxy*
2087 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2088 blink::WebLocalFrame* frame) {
2089 if (!frame || !frame->view())
2090 return NULL;
2091 DCHECK(!frame_ || frame_ == frame);
2092 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2093 this, frame);
2096 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
2097 const WebPopupMenuInfo& popup_menu_info,
2098 WebExternalPopupMenuClient* popup_menu_client) {
2099 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2100 // An IPC message is sent to the browser to build and display the actual
2101 // popup. The user could have time to click a different select by the time
2102 // the popup is shown. In that case external_popup_menu_ is non NULL.
2103 // By returning NULL in that case, we instruct Blink to cancel that new
2104 // popup. So from the user perspective, only the first one will show, and
2105 // will have to close the first one before another one can be shown.
2106 if (external_popup_menu_)
2107 return NULL;
2108 external_popup_menu_.reset(
2109 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
2110 if (render_view_->screen_metrics_emulator_) {
2111 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
2112 external_popup_menu_.get(),
2113 render_view_->screen_metrics_emulator_.get());
2115 return external_popup_menu_.get();
2116 #else
2117 return NULL;
2118 #endif
2121 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
2122 DCHECK(!frame_ || frame_ == frame);
2123 return &cookie_jar_;
2126 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
2127 blink::WebLocalFrame* frame) {
2128 DCHECK(!frame_ || frame_ == frame);
2129 // At this point we should have non-null data source.
2130 DCHECK(frame->dataSource());
2131 if (!ChildThreadImpl::current())
2132 return NULL; // May be null in some tests.
2133 ServiceWorkerNetworkProvider* provider =
2134 ServiceWorkerNetworkProvider::FromDocumentState(
2135 DocumentState::FromDataSource(frame->dataSource()));
2136 return new WebServiceWorkerProviderImpl(
2137 ChildThreadImpl::current()->thread_safe_sender(),
2138 provider ? provider->context() : NULL);
2141 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
2142 DCHECK(!frame_ || frame_ == frame);
2143 // If the request hasn't yet committed, notify the browser process that it is
2144 // no longer safe to show the pending URL of the main frame, since a URL spoof
2145 // is now possible. (If the request has committed, the browser already knows.)
2146 if (!frame->parent()) {
2147 DocumentState* document_state =
2148 DocumentState::FromDataSource(frame->dataSource());
2149 NavigationStateImpl* navigation_state =
2150 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2152 if (!navigation_state->request_committed()) {
2153 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
2158 blink::WebFrame* RenderFrameImpl::createChildFrame(
2159 blink::WebLocalFrame* parent,
2160 const blink::WebString& name,
2161 blink::WebSandboxFlags sandbox_flags) {
2162 // Synchronously notify the browser of a child frame creation to get the
2163 // routing_id for the RenderFrame.
2164 int child_routing_id = MSG_ROUTING_NONE;
2165 Send(new FrameHostMsg_CreateChildFrame(
2166 routing_id_, base::UTF16ToUTF8(name),
2167 WebToContentSandboxFlags(sandbox_flags), &child_routing_id));
2169 // Allocation of routing id failed, so we can't create a child frame. This can
2170 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2171 // out state or synchronous IPC message above has failed.
2172 if (child_routing_id == MSG_ROUTING_NONE) {
2173 NOTREACHED() << "Failed to allocate routing id for child frame.";
2174 return nullptr;
2177 // Create the RenderFrame and WebLocalFrame, linking the two.
2178 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
2179 render_view_.get(), child_routing_id);
2180 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
2181 child_render_frame->SetWebFrame(web_frame);
2183 // Add the frame to the frame tree and initialize it.
2184 parent->appendChild(web_frame);
2185 child_render_frame->Initialize();
2187 return web_frame;
2190 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
2191 DCHECK(!frame_ || frame_ == frame);
2192 // We only need to notify the browser if the active, top-level frame clears
2193 // its opener. We can ignore cases where a swapped out frame clears its
2194 // opener after hearing about it from the browser, and the browser does not
2195 // (yet) care about subframe openers.
2196 if (is_swapped_out_ || frame->parent())
2197 return;
2199 // Notify WebContents and all its swapped out RenderViews.
2200 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
2203 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
2204 // NOTE: This function is called on the frame that is being detached and not
2205 // the parent frame. This is different from createChildFrame() which is
2206 // called on the parent frame.
2207 CHECK(!is_detaching_);
2208 DCHECK(!frame_ || frame_ == frame);
2210 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameDetached());
2211 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2212 FrameDetached(frame));
2214 Send(new FrameHostMsg_Detach(routing_id_));
2216 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2217 // sent before setting |is_detaching_| to true.
2218 is_detaching_ = true;
2220 // We need to clean up subframes by removing them from the map and deleting
2221 // the RenderFrameImpl. In contrast, the main frame is owned by its
2222 // containing RenderViewHost (so that they have the same lifetime), so only
2223 // removal from the map is needed and no deletion.
2224 FrameMap::iterator it = g_frame_map.Get().find(frame);
2225 CHECK(it != g_frame_map.Get().end());
2226 CHECK_EQ(it->second, this);
2227 g_frame_map.Get().erase(it);
2229 if (is_subframe_) {
2230 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2231 switches::kSitePerProcess) && render_widget_) {
2232 render_widget_->UnregisterRenderFrame(this);
2234 frame->parent()->removeChild(frame);
2237 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2238 // object may not be deleted immediately and other methods may try to access
2239 // it.
2240 frame->close();
2241 frame_ = nullptr;
2243 delete this;
2244 // Object is invalid after this point.
2247 void RenderFrameImpl::frameFocused() {
2248 Send(new FrameHostMsg_FrameFocused(routing_id_));
2251 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
2252 DCHECK(!frame_ || frame_ == frame);
2254 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
2255 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2256 FrameWillClose(frame));
2259 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
2260 const blink::WebString& name) {
2261 DCHECK(!frame_ || frame_ == frame);
2263 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2264 // updates may have performance implications for benchmarks like SunSpider.
2265 // For now, send these updates only for --site-per-process, which needs to
2266 // replicate frame names to frame proxies, and when
2267 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2268 // can be optimized further by only sending the update if there are any
2269 // remote frames in the frame tree, or delaying and batching up IPCs if
2270 // updates are happening too frequently.
2271 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
2272 switches::kSitePerProcess);
2273 if (is_site_per_process ||
2274 render_view_->renderer_preferences_.report_frame_name_changes) {
2275 Send(new FrameHostMsg_DidChangeName(routing_id_, base::UTF16ToUTF8(name)));
2279 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame* child_frame,
2280 blink::WebSandboxFlags flags) {
2281 int frame_routing_id = MSG_ROUTING_NONE;
2282 if (child_frame->isWebRemoteFrame()) {
2283 frame_routing_id =
2284 RenderFrameProxy::FromWebFrame(child_frame)->routing_id();
2285 } else {
2286 frame_routing_id =
2287 RenderFrameImpl::FromWebFrame(child_frame)->GetRoutingID();
2290 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_, frame_routing_id,
2291 WebToContentSandboxFlags(flags)));
2294 void RenderFrameImpl::didMatchCSS(
2295 blink::WebLocalFrame* frame,
2296 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2297 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2298 DCHECK(!frame_ || frame_ == frame);
2300 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2301 DidMatchCSS(frame,
2302 newly_matching_selectors,
2303 stopped_matching_selectors));
2306 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2307 const blink::WebString& source) {
2308 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2309 source);
2312 void RenderFrameImpl::didAddMessageToConsole(
2313 const blink::WebConsoleMessage& message,
2314 const blink::WebString& source_name,
2315 unsigned source_line,
2316 const blink::WebString& stack_trace) {
2317 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2318 switch (message.level) {
2319 case blink::WebConsoleMessage::LevelDebug:
2320 log_severity = logging::LOG_VERBOSE;
2321 break;
2322 case blink::WebConsoleMessage::LevelLog:
2323 case blink::WebConsoleMessage::LevelInfo:
2324 log_severity = logging::LOG_INFO;
2325 break;
2326 case blink::WebConsoleMessage::LevelWarning:
2327 log_severity = logging::LOG_WARNING;
2328 break;
2329 case blink::WebConsoleMessage::LevelError:
2330 log_severity = logging::LOG_ERROR;
2331 break;
2332 default:
2333 log_severity = logging::LOG_VERBOSE;
2336 if (shouldReportDetailedMessageForSource(source_name)) {
2337 FOR_EACH_OBSERVER(
2338 RenderFrameObserver, observers_,
2339 DetailedConsoleMessageAdded(message.text,
2340 source_name,
2341 stack_trace,
2342 source_line,
2343 static_cast<int32>(log_severity)));
2346 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2347 static_cast<int32>(log_severity),
2348 message.text,
2349 static_cast<int32>(source_line),
2350 source_name));
2353 void RenderFrameImpl::loadURLExternally(
2354 blink::WebLocalFrame* frame,
2355 const blink::WebURLRequest& request,
2356 blink::WebNavigationPolicy policy,
2357 const blink::WebString& suggested_name) {
2358 DCHECK(!frame_ || frame_ == frame);
2359 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2360 if (policy == blink::WebNavigationPolicyDownload) {
2361 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2362 request.url(), referrer,
2363 suggested_name));
2364 } else {
2365 OpenURL(frame, request.url(), referrer, policy);
2369 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2370 const NavigationPolicyInfo& info) {
2371 DCHECK(!frame_ || frame_ == info.frame);
2372 return DecidePolicyForNavigation(this, info);
2375 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2376 blink::WebFrame* frame) {
2377 DCHECK(!frame_ || frame_ == frame);
2378 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2381 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2382 const blink::WebFormElement& form) {
2383 DCHECK(!frame_ || frame_ == frame);
2385 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSendSubmitEvent(form));
2388 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2389 const blink::WebFormElement& form) {
2390 DCHECK(!frame_ || frame_ == frame);
2391 DocumentState* document_state =
2392 DocumentState::FromDataSource(frame->provisionalDataSource());
2393 NavigationStateImpl* navigation_state =
2394 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2395 InternalDocumentStateData* internal_data =
2396 InternalDocumentStateData::FromDocumentState(document_state);
2398 if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(),
2399 ui::PAGE_TRANSITION_LINK)) {
2400 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2403 // Save these to be processed when the ensuing navigation is committed.
2404 WebSearchableFormData web_searchable_form_data(form);
2405 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2406 internal_data->set_searchable_form_encoding(
2407 web_searchable_form_data.encoding().utf8());
2409 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form));
2412 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2413 blink::WebDataSource* datasource) {
2414 DCHECK(!frame_ || frame_ == frame);
2416 bool content_initiated = !pending_navigation_params_.get();
2418 // Make sure any previous redirect URLs end up in our new data source.
2419 if (pending_navigation_params_.get()) {
2420 for (const auto& i :
2421 pending_navigation_params_->request_params.redirects) {
2422 datasource->appendRedirect(i);
2426 DocumentState* document_state = DocumentState::FromDataSource(datasource);
2427 if (!document_state) {
2428 document_state = new DocumentState;
2429 datasource->setExtraData(document_state);
2430 if (!content_initiated)
2431 PopulateDocumentStateFromPending(document_state);
2434 // Carry over the user agent override flag, if it exists.
2435 blink::WebView* webview = render_view_->webview();
2436 if (content_initiated && webview && webview->mainFrame() &&
2437 webview->mainFrame()->isWebLocalFrame() &&
2438 webview->mainFrame()->dataSource()) {
2439 DocumentState* old_document_state =
2440 DocumentState::FromDataSource(webview->mainFrame()->dataSource());
2441 if (old_document_state) {
2442 InternalDocumentStateData* internal_data =
2443 InternalDocumentStateData::FromDocumentState(document_state);
2444 InternalDocumentStateData* old_internal_data =
2445 InternalDocumentStateData::FromDocumentState(old_document_state);
2446 internal_data->set_is_overriding_user_agent(
2447 old_internal_data->is_overriding_user_agent());
2451 // The rest of RenderView assumes that a WebDataSource will always have a
2452 // non-null NavigationState.
2453 if (content_initiated) {
2454 document_state->set_navigation_state(
2455 NavigationStateImpl::CreateContentInitiated());
2456 } else {
2457 document_state->set_navigation_state(CreateNavigationStateFromPending());
2458 pending_navigation_params_.reset();
2461 // DocumentState::referred_by_prefetcher_ is true if we are
2462 // navigating from a page that used prefetching using a link on that
2463 // page. We are early enough in the request process here that we
2464 // can still see the DocumentState of the previous page and set
2465 // this value appropriately.
2466 // TODO(gavinp): catch the important case of navigation in a new
2467 // renderer process.
2468 if (webview) {
2469 if (WebFrame* old_frame = webview->mainFrame()) {
2470 const WebURLRequest& original_request = datasource->originalRequest();
2471 const GURL referrer(
2472 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2473 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2474 DocumentState::FromDataSource(old_frame->dataSource())
2475 ->was_prefetcher()) {
2476 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2477 WebDataSource* old_frame_datasource = old_frame->dataSource();
2478 if (old_frame_datasource &&
2479 referrer == GURL(old_frame_datasource->request().url())) {
2480 document_state->set_was_referred_by_prefetcher(true);
2481 break;
2488 if (content_initiated) {
2489 const WebURLRequest& request = datasource->request();
2490 switch (request.cachePolicy()) {
2491 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2492 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2493 break;
2494 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2495 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2496 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2497 break;
2498 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2499 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK);
2500 break;
2501 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2502 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2503 break;
2504 default:
2505 NOTREACHED();
2509 // Create the serviceworker's per-document network observing object if it
2510 // does not exist (When navigation happens within a page, the provider already
2511 // exists).
2512 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2513 DocumentState::FromDataSource(datasource))) {
2514 scoped_ptr<ServiceWorkerNetworkProvider> network_provider(
2515 new ServiceWorkerNetworkProvider(routing_id_,
2516 SERVICE_WORKER_PROVIDER_FOR_WINDOW));
2517 ServiceWorkerNetworkProvider::AttachToDocumentState(
2518 DocumentState::FromDataSource(datasource),
2519 network_provider.Pass());
2523 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2524 bool is_transition_navigation,
2525 double triggering_event_time) {
2526 DCHECK(!frame_ || frame_ == frame);
2527 WebDataSource* ds = frame->provisionalDataSource();
2529 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2530 // callback is invoked.
2531 if (!ds)
2532 return;
2534 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2535 "id", routing_id_, "url", ds->request().url().string().utf8());
2536 DocumentState* document_state = DocumentState::FromDataSource(ds);
2538 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2539 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2540 is_swapped_out_) <<
2541 "Heard swappedout:// when not swapped out.";
2543 // Update the request time if WebKit has better knowledge of it.
2544 if (document_state->request_time().is_null() &&
2545 triggering_event_time != 0.0) {
2546 document_state->set_request_time(Time::FromDoubleT(triggering_event_time));
2549 // Start time is only set after request time.
2550 document_state->set_start_load_time(Time::Now());
2552 bool is_top_most = !frame->parent();
2553 if (is_top_most) {
2554 render_view_->set_navigation_gesture(
2555 WebUserGestureIndicator::isProcessingUserGesture() ?
2556 NavigationGestureUser : NavigationGestureAuto);
2557 } else if (ds->replacesCurrentHistoryItem()) {
2558 // Subframe navigations that don't add session history items must be
2559 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2560 // handle loading of error pages.
2561 static_cast<NavigationStateImpl*>(document_state->navigation_state())
2562 ->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2565 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2566 DidStartProvisionalLoad(frame));
2567 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2569 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2570 routing_id_, ds->request().url(), is_transition_navigation));
2573 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2574 blink::WebLocalFrame* frame) {
2575 DCHECK(!frame_ || frame_ == frame);
2576 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2579 void RenderFrameImpl::didFailProvisionalLoad(
2580 blink::WebLocalFrame* frame,
2581 const blink::WebURLError& error,
2582 blink::WebHistoryCommitType commit_type) {
2583 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2584 "id", routing_id_);
2585 DCHECK(!frame_ || frame_ == frame);
2586 WebDataSource* ds = frame->provisionalDataSource();
2587 DCHECK(ds);
2589 const WebURLRequest& failed_request = ds->request();
2591 // Notify the browser that we failed a provisional load with an error.
2593 // Note: It is important this notification occur before DidStopLoading so the
2594 // SSL manager can react to the provisional load failure before being
2595 // notified the load stopped.
2597 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2598 DidFailProvisionalLoad(frame, error));
2599 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2600 DidFailProvisionalLoad(error));
2602 SendFailedProvisionalLoad(failed_request, error, frame);
2604 if (!ShouldDisplayErrorPageForFailedLoad(error.reason, error.unreachableURL))
2605 return;
2607 // Make sure we never show errors in view source mode.
2608 frame->enableViewSourceMode(false);
2610 DocumentState* document_state = DocumentState::FromDataSource(ds);
2611 NavigationStateImpl* navigation_state =
2612 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2614 // If this is a failed back/forward/reload navigation, then we need to do a
2615 // 'replace' load. This is necessary to avoid messing up session history.
2616 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2617 // as session history is concerned.
2618 bool replace = commit_type != blink::WebStandardCommit;
2620 // If we failed on a browser initiated request, then make sure that our error
2621 // page load is regarded as the same browser initiated request.
2622 if (!navigation_state->IsContentInitiated()) {
2623 pending_navigation_params_.reset(new NavigationParams(
2624 navigation_state->common_params(), navigation_state->start_params(),
2625 navigation_state->request_params()));
2626 pending_navigation_params_->request_params.request_time =
2627 document_state->request_time();
2630 // Load an error page.
2631 LoadNavigationErrorPage(failed_request, error, replace);
2634 void RenderFrameImpl::didCommitProvisionalLoad(
2635 blink::WebLocalFrame* frame,
2636 const blink::WebHistoryItem& item,
2637 blink::WebHistoryCommitType commit_type) {
2638 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2639 "id", routing_id_,
2640 "url", GetLoadingUrl().possibly_invalid_spec());
2641 DCHECK(!frame_ || frame_ == frame);
2642 DocumentState* document_state =
2643 DocumentState::FromDataSource(frame->dataSource());
2644 NavigationStateImpl* navigation_state =
2645 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2647 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2648 RenderFrameProxy* proxy =
2649 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2650 CHECK(proxy);
2651 proxy->web_frame()->swap(frame_);
2652 proxy_routing_id_ = MSG_ROUTING_NONE;
2654 // If this is the main frame going from a remote frame to a local frame,
2655 // it needs to set RenderViewImpl's pointer for the main frame to itself.
2656 if (!is_subframe_) {
2657 CHECK(!render_view_->main_render_frame_);
2658 render_view_->main_render_frame_ = this;
2662 // When we perform a new navigation, we need to update the last committed
2663 // session history entry with state for the page we are leaving. Do this
2664 // before updating the HistoryController state.
2665 render_view_->UpdateSessionHistory(frame);
2667 render_view_->history_controller()->UpdateForCommit(
2668 this, item, commit_type, navigation_state->WasWithinSamePage());
2670 InternalDocumentStateData* internal_data =
2671 InternalDocumentStateData::FromDocumentState(document_state);
2673 if (document_state->commit_load_time().is_null())
2674 document_state->set_commit_load_time(Time::Now());
2676 if (internal_data->must_reset_scroll_and_scale_state()) {
2677 render_view_->webview()->resetScrollAndScaleState();
2678 internal_data->set_must_reset_scroll_and_scale_state(false);
2680 internal_data->set_use_error_page(false);
2682 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2683 if (is_new_navigation) {
2684 // We bump our Page ID to correspond with the new session history entry.
2685 render_view_->page_id_ = render_view_->next_page_id_++;
2687 // Don't update history list values for kSwappedOutURL, since
2688 // we don't want to forget the entry that was there, and since we will
2689 // never come back to kSwappedOutURL. Note that we have to call
2690 // UpdateSessionHistory and update page_id_ even in this case, so that
2691 // the current entry gets a state update and so that we don't send a
2692 // state update to the wrong entry when we swap back in.
2693 DCHECK_IMPLIES(
2694 navigation_state->start_params().should_replace_current_entry,
2695 render_view_->history_list_length_ > 0);
2696 if (GetLoadingUrl() != GURL(kSwappedOutURL) &&
2697 !navigation_state->start_params().should_replace_current_entry) {
2698 // Advance our offset in session history, applying the length limit.
2699 // There is now no forward history.
2700 render_view_->history_list_offset_++;
2701 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2702 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2703 render_view_->history_list_length_ =
2704 render_view_->history_list_offset_ + 1;
2706 } else {
2707 const RequestNavigationParams& request_params =
2708 navigation_state->request_params();
2709 if (request_params.nav_entry_id != 0 &&
2710 !request_params.intended_as_new_entry) {
2711 // This is a successful session history navigation!
2712 render_view_->page_id_ = request_params.page_id;
2714 render_view_->history_list_offset_ =
2715 request_params.pending_history_list_offset;
2719 bool sent = Send(
2720 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2721 CHECK(sent); // http://crbug.com/407376
2723 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2724 DidCommitProvisionalLoad(frame, is_new_navigation));
2725 FOR_EACH_OBSERVER(
2726 RenderFrameObserver, observers_,
2727 DidCommitProvisionalLoad(is_new_navigation,
2728 navigation_state->WasWithinSamePage()));
2730 if (!frame->parent()) { // Only for top frames.
2731 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2732 if (render_thread_impl) { // Can be NULL in tests.
2733 render_thread_impl->histogram_customizer()->
2734 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2735 RenderViewImpl::GetRenderViewCount());
2739 // Remember that we've already processed this request, so we don't update
2740 // the session history again. We do this regardless of whether this is
2741 // a session history navigation, because if we attempted a session history
2742 // navigation without valid HistoryItem state, WebCore will think it is a
2743 // new navigation.
2744 navigation_state->set_request_committed(true);
2746 SendDidCommitProvisionalLoad(frame, commit_type);
2748 // Check whether we have new encoding name.
2749 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2752 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2753 DCHECK(!frame_ || frame_ == frame);
2755 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2756 DidCreateNewDocument(frame));
2759 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2760 DCHECK(!frame_ || frame_ == frame);
2762 int enabled_bindings = render_view_->GetEnabledBindings();
2764 if (enabled_bindings & BINDINGS_POLICY_WEB_UI)
2765 WebUIExtension::Install(frame);
2767 if (enabled_bindings & BINDINGS_POLICY_DOM_AUTOMATION)
2768 DomAutomationController::Install(this, frame);
2770 if (enabled_bindings & BINDINGS_POLICY_STATS_COLLECTION)
2771 StatsCollectionController::Install(frame);
2773 const base::CommandLine& command_line =
2774 *base::CommandLine::ForCurrentProcess();
2776 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
2777 GpuBenchmarking::Install(frame);
2779 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2780 MemoryBenchmarkingExtension::Install(frame);
2782 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2783 SkiaBenchmarking::Install(frame);
2785 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2786 DidClearWindowObject(frame));
2787 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2790 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2791 DCHECK(!frame_ || frame_ == frame);
2793 // Notify the browser about non-blank documents loading in the top frame.
2794 GURL url = frame->document().url();
2795 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2796 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2797 // frame->tree()->top().
2798 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2799 if (frame == main_frame) {
2800 // For now, don't remember plugin zoom values. We don't want to mix them
2801 // with normal web content (i.e. a fixed layout plugin would usually want
2802 // them different).
2803 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2804 render_view_->GetRoutingID(),
2805 main_frame->document().isPluginDocument()));
2809 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2810 DidCreateDocumentElement(frame));
2813 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2814 const blink::WebString& title,
2815 blink::WebTextDirection direction) {
2816 DCHECK(!frame_ || frame_ == frame);
2817 // Ignore all but top level navigations.
2818 if (!frame->parent()) {
2819 base::string16 title16 = title;
2820 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2821 routing_id_, base::UTF16ToUTF8(title16));
2823 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2824 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2825 shortened_title, direction));
2828 // Also check whether we have new encoding name.
2829 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2832 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2833 blink::WebIconURL::Type icon_type) {
2834 DCHECK(!frame_ || frame_ == frame);
2835 // TODO(nasko): Investigate wheather implementation should move here.
2836 render_view_->didChangeIcon(frame, icon_type);
2839 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2840 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2841 "id", routing_id_);
2842 DCHECK(!frame_ || frame_ == frame);
2843 WebDataSource* ds = frame->dataSource();
2844 DocumentState* document_state = DocumentState::FromDataSource(ds);
2845 document_state->set_finish_document_load_time(Time::Now());
2847 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2849 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2850 DidFinishDocumentLoad(frame));
2851 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2853 // Check whether we have new encoding name.
2854 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2857 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2858 DCHECK(!frame_ || frame_ == frame);
2859 if (!frame->parent()) {
2860 FrameMsg_UILoadMetricsReportType::Value report_type =
2861 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
2862 frame->dataSource()->request().inputPerfMetricReportPolicy());
2863 base::TimeTicks ui_timestamp = base::TimeTicks() +
2864 base::TimeDelta::FromSecondsD(
2865 frame->dataSource()->request().uiStartTime());
2867 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2868 routing_id_, report_type, ui_timestamp));
2872 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2873 const blink::WebURLError& error,
2874 blink::WebHistoryCommitType commit_type) {
2875 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2876 "id", routing_id_);
2877 DCHECK(!frame_ || frame_ == frame);
2878 // TODO(nasko): Move implementation here. No state needed.
2879 WebDataSource* ds = frame->dataSource();
2880 DCHECK(ds);
2882 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2883 DidFailLoad(frame, error));
2885 const WebURLRequest& failed_request = ds->request();
2886 base::string16 error_description;
2887 GetContentClient()->renderer()->GetNavigationErrorStrings(
2888 render_view_.get(),
2889 frame,
2890 failed_request,
2891 error,
2892 NULL,
2893 &error_description);
2894 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2895 failed_request.url(),
2896 error.reason,
2897 error_description));
2900 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2901 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2902 "id", routing_id_);
2903 DCHECK(!frame_ || frame_ == frame);
2904 WebDataSource* ds = frame->dataSource();
2905 DocumentState* document_state = DocumentState::FromDataSource(ds);
2906 if (document_state->finish_load_time().is_null()) {
2907 if (!frame->parent()) {
2908 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2909 TRACE_EVENT_SCOPE_PROCESS);
2911 document_state->set_finish_load_time(Time::Now());
2914 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2915 DidFinishLoad(frame));
2916 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2918 // Don't send this message while the frame is swapped out.
2919 if (is_swapped_out())
2920 return;
2922 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2923 ds->request().url()));
2926 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2927 const blink::WebHistoryItem& item,
2928 blink::WebHistoryCommitType commit_type) {
2929 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2930 "id", routing_id_);
2931 DCHECK(!frame_ || frame_ == frame);
2932 // If this was a reference fragment navigation that we initiated, then we
2933 // could end up having a non-null pending navigation params. We just need to
2934 // update the ExtraData on the datasource so that others who read the
2935 // ExtraData will get the new NavigationState. Similarly, if we did not
2936 // initiate this navigation, then we need to take care to reset any pre-
2937 // existing navigation state to a content-initiated navigation state.
2938 // didCreateDataSource conveniently takes care of this for us.
2939 didCreateDataSource(frame, frame->dataSource());
2941 DocumentState* document_state =
2942 DocumentState::FromDataSource(frame->dataSource());
2943 static_cast<NavigationStateImpl*>(document_state->navigation_state())
2944 ->set_was_within_same_page(true);
2946 didCommitProvisionalLoad(frame, item, commit_type);
2949 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2950 DCHECK(!frame_ || frame_ == frame);
2951 // TODO(nasko): Move implementation here. Needed methods:
2952 // * StartNavStateSyncTimerIfNecessary
2953 render_view_->didUpdateCurrentHistoryItem(frame);
2956 void RenderFrameImpl::addNavigationTransitionData(
2957 const blink::WebTransitionElementData& data) {
2958 FrameHostMsg_AddNavigationTransitionData_Params params;
2959 params.render_frame_id = routing_id_;
2960 params.allowed_destination_host_pattern =
2961 data.scope.utf8();
2962 params.selector = data.selector.utf8();
2963 params.markup = data.markup.utf8();
2964 params.elements.resize(data.elements.size());
2965 for (size_t i = 0; i < data.elements.size(); i++) {
2966 params.elements[i].id = data.elements[i].id.utf8();
2967 params.elements[i].rect = gfx::Rect(data.elements[i].rect);
2970 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2973 void RenderFrameImpl::didChangeThemeColor() {
2974 if (frame_->parent())
2975 return;
2977 Send(new FrameHostMsg_DidChangeThemeColor(
2978 routing_id_, frame_->document().themeColor()));
2981 void RenderFrameImpl::dispatchLoad() {
2982 Send(new FrameHostMsg_DispatchLoad(routing_id_));
2985 void RenderFrameImpl::requestNotificationPermission(
2986 const blink::WebSecurityOrigin& origin,
2987 blink::WebNotificationPermissionCallback* callback) {
2988 if (!notification_permission_dispatcher_) {
2989 notification_permission_dispatcher_ =
2990 new NotificationPermissionDispatcher(this);
2993 notification_permission_dispatcher_->RequestPermission(origin, callback);
2996 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2997 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2998 return;
3000 if (is_empty_selection)
3001 selection_text_.clear();
3003 // UpdateTextInputType should be called before SyncSelectionIfRequired.
3004 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
3005 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3006 // to notify the selection was changed. Focus change should be notified
3007 // before selection change.
3008 GetRenderWidget()->UpdateTextInputType();
3009 SyncSelectionIfRequired();
3010 #if defined(OS_ANDROID)
3011 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
3012 RenderWidget::FROM_NON_IME);
3013 #endif
3016 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
3017 blink::WebColorChooserClient* client,
3018 const blink::WebColor& initial_color,
3019 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
3020 RendererWebColorChooserImpl* color_chooser =
3021 new RendererWebColorChooserImpl(this, client);
3022 std::vector<ColorSuggestion> color_suggestions;
3023 for (size_t i = 0; i < suggestions.size(); i++) {
3024 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
3026 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
3027 return color_chooser;
3030 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
3031 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
3032 message,
3033 base::string16(),
3034 frame_->document().url(),
3035 NULL);
3038 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
3039 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
3040 message,
3041 base::string16(),
3042 frame_->document().url(),
3043 NULL);
3046 bool RenderFrameImpl::runModalPromptDialog(
3047 const blink::WebString& message,
3048 const blink::WebString& default_value,
3049 blink::WebString* actual_value) {
3050 base::string16 result;
3051 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
3052 message,
3053 default_value,
3054 frame_->document().url(),
3055 &result);
3056 if (ok)
3057 actual_value->assign(result);
3058 return ok;
3061 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3062 bool is_reload,
3063 const blink::WebString& message) {
3064 // If we are swapping out, we have already run the beforeunload handler.
3065 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3066 // at all, to avoid running it twice.
3067 if (is_swapped_out_)
3068 return true;
3070 // Don't allow further dialogs if we are waiting to swap out, since the
3071 // PageGroupLoadDeferrer in our stack prevents it.
3072 if (render_view()->suppress_dialogs_until_swap_out_)
3073 return false;
3075 bool success = false;
3076 // This is an ignored return value, but is included so we can accept the same
3077 // response as RunJavaScriptMessage.
3078 base::string16 ignored_result;
3079 render_view()->SendAndRunNestedMessageLoop(
3080 new FrameHostMsg_RunBeforeUnloadConfirm(
3081 routing_id_, frame_->document().url(), message, is_reload,
3082 &success, &ignored_result));
3083 return success;
3086 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
3087 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
3088 params.source_type = GetRenderWidget()->context_menu_source_type();
3089 GetRenderWidget()->OnShowHostContextMenu(&params);
3090 if (GetRenderWidget()->has_host_context_menu_location()) {
3091 params.x = GetRenderWidget()->host_context_menu_location().x();
3092 params.y = GetRenderWidget()->host_context_menu_location().y();
3095 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3096 // it. We replace it with an empty GURL so the appropriate items are disabled
3097 // in the context menu.
3098 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3099 // data encoded images. We should have a way to save them.
3100 if (params.src_url.spec().size() > GetMaxURLChars())
3101 params.src_url = GURL();
3102 context_menu_node_ = data.node;
3104 #if defined(OS_ANDROID)
3105 gfx::Rect start_rect;
3106 gfx::Rect end_rect;
3107 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
3108 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
3109 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
3110 #endif
3112 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
3115 void RenderFrameImpl::clearContextMenu() {
3116 context_menu_node_.reset();
3119 void RenderFrameImpl::willSendRequest(
3120 blink::WebLocalFrame* frame,
3121 unsigned identifier,
3122 blink::WebURLRequest& request,
3123 const blink::WebURLResponse& redirect_response) {
3124 DCHECK(!frame_ || frame_ == frame);
3125 // The request my be empty during tests.
3126 if (request.url().isEmpty())
3127 return;
3129 // Set the first party for cookies url if it has not been set yet (new
3130 // requests). For redirects, it is updated by WebURLLoaderImpl.
3131 if (request.firstPartyForCookies().isEmpty()) {
3132 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
3133 request.setFirstPartyForCookies(request.url());
3134 } else {
3135 // TODO(nasko): When the top-level frame is remote, there is no document.
3136 // This is broken and should be fixed to propagate the first party.
3137 WebFrame* top = frame->top();
3138 if (top->isWebLocalFrame()) {
3139 request.setFirstPartyForCookies(
3140 frame->top()->document().firstPartyForCookies());
3145 WebFrame* top_frame = frame->top();
3146 // TODO(nasko): Hack around asking about top-frame data source. This means
3147 // for out-of-process iframes we are treating the current frame as the
3148 // top-level frame, which is wrong.
3149 if (!top_frame || top_frame->isWebRemoteFrame())
3150 top_frame = frame;
3151 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
3152 WebDataSource* top_data_source = top_frame->dataSource();
3153 WebDataSource* data_source =
3154 provisional_data_source ? provisional_data_source : top_data_source;
3156 DocumentState* document_state = DocumentState::FromDataSource(data_source);
3157 DCHECK(document_state);
3158 InternalDocumentStateData* internal_data =
3159 InternalDocumentStateData::FromDocumentState(document_state);
3160 NavigationStateImpl* navigation_state =
3161 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3162 ui::PageTransition transition_type = navigation_state->GetTransitionType();
3163 WebDataSource* frame_ds = frame->provisionalDataSource();
3164 if (frame_ds && frame_ds->isClientRedirect()) {
3165 transition_type = ui::PageTransitionFromInt(
3166 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3169 GURL request_url(request.url());
3170 GURL new_url;
3171 if (GetContentClient()->renderer()->WillSendRequest(
3172 frame,
3173 transition_type,
3174 request_url,
3175 request.firstPartyForCookies(),
3176 &new_url)) {
3177 request.setURL(WebURL(new_url));
3180 if (internal_data->is_cache_policy_override_set())
3181 request.setCachePolicy(internal_data->cache_policy_override());
3183 // The request's extra data may indicate that we should set a custom user
3184 // agent. This needs to be done here, after WebKit is through with setting the
3185 // user agent on its own. Similarly, it may indicate that we should set an
3186 // X-Requested-With header. This must be done here to avoid breaking CORS
3187 // checks.
3188 // PlzNavigate: there may also be a stream url associated with the request.
3189 WebString custom_user_agent;
3190 WebString requested_with;
3191 scoped_ptr<StreamOverrideParameters> stream_override;
3192 if (request.extraData()) {
3193 RequestExtraData* old_extra_data =
3194 static_cast<RequestExtraData*>(request.extraData());
3196 custom_user_agent = old_extra_data->custom_user_agent();
3197 if (!custom_user_agent.isNull()) {
3198 if (custom_user_agent.isEmpty())
3199 request.clearHTTPHeaderField("User-Agent");
3200 else
3201 request.setHTTPHeaderField("User-Agent", custom_user_agent);
3204 requested_with = old_extra_data->requested_with();
3205 if (!requested_with.isNull()) {
3206 if (requested_with.isEmpty())
3207 request.clearHTTPHeaderField("X-Requested-With");
3208 else
3209 request.setHTTPHeaderField("X-Requested-With", requested_with);
3211 stream_override = old_extra_data->TakeStreamOverrideOwnership();
3214 // Add the default accept header for frame request if it has not been set
3215 // already.
3216 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3217 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
3218 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
3219 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
3220 WebString::fromUTF8(kDefaultAcceptHeader));
3223 // Add an empty HTTP origin header for non GET methods if none is currently
3224 // present.
3225 request.addHTTPOriginIfNeeded(WebString());
3227 // Attach |should_replace_current_entry| state to requests so that, should
3228 // this navigation later require a request transfer, all state is preserved
3229 // when it is re-created in the new process.
3230 bool should_replace_current_entry = false;
3231 if (navigation_state->IsContentInitiated()) {
3232 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
3233 } else {
3234 // If the navigation is browser-initiated, the NavigationState contains the
3235 // correct value instead of the WebDataSource.
3237 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3238 // NavigationState::should_replace_current_entry().
3239 should_replace_current_entry =
3240 navigation_state->start_params().should_replace_current_entry;
3243 int provider_id = kInvalidServiceWorkerProviderId;
3244 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3245 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
3246 // |provisionalDataSource| may be null in some content::ResourceFetcher
3247 // use cases, we don't hook those requests.
3248 if (frame->provisionalDataSource()) {
3249 ServiceWorkerNetworkProvider* provider =
3250 ServiceWorkerNetworkProvider::FromDocumentState(
3251 DocumentState::FromDataSource(frame->provisionalDataSource()));
3252 provider_id = provider->provider_id();
3254 } else if (frame->dataSource()) {
3255 ServiceWorkerNetworkProvider* provider =
3256 ServiceWorkerNetworkProvider::FromDocumentState(
3257 DocumentState::FromDataSource(frame->dataSource()));
3258 provider_id = provider->provider_id();
3261 WebFrame* parent = frame->parent();
3262 int parent_routing_id = MSG_ROUTING_NONE;
3263 if (!parent) {
3264 parent_routing_id = -1;
3265 } else if (parent->isWebLocalFrame()) {
3266 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
3267 } else {
3268 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
3271 RequestExtraData* extra_data = new RequestExtraData();
3272 extra_data->set_visibility_state(render_view_->visibilityState());
3273 extra_data->set_custom_user_agent(custom_user_agent);
3274 extra_data->set_requested_with(requested_with);
3275 extra_data->set_render_frame_id(routing_id_);
3276 extra_data->set_is_main_frame(!parent);
3277 extra_data->set_frame_origin(
3278 GURL(frame->document().securityOrigin().toString()));
3279 extra_data->set_parent_is_main_frame(parent && !parent->parent());
3280 extra_data->set_parent_render_frame_id(parent_routing_id);
3281 extra_data->set_allow_download(
3282 navigation_state->common_params().allow_download);
3283 extra_data->set_transition_type(transition_type);
3284 extra_data->set_should_replace_current_entry(should_replace_current_entry);
3285 extra_data->set_transferred_request_child_id(
3286 navigation_state->start_params().transferred_request_child_id);
3287 extra_data->set_transferred_request_request_id(
3288 navigation_state->start_params().transferred_request_request_id);
3289 extra_data->set_service_worker_provider_id(provider_id);
3290 extra_data->set_stream_override(stream_override.Pass());
3291 request.setExtraData(extra_data);
3293 DocumentState* top_document_state =
3294 DocumentState::FromDataSource(top_data_source);
3295 if (top_document_state) {
3296 // TODO(gavinp): separate out prefetching and prerender field trials
3297 // if the rel=prerender rel type is sticking around.
3298 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
3299 top_document_state->set_was_prefetcher(true);
3302 // This is an instance where we embed a copy of the routing id
3303 // into the data portion of the message. This can cause problems if we
3304 // don't register this id on the browser side, since the download manager
3305 // expects to find a RenderViewHost based off the id.
3306 request.setRequestorID(render_view_->GetRoutingID());
3307 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3309 if (!navigation_state->start_params().extra_headers.empty()) {
3310 for (net::HttpUtil::HeadersIterator i(
3311 navigation_state->start_params().extra_headers.begin(),
3312 navigation_state->start_params().extra_headers.end(), "\n");
3313 i.GetNext();) {
3314 if (LowerCaseEqualsASCII(i.name(), "referer")) {
3315 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
3316 blink::WebReferrerPolicyDefault,
3317 request.url(),
3318 WebString::fromUTF8(i.values()));
3319 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
3320 } else {
3321 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
3322 WebString::fromUTF8(i.values()));
3327 if (!render_view_->renderer_preferences_.enable_referrers)
3328 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
3331 void RenderFrameImpl::didReceiveResponse(
3332 blink::WebLocalFrame* frame,
3333 unsigned identifier,
3334 const blink::WebURLResponse& response) {
3335 DCHECK(!frame_ || frame_ == frame);
3336 // Only do this for responses that correspond to a provisional data source
3337 // of the top-most frame. If we have a provisional data source, then we
3338 // can't have any sub-resources yet, so we know that this response must
3339 // correspond to a frame load.
3340 if (!frame->provisionalDataSource() || frame->parent())
3341 return;
3343 // If we are in view source mode, then just let the user see the source of
3344 // the server's error page.
3345 if (frame->isViewSourceModeEnabled())
3346 return;
3348 DocumentState* document_state =
3349 DocumentState::FromDataSource(frame->provisionalDataSource());
3350 int http_status_code = response.httpStatusCode();
3352 // Record page load flags.
3353 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3354 if (extra_data) {
3355 document_state->set_was_fetched_via_spdy(
3356 extra_data->was_fetched_via_spdy());
3357 document_state->set_was_npn_negotiated(
3358 extra_data->was_npn_negotiated());
3359 document_state->set_npn_negotiated_protocol(
3360 extra_data->npn_negotiated_protocol());
3361 document_state->set_was_alternate_protocol_available(
3362 extra_data->was_alternate_protocol_available());
3363 document_state->set_connection_info(
3364 extra_data->connection_info());
3365 document_state->set_was_fetched_via_proxy(
3366 extra_data->was_fetched_via_proxy());
3367 document_state->set_proxy_server(
3368 extra_data->proxy_server());
3370 InternalDocumentStateData* internal_data =
3371 InternalDocumentStateData::FromDocumentState(document_state);
3372 internal_data->set_http_status_code(http_status_code);
3373 // Whether or not the http status code actually corresponds to an error is
3374 // only checked when the page is done loading, if |use_error_page| is
3375 // still true.
3376 internal_data->set_use_error_page(true);
3379 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
3380 unsigned identifier) {
3381 DCHECK(!frame_ || frame_ == frame);
3382 InternalDocumentStateData* internal_data =
3383 InternalDocumentStateData::FromDataSource(frame->dataSource());
3384 if (!internal_data->use_error_page())
3385 return;
3387 // Do not show error page when DevTools is attached.
3388 RenderFrameImpl* localRoot = this;
3389 while (localRoot->frame_ && localRoot->frame_->parent() &&
3390 localRoot->frame_->parent()->isWebLocalFrame()) {
3391 localRoot = RenderFrameImpl::FromWebFrame(localRoot->frame_->parent());
3392 DCHECK(localRoot);
3394 if (localRoot->devtools_agent_ && localRoot->devtools_agent_->IsAttached())
3395 return;
3397 // Display error page, if appropriate.
3398 std::string error_domain = "http";
3399 int http_status_code = internal_data->http_status_code();
3400 if (GetContentClient()->renderer()->HasErrorPage(
3401 http_status_code, &error_domain)) {
3402 WebURLError error;
3403 error.unreachableURL = frame->document().url();
3404 error.domain = WebString::fromUTF8(error_domain);
3405 error.reason = http_status_code;
3406 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
3410 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3411 blink::WebLocalFrame* frame,
3412 const blink::WebURLRequest& request,
3413 const blink::WebURLResponse& response) {
3414 DCHECK(!frame_ || frame_ == frame);
3415 // The recipients of this message have no use for data: URLs: they don't
3416 // affect the page's insecure content list and are not in the disk cache. To
3417 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3418 // filter them out here.
3419 GURL url(request.url());
3420 if (url.SchemeIs(url::kDataScheme))
3421 return;
3423 // Let the browser know we loaded a resource from the memory cache. This
3424 // message is needed to display the correct SSL indicators.
3425 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3426 render_view_->GetRoutingID(),
3427 url,
3428 response.securityInfo(),
3429 request.httpMethod().utf8(),
3430 response.mimeType().utf8(),
3431 WebURLRequestToResourceType(request)));
3434 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3435 DCHECK(!frame_ || frame_ == frame);
3436 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
3437 render_view_->GetRoutingID()));
3440 void RenderFrameImpl::didRunInsecureContent(
3441 blink::WebLocalFrame* frame,
3442 const blink::WebSecurityOrigin& origin,
3443 const blink::WebURL& target) {
3444 DCHECK(!frame_ || frame_ == frame);
3445 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
3446 render_view_->GetRoutingID(),
3447 origin.toString().utf8(),
3448 target));
3451 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3452 DCHECK(!frame_ || frame_ == frame);
3453 #if defined(ENABLE_PLUGINS)
3454 if (frame != render_view_->webview()->mainFrame())
3455 return;
3456 PluginChannelHost::Broadcast(
3457 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3458 #endif
3461 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3462 v8::Local<v8::Context> context,
3463 int extension_group,
3464 int world_id) {
3465 DCHECK(!frame_ || frame_ == frame);
3467 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
3468 DidCreateScriptContext(context, extension_group, world_id));
3471 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3472 v8::Local<v8::Context> context,
3473 int world_id) {
3474 DCHECK(!frame_ || frame_ == frame);
3476 FOR_EACH_OBSERVER(RenderFrameObserver,
3477 observers_,
3478 WillReleaseScriptContext(context, world_id));
3481 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3482 blink::WebLocalFrame* frame) {
3483 DCHECK(!frame_ || frame_ == frame);
3484 if (frame->parent())
3485 return;
3487 InternalDocumentStateData* data =
3488 InternalDocumentStateData::FromDataSource(frame->dataSource());
3489 data->set_did_first_visually_non_empty_layout(true);
3491 #if defined(OS_ANDROID)
3492 GetRenderWidget()->DidChangeBodyBackgroundColor(
3493 render_view_->webwidget_->backgroundColor());
3494 #endif
3496 GetRenderWidget()->QueueMessage(
3497 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3498 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3501 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3502 DCHECK(!frame_ || frame_ == frame);
3503 // TODO(nasko): Move implementation here. Needed methods:
3504 // * StartNavStateSyncTimerIfNecessary
3505 render_view_->didChangeScrollOffset(frame);
3507 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeScrollOffset());
3510 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3511 DCHECK(!frame_ || frame_ == frame);
3512 if (!frame->parent()) {
3513 render_view_->Send(new ViewHostMsg_WillInsertBody(
3514 render_view_->GetRoutingID()));
3518 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3519 int count,
3520 bool final_update) {
3521 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3522 if (!count)
3523 active_match_ordinal = 0;
3525 render_view_->Send(new ViewHostMsg_Find_Reply(
3526 render_view_->GetRoutingID(), request_id, count,
3527 gfx::Rect(), active_match_ordinal, final_update));
3530 void RenderFrameImpl::reportFindInPageSelection(
3531 int request_id,
3532 int active_match_ordinal,
3533 const blink::WebRect& selection_rect) {
3534 render_view_->Send(new ViewHostMsg_Find_Reply(
3535 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3536 active_match_ordinal, false));
3539 void RenderFrameImpl::requestStorageQuota(
3540 blink::WebLocalFrame* frame,
3541 blink::WebStorageQuotaType type,
3542 unsigned long long requested_size,
3543 blink::WebStorageQuotaCallbacks callbacks) {
3544 DCHECK(!frame_ || frame_ == frame);
3545 WebSecurityOrigin origin = frame->document().securityOrigin();
3546 if (origin.isUnique()) {
3547 // Unique origins cannot store persistent state.
3548 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3549 return;
3551 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3552 render_view_->GetRoutingID(),
3553 GURL(origin.toString()),
3554 static_cast<storage::StorageType>(type),
3555 requested_size,
3556 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3559 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3560 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3561 impl->set_render_frame_id(routing_id_);
3564 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3565 if (!geolocation_dispatcher_)
3566 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3567 return geolocation_dispatcher_;
3570 blink::WebPresentationClient* RenderFrameImpl::presentationClient() {
3571 if (!presentation_dispatcher_)
3572 presentation_dispatcher_ = new PresentationDispatcher(this);
3573 return presentation_dispatcher_;
3576 blink::WebPushClient* RenderFrameImpl::pushClient() {
3577 if (!push_messaging_dispatcher_)
3578 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3579 return push_messaging_dispatcher_;
3582 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3583 blink::WebLocalFrame* frame,
3584 blink::WebRTCPeerConnectionHandler* handler) {
3585 DCHECK(!frame_ || frame_ == frame);
3586 #if defined(ENABLE_WEBRTC)
3587 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3588 #endif
3591 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3592 if (!web_user_media_client_)
3593 InitializeUserMediaClient();
3594 return web_user_media_client_;
3597 blink::WebEncryptedMediaClient* RenderFrameImpl::encryptedMediaClient() {
3598 if (!web_encrypted_media_client_) {
3599 web_encrypted_media_client_.reset(new media::WebEncryptedMediaClientImpl(
3600 // base::Unretained(this) is safe because WebEncryptedMediaClientImpl
3601 // is destructed before |this|, and does not give away ownership of the
3602 // callback.
3603 base::Bind(&RenderFrameImpl::AreSecureCodecsSupported,
3604 base::Unretained(this)),
3605 GetCdmFactory(), GetMediaPermission()));
3607 return web_encrypted_media_client_.get();
3610 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3611 if (!midi_dispatcher_)
3612 midi_dispatcher_ = new MidiDispatcher(this);
3613 return midi_dispatcher_;
3616 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3617 blink::WebLocalFrame* source_frame,
3618 blink::WebFrame* target_frame,
3619 blink::WebSecurityOrigin target_origin,
3620 blink::WebDOMMessageEvent event) {
3621 DCHECK(!frame_ || frame_ == target_frame);
3623 // Currently, a postMessage that targets a cross-process frame can be plumbed
3624 // either through this function or RenderFrameProxy::postMessageEvent. This
3625 // function is used when the target cross-process frame is a top-level frame
3626 // which has been swapped out. In that case, the corresponding WebLocalFrame
3627 // currently remains in the frame tree even in site-per-process mode (see
3628 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3629 // --site-per-process mode for all other cases.
3631 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3632 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3633 // cross-process postMessages.
3634 if (!is_swapped_out_)
3635 return false;
3637 // It is possible to get here on a swapped-out frame without a
3638 // |render_frame_proxy_|. This happens when:
3639 // - This process only has one active RenderView and is about to go away
3640 // (e.g., due to cross-process navigation).
3641 // - The top frame has a subframe with an unload handler.
3642 // - The subframe sends a postMessage to the top-level frame in its unload
3643 // handler.
3644 // See https://crbug.com/475651 for details. We return false here, since we
3645 // don't want to deliver the message to the new process in this case.
3646 if (!render_frame_proxy_)
3647 return false;
3649 render_frame_proxy_->postMessageEvent(
3650 source_frame, render_frame_proxy_->web_frame(), target_origin, event);
3651 return true;
3654 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3655 const blink::WebURL& url) {
3656 DCHECK(!frame_ || frame_ == frame);
3657 std::string user_agent_override_for_url =
3658 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3659 if (!user_agent_override_for_url.empty())
3660 return WebString::fromUTF8(user_agent_override_for_url);
3662 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3663 render_view_->renderer_preferences_.user_agent_override.empty()) {
3664 return blink::WebString();
3667 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3668 // associated with it, so the checks below are not valid. Temporarily
3669 // return early and fix properly as part of https://crbug.com/426555.
3670 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3671 return blink::WebString();
3673 // If we're in the middle of committing a load, the data source we need
3674 // will still be provisional.
3675 WebFrame* main_frame = render_view_->webview()->mainFrame();
3676 WebDataSource* data_source = NULL;
3677 if (main_frame->provisionalDataSource())
3678 data_source = main_frame->provisionalDataSource();
3679 else
3680 data_source = main_frame->dataSource();
3682 InternalDocumentStateData* internal_data = data_source ?
3683 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3684 if (internal_data && internal_data->is_overriding_user_agent())
3685 return WebString::fromUTF8(
3686 render_view_->renderer_preferences_.user_agent_override);
3687 return blink::WebString();
3690 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3691 DCHECK(!frame_ || frame_ == frame);
3692 if (render_view_->renderer_preferences_.enable_do_not_track)
3693 return WebString::fromUTF8("1");
3694 return WebString();
3697 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3698 bool default_value) {
3699 DCHECK(!frame_ || frame_ == frame);
3700 if (!default_value)
3701 return false;
3703 bool blocked = true;
3704 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3705 render_view_->GetRoutingID(),
3706 GURL(frame->top()->document().securityOrigin().toString()),
3707 THREE_D_API_TYPE_WEBGL,
3708 &blocked));
3709 return !blocked;
3712 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3713 int arb_robustness_status_code) {
3714 DCHECK(!frame_ || frame_ == frame);
3715 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3716 GURL(frame->top()->document().securityOrigin().toString()),
3717 THREE_D_API_TYPE_WEBGL,
3718 arb_robustness_status_code));
3721 blink::WebScreenOrientationClient*
3722 RenderFrameImpl::webScreenOrientationClient() {
3723 if (!screen_orientation_dispatcher_)
3724 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3725 return screen_orientation_dispatcher_;
3728 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3729 ServiceWorkerNetworkProvider* provider =
3730 ServiceWorkerNetworkProvider::FromDocumentState(
3731 DocumentState::FromDataSource(&data_source));
3732 return provider->context()->controller_handle_id() !=
3733 kInvalidServiceWorkerHandleId;
3736 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3737 ServiceWorkerNetworkProvider* provider =
3738 ServiceWorkerNetworkProvider::FromDocumentState(
3739 DocumentState::FromDataSource(&data_source));
3741 if (provider->context()->controller())
3742 return provider->context()->controller()->version_id();
3743 return kInvalidServiceWorkerVersionId;
3746 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3747 blink::WebAXEvent event) {
3748 HandleWebAccessibilityEvent(obj, event);
3751 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3752 int identifier,
3753 int match_index,
3754 const blink::WebAXObject& start_object,
3755 int start_offset,
3756 const blink::WebAXObject& end_object,
3757 int end_offset) {
3758 if (renderer_accessibility_) {
3759 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3760 identifier, match_index, start_object, start_offset,
3761 end_object, end_offset);
3765 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame) {
3766 DCHECK(!frame_ || frame_ == frame);
3768 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3771 void RenderFrameImpl::didChangeDefaultPresentation(
3772 blink::WebLocalFrame* frame) {
3773 DCHECK(!frame_ || frame_ == frame);
3775 FOR_EACH_OBSERVER(
3776 RenderFrameObserver, observers_, DidChangeDefaultPresentation());
3779 bool RenderFrameImpl::enterFullscreen() {
3780 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, true));
3781 return true;
3784 bool RenderFrameImpl::exitFullscreen() {
3785 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, false));
3786 return true;
3789 blink::WebPermissionClient* RenderFrameImpl::permissionClient() {
3790 if (!permission_client_)
3791 permission_client_.reset(new PermissionDispatcher(GetServiceRegistry()));
3793 return permission_client_.get();
3796 blink::WebAppBannerClient* RenderFrameImpl::appBannerClient() {
3797 if (!app_banner_client_) {
3798 app_banner_client_ =
3799 GetContentClient()->renderer()->CreateAppBannerClient(this);
3802 return app_banner_client_.get();
3805 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3806 Send(new FrameHostMsg_MediaPlayingNotification(
3807 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3808 player->hasAudio(), player->isRemote()));
3811 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3812 Send(new FrameHostMsg_MediaPausedNotification(
3813 routing_id_, reinterpret_cast<int64>(player)));
3816 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3817 DidPause(player);
3820 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3821 observers_.AddObserver(observer);
3824 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3825 observer->RenderFrameGone();
3826 observers_.RemoveObserver(observer);
3829 void RenderFrameImpl::OnStop() {
3830 DCHECK(frame_);
3831 frame_->stopLoading();
3832 if (!frame_->parent())
3833 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3835 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3838 void RenderFrameImpl::WasHidden() {
3839 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3842 void RenderFrameImpl::WasShown() {
3843 // TODO(kenrb): Need to figure out how to do this better. Should
3844 // VisibilityState remain a page-level concept or move to frames?
3845 // The semantics of 'Show' might have to change here.
3846 if (render_widget_) {
3847 static_cast<blink::WebFrameWidget*>(render_widget_->webwidget())->
3848 setVisibilityState(blink::WebPageVisibilityStateVisible, false);
3850 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3853 void RenderFrameImpl::WidgetWillClose() {
3854 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WidgetWillClose());
3857 bool RenderFrameImpl::IsHidden() {
3858 return GetRenderWidget()->is_hidden();
3861 // Tell the embedding application that the URL of the active page has changed.
3862 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3863 blink::WebFrame* frame,
3864 blink::WebHistoryCommitType commit_type) {
3865 DCHECK(!frame_ || frame_ == frame);
3866 WebDataSource* ds = frame->dataSource();
3867 DCHECK(ds);
3869 const WebURLRequest& request = ds->request();
3870 const WebURLResponse& response = ds->response();
3872 DocumentState* document_state = DocumentState::FromDataSource(ds);
3873 NavigationStateImpl* navigation_state =
3874 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3875 InternalDocumentStateData* internal_data =
3876 InternalDocumentStateData::FromDocumentState(document_state);
3878 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3879 params.http_status_code = response.httpStatusCode();
3880 params.url_is_unreachable = ds->hasUnreachableURL();
3881 params.is_post = false;
3882 params.intended_as_new_entry =
3883 navigation_state->request_params().intended_as_new_entry;
3884 params.did_create_new_entry = commit_type == blink::WebStandardCommit;
3885 params.post_id = -1;
3886 params.page_id = render_view_->page_id_;
3887 params.nav_entry_id = navigation_state->request_params().nav_entry_id;
3888 // We need to track the RenderViewHost routing_id because of downstream
3889 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3890 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3891 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3892 // based on the ID stored in the resource requests. Once those dependencies
3893 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3894 // client to be based on the routing_id of the RenderFrameHost.
3895 params.render_view_routing_id = render_view_->routing_id();
3896 params.socket_address.set_host(response.remoteIPAddress().utf8());
3897 params.socket_address.set_port(response.remotePort());
3898 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3899 if (extra_data)
3900 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3901 params.was_within_same_page = navigation_state->WasWithinSamePage();
3902 params.security_info = response.securityInfo();
3904 // Set the URL to be displayed in the browser UI to the user.
3905 params.url = GetLoadingUrl();
3906 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3908 // Set the origin of the frame. This will be replicated to the corresponding
3909 // RenderFrameProxies in other processes.
3910 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3911 // to https://crbug.com/439608 and will be replicated as unique origins.
3912 if (!is_swapped_out_) {
3913 WebString serialized_origin(frame->document().securityOrigin().toString());
3914 if (GURL(serialized_origin).IsStandard())
3915 params.origin = url::Origin(serialized_origin.utf8());
3918 if (frame->document().baseURL() != params.url)
3919 params.base_url = frame->document().baseURL();
3921 GetRedirectChain(ds, &params.redirects);
3922 params.should_update_history = !ds->hasUnreachableURL() &&
3923 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3925 params.searchable_form_url = internal_data->searchable_form_url();
3926 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3928 params.gesture = render_view_->navigation_gesture_;
3929 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3931 // Make navigation state a part of the DidCommitProvisionalLoad message so
3932 // that committed entry has it at all times.
3933 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3934 if (entry)
3935 params.page_state = HistoryEntryToPageState(entry);
3936 else
3937 params.page_state = PageState::CreateFromURL(request.url());
3939 if (!frame->parent()) {
3940 // Top-level navigation.
3942 // Reset the zoom limits in case a plugin had changed them previously. This
3943 // will also call us back which will cause us to send a message to
3944 // update WebContentsImpl.
3945 render_view_->webview()->zoomLimitsChanged(
3946 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3947 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3949 // Set zoom level, but don't do it for full-page plugin since they don't use
3950 // the same zoom settings.
3951 HostZoomLevels::iterator host_zoom =
3952 render_view_->host_zoom_levels_.find(GURL(request.url()));
3953 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3954 // Reset the zoom levels for plugins.
3955 render_view_->webview()->setZoomLevel(0);
3956 } else {
3957 // If the zoom level is not found, then do nothing. In-page navigation
3958 // relies on not changing the zoom level in this case.
3959 if (host_zoom != render_view_->host_zoom_levels_.end())
3960 render_view_->webview()->setZoomLevel(host_zoom->second);
3963 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3964 // This zoom level was merely recorded transiently for this load. We can
3965 // erase it now. If at some point we reload this page, the browser will
3966 // send us a new, up-to-date zoom level.
3967 render_view_->host_zoom_levels_.erase(host_zoom);
3970 // Update contents MIME type for main frame.
3971 params.contents_mime_type = ds->response().mimeType().utf8();
3973 params.transition = navigation_state->GetTransitionType();
3974 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3975 // If the main frame does a load, it should not be reported as a subframe
3976 // navigation. This can occur in the following case:
3977 // 1. You're on a site with frames.
3978 // 2. You do a subframe navigation. This is stored with transition type
3979 // MANUAL_SUBFRAME.
3980 // 3. You navigate to some non-frame site, say, google.com.
3981 // 4. You navigate back to the page from step 2. Since it was initially
3982 // MANUAL_SUBFRAME, it will be that same transition type here.
3983 // We don't want that, because any navigation that changes the toplevel
3984 // frame should be tracked as a toplevel navigation (this allows us to
3985 // update the URL bar, etc).
3986 params.transition = ui::PAGE_TRANSITION_LINK;
3989 // If the page contained a client redirect (meta refresh, document.loc...),
3990 // set the referrer and transition appropriately.
3991 if (ds->isClientRedirect()) {
3992 params.referrer =
3993 Referrer(params.redirects[0], ds->request().referrerPolicy());
3994 params.transition = ui::PageTransitionFromInt(
3995 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3996 } else {
3997 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3998 frame, ds->request());
4001 base::string16 method = request.httpMethod();
4002 if (EqualsASCII(method, "POST")) {
4003 params.is_post = true;
4004 params.post_id = ExtractPostId(entry);
4007 // Send the user agent override back.
4008 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
4010 // Track the URL of the original request. We use the first entry of the
4011 // redirect chain if it exists because the chain may have started in another
4012 // process.
4013 params.original_request_url = GetOriginalRequestURL(ds);
4015 params.history_list_was_cleared =
4016 navigation_state->request_params().should_clear_history_list;
4018 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
4019 frame->dataSource()->request().inputPerfMetricReportPolicy());
4020 params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD(
4021 frame->dataSource()->request().uiStartTime());
4023 // Save some histogram data so we can compute the average memory used per
4024 // page load of the glyphs.
4025 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4026 blink::WebGlyphCache::pageCount());
4028 // This message needs to be sent before any of allowScripts(),
4029 // allowImages(), allowPlugins() is called for the new page, so that when
4030 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4031 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4032 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4033 } else {
4034 // Subframe navigation: the type depends on whether this navigation
4035 // generated a new session history entry. When they do generate a session
4036 // history entry, it means the user initiated the navigation and we should
4037 // mark it as such.
4038 if (commit_type == blink::WebStandardCommit)
4039 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
4040 else
4041 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
4043 DCHECK(!navigation_state->request_params().should_clear_history_list);
4044 params.history_list_was_cleared = false;
4045 params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT;
4047 // Don't send this message while the subframe is swapped out.
4048 if (!is_swapped_out())
4049 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4052 // If we end up reusing this WebRequest (for example, due to a #ref click),
4053 // we don't want the transition type to persist. Just clear it.
4054 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
4057 void RenderFrameImpl::didStartLoading(bool to_different_document) {
4058 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4059 "id", routing_id_);
4060 render_view_->FrameDidStartLoading(frame_);
4061 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
4064 void RenderFrameImpl::didStopLoading() {
4065 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4066 "id", routing_id_);
4067 render_view_->FrameDidStopLoading(frame_);
4068 Send(new FrameHostMsg_DidStopLoading(routing_id_));
4071 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
4072 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
4075 void RenderFrameImpl::HandleWebAccessibilityEvent(
4076 const blink::WebAXObject& obj, blink::WebAXEvent event) {
4077 if (renderer_accessibility_)
4078 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
4081 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
4082 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FocusedNodeChanged(node));
4085 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) {
4086 if (renderer_accessibility())
4087 renderer_accessibility()->AccessibilityFocusedNodeChanged(node);
4090 // PlzNavigate
4091 void RenderFrameImpl::OnCommitNavigation(
4092 const ResourceResponseHead& response,
4093 const GURL& stream_url,
4094 const CommonNavigationParams& common_params,
4095 const RequestNavigationParams& request_params) {
4096 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4097 switches::kEnableBrowserSideNavigation));
4098 // This will override the url requested by the WebURLLoader, as well as
4099 // provide it with the response to the request.
4100 scoped_ptr<StreamOverrideParameters> stream_override(
4101 new StreamOverrideParameters());
4102 stream_override->stream_url = stream_url;
4103 stream_override->response = response;
4105 NavigateInternal(common_params, StartNavigationParams(), request_params,
4106 stream_override.Pass());
4109 void RenderFrameImpl::OnFailedNavigation(
4110 const CommonNavigationParams& common_params,
4111 const RequestNavigationParams& request_params,
4112 bool has_stale_copy_in_cache,
4113 int error_code) {
4114 bool is_reload = IsReload(common_params.navigation_type);
4115 bool is_history_navigation = request_params.page_state.IsValid();
4116 WebURLRequest::CachePolicy cache_policy =
4117 WebURLRequest::UseProtocolCachePolicy;
4118 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4119 common_params.url, is_history_navigation, request_params, &is_reload,
4120 &cache_policy)) {
4121 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4122 return;
4125 GetContentClient()->SetActiveURL(common_params.url);
4127 pending_navigation_params_.reset(new NavigationParams(
4128 common_params, StartNavigationParams(), request_params));
4130 // Inform the browser of the start of the provisional load. This is needed so
4131 // that the load is properly tracked by the WebNavigation API.
4132 // TODO(clamy): Properly set is_transition_navigation.
4133 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4134 routing_id_, common_params.url, false));
4136 // Send the provisional load failure.
4137 blink::WebURLError error =
4138 CreateWebURLError(common_params.url, has_stale_copy_in_cache, error_code);
4139 WebURLRequest failed_request = CreateURLRequestForNavigation(
4140 common_params, scoped_ptr<StreamOverrideParameters>(),
4141 frame_->isViewSourceModeEnabled());
4142 SendFailedProvisionalLoad(failed_request, error, frame_);
4144 if (!ShouldDisplayErrorPageForFailedLoad(error_code, common_params.url)) {
4145 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4146 return;
4149 // Make sure errors are not shown in view source mode.
4150 frame_->enableViewSourceMode(false);
4152 // Replace the current history entry in reloads, history navigations and loads
4153 // of the same url. This corresponds to Blink's notion of a standard
4154 // commit.
4155 // TODO(clamy): see if initial commits in subframes should be handled
4156 // separately.
4157 bool replace = is_reload || is_history_navigation ||
4158 common_params.url == GetLoadingUrl();
4159 LoadNavigationErrorPage(failed_request, error, replace);
4162 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
4163 RenderFrame* render_frame,
4164 const NavigationPolicyInfo& info) {
4165 #ifdef OS_ANDROID
4166 // The handlenavigation API is deprecated and will be removed once
4167 // crbug.com/325351 is resolved.
4168 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
4169 GetContentClient()->renderer()->HandleNavigation(
4170 render_frame,
4171 static_cast<DocumentState*>(info.extraData),
4172 render_view_->opener_id_,
4173 info.frame,
4174 info.urlRequest,
4175 info.navigationType,
4176 info.defaultPolicy,
4177 info.isRedirect)) {
4178 return blink::WebNavigationPolicyIgnore;
4180 #endif
4182 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
4183 info.urlRequest));
4184 const base::CommandLine& command_line =
4185 *base::CommandLine::ForCurrentProcess();
4187 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe_) {
4188 // There's no reason to ignore navigations on subframes, since the swap out
4189 // logic no longer applies.
4190 } else {
4191 if (is_swapped_out_) {
4192 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
4193 // Targeted links may try to navigate a swapped out frame. Allow the
4194 // browser process to navigate the tab instead. Note that it is also
4195 // possible for non-targeted navigations (from this view) to arrive
4196 // here just after we are swapped out. It's ok to send them to the
4197 // browser, as long as they're for the top level frame.
4198 // TODO(creis): Ensure this supports targeted form submissions when
4199 // fixing http://crbug.com/101395.
4200 if (info.frame->parent() == NULL) {
4201 OpenURL(info.frame, info.urlRequest.url(), referrer,
4202 info.defaultPolicy);
4203 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4206 // We should otherwise ignore in-process iframe navigations, if they
4207 // arrive just after we are swapped out.
4208 return blink::WebNavigationPolicyIgnore;
4211 // Allow kSwappedOutURL to complete.
4212 return info.defaultPolicy;
4216 // Webkit is asking whether to navigate to a new URL.
4217 // This is fine normally, except if we're showing UI from one security
4218 // context and they're trying to navigate to a different context.
4219 const GURL& url = info.urlRequest.url();
4221 // A content initiated navigation may have originated from a link-click,
4222 // script, drag-n-drop operation, etc.
4223 DocumentState* document_state = static_cast<DocumentState*>(info.extraData);
4224 bool is_content_initiated =
4225 document_state->navigation_state()->IsContentInitiated();
4227 // Experimental:
4228 // If --enable-strict-site-isolation is enabled, send all top-level
4229 // navigations to the browser to let it swap processes when crossing site
4230 // boundaries. This is currently expected to break some script calls and
4231 // navigations, such as form submissions.
4232 bool force_swap_due_to_flag =
4233 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
4234 if (force_swap_due_to_flag &&
4235 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
4236 WebString origin_str = info.frame->document().securityOrigin().toString();
4237 GURL frame_url(origin_str.utf8().data());
4238 // TODO(cevans): revisit whether this site check is still necessary once
4239 // crbug.com/101395 is fixed.
4240 bool same_domain_or_host =
4241 net::registry_controlled_domains::SameDomainOrHost(
4242 frame_url,
4243 url,
4244 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
4245 // Only keep same-site (domain + scheme) and data URLs in the same process.
4246 bool is_same_site =
4247 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
4248 url.SchemeIs(url::kDataScheme);
4249 if (!is_same_site) {
4250 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4251 return blink::WebNavigationPolicyIgnore;
4255 // If the browser is interested, then give it a chance to look at the request.
4256 if (is_content_initiated) {
4257 bool is_form_post =
4258 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
4259 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
4260 EqualsASCII(info.urlRequest.httpMethod(), "POST");
4261 bool browser_handles_request =
4262 render_view_->renderer_preferences_
4263 .browser_handles_non_local_top_level_requests
4264 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
4265 is_form_post);
4266 if (!browser_handles_request) {
4267 browser_handles_request = IsTopLevelNavigation(info.frame) &&
4268 render_view_->renderer_preferences_
4269 .browser_handles_all_top_level_requests;
4272 if (browser_handles_request) {
4273 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4274 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4278 // Use the frame's original request's URL rather than the document's URL for
4279 // subsequent checks. For a popup, the document's URL may become the opener
4280 // window's URL if the opener has called document.write().
4281 // See http://crbug.com/93517.
4282 GURL old_url(info.frame->dataSource()->request().url());
4284 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4285 // an extension or app origin, leaving a WebUI page, etc). We only care about
4286 // top-level navigations (not iframes). But we sometimes navigate to
4287 // about:blank to clear a tab, and we want to still allow that.
4289 // Note: this is known to break POST submissions when crossing process
4290 // boundaries until http://crbug.com/101395 is fixed. This is better for
4291 // security than loading a WebUI, extension or app page in the wrong process.
4292 // POST requests don't work because this mechanism does not preserve form
4293 // POST data. We will need to send the request's httpBody data up to the
4294 // browser process, and issue a special POST navigation in WebKit (via
4295 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4296 // for examples of how to send the httpBody data.
4297 if (!info.frame->parent() && is_content_initiated &&
4298 !url.SchemeIs(url::kAboutScheme)) {
4299 bool send_referrer = false;
4301 // All navigations to or from WebUI URLs or within WebUI-enabled
4302 // RenderProcesses must be handled by the browser process so that the
4303 // correct bindings and data sources can be registered.
4304 // Similarly, navigations to view-source URLs or within ViewSource mode
4305 // must be handled by the browser process (except for reloads - those are
4306 // safe to leave within the renderer).
4307 // Lastly, access to file:// URLs from non-file:// URL pages must be
4308 // handled by the browser so that ordinary renderer processes don't get
4309 // blessed with file permissions.
4310 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
4311 bool is_initial_navigation = render_view_->history_list_length_ == 0;
4312 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
4313 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
4314 url.SchemeIs(kViewSourceScheme) ||
4315 (info.frame->isViewSourceModeEnabled() &&
4316 info.navigationType != blink::WebNavigationTypeReload);
4318 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
4319 // Fork non-file to file opens. Check the opener URL if this is the
4320 // initial navigation in a newly opened window.
4321 GURL source_url(old_url);
4322 if (is_initial_navigation && source_url.is_empty() &&
4323 info.frame->opener())
4324 source_url = info.frame->opener()->top()->document().url();
4325 DCHECK(!source_url.is_empty());
4326 should_fork = !source_url.SchemeIs(url::kFileScheme);
4329 if (!should_fork) {
4330 // Give the embedder a chance.
4331 should_fork = GetContentClient()->renderer()->ShouldFork(
4332 info.frame, url, info.urlRequest.httpMethod().utf8(),
4333 is_initial_navigation, info.isRedirect, &send_referrer);
4336 if (should_fork) {
4337 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
4338 info.defaultPolicy);
4339 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4343 // Detect when a page is "forking" a new tab that can be safely rendered in
4344 // its own process. This is done by sites like Gmail that try to open links
4345 // in new windows without script connections back to the original page. We
4346 // treat such cases as browser navigations (in which we will create a new
4347 // renderer for a cross-site navigation), rather than WebKit navigations.
4349 // We use the following heuristic to decide whether to fork a new page in its
4350 // own process:
4351 // The parent page must open a new tab to about:blank, set the new tab's
4352 // window.opener to null, and then redirect the tab to a cross-site URL using
4353 // JavaScript.
4355 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4356 // (see below).
4357 bool is_fork =
4358 // Must start from a tab showing about:blank, which is later redirected.
4359 old_url == GURL(url::kAboutBlankURL) &&
4360 // Must be the first real navigation of the tab.
4361 render_view_->historyBackListCount() < 1 &&
4362 render_view_->historyForwardListCount() < 1 &&
4363 // The parent page must have set the child's window.opener to null before
4364 // redirecting to the desired URL.
4365 info.frame->opener() == NULL &&
4366 // Must be a top-level frame.
4367 info.frame->parent() == NULL &&
4368 // Must not have issued the request from this page.
4369 is_content_initiated &&
4370 // Must be targeted at the current tab.
4371 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
4372 // Must be a JavaScript navigation, which appears as "other".
4373 info.navigationType == blink::WebNavigationTypeOther;
4375 if (is_fork) {
4376 // Open the URL via the browser, not via WebKit.
4377 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
4378 return blink::WebNavigationPolicyIgnore;
4381 // PlzNavigate: send the request to the browser if needed.
4382 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4383 switches::kEnableBrowserSideNavigation) &&
4384 info.urlRequest.checkForBrowserSideNavigation()) {
4385 BeginNavigation(&info.urlRequest);
4386 return blink::WebNavigationPolicyIgnore;
4389 return info.defaultPolicy;
4392 void RenderFrameImpl::OpenURL(WebFrame* frame,
4393 const GURL& url,
4394 const Referrer& referrer,
4395 WebNavigationPolicy policy) {
4396 DCHECK_EQ(frame_, frame);
4398 FrameHostMsg_OpenURL_Params params;
4399 params.url = url;
4400 params.referrer = referrer;
4401 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
4402 WebDataSource* ds = frame->provisionalDataSource();
4403 if (ds) {
4404 DocumentState* document_state = DocumentState::FromDataSource(ds);
4405 NavigationStateImpl* navigation_state =
4406 static_cast<NavigationStateImpl*>(document_state->navigation_state());
4407 if (navigation_state->IsContentInitiated()) {
4408 params.should_replace_current_entry =
4409 ds->replacesCurrentHistoryItem() &&
4410 render_view_->history_list_length_;
4411 } else {
4412 // This is necessary to preserve the should_replace_current_entry value on
4413 // cross-process redirects, in the event it was set by a previous process.
4415 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4416 // NavigationState::should_replace_current_entry().
4417 params.should_replace_current_entry =
4418 navigation_state->start_params().should_replace_current_entry;
4420 } else {
4421 params.should_replace_current_entry = false;
4423 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
4424 if (GetContentClient()->renderer()->AllowPopup())
4425 params.user_gesture = true;
4427 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
4428 policy == blink::WebNavigationPolicyNewForegroundTab ||
4429 policy == blink::WebNavigationPolicyNewWindow ||
4430 policy == blink::WebNavigationPolicyNewPopup) {
4431 WebUserGestureIndicator::consumeUserGesture();
4434 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4437 void RenderFrameImpl::NavigateInternal(
4438 const CommonNavigationParams& common_params,
4439 const StartNavigationParams& start_params,
4440 const RequestNavigationParams& request_params,
4441 scoped_ptr<StreamOverrideParameters> stream_params) {
4442 bool browser_side_navigation =
4443 base::CommandLine::ForCurrentProcess()->HasSwitch(
4444 switches::kEnableBrowserSideNavigation);
4445 bool is_reload = IsReload(common_params.navigation_type);
4446 bool is_history_navigation = request_params.page_state.IsValid();
4447 WebURLRequest::CachePolicy cache_policy =
4448 WebURLRequest::UseProtocolCachePolicy;
4449 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4450 common_params.url, is_history_navigation, request_params, &is_reload,
4451 &cache_policy)) {
4452 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4453 return;
4456 GetContentClient()->SetActiveURL(common_params.url);
4458 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
4459 // We cannot reload if we do not have any history state. This happens, for
4460 // example, when recovering from a crash.
4461 is_reload = false;
4462 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4465 pending_navigation_params_.reset(
4466 new NavigationParams(common_params, start_params, request_params));
4468 // If we are reloading, then Blink will use the history state of the current
4469 // page, so we should just ignore any given history state. Otherwise, if we
4470 // have history state, then we need to navigate to it, which corresponds to a
4471 // back/forward navigation event.
4472 if (is_reload && !browser_side_navigation) {
4473 // TODO(clamy): adapt this code for PlzNavigate. In particular the stream
4474 // override should be given to the generated request.
4475 bool reload_original_url =
4476 (common_params.navigation_type ==
4477 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
4478 bool ignore_cache = (common_params.navigation_type ==
4479 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
4481 if (reload_original_url)
4482 frame_->reloadWithOverrideURL(common_params.url, true);
4483 else
4484 frame_->reload(ignore_cache);
4485 } else if (is_history_navigation && !browser_side_navigation) {
4486 // TODO(clamy): adapt this code for PlzNavigate. In particular the stream
4487 // override should be given to the generated request.
4489 // We must know the page ID of the page we are navigating back to.
4490 DCHECK_NE(request_params.page_id, -1);
4491 // We must know the nav entry ID of the page we are navigating back to,
4492 // which should be the case because history navigations are routed via the
4493 // browser.
4494 DCHECK_NE(0, request_params.nav_entry_id);
4495 scoped_ptr<HistoryEntry> entry =
4496 PageStateToHistoryEntry(request_params.page_state);
4497 if (entry) {
4498 // Ensure we didn't save the swapped out URL in UpdateState, since the
4499 // browser should never be telling us to navigate to swappedout://.
4500 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
4501 scoped_ptr<NavigationParams> navigation_params(
4502 new NavigationParams(*pending_navigation_params_.get()));
4503 render_view_->history_controller()->GoToEntry(
4504 entry.Pass(), navigation_params.Pass(), cache_policy);
4506 } else if (!common_params.base_url_for_data_url.is_empty() ||
4507 (browser_side_navigation &&
4508 common_params.url.SchemeIs(url::kDataScheme))) {
4509 LoadDataURL(common_params, frame_);
4510 } else {
4511 // Navigate to the given URL.
4512 WebURLRequest request = CreateURLRequestForNavigation(
4513 common_params, stream_params.Pass(), frame_->isViewSourceModeEnabled());
4515 if (!start_params.extra_headers.empty() && !browser_side_navigation) {
4516 for (net::HttpUtil::HeadersIterator i(start_params.extra_headers.begin(),
4517 start_params.extra_headers.end(),
4518 "\n");
4519 i.GetNext();) {
4520 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
4521 WebString::fromUTF8(i.values()));
4525 if (start_params.is_post && !browser_side_navigation) {
4526 request.setHTTPMethod(WebString::fromUTF8("POST"));
4528 // Set post data.
4529 WebHTTPBody http_body;
4530 http_body.initialize();
4531 const char* data = nullptr;
4532 if (start_params.browser_initiated_post_data.size()) {
4533 data = reinterpret_cast<const char*>(
4534 &start_params.browser_initiated_post_data.front());
4536 http_body.appendData(
4537 WebData(data, start_params.browser_initiated_post_data.size()));
4538 request.setHTTPBody(http_body);
4541 // A session history navigation should have been accompanied by state.
4542 CHECK_EQ(request_params.page_id, -1);
4544 // PlzNavigate: Make sure that Blink's loader will not try to use browser
4545 // side navigation for this request (since it already went to the browser).
4546 if (browser_side_navigation)
4547 request.setCheckForBrowserSideNavigation(false);
4549 // Record this before starting the load. We need a lower bound of this time
4550 // to sanitize the navigationStart override set below.
4551 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
4552 frame_->loadRequest(request);
4554 UpdateFrameNavigationTiming(frame_, request_params.browser_navigation_start,
4555 renderer_navigation_start);
4558 // In case LoadRequest failed before didCreateDataSource was called.
4559 pending_navigation_params_.reset();
4562 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4563 const std::string& encoding_name) {
4564 // Only update main frame's encoding_name.
4565 if (!frame->parent())
4566 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4569 void RenderFrameImpl::SyncSelectionIfRequired() {
4570 base::string16 text;
4571 size_t offset;
4572 gfx::Range range;
4573 #if defined(ENABLE_PLUGINS)
4574 if (render_view_->focused_pepper_plugin_) {
4575 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4576 offset = 0; // Pepper API does not support offset reporting.
4577 // TODO(kinaba): cut as needed.
4578 } else
4579 #endif
4581 size_t location, length;
4582 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4583 &location, &length)) {
4584 return;
4587 range = gfx::Range(location, location + length);
4589 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4590 blink::WebTextInputTypeNone) {
4591 // If current focused element is editable, we will send 100 more chars
4592 // before and after selection. It is for input method surrounding text
4593 // feature.
4594 if (location > kExtraCharsBeforeAndAfterSelection)
4595 offset = location - kExtraCharsBeforeAndAfterSelection;
4596 else
4597 offset = 0;
4598 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4599 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4600 if (!webrange.isNull())
4601 text = webrange.toPlainText();
4602 } else {
4603 offset = location;
4604 text = frame_->selectionAsText();
4605 // http://crbug.com/101435
4606 // In some case, frame->selectionAsText() returned text's length is not
4607 // equal to the length returned from webwidget()->caretOrSelectionRange().
4608 // So we have to set the range according to text.length().
4609 range.set_end(range.start() + text.length());
4613 // Sometimes we get repeated didChangeSelection calls from webkit when
4614 // the selection hasn't actually changed. We don't want to report these
4615 // because it will cause us to continually claim the X clipboard.
4616 if (selection_text_offset_ != offset ||
4617 selection_range_ != range ||
4618 selection_text_ != text) {
4619 selection_text_ = text;
4620 selection_text_offset_ = offset;
4621 selection_range_ = range;
4622 SetSelectedText(text, offset, range);
4624 GetRenderWidget()->UpdateSelectionBounds();
4627 void RenderFrameImpl::InitializeUserMediaClient() {
4628 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4629 return;
4631 #if defined(OS_ANDROID)
4632 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4633 switches::kDisableWebRTC))
4634 return;
4635 #endif
4637 #if defined(ENABLE_WEBRTC)
4638 DCHECK(!web_user_media_client_);
4639 web_user_media_client_ = new UserMediaClientImpl(
4640 this,
4641 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4642 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4643 #endif
4646 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4647 const blink::WebURL& url,
4648 WebMediaPlayerClient* client) {
4649 #if defined(ENABLE_WEBRTC)
4650 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4651 bool found_neon =
4652 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4653 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4654 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4655 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4656 new RenderMediaLog(),
4657 CreateRendererFactory());
4658 #else
4659 return NULL;
4660 #endif // defined(ENABLE_WEBRTC)
4663 scoped_ptr<MediaStreamRendererFactory>
4664 RenderFrameImpl::CreateRendererFactory() {
4665 #if defined(ENABLE_WEBRTC)
4666 return scoped_ptr<MediaStreamRendererFactory>(
4667 new MediaStreamRendererFactory());
4668 #else
4669 return scoped_ptr<MediaStreamRendererFactory>(
4670 static_cast<MediaStreamRendererFactory*>(NULL));
4671 #endif
4674 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4675 const GURL& url,
4676 bool is_history_navigation,
4677 const RequestNavigationParams& request_params,
4678 bool* is_reload,
4679 WebURLRequest::CachePolicy* cache_policy) {
4680 MaybeHandleDebugURL(url);
4681 if (!render_view_->webview())
4682 return false;
4684 FOR_EACH_OBSERVER(
4685 RenderViewObserver, render_view_->observers_, Navigate(url));
4687 // If this is a stale back/forward (due to a recent navigation the browser
4688 // didn't know about), ignore it. Only check if swapped in because if the
4689 // frame is swapped out, it won't commit before asking the browser.
4690 if (!render_view_->is_swapped_out() && is_history_navigation &&
4691 render_view_->history_list_offset_ !=
4692 request_params.current_history_list_offset) {
4693 return false;
4696 render_view_->history_list_offset_ =
4697 request_params.current_history_list_offset;
4698 render_view_->history_list_length_ =
4699 request_params.current_history_list_length;
4700 if (request_params.should_clear_history_list) {
4701 CHECK_EQ(-1, render_view_->history_list_offset_);
4702 CHECK_EQ(0, render_view_->history_list_length_);
4705 if (!is_swapped_out_ || frame_->parent())
4706 return true;
4708 // This is a swapped out main frame, so swap the renderer back in.
4709 // We marked the view as hidden when swapping the view out, so be sure to
4710 // reset the visibility state before navigating to the new URL.
4711 render_view_->webview()->setVisibilityState(
4712 render_view_->visibilityState(), false);
4714 // If this is an attempt to reload while we are swapped out, we should not
4715 // reload swappedout://, but the previous page, which is stored in
4716 // params.state. Setting is_reload to false will treat this like a back
4717 // navigation to accomplish that.
4718 *is_reload = false;
4719 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4721 // We refresh timezone when a view is swapped in since timezone
4722 // can get out of sync when the system timezone is updated while
4723 // the view is swapped out.
4724 RenderThreadImpl::NotifyTimezoneChange();
4726 render_view_->SetSwappedOut(false);
4727 is_swapped_out_ = false;
4728 return true;
4731 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4732 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4733 switches::kEnableBrowserSideNavigation));
4734 DCHECK(request);
4735 // TODO(clamy): Execute the beforeunload event.
4737 // Note: At this stage, the goal is to apply all the modifications the
4738 // renderer wants to make to the request, and then send it to the browser, so
4739 // that the actual network request can be started. Ideally, all such
4740 // modifications should take place in willSendRequest, and in the
4741 // implementation of willSendRequest for the various InspectorAgents
4742 // (devtools).
4744 // TODO(clamy): Apply devtools override.
4745 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4746 // else in blink.
4747 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4749 // TODO(clamy): Same-document navigations should not be sent back to the
4750 // browser.
4751 // TODO(clamy): Data urls should not be sent back to the browser either.
4752 Send(new FrameHostMsg_DidStartLoading(routing_id_, true));
4753 Send(new FrameHostMsg_BeginNavigation(
4754 routing_id_, MakeCommonNavigationParams(request),
4755 BeginNavigationParams(request->httpMethod().latin1(),
4756 GetWebURLRequestHeaders(*request),
4757 GetLoadFlagsForWebURLRequest(*request),
4758 request->hasUserGesture()),
4759 GetRequestBodyForWebURLRequest(*request)));
4762 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams& params,
4763 WebFrame* frame) {
4764 // A loadData request with a specified base URL.
4765 std::string mime_type, charset, data;
4766 if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) {
4767 const GURL base_url = params.base_url_for_data_url.is_empty() ?
4768 params.url : params.base_url_for_data_url;
4769 frame->loadData(
4770 WebData(data.c_str(), data.length()),
4771 WebString::fromUTF8(mime_type),
4772 WebString::fromUTF8(charset),
4773 base_url,
4774 params.history_url_for_data_url,
4775 false);
4776 } else {
4777 CHECK(false) << "Invalid URL passed: "
4778 << params.url.possibly_invalid_spec();
4782 void RenderFrameImpl::SendFailedProvisionalLoad(
4783 const blink::WebURLRequest& request,
4784 const blink::WebURLError& error,
4785 blink::WebLocalFrame* frame) {
4786 bool show_repost_interstitial = (error.reason == net::ERR_CACHE_MISS &&
4787 EqualsASCII(request.httpMethod(), "POST"));
4789 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
4790 params.error_code = error.reason;
4791 GetContentClient()->renderer()->GetNavigationErrorStrings(
4792 render_view_.get(), frame, request, error, NULL,
4793 &params.error_description);
4794 params.url = error.unreachableURL;
4795 params.showing_repost_interstitial = show_repost_interstitial;
4796 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_, params));
4799 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4800 int error_code,
4801 const GURL& unreachable_url) {
4802 // Don't display an error page if this is simply a cancelled load. Aside
4803 // from being dumb, Blink doesn't expect it and it will cause a crash.
4804 if (error_code == net::ERR_ABORTED)
4805 return false;
4807 // Don't display "client blocked" error page if browser has asked us not to.
4808 if (error_code == net::ERR_BLOCKED_BY_CLIENT &&
4809 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
4810 return false;
4813 // Allow the embedder to suppress an error page.
4814 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4815 this, unreachable_url)) {
4816 return false;
4819 if (RenderThreadImpl::current() &&
4820 RenderThreadImpl::current()->layout_test_mode()) {
4821 return false;
4824 return true;
4827 GURL RenderFrameImpl::GetLoadingUrl() const {
4828 WebDataSource* ds = frame_->dataSource();
4829 if (ds->hasUnreachableURL())
4830 return ds->unreachableURL();
4832 const WebURLRequest& request = ds->request();
4833 return request.url();
4836 void RenderFrameImpl::PopulateDocumentStateFromPending(
4837 DocumentState* document_state) {
4838 document_state->set_request_time(
4839 pending_navigation_params_->request_params.request_time);
4841 InternalDocumentStateData* internal_data =
4842 InternalDocumentStateData::FromDocumentState(document_state);
4844 if (!pending_navigation_params_->common_params.url.SchemeIs(
4845 url::kJavaScriptScheme) &&
4846 pending_navigation_params_->common_params.navigation_type ==
4847 FrameMsg_Navigate_Type::RESTORE) {
4848 // We're doing a load of a page that was restored from the last session. By
4849 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4850 // can result in stale data for pages that are set to expire. We explicitly
4851 // override that by setting the policy here so that as necessary we load
4852 // from the network.
4854 // TODO(davidben): Remove this in favor of passing a cache policy to the
4855 // loadHistoryItem call in OnNavigate. That requires not overloading
4856 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4857 // policy based on load type, etc".
4858 internal_data->set_cache_policy_override(
4859 WebURLRequest::UseProtocolCachePolicy);
4862 if (IsReload(pending_navigation_params_->common_params.navigation_type))
4863 document_state->set_load_type(DocumentState::RELOAD);
4864 else if (pending_navigation_params_->request_params.page_state.IsValid())
4865 document_state->set_load_type(DocumentState::HISTORY_LOAD);
4866 else
4867 document_state->set_load_type(DocumentState::NORMAL_LOAD);
4869 internal_data->set_is_overriding_user_agent(
4870 pending_navigation_params_->request_params.is_overriding_user_agent);
4871 internal_data->set_must_reset_scroll_and_scale_state(
4872 pending_navigation_params_->common_params.navigation_type ==
4873 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
4874 document_state->set_can_load_local_resources(
4875 pending_navigation_params_->request_params.can_load_local_resources);
4878 NavigationState* RenderFrameImpl::CreateNavigationStateFromPending() {
4879 // A navigation resulting from loading a javascript URL should not be treated
4880 // as a browser initiated event. Instead, we want it to look as if the page
4881 // initiated any load resulting from JS execution.
4882 if (!pending_navigation_params_->common_params.url.SchemeIs(
4883 url::kJavaScriptScheme)) {
4884 return NavigationStateImpl::CreateBrowserInitiated(
4885 pending_navigation_params_->common_params,
4886 pending_navigation_params_->start_params,
4887 pending_navigation_params_->request_params);
4889 return NavigationStateImpl::CreateContentInitiated();
4892 #if defined(OS_ANDROID)
4894 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4895 const blink::WebURL& url,
4896 WebMediaPlayerClient* client,
4897 media::MediaPermission* media_permission,
4898 blink::WebContentDecryptionModule* initial_cdm) {
4899 GpuChannelHost* gpu_channel_host =
4900 RenderThreadImpl::current()->EstablishGpuChannelSync(
4901 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4902 if (!gpu_channel_host) {
4903 LOG(ERROR) << "Failed to establish GPU channel for media player";
4904 return NULL;
4907 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4908 if (SynchronousCompositorFactory* factory =
4909 SynchronousCompositorFactory::GetInstance()) {
4910 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4911 } else {
4912 scoped_refptr<cc_blink::ContextProviderWebContext> context_provider =
4913 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4915 if (!context_provider.get()) {
4916 LOG(ERROR) << "Failed to get context3d for media player";
4917 return NULL;
4920 stream_texture_factory = StreamTextureFactoryImpl::Create(
4921 context_provider, gpu_channel_host, routing_id_);
4924 return new WebMediaPlayerAndroid(
4925 frame_, client, weak_factory_.GetWeakPtr(), GetMediaPlayerManager(),
4926 GetCdmFactory(), media_permission, initial_cdm, stream_texture_factory,
4927 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4928 new RenderMediaLog());
4931 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4932 if (!media_player_manager_)
4933 media_player_manager_ = new RendererMediaPlayerManager(this);
4934 return media_player_manager_;
4937 #endif // defined(OS_ANDROID)
4939 media::MediaPermission* RenderFrameImpl::GetMediaPermission() {
4940 if (!media_permission_dispatcher_)
4941 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
4942 return media_permission_dispatcher_;
4945 bool RenderFrameImpl::AreSecureCodecsSupported() {
4946 #if defined(OS_ANDROID)
4947 // Hardware-secure codecs are only supported if secure surfaces are enabled.
4948 return render_view_->renderer_preferences_
4949 .use_video_overlay_for_embedded_encrypted_video;
4950 #else
4951 return false;
4952 #endif // defined(OS_ANDROID)
4955 media::CdmFactory* RenderFrameImpl::GetCdmFactory() {
4956 #if defined(ENABLE_BROWSER_CDMS)
4957 if (!cdm_manager_)
4958 cdm_manager_ = new RendererCdmManager(this);
4959 #endif // defined(ENABLE_BROWSER_CDMS)
4961 if (!cdm_factory_) {
4962 DCHECK(frame_);
4963 cdm_factory_ = new RenderCdmFactory(
4964 #if defined(ENABLE_PEPPER_CDMS)
4965 base::Bind(&PepperCdmWrapperImpl::Create, frame_),
4966 #elif defined(ENABLE_BROWSER_CDMS)
4967 cdm_manager_,
4968 #endif
4969 this);
4972 return cdm_factory_;
4975 } // namespace content