third_party/re2: Remove remove-static-initializers.patch.
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blob1e7ead77c322959ec7507d72fa9a3ff93b87fd8b
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/navigation_state.h"
58 #include "content/public/renderer/render_frame_observer.h"
59 #include "content/public/renderer/renderer_ppapi_host.h"
60 #include "content/renderer/accessibility/renderer_accessibility.h"
61 #include "content/renderer/browser_plugin/browser_plugin.h"
62 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
63 #include "content/renderer/child_frame_compositing_helper.h"
64 #include "content/renderer/context_menu_params_builder.h"
65 #include "content/renderer/devtools/devtools_agent.h"
66 #include "content/renderer/dom_automation_controller.h"
67 #include "content/renderer/dom_utils.h"
68 #include "content/renderer/external_popup_menu.h"
69 #include "content/renderer/geolocation_dispatcher.h"
70 #include "content/renderer/gpu/gpu_benchmarking_extension.h"
71 #include "content/renderer/history_controller.h"
72 #include "content/renderer/history_serialization.h"
73 #include "content/renderer/image_loading_helper.h"
74 #include "content/renderer/ime_event_guard.h"
75 #include "content/renderer/internal_document_state_data.h"
76 #include "content/renderer/manifest/manifest_manager.h"
77 #include "content/renderer/media/audio_renderer_mixer_manager.h"
78 #include "content/renderer/media/crypto/render_cdm_factory.h"
79 #include "content/renderer/media/media_permission_dispatcher.h"
80 #include "content/renderer/media/media_stream_dispatcher.h"
81 #include "content/renderer/media/media_stream_renderer_factory.h"
82 #include "content/renderer/media/midi_dispatcher.h"
83 #include "content/renderer/media/render_media_log.h"
84 #include "content/renderer/media/user_media_client_impl.h"
85 #include "content/renderer/media/webmediaplayer_ms.h"
86 #include "content/renderer/memory_benchmarking_extension.h"
87 #include "content/renderer/mojo/service_registry_js_wrapper.h"
88 #include "content/renderer/navigation_state_impl.h"
89 #include "content/renderer/notification_permission_dispatcher.h"
90 #include "content/renderer/npapi/plugin_channel_host.h"
91 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
92 #include "content/renderer/presentation/presentation_dispatcher.h"
93 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
94 #include "content/renderer/render_frame_proxy.h"
95 #include "content/renderer/render_process.h"
96 #include "content/renderer/render_thread_impl.h"
97 #include "content/renderer/render_view_impl.h"
98 #include "content/renderer/render_widget_fullscreen_pepper.h"
99 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
100 #include "content/renderer/renderer_webcolorchooser_impl.h"
101 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
102 #include "content/renderer/shared_worker_repository.h"
103 #include "content/renderer/skia_benchmarking_extension.h"
104 #include "content/renderer/stats_collection_controller.h"
105 #include "content/renderer/web_ui_extension.h"
106 #include "content/renderer/websharedworker_proxy.h"
107 #include "gin/modules/module_registry.h"
108 #include "media/base/audio_renderer_mixer_input.h"
109 #include "media/base/media_log.h"
110 #include "media/blink/webencryptedmediaclient_impl.h"
111 #include "media/blink/webmediaplayer_impl.h"
112 #include "media/blink/webmediaplayer_params.h"
113 #include "media/renderers/gpu_video_accelerator_factories.h"
114 #include "net/base/data_url.h"
115 #include "net/base/net_errors.h"
116 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
117 #include "net/http/http_util.h"
118 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
119 #include "third_party/WebKit/public/platform/WebString.h"
120 #include "third_party/WebKit/public/platform/WebURL.h"
121 #include "third_party/WebKit/public/platform/WebURLError.h"
122 #include "third_party/WebKit/public/platform/WebURLResponse.h"
123 #include "third_party/WebKit/public/platform/WebVector.h"
124 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
125 #include "third_party/WebKit/public/web/WebDocument.h"
126 #include "third_party/WebKit/public/web/WebFrameWidget.h"
127 #include "third_party/WebKit/public/web/WebGlyphCache.h"
128 #include "third_party/WebKit/public/web/WebKit.h"
129 #include "third_party/WebKit/public/web/WebLocalFrame.h"
130 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
131 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
132 #include "third_party/WebKit/public/web/WebPlugin.h"
133 #include "third_party/WebKit/public/web/WebPluginParams.h"
134 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
135 #include "third_party/WebKit/public/web/WebRange.h"
136 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
137 #include "third_party/WebKit/public/web/WebScriptSource.h"
138 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
139 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
140 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
141 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
142 #include "third_party/WebKit/public/web/WebSettings.h"
143 #include "third_party/WebKit/public/web/WebSurroundingText.h"
144 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
145 #include "third_party/WebKit/public/web/WebView.h"
146 #include "third_party/mojo/src/mojo/edk/js/core.h"
147 #include "third_party/mojo/src/mojo/edk/js/support.h"
149 #if defined(ENABLE_PLUGINS)
150 #include "content/renderer/npapi/webplugin_impl.h"
151 #include "content/renderer/pepper/pepper_browser_connection.h"
152 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
153 #include "content/renderer/pepper/pepper_webplugin_impl.h"
154 #include "content/renderer/pepper/plugin_module.h"
155 #endif
157 #if defined(ENABLE_WEBRTC)
158 #include "content/renderer/media/rtc_peer_connection_handler.h"
159 #endif
161 #if defined(OS_ANDROID)
162 #include <cpu-features.h>
164 #include "content/common/gpu/client/context_provider_command_buffer.h"
165 #include "content/renderer/android/synchronous_compositor_factory.h"
166 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
167 #include "content/renderer/media/android/renderer_media_player_manager.h"
168 #include "content/renderer/media/android/stream_texture_factory_impl.h"
169 #include "content/renderer/media/android/webmediaplayer_android.h"
170 #else
171 #include "cc/blink/context_provider_web_context.h"
172 #endif
174 #if defined(ENABLE_PEPPER_CDMS)
175 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
176 #elif defined(ENABLE_BROWSER_CDMS)
177 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
178 #endif
180 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
181 #include "content/renderer/media/media_renderer_service_provider.h"
182 #include "media/mojo/services/mojo_renderer_factory.h"
183 #else
184 #include "media/renderers/default_renderer_factory.h"
185 #endif
187 using blink::WebContextMenuData;
188 using blink::WebData;
189 using blink::WebDataSource;
190 using blink::WebDocument;
191 using blink::WebDOMEvent;
192 using blink::WebDOMMessageEvent;
193 using blink::WebElement;
194 using blink::WebExternalPopupMenu;
195 using blink::WebExternalPopupMenuClient;
196 using blink::WebFrame;
197 using blink::WebHistoryItem;
198 using blink::WebHTTPBody;
199 using blink::WebLocalFrame;
200 using blink::WebMediaPlayer;
201 using blink::WebMediaPlayerClient;
202 using blink::WebNavigationPolicy;
203 using blink::WebNavigationType;
204 using blink::WebNode;
205 using blink::WebPluginParams;
206 using blink::WebPopupMenuInfo;
207 using blink::WebRange;
208 using blink::WebReferrerPolicy;
209 using blink::WebScriptSource;
210 using blink::WebSearchableFormData;
211 using blink::WebSecurityOrigin;
212 using blink::WebSecurityPolicy;
213 using blink::WebSerializedScriptValue;
214 using blink::WebServiceWorkerProvider;
215 using blink::WebStorageQuotaCallbacks;
216 using blink::WebString;
217 using blink::WebURL;
218 using blink::WebURLError;
219 using blink::WebURLRequest;
220 using blink::WebURLResponse;
221 using blink::WebUserGestureIndicator;
222 using blink::WebVector;
223 using blink::WebView;
224 using base::Time;
225 using base::TimeDelta;
227 namespace content {
229 namespace {
231 const char kDefaultAcceptHeader[] =
232 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
233 "*;q=0.8";
234 const char kAcceptHeader[] = "Accept";
236 const size_t kExtraCharsBeforeAndAfterSelection = 100;
238 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
239 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
240 LAZY_INSTANCE_INITIALIZER;
242 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
243 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
245 int64 ExtractPostId(HistoryEntry* entry) {
246 if (!entry)
247 return -1;
249 const WebHistoryItem& item = entry->root();
250 if (item.isNull() || item.httpBody().isNull())
251 return -1;
253 return item.httpBody().identifier();
256 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
257 const WebURLResponse& response) {
258 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
261 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
262 // Replace any occurrences of swappedout:// with about:blank.
263 const WebURL& blank_url = GURL(url::kAboutBlankURL);
264 WebVector<WebURL> urls;
265 ds->redirectChain(urls);
266 result->reserve(urls.size());
267 for (size_t i = 0; i < urls.size(); ++i) {
268 if (urls[i] != GURL(kSwappedOutURL))
269 result->push_back(urls[i]);
270 else
271 result->push_back(blank_url);
275 // Returns the original request url. If there is no redirect, the original
276 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
277 // frame was loaded by loadData, the original url will be ds->unreachableURL()
278 GURL GetOriginalRequestURL(WebDataSource* ds) {
279 // WebDataSource has unreachable URL means that the frame is loaded through
280 // blink::WebFrame::loadData(), and the base URL will be in the redirect
281 // chain. However, we never visited the baseURL. So in this case, we should
282 // use the unreachable URL as the original URL.
283 if (ds->hasUnreachableURL())
284 return ds->unreachableURL();
286 std::vector<GURL> redirects;
287 GetRedirectChain(ds, &redirects);
288 if (!redirects.empty())
289 return redirects.at(0);
291 return ds->originalRequest().url();
294 NOINLINE void CrashIntentionally() {
295 // NOTE(shess): Crash directly rather than using NOTREACHED() so
296 // that the signature is easier to triage in crash reports.
297 volatile int* zero = NULL;
298 *zero = 0;
301 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
302 NOINLINE void MaybeTriggerAsanError(const GURL& url) {
303 // NOTE(rogerm): We intentionally perform an invalid heap access here in
304 // order to trigger an Address Sanitizer (ASAN) error report.
305 const char kCrashDomain[] = "crash";
306 const char kHeapOverflow[] = "/heap-overflow";
307 const char kHeapUnderflow[] = "/heap-underflow";
308 const char kUseAfterFree[] = "/use-after-free";
309 #if defined(SYZYASAN)
310 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
311 const char kCorruptHeap[] = "/corrupt-heap";
312 #endif
314 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
315 return;
317 if (!url.has_path())
318 return;
320 std::string crash_type(url.path());
321 if (crash_type == kHeapOverflow) {
322 base::debug::AsanHeapOverflow();
323 } else if (crash_type == kHeapUnderflow ) {
324 base::debug::AsanHeapUnderflow();
325 } else if (crash_type == kUseAfterFree) {
326 base::debug::AsanHeapUseAfterFree();
327 #if defined(SYZYASAN)
328 } else if (crash_type == kCorruptHeapBlock) {
329 base::debug::AsanCorruptHeapBlock();
330 } else if (crash_type == kCorruptHeap) {
331 base::debug::AsanCorruptHeap();
332 #endif
335 #endif // ADDRESS_SANITIZER || SYZYASAN
337 void MaybeHandleDebugURL(const GURL& url) {
338 if (!url.SchemeIs(kChromeUIScheme))
339 return;
340 if (url == GURL(kChromeUICrashURL)) {
341 CrashIntentionally();
342 } else if (url == GURL(kChromeUIDumpURL)) {
343 // This URL will only correctly create a crash dump file if content is
344 // hosted in a process that has correctly called
345 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
346 // of base::debug::DumpWithoutCrashing for more details.
347 base::debug::DumpWithoutCrashing();
348 } else if (url == GURL(kChromeUIKillURL)) {
349 base::Process::Current().Terminate(1, false);
350 } else if (url == GURL(kChromeUIHangURL)) {
351 for (;;) {
352 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
354 } else if (url == GURL(kChromeUIShorthangURL)) {
355 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
358 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
359 MaybeTriggerAsanError(url);
360 #endif // ADDRESS_SANITIZER || SYZYASAN
363 // Returns false unless this is a top-level navigation.
364 bool IsTopLevelNavigation(WebFrame* frame) {
365 return frame->parent() == NULL;
368 // Returns false unless this is a top-level navigation that crosses origins.
369 bool IsNonLocalTopLevelNavigation(const GURL& url,
370 WebFrame* frame,
371 WebNavigationType type,
372 bool is_form_post) {
373 if (!IsTopLevelNavigation(frame))
374 return false;
376 // Navigations initiated within Webkit are not sent out to the external host
377 // in the following cases.
378 // 1. The url scheme is not http/https
379 // 2. The origin of the url and the opener is the same in which case the
380 // opener relationship is maintained.
381 // 3. Reloads/form submits/back forward navigations
382 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
383 return false;
385 if (type != blink::WebNavigationTypeReload &&
386 type != blink::WebNavigationTypeBackForward && !is_form_post) {
387 // The opener relationship between the new window and the parent allows the
388 // new window to script the parent and vice versa. This is not allowed if
389 // the origins of the two domains are different. This can be treated as a
390 // top level navigation and routed back to the host.
391 blink::WebFrame* opener = frame->opener();
392 if (!opener)
393 return true;
395 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
396 return true;
398 return false;
401 WebURLRequest CreateURLRequestForNavigation(
402 const CommonNavigationParams& common_params,
403 scoped_ptr<StreamOverrideParameters> stream_override,
404 bool is_view_source_mode_enabled) {
405 WebURLRequest request(common_params.url);
406 if (is_view_source_mode_enabled)
407 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
409 if (common_params.referrer.url.is_valid()) {
410 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
411 common_params.referrer.policy,
412 common_params.url,
413 WebString::fromUTF8(common_params.referrer.url.spec()));
414 if (!web_referrer.isEmpty())
415 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
418 RequestExtraData* extra_data = new RequestExtraData();
419 extra_data->set_stream_override(stream_override.Pass());
420 request.setExtraData(extra_data);
422 // Set the ui timestamp for this navigation. Currently the timestamp here is
423 // only non empty when the navigation was triggered by an Android intent. The
424 // timestamp is converted to a double version supported by blink. It will be
425 // passed back to the browser in the DidCommitProvisionalLoad and the
426 // DocumentLoadComplete IPCs.
427 base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
428 request.setUiStartTime(ui_timestamp.InSecondsF());
429 request.setInputPerfMetricReportPolicy(
430 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
431 common_params.report_type));
432 return request;
435 void UpdateFrameNavigationTiming(WebFrame* frame,
436 base::TimeTicks browser_navigation_start,
437 base::TimeTicks renderer_navigation_start) {
438 // The browser provides the navigation_start time to bootstrap the
439 // Navigation Timing information for the browser-initiated navigations. In
440 // case of cross-process navigations, this carries over the time of
441 // finishing the onbeforeunload handler of the previous page.
442 DCHECK(!browser_navigation_start.is_null());
443 if (frame->provisionalDataSource()) {
444 // |browser_navigation_start| is likely before this process existed, so we
445 // can't use InterProcessTimeTicksConverter. We need at least to ensure
446 // that the browser-side navigation start we set is not later than the one
447 // on the renderer side.
448 base::TimeTicks navigation_start = std::min(
449 browser_navigation_start, renderer_navigation_start);
450 double navigation_start_seconds =
451 (navigation_start - base::TimeTicks()).InSecondsF();
452 frame->provisionalDataSource()->setNavigationStartTime(
453 navigation_start_seconds);
454 // TODO(clamy): We need to provide additional timing values for the
455 // Navigation Timing API to work with browser-side navigations.
459 // PlzNavigate
460 CommonNavigationParams MakeCommonNavigationParams(
461 blink::WebURLRequest* request) {
462 const RequestExtraData kEmptyData;
463 const RequestExtraData* extra_data =
464 static_cast<RequestExtraData*>(request->extraData());
465 if (!extra_data)
466 extra_data = &kEmptyData;
467 Referrer referrer(
468 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
469 request->referrerPolicy());
471 // Set the ui timestamp for this navigation. Currently the timestamp here is
472 // only non empty when the navigation was triggered by an Android intent, or
473 // by the user clicking on a link. The timestamp is converted from a double
474 // version supported by blink. It will be passed back to the renderer in the
475 // CommitNavigation IPC, and then back to the browser again in the
476 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
477 base::TimeTicks ui_timestamp =
478 base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
479 FrameMsg_UILoadMetricsReportType::Value report_type =
480 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
481 request->inputPerfMetricReportPolicy());
482 return CommonNavigationParams(request->url(), referrer,
483 extra_data->transition_type(),
484 FrameMsg_Navigate_Type::NORMAL, true,
485 ui_timestamp, report_type, GURL(), GURL());
488 #if !defined(OS_ANDROID)
489 media::Context3D GetSharedMainThreadContext3D() {
490 cc::ContextProvider* provider =
491 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
492 if (!provider)
493 return media::Context3D();
494 return media::Context3D(provider->ContextGL(), provider->GrContext());
496 #endif
498 bool IsReload(FrameMsg_Navigate_Type::Value navigation_type) {
499 return navigation_type == FrameMsg_Navigate_Type::RELOAD ||
500 navigation_type == FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE ||
501 navigation_type == FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
504 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
505 nullptr;
507 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
508 static_assert( \
509 static_cast<int>(content_name) == static_cast<int>(blink_name), \
510 "enum values must match")
512 // Check that blink::WebSandboxFlags is kept in sync with
513 // content::SandboxFlags.
514 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE,
515 blink::WebSandboxFlags::None);
516 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION,
517 blink::WebSandboxFlags::Navigation);
518 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS,
519 blink::WebSandboxFlags::Plugins);
520 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN,
521 blink::WebSandboxFlags::Origin);
522 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS,
523 blink::WebSandboxFlags::Forms);
524 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS,
525 blink::WebSandboxFlags::Scripts);
526 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION,
527 blink::WebSandboxFlags::TopNavigation);
528 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS,
529 blink::WebSandboxFlags::Popups);
530 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES,
531 blink::WebSandboxFlags::AutomaticFeatures);
532 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK,
533 blink::WebSandboxFlags::PointerLock);
534 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN,
535 blink::WebSandboxFlags::DocumentDomain);
536 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK,
537 blink::WebSandboxFlags::OrientationLock);
538 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL,
539 blink::WebSandboxFlags::All);
541 } // namespace
543 // static
544 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
545 int32 routing_id) {
546 DCHECK(routing_id != MSG_ROUTING_NONE);
548 if (g_create_render_frame_impl)
549 return g_create_render_frame_impl(render_view, routing_id);
550 else
551 return new RenderFrameImpl(render_view, routing_id);
554 // static
555 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
556 RoutingIDFrameMap::iterator iter =
557 g_routing_id_frame_map.Get().find(routing_id);
558 if (iter != g_routing_id_frame_map.Get().end())
559 return iter->second;
560 return NULL;
563 // static
564 void RenderFrameImpl::CreateFrame(
565 int routing_id,
566 int parent_routing_id,
567 int proxy_routing_id,
568 const FrameReplicationState& replicated_state,
569 CompositorDependencies* compositor_deps,
570 const FrameMsg_NewFrame_WidgetParams& widget_params) {
571 // TODO(nasko): For now, this message is only sent for subframes, as the
572 // top level frame is created when the RenderView is created through the
573 // ViewMsg_New IPC.
574 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
576 blink::WebLocalFrame* web_frame;
577 RenderFrameImpl* render_frame;
578 if (proxy_routing_id == MSG_ROUTING_NONE) {
579 RenderFrameProxy* parent_proxy =
580 RenderFrameProxy::FromRoutingID(parent_routing_id);
581 // If the browser is sending a valid parent routing id, it should already
582 // be created and registered.
583 CHECK(parent_proxy);
584 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
586 // Create the RenderFrame and WebLocalFrame, linking the two.
587 render_frame =
588 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
589 web_frame = parent_web_frame->createLocalChild(
590 WebString::fromUTF8(replicated_state.name),
591 ContentToWebSandboxFlags(replicated_state.sandbox_flags), render_frame);
592 } else {
593 RenderFrameProxy* proxy =
594 RenderFrameProxy::FromRoutingID(proxy_routing_id);
595 CHECK(proxy);
596 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
597 web_frame = blink::WebLocalFrame::create(render_frame);
598 render_frame->proxy_routing_id_ = proxy_routing_id;
599 web_frame->initializeToReplaceRemoteFrame(
600 proxy->web_frame(), WebString::fromUTF8(replicated_state.name),
601 ContentToWebSandboxFlags(replicated_state.sandbox_flags));
603 render_frame->SetWebFrame(web_frame);
605 if (widget_params.routing_id != MSG_ROUTING_NONE) {
606 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
607 switches::kSitePerProcess));
608 render_frame->render_widget_ = RenderWidget::CreateForFrame(
609 widget_params.routing_id, widget_params.surface_id,
610 widget_params.hidden, render_frame->render_view_->screen_info(),
611 compositor_deps, web_frame);
612 // TODO(kenrb): Observing shouldn't be necessary when we sort out
613 // WasShown and WasHidden, separating page-level visibility from
614 // frame-level visibility.
615 render_frame->render_widget_->RegisterRenderFrame(render_frame);
618 render_frame->Initialize();
621 // static
622 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
623 return RenderFrameImpl::FromWebFrame(web_frame);
626 // static
627 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
628 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
629 if (iter != g_frame_map.Get().end())
630 return iter->second;
631 return NULL;
634 // static
635 void RenderFrameImpl::InstallCreateHook(
636 CreateRenderFrameImplFunction create_render_frame_impl) {
637 CHECK(!g_create_render_frame_impl);
638 g_create_render_frame_impl = create_render_frame_impl;
641 // static
642 content::SandboxFlags RenderFrameImpl::WebToContentSandboxFlags(
643 blink::WebSandboxFlags flags) {
644 return static_cast<content::SandboxFlags>(flags);
647 // static
648 blink::WebSandboxFlags RenderFrameImpl::ContentToWebSandboxFlags(
649 content::SandboxFlags flags) {
650 return static_cast<blink::WebSandboxFlags>(flags);
653 // RenderFrameImpl ----------------------------------------------------------
654 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
655 : frame_(NULL),
656 is_local_root_(false),
657 render_view_(render_view->AsWeakPtr()),
658 routing_id_(routing_id),
659 is_swapped_out_(false),
660 render_frame_proxy_(NULL),
661 is_detaching_(false),
662 proxy_routing_id_(MSG_ROUTING_NONE),
663 #if defined(ENABLE_PLUGINS)
664 plugin_power_saver_helper_(NULL),
665 #endif
666 cookie_jar_(this),
667 selection_text_offset_(0),
668 selection_range_(gfx::Range::InvalidRange()),
669 handling_select_range_(false),
670 notification_permission_dispatcher_(NULL),
671 web_user_media_client_(NULL),
672 media_permission_dispatcher_(NULL),
673 midi_dispatcher_(NULL),
674 #if defined(OS_ANDROID)
675 media_player_manager_(NULL),
676 #endif
677 #if defined(ENABLE_BROWSER_CDMS)
678 cdm_manager_(NULL),
679 #endif
680 cdm_factory_(NULL),
681 #if defined(VIDEO_HOLE)
682 contains_media_player_(false),
683 #endif
684 devtools_agent_(nullptr),
685 geolocation_dispatcher_(NULL),
686 push_messaging_dispatcher_(NULL),
687 presentation_dispatcher_(NULL),
688 screen_orientation_dispatcher_(NULL),
689 manifest_manager_(NULL),
690 accessibility_mode_(AccessibilityModeOff),
691 renderer_accessibility_(NULL),
692 weak_factory_(this) {
693 std::pair<RoutingIDFrameMap::iterator, bool> result =
694 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
695 CHECK(result.second) << "Inserting a duplicate item.";
697 RenderThread::Get()->AddRoute(routing_id_, this);
699 render_view_->RegisterRenderFrame(this);
701 // Everything below subclasses RenderFrameObserver and is automatically
702 // deleted when the RenderFrame gets deleted.
703 #if defined(OS_ANDROID)
704 new GinJavaBridgeDispatcher(this);
705 #endif
707 #if defined(ENABLE_PLUGINS)
708 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
709 #endif
711 manifest_manager_ = new ManifestManager(this);
714 RenderFrameImpl::~RenderFrameImpl() {
715 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
716 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
718 #if defined(VIDEO_HOLE)
719 if (contains_media_player_)
720 render_view_->UnregisterVideoHoleFrame(this);
721 #endif
723 if (render_frame_proxy_)
724 delete render_frame_proxy_;
726 render_view_->UnregisterRenderFrame(this);
727 g_routing_id_frame_map.Get().erase(routing_id_);
728 RenderThread::Get()->RemoveRoute(routing_id_);
731 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
732 DCHECK(!frame_);
734 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
735 std::make_pair(web_frame, this));
736 CHECK(result.second) << "Inserting a duplicate item.";
738 frame_ = web_frame;
741 void RenderFrameImpl::Initialize() {
742 is_local_root_ = !frame_->parent() || frame_->parent()->isWebRemoteFrame();
744 #if defined(ENABLE_PLUGINS)
745 new PepperBrowserConnection(this);
746 #endif
747 new SharedWorkerRepository(this);
749 if (!frame_->parent())
750 new ImageLoadingHelper(this);
752 if (is_local_root_ && !render_frame_proxy_) {
753 // DevToolsAgent is a RenderFrameObserver, and will destruct itself
754 // when |this| is deleted.
755 devtools_agent_ = new DevToolsAgent(this);
758 // We delay calling this until we have the WebFrame so that any observer or
759 // embedder can call GetWebFrame on any RenderFrame.
760 GetContentClient()->renderer()->RenderFrameCreated(this);
763 RenderWidget* RenderFrameImpl::GetRenderWidget() {
764 return render_view_.get();
767 #if defined(ENABLE_PLUGINS)
768 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
769 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
770 DidCreatePepperPlugin(host));
771 if (host->GetPluginName() == kFlashPluginName) {
772 RenderThread::Get()->RecordAction(
773 base::UserMetricsAction("FrameLoadWithFlash"));
777 void RenderFrameImpl::PepperDidChangeCursor(
778 PepperPluginInstanceImpl* instance,
779 const blink::WebCursorInfo& cursor) {
780 // Update the cursor appearance immediately if the requesting plugin is the
781 // one which receives the last mouse event. Otherwise, the new cursor won't be
782 // picked up until the plugin gets the next input event. That is bad if, e.g.,
783 // the plugin would like to set an invisible cursor when there isn't any user
784 // input for a while.
785 if (instance == render_view_->pepper_last_mouse_event_target())
786 GetRenderWidget()->didChangeCursor(cursor);
789 void RenderFrameImpl::PepperDidReceiveMouseEvent(
790 PepperPluginInstanceImpl* instance) {
791 render_view_->set_pepper_last_mouse_event_target(instance);
794 void RenderFrameImpl::PepperTextInputTypeChanged(
795 PepperPluginInstanceImpl* instance) {
796 if (instance != render_view_->focused_pepper_plugin())
797 return;
799 GetRenderWidget()->UpdateTextInputType();
801 FocusedNodeChangedForAccessibility(WebNode());
804 void RenderFrameImpl::PepperCaretPositionChanged(
805 PepperPluginInstanceImpl* instance) {
806 if (instance != render_view_->focused_pepper_plugin())
807 return;
808 GetRenderWidget()->UpdateSelectionBounds();
811 void RenderFrameImpl::PepperCancelComposition(
812 PepperPluginInstanceImpl* instance) {
813 if (instance != render_view_->focused_pepper_plugin())
814 return;
815 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
816 #if defined(OS_MACOSX) || defined(USE_AURA)
817 GetRenderWidget()->UpdateCompositionInfo(true);
818 #endif
821 void RenderFrameImpl::PepperSelectionChanged(
822 PepperPluginInstanceImpl* instance) {
823 if (instance != render_view_->focused_pepper_plugin())
824 return;
825 SyncSelectionIfRequired();
828 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
829 PepperPluginInstanceImpl* plugin) {
830 GURL active_url;
831 if (render_view_->webview() && render_view_->webview()->mainFrame())
832 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
833 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
834 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
835 plugin, active_url, GetRenderWidget()->screenInfo());
836 widget->show(blink::WebNavigationPolicyIgnore);
837 return widget;
840 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
841 if (!render_view_->focused_pepper_plugin())
842 return false;
843 return render_view_->focused_pepper_plugin()->
844 IsPluginAcceptingCompositionEvents();
847 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
848 base::ProcessId plugin_pid) {
849 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
850 // routing_id_ as a result.
851 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
854 void RenderFrameImpl::SimulateImeSetComposition(
855 const base::string16& text,
856 const std::vector<blink::WebCompositionUnderline>& underlines,
857 int selection_start,
858 int selection_end) {
859 render_view_->OnImeSetComposition(
860 text, underlines, selection_start, selection_end);
863 void RenderFrameImpl::SimulateImeConfirmComposition(
864 const base::string16& text,
865 const gfx::Range& replacement_range) {
866 render_view_->OnImeConfirmComposition(text, replacement_range, false);
869 void RenderFrameImpl::OnImeSetComposition(
870 const base::string16& text,
871 const std::vector<blink::WebCompositionUnderline>& underlines,
872 int selection_start,
873 int selection_end) {
874 // When a PPAPI plugin has focus, we bypass WebKit.
875 if (!IsPepperAcceptingCompositionEvents()) {
876 pepper_composition_text_ = text;
877 } else {
878 // TODO(kinaba) currently all composition events are sent directly to
879 // plugins. Use DOM event mechanism after WebKit is made aware about
880 // plugins that support composition.
881 // The code below mimics the behavior of WebCore::Editor::setComposition.
883 // Empty -> nonempty: composition started.
884 if (pepper_composition_text_.empty() && !text.empty()) {
885 render_view_->focused_pepper_plugin()->HandleCompositionStart(
886 base::string16());
888 // Nonempty -> empty: composition canceled.
889 if (!pepper_composition_text_.empty() && text.empty()) {
890 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
891 base::string16());
893 pepper_composition_text_ = text;
894 // Nonempty: composition is ongoing.
895 if (!pepper_composition_text_.empty()) {
896 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
897 pepper_composition_text_, underlines, selection_start,
898 selection_end);
903 void RenderFrameImpl::OnImeConfirmComposition(
904 const base::string16& text,
905 const gfx::Range& replacement_range,
906 bool keep_selection) {
907 // When a PPAPI plugin has focus, we bypass WebKit.
908 // Here, text.empty() has a special meaning. It means to commit the last
909 // update of composition text (see
910 // RenderWidgetHost::ImeConfirmComposition()).
911 const base::string16& last_text = text.empty() ? pepper_composition_text_
912 : text;
914 // last_text is empty only when both text and pepper_composition_text_ is.
915 // Ignore it.
916 if (last_text.empty())
917 return;
919 if (!IsPepperAcceptingCompositionEvents()) {
920 base::i18n::UTF16CharIterator iterator(&last_text);
921 int32 i = 0;
922 while (iterator.Advance()) {
923 blink::WebKeyboardEvent char_event;
924 char_event.type = blink::WebInputEvent::Char;
925 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
926 char_event.modifiers = 0;
927 char_event.windowsKeyCode = last_text[i];
928 char_event.nativeKeyCode = last_text[i];
930 const int32 char_start = i;
931 for (; i < iterator.array_pos(); ++i) {
932 char_event.text[i - char_start] = last_text[i];
933 char_event.unmodifiedText[i - char_start] = last_text[i];
936 if (GetRenderWidget()->webwidget())
937 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
939 } else {
940 // Mimics the order of events sent by WebKit.
941 // See WebCore::Editor::setComposition() for the corresponding code.
942 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
943 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
945 pepper_composition_text_.clear();
947 #endif // defined(ENABLE_PLUGINS)
949 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
950 if (!web_user_media_client_)
951 InitializeUserMediaClient();
952 return web_user_media_client_ ?
953 web_user_media_client_->media_stream_dispatcher() : NULL;
956 bool RenderFrameImpl::Send(IPC::Message* message) {
957 if (is_detaching_) {
958 delete message;
959 return false;
961 if (is_swapped_out_) {
962 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
963 delete message;
964 return false;
968 return RenderThread::Get()->Send(message);
971 #if defined(OS_MACOSX) || defined(OS_ANDROID)
972 void RenderFrameImpl::DidHideExternalPopupMenu() {
973 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
974 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
975 external_popup_menu_.reset();
977 #endif
979 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
980 // We may get here while detaching, when the WebFrame has been deleted. Do
981 // not process any messages in this state.
982 if (!frame_)
983 return false;
985 // TODO(kenrb): document() should not be null, but as a transitional step
986 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
987 // to this method. This happens for a top-level remote frame, where a
988 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
989 // around and is still able to receive messages.
990 if (!frame_->document().isNull())
991 GetContentClient()->SetActiveURL(frame_->document().url());
993 ObserverListBase<RenderFrameObserver>::Iterator it(&observers_);
994 RenderFrameObserver* observer;
995 while ((observer = it.GetNext()) != NULL) {
996 if (observer->OnMessageReceived(msg))
997 return true;
1000 bool handled = true;
1001 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
1002 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
1003 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
1004 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
1005 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
1006 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
1007 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
1008 OnCustomContextMenuAction)
1009 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
1010 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
1011 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
1012 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
1013 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
1014 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
1015 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
1016 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
1017 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
1018 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
1019 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
1020 OnMoveRangeSelectionExtent)
1021 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
1022 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
1023 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
1024 OnExtendSelectionAndDelete)
1025 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
1026 OnSetCompositionFromExistingText)
1027 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
1028 OnExecuteNoValueEditCommand)
1029 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
1030 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
1031 OnJavaScriptExecuteRequest)
1032 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
1033 OnJavaScriptExecuteRequestForTests)
1034 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
1035 OnVisualStateRequest)
1036 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
1037 OnSetEditableSelectionOffsets)
1038 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
1039 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
1040 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition, OnRevertExitTransition)
1041 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements,
1042 OnHideTransitionElements)
1043 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements,
1044 OnShowTransitionElements)
1045 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
1046 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
1047 OnTextSurroundingSelectionRequest)
1048 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
1049 OnAddStyleSheetByURL)
1050 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
1051 OnSetAccessibilityMode)
1052 IPC_MESSAGE_HANDLER(AccessibilityMsg_SnapshotTree,
1053 OnSnapshotAccessibilityTree)
1054 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
1055 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
1056 IPC_MESSAGE_HANDLER(FrameMsg_DidUpdateSandboxFlags, OnDidUpdateSandboxFlags)
1057 IPC_MESSAGE_HANDLER(FrameMsg_SetTextTrackSettings,
1058 OnTextTrackSettingsChanged)
1059 IPC_MESSAGE_HANDLER(FrameMsg_PostMessageEvent, OnPostMessageEvent)
1060 IPC_MESSAGE_HANDLER(FrameMsg_FailedNavigation, OnFailedNavigation)
1061 #if defined(OS_ANDROID)
1062 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1063 #elif defined(OS_MACOSX)
1064 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1065 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1066 #endif
1067 IPC_END_MESSAGE_MAP()
1069 return handled;
1072 void RenderFrameImpl::OnNavigate(
1073 const CommonNavigationParams& common_params,
1074 const StartNavigationParams& start_params,
1075 const RequestNavigationParams& request_params) {
1076 DCHECK(!base::CommandLine::ForCurrentProcess()->HasSwitch(
1077 switches::kEnableBrowserSideNavigation));
1078 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate", "id", routing_id_,
1079 "url", common_params.url.possibly_invalid_spec());
1081 bool is_reload = IsReload(common_params.navigation_type);
1082 bool is_history_navigation = request_params.page_state.IsValid();
1083 WebURLRequest::CachePolicy cache_policy =
1084 WebURLRequest::UseProtocolCachePolicy;
1085 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1086 common_params.url, is_history_navigation, request_params, &is_reload,
1087 &cache_policy)) {
1088 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
1089 return;
1092 GetContentClient()->SetActiveURL(common_params.url);
1094 WebFrame* frame = frame_;
1095 if (!request_params.frame_to_navigate.empty()) {
1096 // TODO(nasko): Move this lookup to the browser process.
1097 frame = render_view_->webview()->findFrameByName(
1098 WebString::fromUTF8(request_params.frame_to_navigate));
1099 CHECK(frame) << "Invalid frame name passed: "
1100 << request_params.frame_to_navigate;
1103 // If this frame isn't in the same process as its parent, it will naively
1104 // assume that this is the first navigation in the iframe, but this may not
1105 // actually be the case. The PageTransition differentiates between the first
1106 // navigation in a subframe and subsequent navigations, so if this is a
1107 // subsequent navigation, force the frame's state machine forward.
1108 if (ui::PageTransitionCoreTypeIs(common_params.transition,
1109 ui::PAGE_TRANSITION_MANUAL_SUBFRAME)) {
1110 CHECK(frame_->parent());
1111 if (frame_->parent()->isWebRemoteFrame()) {
1112 CHECK_EQ(frame, frame_);
1113 frame_->setCommittedFirstRealLoad();
1117 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
1118 // We cannot reload if we do not have any history state. This happens, for
1119 // example, when recovering from a crash.
1120 is_reload = false;
1121 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
1124 pending_navigation_params_.reset(
1125 new NavigationParams(common_params, start_params, request_params));
1127 // If we are reloading, then WebKit will use the history state of the current
1128 // page, so we should just ignore any given history state. Otherwise, if we
1129 // have history state, then we need to navigate to it, which corresponds to a
1130 // back/forward navigation event.
1131 if (is_reload) {
1132 bool reload_original_url =
1133 (common_params.navigation_type ==
1134 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
1135 bool ignore_cache = (common_params.navigation_type ==
1136 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
1138 if (reload_original_url)
1139 frame->reloadWithOverrideURL(common_params.url, true);
1140 else
1141 frame->reload(ignore_cache);
1142 } else if (is_history_navigation) {
1143 // We must know the page ID of the page we are navigating back to.
1144 DCHECK_NE(request_params.page_id, -1);
1145 scoped_ptr<HistoryEntry> entry =
1146 PageStateToHistoryEntry(request_params.page_state);
1147 if (entry) {
1148 // Ensure we didn't save the swapped out URL in UpdateState, since the
1149 // browser should never be telling us to navigate to swappedout://.
1150 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
1151 scoped_ptr<NavigationParams> navigation_params(
1152 new NavigationParams(*pending_navigation_params_.get()));
1153 render_view_->history_controller()->GoToEntry(
1154 entry.Pass(), navigation_params.Pass(), cache_policy);
1156 } else if (!common_params.base_url_for_data_url.is_empty()) {
1157 LoadDataURL(common_params, frame);
1158 } else {
1159 // Navigate to the given URL.
1160 WebURLRequest request = CreateURLRequestForNavigation(
1161 common_params, scoped_ptr<StreamOverrideParameters>(),
1162 frame->isViewSourceModeEnabled());
1164 if (!start_params.extra_headers.empty()) {
1165 for (net::HttpUtil::HeadersIterator i(start_params.extra_headers.begin(),
1166 start_params.extra_headers.end(),
1167 "\n");
1168 i.GetNext();) {
1169 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
1170 WebString::fromUTF8(i.values()));
1174 if (start_params.is_post) {
1175 request.setHTTPMethod(WebString::fromUTF8("POST"));
1177 // Set post data.
1178 WebHTTPBody http_body;
1179 http_body.initialize();
1180 const char* data = NULL;
1181 if (start_params.browser_initiated_post_data.size()) {
1182 data = reinterpret_cast<const char*>(
1183 &start_params.browser_initiated_post_data.front());
1185 http_body.appendData(
1186 WebData(data, start_params.browser_initiated_post_data.size()));
1187 request.setHTTPBody(http_body);
1190 // A session history navigation should have been accompanied by state.
1191 CHECK_EQ(request_params.page_id, -1);
1193 // Record this before starting the load, we need a lower bound of this time
1194 // to sanitize the navigationStart override set below.
1195 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
1196 frame->loadRequest(request);
1198 UpdateFrameNavigationTiming(frame, request_params.browser_navigation_start,
1199 renderer_navigation_start);
1202 // In case LoadRequest failed before didCreateDataSource was called.
1203 pending_navigation_params_.reset();
1206 void RenderFrameImpl::NavigateToSwappedOutURL() {
1207 // We use loadRequest instead of loadHTMLString because the former commits
1208 // synchronously. Otherwise a new navigation can interrupt the navigation
1209 // to kSwappedOutURL. If that happens to be to the page we had been
1210 // showing, then WebKit will never send a commit and we'll be left spinning.
1211 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1212 // the navigation to swappedout:// is not announced to the browser side.
1213 is_swapped_out_ = true;
1214 GURL swappedOutURL(kSwappedOutURL);
1215 WebURLRequest request(swappedOutURL);
1216 frame_->loadRequest(request);
1219 void RenderFrameImpl::BindServiceRegistry(
1220 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1221 mojo::ServiceProviderPtr exposed_services) {
1222 service_registry_.Bind(services.Pass());
1223 service_registry_.BindRemoteServiceProvider(exposed_services.Pass());
1226 ManifestManager* RenderFrameImpl::manifest_manager() {
1227 return manifest_manager_;
1230 void RenderFrameImpl::SetPendingNavigationParams(
1231 scoped_ptr<NavigationParams> navigation_params) {
1232 pending_navigation_params_ = navigation_params.Pass();
1235 void RenderFrameImpl::OnBeforeUnload() {
1236 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1237 "id", routing_id_);
1238 // TODO(creis): Right now, this is only called on the main frame. Make the
1239 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1240 // it.
1241 CHECK(!frame_->parent());
1243 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1244 bool proceed = frame_->dispatchBeforeUnloadEvent();
1245 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1246 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1247 before_unload_start_time,
1248 before_unload_end_time));
1251 void RenderFrameImpl::OnSwapOut(
1252 int proxy_routing_id,
1253 bool is_loading,
1254 const FrameReplicationState& replicated_frame_state) {
1255 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1256 RenderFrameProxy* proxy = NULL;
1257 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
1258 switches::kSitePerProcess);
1259 bool is_main_frame = !frame_->parent();
1261 // Only run unload if we're not swapped out yet, but send the ack either way.
1262 if (!is_swapped_out_) {
1263 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1264 // a different process. This involves running the unload handler and
1265 // clearing the page. We also allow this process to exit if there are no
1266 // other active RenderFrames in it.
1268 // Send an UpdateState message before we get swapped out.
1269 render_view_->SyncNavigationState();
1271 // If we need a proxy to replace this, create it now so its routing id is
1272 // registered for receiving IPC messages.
1273 if (proxy_routing_id != MSG_ROUTING_NONE) {
1274 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1275 proxy_routing_id);
1278 // Synchronously run the unload handler before sending the ACK.
1279 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1280 // unload on subframes as well.
1281 if (is_main_frame)
1282 frame_->dispatchUnloadEvent();
1284 // Swap out and stop sending any IPC messages that are not ACKs.
1285 if (is_main_frame)
1286 render_view_->SetSwappedOut(true);
1287 is_swapped_out_ = true;
1289 // Set the proxy here, since OnStop() below could cause an onload event
1290 // handler to execute, which could trigger code such as
1291 // willCheckAndDispatchMessageEvent() that needs the proxy.
1292 if (proxy)
1293 set_render_frame_proxy(proxy);
1295 // Now that we're swapped out and filtering IPC messages, stop loading to
1296 // ensure that no other in-progress navigation continues. We do this here
1297 // to avoid sending a DidStopLoading message to the browser process.
1298 // TODO(creis): Should we be stopping all frames here and using
1299 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1300 // frame?
1301 OnStop();
1303 // Transfer settings such as initial drawing parameters to the remote frame,
1304 // if one is created, that will replace this frame.
1305 if (!is_main_frame && proxy)
1306 proxy->web_frame()->initializeFromFrame(frame_);
1308 // Replace the page with a blank dummy URL. The unload handler will not be
1309 // run a second time, thanks to a check in FrameLoader::stopLoading.
1310 // TODO(creis): Need to add a better way to do this that avoids running the
1311 // beforeunload handler. For now, we just run it a second time silently.
1312 if (!is_site_per_process || is_main_frame)
1313 NavigateToSwappedOutURL();
1315 // Let WebKit know that this view is hidden so it can drop resources and
1316 // stop compositing.
1317 // TODO(creis): Support this for subframes as well.
1318 if (is_main_frame) {
1319 render_view_->webview()->setVisibilityState(
1320 blink::WebPageVisibilityStateHidden, false);
1324 // It is now safe to show modal dialogs again.
1325 // TODO(creis): Deal with modal dialogs from subframes.
1326 if (is_main_frame)
1327 render_view_->suppress_dialogs_until_swap_out_ = false;
1329 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1331 // Now that all of the cleanup is complete and the browser side is notified,
1332 // start using the RenderFrameProxy, if one is created.
1333 if (proxy) {
1334 if (!is_main_frame) {
1335 frame_->swap(proxy->web_frame());
1337 if (is_loading)
1338 proxy->OnDidStartLoading();
1340 if (is_site_per_process) {
1341 // TODO(nasko): delete the frame here, since we've replaced it with a
1342 // proxy.
1347 // In --site-per-process, initialize the WebRemoteFrame with the replication
1348 // state passed by the process that is now rendering the frame.
1349 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1350 // in that case we leave the LocalFrame as the main frame visible to Blink
1351 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1352 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1353 // When we do an unconditional swap for all frames, we can remove
1354 // !is_main_frame below.
1355 if (is_site_per_process && proxy && !is_main_frame)
1356 proxy->SetReplicatedState(replicated_frame_state);
1358 // Safe to exit if no one else is using the process.
1359 if (is_main_frame)
1360 render_view_->WasSwappedOut();
1363 void RenderFrameImpl::OnContextMenuClosed(
1364 const CustomContextMenuContext& custom_context) {
1365 if (custom_context.request_id) {
1366 // External request, should be in our map.
1367 ContextMenuClient* client =
1368 pending_context_menus_.Lookup(custom_context.request_id);
1369 if (client) {
1370 client->OnMenuClosed(custom_context.request_id);
1371 pending_context_menus_.Remove(custom_context.request_id);
1373 } else {
1374 if (custom_context.link_followed.is_valid()) {
1375 frame_->sendPings(
1376 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1377 custom_context.link_followed);
1379 // Internal request, forward to WebKit.
1380 context_menu_node_.reset();
1384 void RenderFrameImpl::OnCustomContextMenuAction(
1385 const CustomContextMenuContext& custom_context,
1386 unsigned action) {
1387 if (custom_context.request_id) {
1388 // External context menu request, look in our map.
1389 ContextMenuClient* client =
1390 pending_context_menus_.Lookup(custom_context.request_id);
1391 if (client)
1392 client->OnMenuAction(custom_context.request_id, action);
1393 } else {
1394 // Internal request, forward to WebKit.
1395 render_view_->webview()->performCustomContextMenuAction(action);
1399 void RenderFrameImpl::OnUndo() {
1400 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1403 void RenderFrameImpl::OnRedo() {
1404 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1407 void RenderFrameImpl::OnCut() {
1408 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1409 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1412 void RenderFrameImpl::OnCopy() {
1413 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1414 WebNode current_node = context_menu_node_.isNull() ?
1415 GetFocusedElement() : context_menu_node_;
1416 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1419 void RenderFrameImpl::OnPaste() {
1420 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1421 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1424 void RenderFrameImpl::OnPasteAndMatchStyle() {
1425 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1426 frame_->executeCommand(
1427 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1430 #if defined(OS_MACOSX)
1431 void RenderFrameImpl::OnCopyToFindPboard() {
1432 // Since the find pasteboard supports only plain text, this can be simpler
1433 // than the |OnCopy()| case.
1434 if (frame_->hasSelection()) {
1435 base::string16 selection = frame_->selectionAsText();
1436 RenderThread::Get()->Send(
1437 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1440 #endif
1442 void RenderFrameImpl::OnDelete() {
1443 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1446 void RenderFrameImpl::OnSelectAll() {
1447 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1448 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1451 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1452 const gfx::Point& extent) {
1453 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1454 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1456 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1457 frame_->selectRange(base, extent);
1460 void RenderFrameImpl::OnUnselect() {
1461 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1462 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1465 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1466 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1467 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1468 GetRenderWidget()->routing_id()));
1470 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1471 frame_->moveRangeSelectionExtent(point);
1474 void RenderFrameImpl::OnReplace(const base::string16& text) {
1475 if (!frame_->hasSelection())
1476 frame_->selectWordAroundCaret();
1478 frame_->replaceSelection(text);
1481 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1482 if (!frame_->hasSelection())
1483 return;
1485 frame_->replaceMisspelledRange(text);
1488 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1489 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1492 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1493 const base::string16& jscript,
1494 int id,
1495 bool notify_result) {
1496 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1497 TRACE_EVENT_SCOPE_THREAD);
1499 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1500 v8::Handle<v8::Value> result =
1501 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1503 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1506 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1507 const base::string16& jscript,
1508 int id,
1509 bool notify_result) {
1510 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1511 TRACE_EVENT_SCOPE_THREAD);
1513 // A bunch of tests expect to run code in the context of a user gesture, which
1514 // can grant additional privileges (e.g. the ability to create popups).
1515 blink::WebScopedUserGesture gesture;
1516 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1517 v8::Handle<v8::Value> result =
1518 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1520 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1523 void RenderFrameImpl::HandleJavascriptExecutionResult(
1524 const base::string16& jscript,
1525 int id,
1526 bool notify_result,
1527 v8::Handle<v8::Value> result) {
1528 if (notify_result) {
1529 base::ListValue list;
1530 if (!result.IsEmpty()) {
1531 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1532 v8::Context::Scope context_scope(context);
1533 V8ValueConverterImpl converter;
1534 converter.SetDateAllowed(true);
1535 converter.SetRegExpAllowed(true);
1536 base::Value* result_value = converter.FromV8Value(result, context);
1537 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
1538 } else {
1539 list.Set(0, base::Value::CreateNullValue());
1541 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1545 void RenderFrameImpl::OnVisualStateRequest(uint64 id) {
1546 GetRenderWidget()->QueueMessage(
1547 new FrameHostMsg_VisualStateResponse(routing_id_, id),
1548 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1551 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1552 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1553 if (!GetRenderWidget()->ShouldHandleImeEvent())
1554 return;
1555 ImeEventGuard guard(GetRenderWidget());
1556 frame_->setEditableSelectionOffsets(start, end);
1559 void RenderFrameImpl::OnSetCompositionFromExistingText(
1560 int start, int end,
1561 const std::vector<blink::WebCompositionUnderline>& underlines) {
1562 if (!GetRenderWidget()->ShouldHandleImeEvent())
1563 return;
1564 ImeEventGuard guard(GetRenderWidget());
1565 frame_->setCompositionFromExistingText(start, end, underlines);
1568 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
1569 frame_->executeCommand(WebString::fromUTF8(name), GetFocusedElement());
1572 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1573 if (!GetRenderWidget()->ShouldHandleImeEvent())
1574 return;
1575 ImeEventGuard guard(GetRenderWidget());
1576 frame_->extendSelectionAndDelete(before, after);
1579 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1580 if (accessibility_mode_ == new_mode)
1581 return;
1582 accessibility_mode_ = new_mode;
1583 if (renderer_accessibility_) {
1584 // Note: this isn't called automatically by the destructor because
1585 // there'd be no point in calling it in frame teardown, only if there's
1586 // an accessibility mode change but the frame is persisting.
1587 renderer_accessibility_->DisableAccessibility();
1589 delete renderer_accessibility_;
1590 renderer_accessibility_ = NULL;
1592 if (accessibility_mode_ == AccessibilityModeOff)
1593 return;
1595 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1596 renderer_accessibility_ = new RendererAccessibility(this);
1599 void RenderFrameImpl::OnSnapshotAccessibilityTree(int callback_id) {
1600 ui::AXTreeUpdate response;
1601 RendererAccessibility::SnapshotAccessibilityTree(this, &response);
1602 Send(new AccessibilityHostMsg_SnapshotResponse(
1603 routing_id_, callback_id, response));
1606 void RenderFrameImpl::OnDisownOpener() {
1607 // TODO(creis): We should only see this for main frames for now. To support
1608 // disowning the opener on subframes, we will need to move WebContentsImpl's
1609 // opener_ to FrameTreeNode.
1610 CHECK(!frame_->parent());
1612 if (frame_->opener())
1613 frame_->setOpener(NULL);
1616 void RenderFrameImpl::OnDidUpdateSandboxFlags(SandboxFlags flags) {
1617 frame_->setFrameOwnerSandboxFlags(ContentToWebSandboxFlags(flags));
1620 void RenderFrameImpl::OnTextTrackSettingsChanged(
1621 const FrameMsg_TextTrackSettings_Params& params) {
1622 DCHECK(!frame_->parent());
1623 if (!render_view_->webview())
1624 return;
1625 render_view_->webview()->settings()->setTextTrackBackgroundColor(
1626 WebString::fromUTF8(params.text_track_background_color));
1627 render_view_->webview()->settings()->setTextTrackFontFamily(
1628 WebString::fromUTF8(params.text_track_font_family));
1629 render_view_->webview()->settings()->setTextTrackFontStyle(
1630 WebString::fromUTF8(params.text_track_font_style));
1631 render_view_->webview()->settings()->setTextTrackFontVariant(
1632 WebString::fromUTF8(params.text_track_font_variant));
1633 render_view_->webview()->settings()->setTextTrackTextColor(
1634 WebString::fromUTF8(params.text_track_text_color));
1635 render_view_->webview()->settings()->setTextTrackTextShadow(
1636 WebString::fromUTF8(params.text_track_text_shadow));
1637 render_view_->webview()->settings()->setTextTrackTextSize(
1638 WebString::fromUTF8(params.text_track_text_size));
1641 void RenderFrameImpl::OnPostMessageEvent(
1642 const FrameMsg_PostMessage_Params& params) {
1643 // Find the source frame if it exists.
1644 WebFrame* source_frame = NULL;
1645 if (params.source_view_routing_id != MSG_ROUTING_NONE) {
1646 // Support a legacy postMessage path for specifying a source RenderView;
1647 // this is currently used when sending messages to Android WebView.
1648 // TODO(alexmos): This path can be removed once crbug.com/473258 is fixed.
1649 RenderViewImpl* source_view =
1650 RenderViewImpl::FromRoutingID(params.source_view_routing_id);
1651 if (source_view)
1652 source_frame = source_view->webview()->mainFrame();
1653 } else if (params.source_routing_id != MSG_ROUTING_NONE) {
1654 RenderFrameProxy* source_proxy =
1655 RenderFrameProxy::FromRoutingID(params.source_routing_id);
1656 if (source_proxy) {
1657 // Currently, navigating a top-level frame cross-process does not swap
1658 // the WebLocalFrame for a WebRemoteFrame in the frame tree, and the
1659 // WebRemoteFrame will not have an associated blink::Frame. If this is
1660 // the case for |source_proxy|, use the corresponding (swapped-out)
1661 // WebLocalFrame instead, so that event.source for this message can be
1662 // set and used properly.
1663 if (source_proxy->IsMainFrameDetachedFromTree())
1664 source_frame = source_proxy->render_view()->webview()->mainFrame();
1665 else
1666 source_frame = source_proxy->web_frame();
1670 // If the message contained MessagePorts, create the corresponding endpoints.
1671 blink::WebMessagePortChannelArray channels =
1672 WebMessagePortChannelImpl::CreatePorts(
1673 params.message_ports, params.new_routing_ids,
1674 base::MessageLoopProxy::current().get());
1676 WebSerializedScriptValue serialized_script_value;
1677 if (params.is_data_raw_string) {
1678 v8::HandleScope handle_scope(blink::mainThreadIsolate());
1679 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1680 v8::Context::Scope context_scope(context);
1681 V8ValueConverterImpl converter;
1682 converter.SetDateAllowed(true);
1683 converter.SetRegExpAllowed(true);
1684 scoped_ptr<base::Value> value(new base::StringValue(params.data));
1685 v8::Handle<v8::Value> result_value = converter.ToV8Value(value.get(),
1686 context);
1687 serialized_script_value = WebSerializedScriptValue::serialize(result_value);
1688 } else {
1689 serialized_script_value = WebSerializedScriptValue::fromString(params.data);
1692 // Create an event with the message. The next-to-last parameter to
1693 // initMessageEvent is the last event ID, which is not used with postMessage.
1694 WebDOMEvent event = frame_->document().createEvent("MessageEvent");
1695 WebDOMMessageEvent msg_event = event.to<WebDOMMessageEvent>();
1696 msg_event.initMessageEvent("message",
1697 // |canBubble| and |cancellable| are always false
1698 false, false,
1699 serialized_script_value,
1700 params.source_origin, source_frame, "", channels);
1702 // We must pass in the target_origin to do the security check on this side,
1703 // since it may have changed since the original postMessage call was made.
1704 WebSecurityOrigin target_origin;
1705 if (!params.target_origin.empty()) {
1706 target_origin =
1707 WebSecurityOrigin::createFromString(WebString(params.target_origin));
1709 frame_->dispatchMessageEventWithOriginCheck(target_origin, msg_event);
1712 #if defined(OS_ANDROID)
1713 void RenderFrameImpl::OnSelectPopupMenuItems(
1714 bool canceled,
1715 const std::vector<int>& selected_indices) {
1716 // It is possible to receive more than one of these calls if the user presses
1717 // a select faster than it takes for the show-select-popup IPC message to make
1718 // it to the browser UI thread. Ignore the extra-messages.
1719 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1720 if (!external_popup_menu_)
1721 return;
1723 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1724 external_popup_menu_.reset();
1726 #endif
1728 #if defined(OS_MACOSX)
1729 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1730 if (external_popup_menu_ == NULL)
1731 return;
1732 external_popup_menu_->DidSelectItem(selected_index);
1733 external_popup_menu_.reset();
1735 #endif
1737 void RenderFrameImpl::OnReload(bool ignore_cache) {
1738 frame_->reload(ignore_cache);
1741 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1742 blink::WebSurroundingText surroundingText;
1743 surroundingText.initialize(frame_->selectionRange(), max_length);
1745 if (surroundingText.isNull()) {
1746 // |surroundingText| might not be correctly initialized, for example if
1747 // |frame_->selectionRange().isNull()|, in other words, if there was no
1748 // selection.
1749 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1750 routing_id_, base::string16(), 0, 0));
1751 return;
1754 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1755 routing_id_,
1756 surroundingText.textContent(),
1757 surroundingText.startOffsetInTextContent(),
1758 surroundingText.endOffsetInTextContent()));
1761 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1762 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1765 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1766 frame_->document().setIsTransitionDocument(true);
1767 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1770 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector,
1771 bool exit_to_native_app) {
1772 frame_->document().setIsTransitionDocument(true);
1773 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector),
1774 exit_to_native_app);
1777 void RenderFrameImpl::OnRevertExitTransition() {
1778 frame_->document().setIsTransitionDocument(false);
1779 frame_->document().revertExitTransition();
1782 void RenderFrameImpl::OnHideTransitionElements(
1783 const std::string& css_selector) {
1784 frame_->document().hideTransitionElements(WebString::fromUTF8(css_selector));
1787 void RenderFrameImpl::OnShowTransitionElements(
1788 const std::string& css_selector) {
1789 frame_->document().showTransitionElements(WebString::fromUTF8(css_selector));
1792 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1793 const base::string16& message,
1794 const base::string16& default_value,
1795 const GURL& frame_url,
1796 base::string16* result) {
1797 // Don't allow further dialogs if we are waiting to swap out, since the
1798 // PageGroupLoadDeferrer in our stack prevents it.
1799 if (render_view()->suppress_dialogs_until_swap_out_)
1800 return false;
1802 bool success = false;
1803 base::string16 result_temp;
1804 if (!result)
1805 result = &result_temp;
1807 render_view()->SendAndRunNestedMessageLoop(
1808 new FrameHostMsg_RunJavaScriptMessage(
1809 routing_id_, message, default_value, frame_url, type, &success,
1810 result));
1811 return success;
1814 void RenderFrameImpl::LoadNavigationErrorPage(
1815 const WebURLRequest& failed_request,
1816 const WebURLError& error,
1817 bool replace) {
1818 std::string error_html;
1819 GetContentClient()->renderer()->GetNavigationErrorStrings(
1820 render_view(), frame_, failed_request, error, &error_html, NULL);
1822 frame_->loadHTMLString(error_html,
1823 GURL(kUnreachableWebDataURL),
1824 error.unreachableURL,
1825 replace);
1828 void RenderFrameImpl::DidCommitCompositorFrame() {
1829 if (BrowserPluginManager::Get())
1830 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1831 FOR_EACH_OBSERVER(
1832 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1835 RenderView* RenderFrameImpl::GetRenderView() {
1836 return render_view_.get();
1839 int RenderFrameImpl::GetRoutingID() {
1840 return routing_id_;
1843 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1844 DCHECK(frame_);
1845 return frame_;
1848 WebElement RenderFrameImpl::GetFocusedElement() const {
1849 WebDocument doc = frame_->document();
1850 if (!doc.isNull())
1851 return doc.focusedElement();
1853 return WebElement();
1856 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1857 return render_view_->GetWebkitPreferences();
1860 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1861 const ContextMenuParams& params) {
1862 DCHECK(client); // A null client means "internal" when we issue callbacks.
1863 ContextMenuParams our_params(params);
1864 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1865 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1866 return our_params.custom_context.request_id;
1869 void RenderFrameImpl::CancelContextMenu(int request_id) {
1870 DCHECK(pending_context_menus_.Lookup(request_id));
1871 pending_context_menus_.Remove(request_id);
1874 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1875 return context_menu_node_;
1878 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1879 blink::WebFrame* frame,
1880 const WebPluginInfo& info,
1881 const blink::WebPluginParams& params,
1882 scoped_ptr<content::PluginInstanceThrottler> throttler) {
1883 DCHECK_EQ(frame_, frame);
1884 #if defined(ENABLE_PLUGINS)
1885 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1886 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1887 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1888 this, params.mimeType.utf8(), GURL(params.url)));
1889 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1890 this, browser_plugin_delegate.Pass());
1893 bool pepper_plugin_was_registered = false;
1894 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1895 this, info, &pepper_plugin_was_registered));
1896 if (pepper_plugin_was_registered) {
1897 if (pepper_module.get()) {
1898 return new PepperWebPluginImpl(
1899 pepper_module.get(), params, this,
1900 make_scoped_ptr(
1901 static_cast<PluginInstanceThrottlerImpl*>(throttler.release())));
1904 #if defined(OS_CHROMEOS)
1905 LOG(WARNING) << "Pepper module/plugin creation failed.";
1906 return NULL;
1907 #else
1908 // TODO(jam): change to take RenderFrame.
1909 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1910 #endif
1911 #else
1912 return NULL;
1913 #endif
1916 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1917 const blink::WebURLRequest& request,
1918 blink::WebNavigationPolicy policy) {
1919 DCHECK(!frame_ || frame_ == frame);
1920 loadURLExternally(frame, request, policy, WebString());
1923 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1924 OnJavaScriptExecuteRequest(javascript, 0, false);
1927 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1928 return &service_registry_;
1931 #if defined(ENABLE_PLUGINS)
1932 void RenderFrameImpl::RegisterPeripheralPlugin(
1933 const GURL& content_origin,
1934 const base::Closure& unthrottle_callback) {
1935 return plugin_power_saver_helper_->RegisterPeripheralPlugin(
1936 content_origin, unthrottle_callback);
1938 #endif // defined(ENABLE_PLUGINS)
1940 bool RenderFrameImpl::IsFTPDirectoryListing() {
1941 WebURLResponseExtraDataImpl* extra_data =
1942 GetExtraDataFromResponse(frame_->dataSource()->response());
1943 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1946 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1947 BrowserPluginManager::Get()->Attach(element_instance_id);
1950 void RenderFrameImpl::DetachGuest(int element_instance_id) {
1951 BrowserPluginManager::Get()->Detach(element_instance_id);
1954 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1955 size_t offset,
1956 const gfx::Range& range) {
1957 // Use the routing id of Render Widget Host.
1958 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1959 selection_text,
1960 offset,
1961 range));
1964 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1965 v8::Isolate* isolate,
1966 v8::Local<v8::Context> context) {
1967 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1968 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1969 return;
1971 v8::HandleScope handle_scope(isolate);
1972 registry->AddBuiltinModule(
1973 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1974 registry->AddBuiltinModule(isolate,
1975 mojo::js::Support::kModuleName,
1976 mojo::js::Support::GetModule(isolate));
1977 registry->AddBuiltinModule(
1978 isolate,
1979 ServiceRegistryJsWrapper::kModuleName,
1980 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1983 // blink::WebFrameClient implementation ----------------------------------------
1985 blink::WebPluginPlaceholder* RenderFrameImpl::createPluginPlaceholder(
1986 blink::WebLocalFrame* frame,
1987 const blink::WebPluginParams& params) {
1988 DCHECK_EQ(frame_, frame);
1989 return GetContentClient()
1990 ->renderer()
1991 ->CreatePluginPlaceholder(this, frame, params)
1992 .release();
1995 blink::WebPlugin* RenderFrameImpl::createPlugin(
1996 blink::WebLocalFrame* frame,
1997 const blink::WebPluginParams& params) {
1998 DCHECK_EQ(frame_, frame);
1999 blink::WebPlugin* plugin = NULL;
2000 if (GetContentClient()->renderer()->OverrideCreatePlugin(
2001 this, frame, params, &plugin)) {
2002 return plugin;
2005 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
2006 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
2007 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
2008 kBrowserPluginMimeType, GURL(params.url)));
2009 return BrowserPluginManager::Get()->CreateBrowserPlugin(
2010 this, browser_plugin_delegate.Pass());
2013 #if defined(ENABLE_PLUGINS)
2014 WebPluginInfo info;
2015 std::string mime_type;
2016 bool found = false;
2017 Send(new FrameHostMsg_GetPluginInfo(
2018 routing_id_, params.url, frame->top()->document().url(),
2019 params.mimeType.utf8(), &found, &info, &mime_type));
2020 if (!found)
2021 return NULL;
2023 WebPluginParams params_to_use = params;
2024 params_to_use.mimeType = WebString::fromUTF8(mime_type);
2025 return CreatePlugin(frame, info, params_to_use, nullptr /* throttler */);
2026 #else
2027 return NULL;
2028 #endif // defined(ENABLE_PLUGINS)
2031 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
2032 blink::WebLocalFrame* frame,
2033 const blink::WebURL& url,
2034 blink::WebMediaPlayerClient* client) {
2035 return createMediaPlayer(frame, url, client, nullptr);
2038 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
2039 blink::WebLocalFrame* frame,
2040 const blink::WebURL& url,
2041 blink::WebMediaPlayerClient* client,
2042 blink::WebContentDecryptionModule* initial_cdm) {
2043 #if defined(VIDEO_HOLE)
2044 if (!contains_media_player_) {
2045 render_view_->RegisterVideoHoleFrame(this);
2046 contains_media_player_ = true;
2048 #endif // defined(VIDEO_HOLE)
2050 blink::WebMediaStream web_stream(
2051 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
2052 if (!web_stream.isNull())
2053 return CreateWebMediaPlayerForMediaStream(url, client);
2055 #if defined(OS_ANDROID)
2056 return CreateAndroidWebMediaPlayer(url, client, GetMediaPermission(),
2057 initial_cdm);
2058 #else
2059 scoped_refptr<media::MediaLog> media_log(new RenderMediaLog());
2061 RenderThreadImpl* render_thread = RenderThreadImpl::current();
2062 media::WebMediaPlayerParams params(
2063 base::Bind(&ContentRendererClient::DeferMediaLoad,
2064 base::Unretained(GetContentClient()->renderer()),
2065 static_cast<RenderFrame*>(this)),
2066 render_thread->GetAudioRendererMixerManager()->CreateInput(routing_id_),
2067 media_log, render_thread->GetMediaThreadTaskRunner(),
2068 render_thread->compositor_message_loop_proxy(),
2069 base::Bind(&GetSharedMainThreadContext3D), GetMediaPermission(),
2070 initial_cdm);
2072 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
2073 scoped_ptr<media::RendererFactory> media_renderer_factory(
2074 new media::MojoRendererFactory(make_scoped_ptr(
2075 new MediaRendererServiceProvider(GetServiceRegistry()))));
2076 #else
2077 scoped_ptr<media::RendererFactory> media_renderer_factory =
2078 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
2079 media_log);
2081 if (!media_renderer_factory.get()) {
2082 media_renderer_factory.reset(new media::DefaultRendererFactory(
2083 media_log, render_thread->GetGpuFactories(),
2084 *render_thread->GetAudioHardwareConfig()));
2086 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
2088 return new media::WebMediaPlayerImpl(
2089 frame, client, weak_factory_.GetWeakPtr(), media_renderer_factory.Pass(),
2090 GetCdmFactory(), params);
2091 #endif // defined(OS_ANDROID)
2094 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
2095 blink::WebLocalFrame* frame,
2096 blink::WebApplicationCacheHostClient* client) {
2097 if (!frame || !frame->view())
2098 return NULL;
2099 DCHECK(!frame_ || frame_ == frame);
2100 return new RendererWebApplicationCacheHostImpl(
2101 RenderViewImpl::FromWebView(frame->view()), client,
2102 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
2105 blink::WebWorkerContentSettingsClientProxy*
2106 RenderFrameImpl::createWorkerContentSettingsClientProxy(
2107 blink::WebLocalFrame* frame) {
2108 if (!frame || !frame->view())
2109 return NULL;
2110 DCHECK(!frame_ || frame_ == frame);
2111 return GetContentClient()->renderer()->CreateWorkerContentSettingsClientProxy(
2112 this, frame);
2115 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
2116 const WebPopupMenuInfo& popup_menu_info,
2117 WebExternalPopupMenuClient* popup_menu_client) {
2118 #if defined(OS_MACOSX) || defined(OS_ANDROID)
2119 // An IPC message is sent to the browser to build and display the actual
2120 // popup. The user could have time to click a different select by the time
2121 // the popup is shown. In that case external_popup_menu_ is non NULL.
2122 // By returning NULL in that case, we instruct Blink to cancel that new
2123 // popup. So from the user perspective, only the first one will show, and
2124 // will have to close the first one before another one can be shown.
2125 if (external_popup_menu_)
2126 return NULL;
2127 external_popup_menu_.reset(
2128 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
2129 if (render_view_->screen_metrics_emulator_) {
2130 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
2131 external_popup_menu_.get(),
2132 render_view_->screen_metrics_emulator_.get());
2134 return external_popup_menu_.get();
2135 #else
2136 return NULL;
2137 #endif
2140 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
2141 DCHECK(!frame_ || frame_ == frame);
2142 return &cookie_jar_;
2145 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
2146 blink::WebLocalFrame* frame) {
2147 DCHECK(!frame_ || frame_ == frame);
2148 // At this point we should have non-null data source.
2149 DCHECK(frame->dataSource());
2150 if (!ChildThreadImpl::current())
2151 return NULL; // May be null in some tests.
2152 ServiceWorkerNetworkProvider* provider =
2153 ServiceWorkerNetworkProvider::FromDocumentState(
2154 DocumentState::FromDataSource(frame->dataSource()));
2155 return new WebServiceWorkerProviderImpl(
2156 ChildThreadImpl::current()->thread_safe_sender(),
2157 provider ? provider->context() : NULL);
2160 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
2161 DCHECK(!frame_ || frame_ == frame);
2162 // If the request hasn't yet committed, notify the browser process that it is
2163 // no longer safe to show the pending URL of the main frame, since a URL spoof
2164 // is now possible. (If the request has committed, the browser already knows.)
2165 if (!frame->parent()) {
2166 DocumentState* document_state =
2167 DocumentState::FromDataSource(frame->dataSource());
2168 NavigationStateImpl* navigation_state =
2169 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2171 if (!navigation_state->request_committed()) {
2172 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
2177 blink::WebFrame* RenderFrameImpl::createChildFrame(
2178 blink::WebLocalFrame* parent,
2179 const blink::WebString& name,
2180 blink::WebSandboxFlags sandbox_flags) {
2181 // Synchronously notify the browser of a child frame creation to get the
2182 // routing_id for the RenderFrame.
2183 int child_routing_id = MSG_ROUTING_NONE;
2184 Send(new FrameHostMsg_CreateChildFrame(
2185 routing_id_, base::UTF16ToUTF8(name),
2186 WebToContentSandboxFlags(sandbox_flags), &child_routing_id));
2188 // Allocation of routing id failed, so we can't create a child frame. This can
2189 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2190 // out state or synchronous IPC message above has failed.
2191 if (child_routing_id == MSG_ROUTING_NONE) {
2192 NOTREACHED() << "Failed to allocate routing id for child frame.";
2193 return nullptr;
2196 // Create the RenderFrame and WebLocalFrame, linking the two.
2197 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
2198 render_view_.get(), child_routing_id);
2199 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
2200 child_render_frame->SetWebFrame(web_frame);
2202 // Add the frame to the frame tree and initialize it.
2203 parent->appendChild(web_frame);
2204 child_render_frame->Initialize();
2206 return web_frame;
2209 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
2210 DCHECK(!frame_ || frame_ == frame);
2211 // We only need to notify the browser if the active, top-level frame clears
2212 // its opener. We can ignore cases where a swapped out frame clears its
2213 // opener after hearing about it from the browser, and the browser does not
2214 // (yet) care about subframe openers.
2215 if (is_swapped_out_ || frame->parent())
2216 return;
2218 // Notify WebContents and all its swapped out RenderViews.
2219 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
2222 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
2223 // NOTE: This function is called on the frame that is being detached and not
2224 // the parent frame. This is different from createChildFrame() which is
2225 // called on the parent frame.
2226 CHECK(!is_detaching_);
2227 DCHECK(!frame_ || frame_ == frame);
2229 bool is_subframe = !!frame->parent();
2231 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameDetached());
2232 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2233 FrameDetached(frame));
2235 Send(new FrameHostMsg_Detach(routing_id_));
2237 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2238 // sent before setting |is_detaching_| to true.
2239 is_detaching_ = true;
2241 // We need to clean up subframes by removing them from the map and deleting
2242 // the RenderFrameImpl. In contrast, the main frame is owned by its
2243 // containing RenderViewHost (so that they have the same lifetime), so only
2244 // removal from the map is needed and no deletion.
2245 FrameMap::iterator it = g_frame_map.Get().find(frame);
2246 CHECK(it != g_frame_map.Get().end());
2247 CHECK_EQ(it->second, this);
2248 g_frame_map.Get().erase(it);
2250 if (is_subframe)
2251 frame->parent()->removeChild(frame);
2253 // |frame| is invalid after here. Be sure to clear frame_ as well, since this
2254 // object may not be deleted immediately and other methods may try to access
2255 // it.
2256 frame->close();
2257 frame_ = nullptr;
2259 if (is_subframe) {
2260 delete this;
2261 // Object is invalid after this point.
2265 void RenderFrameImpl::frameFocused() {
2266 Send(new FrameHostMsg_FrameFocused(routing_id_));
2269 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
2270 DCHECK(!frame_ || frame_ == frame);
2272 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
2273 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2274 FrameWillClose(frame));
2277 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
2278 const blink::WebString& name) {
2279 DCHECK(!frame_ || frame_ == frame);
2281 // TODO(alexmos): According to https://crbug.com/169110, sending window.name
2282 // updates may have performance implications for benchmarks like SunSpider.
2283 // For now, send these updates only for --site-per-process, which needs to
2284 // replicate frame names to frame proxies, and when
2285 // |report_frame_name_changes| is set (used by <webview>). If needed, this
2286 // can be optimized further by only sending the update if there are any
2287 // remote frames in the frame tree, or delaying and batching up IPCs if
2288 // updates are happening too frequently.
2289 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
2290 switches::kSitePerProcess);
2291 if (is_site_per_process ||
2292 render_view_->renderer_preferences_.report_frame_name_changes) {
2293 Send(new FrameHostMsg_DidChangeName(routing_id_, base::UTF16ToUTF8(name)));
2297 void RenderFrameImpl::didChangeSandboxFlags(blink::WebFrame* child_frame,
2298 blink::WebSandboxFlags flags) {
2299 int frame_routing_id = MSG_ROUTING_NONE;
2300 if (child_frame->isWebRemoteFrame()) {
2301 frame_routing_id =
2302 RenderFrameProxy::FromWebFrame(child_frame)->routing_id();
2303 } else {
2304 frame_routing_id =
2305 RenderFrameImpl::FromWebFrame(child_frame)->GetRoutingID();
2308 Send(new FrameHostMsg_DidChangeSandboxFlags(routing_id_, frame_routing_id,
2309 WebToContentSandboxFlags(flags)));
2312 void RenderFrameImpl::didMatchCSS(
2313 blink::WebLocalFrame* frame,
2314 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2315 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2316 DCHECK(!frame_ || frame_ == frame);
2318 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2319 DidMatchCSS(frame,
2320 newly_matching_selectors,
2321 stopped_matching_selectors));
2324 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2325 const blink::WebString& source) {
2326 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2327 source);
2330 void RenderFrameImpl::didAddMessageToConsole(
2331 const blink::WebConsoleMessage& message,
2332 const blink::WebString& source_name,
2333 unsigned source_line,
2334 const blink::WebString& stack_trace) {
2335 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2336 switch (message.level) {
2337 case blink::WebConsoleMessage::LevelDebug:
2338 log_severity = logging::LOG_VERBOSE;
2339 break;
2340 case blink::WebConsoleMessage::LevelLog:
2341 case blink::WebConsoleMessage::LevelInfo:
2342 log_severity = logging::LOG_INFO;
2343 break;
2344 case blink::WebConsoleMessage::LevelWarning:
2345 log_severity = logging::LOG_WARNING;
2346 break;
2347 case blink::WebConsoleMessage::LevelError:
2348 log_severity = logging::LOG_ERROR;
2349 break;
2350 default:
2351 log_severity = logging::LOG_VERBOSE;
2354 if (shouldReportDetailedMessageForSource(source_name)) {
2355 FOR_EACH_OBSERVER(
2356 RenderFrameObserver, observers_,
2357 DetailedConsoleMessageAdded(message.text,
2358 source_name,
2359 stack_trace,
2360 source_line,
2361 static_cast<int32>(log_severity)));
2364 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2365 static_cast<int32>(log_severity),
2366 message.text,
2367 static_cast<int32>(source_line),
2368 source_name));
2371 void RenderFrameImpl::loadURLExternally(
2372 blink::WebLocalFrame* frame,
2373 const blink::WebURLRequest& request,
2374 blink::WebNavigationPolicy policy,
2375 const blink::WebString& suggested_name) {
2376 DCHECK(!frame_ || frame_ == frame);
2377 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2378 if (policy == blink::WebNavigationPolicyDownload) {
2379 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2380 request.url(), referrer,
2381 suggested_name));
2382 } else {
2383 OpenURL(frame, request.url(), referrer, policy);
2387 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2388 const NavigationPolicyInfo& info) {
2389 DCHECK(!frame_ || frame_ == info.frame);
2390 return DecidePolicyForNavigation(this, info);
2393 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2394 blink::WebFrame* frame) {
2395 DCHECK(!frame_ || frame_ == frame);
2396 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2399 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2400 const blink::WebFormElement& form) {
2401 DCHECK(!frame_ || frame_ == frame);
2403 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSendSubmitEvent(form));
2406 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2407 const blink::WebFormElement& form) {
2408 DCHECK(!frame_ || frame_ == frame);
2409 DocumentState* document_state =
2410 DocumentState::FromDataSource(frame->provisionalDataSource());
2411 NavigationStateImpl* navigation_state =
2412 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2413 InternalDocumentStateData* internal_data =
2414 InternalDocumentStateData::FromDocumentState(document_state);
2416 if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(),
2417 ui::PAGE_TRANSITION_LINK)) {
2418 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2421 // Save these to be processed when the ensuing navigation is committed.
2422 WebSearchableFormData web_searchable_form_data(form);
2423 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2424 internal_data->set_searchable_form_encoding(
2425 web_searchable_form_data.encoding().utf8());
2427 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form));
2430 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2431 blink::WebDataSource* datasource) {
2432 DCHECK(!frame_ || frame_ == frame);
2434 bool content_initiated = !pending_navigation_params_.get();
2436 // Make sure any previous redirect URLs end up in our new data source.
2437 if (pending_navigation_params_.get()) {
2438 for (const auto& i :
2439 pending_navigation_params_->request_params.redirects) {
2440 datasource->appendRedirect(i);
2444 DocumentState* document_state = DocumentState::FromDataSource(datasource);
2445 if (!document_state) {
2446 document_state = new DocumentState;
2447 datasource->setExtraData(document_state);
2448 if (!content_initiated)
2449 PopulateDocumentStateFromPending(document_state);
2452 // Carry over the user agent override flag, if it exists.
2453 blink::WebView* webview = render_view_->webview();
2454 if (content_initiated && webview && webview->mainFrame() &&
2455 webview->mainFrame()->isWebLocalFrame() &&
2456 webview->mainFrame()->dataSource()) {
2457 DocumentState* old_document_state =
2458 DocumentState::FromDataSource(webview->mainFrame()->dataSource());
2459 if (old_document_state) {
2460 InternalDocumentStateData* internal_data =
2461 InternalDocumentStateData::FromDocumentState(document_state);
2462 InternalDocumentStateData* old_internal_data =
2463 InternalDocumentStateData::FromDocumentState(old_document_state);
2464 internal_data->set_is_overriding_user_agent(
2465 old_internal_data->is_overriding_user_agent());
2469 // The rest of RenderView assumes that a WebDataSource will always have a
2470 // non-null NavigationState.
2471 if (content_initiated) {
2472 document_state->set_navigation_state(
2473 NavigationStateImpl::CreateContentInitiated());
2474 } else {
2475 document_state->set_navigation_state(CreateNavigationStateFromPending());
2476 pending_navigation_params_.reset();
2479 // DocumentState::referred_by_prefetcher_ is true if we are
2480 // navigating from a page that used prefetching using a link on that
2481 // page. We are early enough in the request process here that we
2482 // can still see the DocumentState of the previous page and set
2483 // this value appropriately.
2484 // TODO(gavinp): catch the important case of navigation in a new
2485 // renderer process.
2486 if (webview) {
2487 if (WebFrame* old_frame = webview->mainFrame()) {
2488 const WebURLRequest& original_request = datasource->originalRequest();
2489 const GURL referrer(
2490 original_request.httpHeaderField(WebString::fromUTF8("Referer")));
2491 if (!referrer.is_empty() && old_frame->isWebLocalFrame() &&
2492 DocumentState::FromDataSource(old_frame->dataSource())
2493 ->was_prefetcher()) {
2494 for (; old_frame; old_frame = old_frame->traverseNext(false)) {
2495 WebDataSource* old_frame_datasource = old_frame->dataSource();
2496 if (old_frame_datasource &&
2497 referrer == GURL(old_frame_datasource->request().url())) {
2498 document_state->set_was_referred_by_prefetcher(true);
2499 break;
2506 if (content_initiated) {
2507 const WebURLRequest& request = datasource->request();
2508 switch (request.cachePolicy()) {
2509 case WebURLRequest::UseProtocolCachePolicy: // normal load.
2510 document_state->set_load_type(DocumentState::LINK_LOAD_NORMAL);
2511 break;
2512 case WebURLRequest::ReloadIgnoringCacheData: // reload.
2513 case WebURLRequest::ReloadBypassingCache: // end-to-end reload.
2514 document_state->set_load_type(DocumentState::LINK_LOAD_RELOAD);
2515 break;
2516 case WebURLRequest::ReturnCacheDataElseLoad: // allow stale data.
2517 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_STALE_OK);
2518 break;
2519 case WebURLRequest::ReturnCacheDataDontLoad: // Don't re-post.
2520 document_state->set_load_type(DocumentState::LINK_LOAD_CACHE_ONLY);
2521 break;
2522 default:
2523 NOTREACHED();
2527 // Create the serviceworker's per-document network observing object if it
2528 // does not exist (When navigation happens within a page, the provider already
2529 // exists).
2530 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2531 DocumentState::FromDataSource(datasource))) {
2532 scoped_ptr<ServiceWorkerNetworkProvider> network_provider(
2533 new ServiceWorkerNetworkProvider(routing_id_,
2534 SERVICE_WORKER_PROVIDER_FOR_WINDOW));
2535 ServiceWorkerNetworkProvider::AttachToDocumentState(
2536 DocumentState::FromDataSource(datasource),
2537 network_provider.Pass());
2541 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2542 bool is_transition_navigation,
2543 double triggering_event_time) {
2544 DCHECK(!frame_ || frame_ == frame);
2545 WebDataSource* ds = frame->provisionalDataSource();
2547 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2548 // callback is invoked.
2549 if (!ds)
2550 return;
2552 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2553 "id", routing_id_, "url", ds->request().url().string().utf8());
2554 DocumentState* document_state = DocumentState::FromDataSource(ds);
2556 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2557 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2558 is_swapped_out_) <<
2559 "Heard swappedout:// when not swapped out.";
2561 // Update the request time if WebKit has better knowledge of it.
2562 if (document_state->request_time().is_null() &&
2563 triggering_event_time != 0.0) {
2564 document_state->set_request_time(Time::FromDoubleT(triggering_event_time));
2567 // Start time is only set after request time.
2568 document_state->set_start_load_time(Time::Now());
2570 bool is_top_most = !frame->parent();
2571 NavigationStateImpl* navigation_state =
2572 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2573 if (is_top_most) {
2574 render_view_->set_navigation_gesture(
2575 WebUserGestureIndicator::isProcessingUserGesture() ?
2576 NavigationGestureUser : NavigationGestureAuto);
2577 } else if (ds->replacesCurrentHistoryItem()) {
2578 // Subframe navigations that don't add session history items must be
2579 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2580 // handle loading of error pages.
2581 navigation_state->set_transition_type(ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2582 } else if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(),
2583 ui::PAGE_TRANSITION_LINK)) {
2584 // Subframe navigations that are creating a new history item should be
2585 // marked MANUAL_SUBFRAME, unless it has already been marked as a
2586 // FORM_SUBMIT. This state will be attached to a main resource request
2587 // in the process that began the request. If the request is transferred
2588 // to a different process, this state will be used in
2589 // RenderFrameImpl::OnNavigate() in the new process (as well as in the
2590 // browser process).
2591 navigation_state->set_transition_type(ui::PAGE_TRANSITION_MANUAL_SUBFRAME);
2594 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2595 DidStartProvisionalLoad(frame));
2596 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2598 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2599 routing_id_, ds->request().url(), is_transition_navigation));
2602 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2603 blink::WebLocalFrame* frame) {
2604 DCHECK(!frame_ || frame_ == frame);
2605 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2608 void RenderFrameImpl::didFailProvisionalLoad(
2609 blink::WebLocalFrame* frame,
2610 const blink::WebURLError& error,
2611 blink::WebHistoryCommitType commit_type) {
2612 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2613 "id", routing_id_);
2614 DCHECK(!frame_ || frame_ == frame);
2615 WebDataSource* ds = frame->provisionalDataSource();
2616 DCHECK(ds);
2618 const WebURLRequest& failed_request = ds->request();
2620 // Notify the browser that we failed a provisional load with an error.
2622 // Note: It is important this notification occur before DidStopLoading so the
2623 // SSL manager can react to the provisional load failure before being
2624 // notified the load stopped.
2626 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2627 DidFailProvisionalLoad(frame, error));
2628 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2629 DidFailProvisionalLoad(error));
2631 SendFailedProvisionalLoad(failed_request, error, frame);
2633 if (!ShouldDisplayErrorPageForFailedLoad(error.reason, error.unreachableURL))
2634 return;
2636 // Make sure we never show errors in view source mode.
2637 frame->enableViewSourceMode(false);
2639 DocumentState* document_state = DocumentState::FromDataSource(ds);
2640 NavigationStateImpl* navigation_state =
2641 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2643 // If this is a failed back/forward/reload navigation, then we need to do a
2644 // 'replace' load. This is necessary to avoid messing up session history.
2645 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2646 // as session history is concerned.
2647 bool replace = commit_type != blink::WebStandardCommit;
2649 // If we failed on a browser initiated request, then make sure that our error
2650 // page load is regarded as the same browser initiated request.
2651 if (!navigation_state->IsContentInitiated()) {
2652 pending_navigation_params_.reset(new NavigationParams(
2653 navigation_state->common_params(), navigation_state->start_params(),
2654 navigation_state->request_params()));
2655 pending_navigation_params_->request_params.request_time =
2656 document_state->request_time();
2659 // Load an error page.
2660 LoadNavigationErrorPage(failed_request, error, replace);
2663 void RenderFrameImpl::didCommitProvisionalLoad(
2664 blink::WebLocalFrame* frame,
2665 const blink::WebHistoryItem& item,
2666 blink::WebHistoryCommitType commit_type) {
2667 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2668 "id", routing_id_,
2669 "url", GetLoadingUrl().possibly_invalid_spec());
2670 DCHECK(!frame_ || frame_ == frame);
2671 DocumentState* document_state =
2672 DocumentState::FromDataSource(frame->dataSource());
2673 NavigationStateImpl* navigation_state =
2674 static_cast<NavigationStateImpl*>(document_state->navigation_state());
2676 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2677 RenderFrameProxy* proxy =
2678 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2679 CHECK(proxy);
2680 proxy->web_frame()->swap(frame_);
2681 proxy_routing_id_ = MSG_ROUTING_NONE;
2684 // When we perform a new navigation, we need to update the last committed
2685 // session history entry with state for the page we are leaving. Do this
2686 // before updating the HistoryController state.
2687 render_view_->UpdateSessionHistory(frame);
2689 render_view_->history_controller()->UpdateForCommit(
2690 this, item, commit_type, navigation_state->WasWithinSamePage());
2692 InternalDocumentStateData* internal_data =
2693 InternalDocumentStateData::FromDocumentState(document_state);
2695 if (document_state->commit_load_time().is_null())
2696 document_state->set_commit_load_time(Time::Now());
2698 if (internal_data->must_reset_scroll_and_scale_state()) {
2699 render_view_->webview()->resetScrollAndScaleState();
2700 internal_data->set_must_reset_scroll_and_scale_state(false);
2702 internal_data->set_use_error_page(false);
2704 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2705 if (is_new_navigation) {
2706 // We bump our Page ID to correspond with the new session history entry.
2707 render_view_->page_id_ = render_view_->next_page_id_++;
2709 // Don't update history list values for kSwappedOutURL, since
2710 // we don't want to forget the entry that was there, and since we will
2711 // never come back to kSwappedOutURL. Note that we have to call
2712 // UpdateSessionHistory and update page_id_ even in this case, so that
2713 // the current entry gets a state update and so that we don't send a
2714 // state update to the wrong entry when we swap back in.
2715 DCHECK_IMPLIES(
2716 navigation_state->start_params().should_replace_current_entry,
2717 render_view_->history_list_length_ > 0);
2718 if (GetLoadingUrl() != GURL(kSwappedOutURL) &&
2719 !navigation_state->start_params().should_replace_current_entry) {
2720 // Advance our offset in session history, applying the length limit.
2721 // There is now no forward history.
2722 render_view_->history_list_offset_++;
2723 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2724 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2725 render_view_->history_list_length_ =
2726 render_view_->history_list_offset_ + 1;
2728 } else {
2729 // Inspect the navigation_state on this frame to see if the navigation
2730 // corresponds to a session history navigation... Note: |frame| may or
2731 // may not be the toplevel frame, but for the case of capturing session
2732 // history, the first committed frame suffices. We keep track of whether
2733 // we've seen this commit before so that only capture session history once
2734 // per navigation.
2736 // Note that we need to check if the page ID changed. In the case of a
2737 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2738 // previous URL and the current page ID, which would be wrong.
2739 if (navigation_state->request_params().page_id != -1 &&
2740 navigation_state->request_params().page_id != render_view_->page_id_) {
2741 // This is a successful session history navigation!
2742 render_view_->page_id_ = navigation_state->request_params().page_id;
2744 render_view_->history_list_offset_ =
2745 navigation_state->request_params().pending_history_list_offset;
2749 bool sent = Send(
2750 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2751 CHECK(sent); // http://crbug.com/407376
2753 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2754 DidCommitProvisionalLoad(frame, is_new_navigation));
2755 FOR_EACH_OBSERVER(
2756 RenderFrameObserver, observers_,
2757 DidCommitProvisionalLoad(is_new_navigation,
2758 navigation_state->WasWithinSamePage()));
2760 if (!frame->parent()) { // Only for top frames.
2761 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2762 if (render_thread_impl) { // Can be NULL in tests.
2763 render_thread_impl->histogram_customizer()->
2764 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2765 RenderViewImpl::GetRenderViewCount());
2769 // Remember that we've already processed this request, so we don't update
2770 // the session history again. We do this regardless of whether this is
2771 // a session history navigation, because if we attempted a session history
2772 // navigation without valid HistoryItem state, WebCore will think it is a
2773 // new navigation.
2774 navigation_state->set_request_committed(true);
2776 SendDidCommitProvisionalLoad(frame, commit_type);
2778 // Check whether we have new encoding name.
2779 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2782 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2783 DCHECK(!frame_ || frame_ == frame);
2785 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2786 DidCreateNewDocument(frame));
2789 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2790 DCHECK(!frame_ || frame_ == frame);
2792 int enabled_bindings = render_view_->GetEnabledBindings();
2794 if (enabled_bindings & BINDINGS_POLICY_WEB_UI)
2795 WebUIExtension::Install(frame);
2797 if (enabled_bindings & BINDINGS_POLICY_DOM_AUTOMATION)
2798 DomAutomationController::Install(this, frame);
2800 if (enabled_bindings & BINDINGS_POLICY_STATS_COLLECTION)
2801 StatsCollectionController::Install(frame);
2803 const base::CommandLine& command_line =
2804 *base::CommandLine::ForCurrentProcess();
2806 if (command_line.HasSwitch(cc::switches::kEnableGpuBenchmarking))
2807 GpuBenchmarking::Install(frame);
2809 if (command_line.HasSwitch(switches::kEnableMemoryBenchmarking))
2810 MemoryBenchmarkingExtension::Install(frame);
2812 if (command_line.HasSwitch(switches::kEnableSkiaBenchmarking))
2813 SkiaBenchmarking::Install(frame);
2815 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2816 DidClearWindowObject(frame));
2817 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2820 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2821 DCHECK(!frame_ || frame_ == frame);
2823 // Notify the browser about non-blank documents loading in the top frame.
2824 GURL url = frame->document().url();
2825 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2826 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2827 // frame->tree()->top().
2828 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2829 if (frame == main_frame) {
2830 // For now, don't remember plugin zoom values. We don't want to mix them
2831 // with normal web content (i.e. a fixed layout plugin would usually want
2832 // them different).
2833 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2834 render_view_->GetRoutingID(),
2835 main_frame->document().isPluginDocument()));
2839 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2840 DidCreateDocumentElement(frame));
2843 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2844 const blink::WebString& title,
2845 blink::WebTextDirection direction) {
2846 DCHECK(!frame_ || frame_ == frame);
2847 // Ignore all but top level navigations.
2848 if (!frame->parent()) {
2849 base::string16 title16 = title;
2850 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2851 routing_id_, base::UTF16ToUTF8(title16));
2853 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2854 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2855 shortened_title, direction));
2858 // Also check whether we have new encoding name.
2859 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2862 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2863 blink::WebIconURL::Type icon_type) {
2864 DCHECK(!frame_ || frame_ == frame);
2865 // TODO(nasko): Investigate wheather implementation should move here.
2866 render_view_->didChangeIcon(frame, icon_type);
2869 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2870 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2871 "id", routing_id_);
2872 DCHECK(!frame_ || frame_ == frame);
2873 WebDataSource* ds = frame->dataSource();
2874 DocumentState* document_state = DocumentState::FromDataSource(ds);
2875 document_state->set_finish_document_load_time(Time::Now());
2877 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2879 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2880 DidFinishDocumentLoad(frame));
2881 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2883 // Check whether we have new encoding name.
2884 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2887 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2888 DCHECK(!frame_ || frame_ == frame);
2889 if (!frame->parent()) {
2890 FrameMsg_UILoadMetricsReportType::Value report_type =
2891 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
2892 frame->dataSource()->request().inputPerfMetricReportPolicy());
2893 base::TimeTicks ui_timestamp = base::TimeTicks() +
2894 base::TimeDelta::FromSecondsD(
2895 frame->dataSource()->request().uiStartTime());
2897 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2898 routing_id_, report_type, ui_timestamp));
2902 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2903 const blink::WebURLError& error,
2904 blink::WebHistoryCommitType commit_type) {
2905 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2906 "id", routing_id_);
2907 DCHECK(!frame_ || frame_ == frame);
2908 // TODO(nasko): Move implementation here. No state needed.
2909 WebDataSource* ds = frame->dataSource();
2910 DCHECK(ds);
2912 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2913 DidFailLoad(frame, error));
2915 const WebURLRequest& failed_request = ds->request();
2916 base::string16 error_description;
2917 GetContentClient()->renderer()->GetNavigationErrorStrings(
2918 render_view_.get(),
2919 frame,
2920 failed_request,
2921 error,
2922 NULL,
2923 &error_description);
2924 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2925 failed_request.url(),
2926 error.reason,
2927 error_description));
2930 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2931 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2932 "id", routing_id_);
2933 DCHECK(!frame_ || frame_ == frame);
2934 WebDataSource* ds = frame->dataSource();
2935 DocumentState* document_state = DocumentState::FromDataSource(ds);
2936 if (document_state->finish_load_time().is_null()) {
2937 if (!frame->parent()) {
2938 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2939 TRACE_EVENT_SCOPE_PROCESS);
2941 document_state->set_finish_load_time(Time::Now());
2944 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2945 DidFinishLoad(frame));
2946 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2948 // Don't send this message while the frame is swapped out.
2949 if (is_swapped_out())
2950 return;
2952 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2953 ds->request().url()));
2956 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2957 const blink::WebHistoryItem& item,
2958 blink::WebHistoryCommitType commit_type) {
2959 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2960 "id", routing_id_);
2961 DCHECK(!frame_ || frame_ == frame);
2962 // If this was a reference fragment navigation that we initiated, then we
2963 // could end up having a non-null pending navigation params. We just need to
2964 // update the ExtraData on the datasource so that others who read the
2965 // ExtraData will get the new NavigationState. Similarly, if we did not
2966 // initiate this navigation, then we need to take care to reset any pre-
2967 // existing navigation state to a content-initiated navigation state.
2968 // didCreateDataSource conveniently takes care of this for us.
2969 didCreateDataSource(frame, frame->dataSource());
2971 DocumentState* document_state =
2972 DocumentState::FromDataSource(frame->dataSource());
2973 static_cast<NavigationStateImpl*>(document_state->navigation_state())
2974 ->set_was_within_same_page(true);
2976 didCommitProvisionalLoad(frame, item, commit_type);
2979 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2980 DCHECK(!frame_ || frame_ == frame);
2981 // TODO(nasko): Move implementation here. Needed methods:
2982 // * StartNavStateSyncTimerIfNecessary
2983 render_view_->didUpdateCurrentHistoryItem(frame);
2986 void RenderFrameImpl::addNavigationTransitionData(
2987 const blink::WebTransitionElementData& data) {
2988 FrameHostMsg_AddNavigationTransitionData_Params params;
2989 params.render_frame_id = routing_id_;
2990 params.allowed_destination_host_pattern =
2991 data.scope.utf8();
2992 params.selector = data.selector.utf8();
2993 params.markup = data.markup.utf8();
2994 params.elements.resize(data.elements.size());
2995 for (size_t i = 0; i < data.elements.size(); i++) {
2996 params.elements[i].id = data.elements[i].id.utf8();
2997 params.elements[i].rect = gfx::Rect(data.elements[i].rect);
3000 Send(new FrameHostMsg_AddNavigationTransitionData(params));
3003 void RenderFrameImpl::didChangeThemeColor() {
3004 if (frame_->parent())
3005 return;
3007 Send(new FrameHostMsg_DidChangeThemeColor(
3008 routing_id_, frame_->document().themeColor()));
3011 void RenderFrameImpl::dispatchLoad() {
3012 Send(new FrameHostMsg_DispatchLoad(routing_id_));
3015 void RenderFrameImpl::requestNotificationPermission(
3016 const blink::WebSecurityOrigin& origin,
3017 blink::WebNotificationPermissionCallback* callback) {
3018 if (!notification_permission_dispatcher_) {
3019 notification_permission_dispatcher_ =
3020 new NotificationPermissionDispatcher(this);
3023 notification_permission_dispatcher_->RequestPermission(origin, callback);
3026 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
3027 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
3028 return;
3030 if (is_empty_selection)
3031 selection_text_.clear();
3033 // UpdateTextInputType should be called before SyncSelectionIfRequired.
3034 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
3035 // was changed, and SyncSelectionIfRequired may send SelectionChanged
3036 // to notify the selection was changed. Focus change should be notified
3037 // before selection change.
3038 GetRenderWidget()->UpdateTextInputType();
3039 SyncSelectionIfRequired();
3040 #if defined(OS_ANDROID)
3041 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
3042 RenderWidget::FROM_NON_IME);
3043 #endif
3046 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
3047 blink::WebColorChooserClient* client,
3048 const blink::WebColor& initial_color,
3049 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
3050 RendererWebColorChooserImpl* color_chooser =
3051 new RendererWebColorChooserImpl(this, client);
3052 std::vector<ColorSuggestion> color_suggestions;
3053 for (size_t i = 0; i < suggestions.size(); i++) {
3054 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
3056 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
3057 return color_chooser;
3060 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
3061 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
3062 message,
3063 base::string16(),
3064 frame_->document().url(),
3065 NULL);
3068 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
3069 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
3070 message,
3071 base::string16(),
3072 frame_->document().url(),
3073 NULL);
3076 bool RenderFrameImpl::runModalPromptDialog(
3077 const blink::WebString& message,
3078 const blink::WebString& default_value,
3079 blink::WebString* actual_value) {
3080 base::string16 result;
3081 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
3082 message,
3083 default_value,
3084 frame_->document().url(),
3085 &result);
3086 if (ok)
3087 actual_value->assign(result);
3088 return ok;
3091 bool RenderFrameImpl::runModalBeforeUnloadDialog(
3092 bool is_reload,
3093 const blink::WebString& message) {
3094 // If we are swapping out, we have already run the beforeunload handler.
3095 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
3096 // at all, to avoid running it twice.
3097 if (is_swapped_out_)
3098 return true;
3100 // Don't allow further dialogs if we are waiting to swap out, since the
3101 // PageGroupLoadDeferrer in our stack prevents it.
3102 if (render_view()->suppress_dialogs_until_swap_out_)
3103 return false;
3105 bool success = false;
3106 // This is an ignored return value, but is included so we can accept the same
3107 // response as RunJavaScriptMessage.
3108 base::string16 ignored_result;
3109 render_view()->SendAndRunNestedMessageLoop(
3110 new FrameHostMsg_RunBeforeUnloadConfirm(
3111 routing_id_, frame_->document().url(), message, is_reload,
3112 &success, &ignored_result));
3113 return success;
3116 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
3117 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
3118 params.source_type = GetRenderWidget()->context_menu_source_type();
3119 GetRenderWidget()->OnShowHostContextMenu(&params);
3120 if (GetRenderWidget()->has_host_context_menu_location()) {
3121 params.x = GetRenderWidget()->host_context_menu_location().x();
3122 params.y = GetRenderWidget()->host_context_menu_location().y();
3125 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
3126 // it. We replace it with an empty GURL so the appropriate items are disabled
3127 // in the context menu.
3128 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
3129 // data encoded images. We should have a way to save them.
3130 if (params.src_url.spec().size() > GetMaxURLChars())
3131 params.src_url = GURL();
3132 context_menu_node_ = data.node;
3134 #if defined(OS_ANDROID)
3135 gfx::Rect start_rect;
3136 gfx::Rect end_rect;
3137 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
3138 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
3139 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
3140 #endif
3142 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
3145 void RenderFrameImpl::clearContextMenu() {
3146 context_menu_node_.reset();
3149 void RenderFrameImpl::willSendRequest(
3150 blink::WebLocalFrame* frame,
3151 unsigned identifier,
3152 blink::WebURLRequest& request,
3153 const blink::WebURLResponse& redirect_response) {
3154 DCHECK(!frame_ || frame_ == frame);
3155 // The request my be empty during tests.
3156 if (request.url().isEmpty())
3157 return;
3159 // Set the first party for cookies url if it has not been set yet (new
3160 // requests). For redirects, it is updated by WebURLLoaderImpl.
3161 if (request.firstPartyForCookies().isEmpty()) {
3162 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
3163 request.setFirstPartyForCookies(request.url());
3164 } else {
3165 // TODO(nasko): When the top-level frame is remote, there is no document.
3166 // This is broken and should be fixed to propagate the first party.
3167 WebFrame* top = frame->top();
3168 if (top->isWebLocalFrame()) {
3169 request.setFirstPartyForCookies(
3170 frame->top()->document().firstPartyForCookies());
3175 WebDataSource* provisional_data_source = frame->provisionalDataSource();
3176 WebDataSource* data_source =
3177 provisional_data_source ? provisional_data_source : frame->dataSource();
3179 DocumentState* document_state = DocumentState::FromDataSource(data_source);
3180 DCHECK(document_state);
3181 InternalDocumentStateData* internal_data =
3182 InternalDocumentStateData::FromDocumentState(document_state);
3183 NavigationStateImpl* navigation_state =
3184 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3185 ui::PageTransition transition_type = navigation_state->GetTransitionType();
3186 WebDataSource* frame_ds = frame->provisionalDataSource();
3187 if (frame_ds && frame_ds->isClientRedirect()) {
3188 transition_type = ui::PageTransitionFromInt(
3189 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3192 GURL request_url(request.url());
3193 GURL new_url;
3194 if (GetContentClient()->renderer()->WillSendRequest(
3195 frame,
3196 transition_type,
3197 request_url,
3198 request.firstPartyForCookies(),
3199 &new_url)) {
3200 request.setURL(WebURL(new_url));
3203 if (internal_data->is_cache_policy_override_set())
3204 request.setCachePolicy(internal_data->cache_policy_override());
3206 // The request's extra data may indicate that we should set a custom user
3207 // agent. This needs to be done here, after WebKit is through with setting the
3208 // user agent on its own. Similarly, it may indicate that we should set an
3209 // X-Requested-With header. This must be done here to avoid breaking CORS
3210 // checks.
3211 // PlzNavigate: there may also be a stream url associated with the request.
3212 WebString custom_user_agent;
3213 WebString requested_with;
3214 scoped_ptr<StreamOverrideParameters> stream_override;
3215 if (request.extraData()) {
3216 RequestExtraData* old_extra_data =
3217 static_cast<RequestExtraData*>(request.extraData());
3219 custom_user_agent = old_extra_data->custom_user_agent();
3220 if (!custom_user_agent.isNull()) {
3221 if (custom_user_agent.isEmpty())
3222 request.clearHTTPHeaderField("User-Agent");
3223 else
3224 request.setHTTPHeaderField("User-Agent", custom_user_agent);
3227 requested_with = old_extra_data->requested_with();
3228 if (!requested_with.isNull()) {
3229 if (requested_with.isEmpty())
3230 request.clearHTTPHeaderField("X-Requested-With");
3231 else
3232 request.setHTTPHeaderField("X-Requested-With", requested_with);
3234 stream_override = old_extra_data->TakeStreamOverrideOwnership();
3237 // Add the default accept header for frame request if it has not been set
3238 // already.
3239 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3240 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
3241 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
3242 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
3243 WebString::fromUTF8(kDefaultAcceptHeader));
3246 // Add an empty HTTP origin header for non GET methods if none is currently
3247 // present.
3248 request.addHTTPOriginIfNeeded(WebString());
3250 // Attach |should_replace_current_entry| state to requests so that, should
3251 // this navigation later require a request transfer, all state is preserved
3252 // when it is re-created in the new process.
3253 bool should_replace_current_entry = false;
3254 if (navigation_state->IsContentInitiated()) {
3255 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
3256 } else {
3257 // If the navigation is browser-initiated, the NavigationState contains the
3258 // correct value instead of the WebDataSource.
3260 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3261 // NavigationState::should_replace_current_entry().
3262 should_replace_current_entry =
3263 navigation_state->start_params().should_replace_current_entry;
3266 int provider_id = kInvalidServiceWorkerProviderId;
3267 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3268 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
3269 // |provisionalDataSource| may be null in some content::ResourceFetcher
3270 // use cases, we don't hook those requests.
3271 if (frame->provisionalDataSource()) {
3272 ServiceWorkerNetworkProvider* provider =
3273 ServiceWorkerNetworkProvider::FromDocumentState(
3274 DocumentState::FromDataSource(frame->provisionalDataSource()));
3275 provider_id = provider->provider_id();
3277 } else if (frame->dataSource()) {
3278 ServiceWorkerNetworkProvider* provider =
3279 ServiceWorkerNetworkProvider::FromDocumentState(
3280 DocumentState::FromDataSource(frame->dataSource()));
3281 provider_id = provider->provider_id();
3284 WebFrame* parent = frame->parent();
3285 int parent_routing_id = MSG_ROUTING_NONE;
3286 if (!parent) {
3287 parent_routing_id = -1;
3288 } else if (parent->isWebLocalFrame()) {
3289 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
3290 } else {
3291 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
3294 RequestExtraData* extra_data = new RequestExtraData();
3295 extra_data->set_visibility_state(render_view_->visibilityState());
3296 extra_data->set_custom_user_agent(custom_user_agent);
3297 extra_data->set_requested_with(requested_with);
3298 extra_data->set_render_frame_id(routing_id_);
3299 extra_data->set_is_main_frame(!parent);
3300 extra_data->set_frame_origin(
3301 GURL(frame->document().securityOrigin().toString()));
3302 extra_data->set_parent_is_main_frame(parent && !parent->parent());
3303 extra_data->set_parent_render_frame_id(parent_routing_id);
3304 extra_data->set_allow_download(
3305 navigation_state->common_params().allow_download);
3306 extra_data->set_transition_type(transition_type);
3307 extra_data->set_should_replace_current_entry(should_replace_current_entry);
3308 extra_data->set_transferred_request_child_id(
3309 navigation_state->start_params().transferred_request_child_id);
3310 extra_data->set_transferred_request_request_id(
3311 navigation_state->start_params().transferred_request_request_id);
3312 extra_data->set_service_worker_provider_id(provider_id);
3313 extra_data->set_stream_override(stream_override.Pass());
3314 request.setExtraData(extra_data);
3316 WebFrame* top_frame = frame->top();
3317 // TODO(nasko): Hack around asking about top-frame data source. This means
3318 // for out-of-process iframes we are treating the current frame as the
3319 // top-level frame, which is wrong.
3320 if (!top_frame || top_frame->isWebRemoteFrame())
3321 top_frame = frame;
3322 DocumentState* top_document_state =
3323 DocumentState::FromDataSource(top_frame->dataSource());
3324 if (top_document_state) {
3325 // TODO(gavinp): separate out prefetching and prerender field trials
3326 // if the rel=prerender rel type is sticking around.
3327 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
3328 top_document_state->set_was_prefetcher(true);
3331 // This is an instance where we embed a copy of the routing id
3332 // into the data portion of the message. This can cause problems if we
3333 // don't register this id on the browser side, since the download manager
3334 // expects to find a RenderViewHost based off the id.
3335 request.setRequestorID(render_view_->GetRoutingID());
3336 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3338 if (!navigation_state->start_params().extra_headers.empty()) {
3339 for (net::HttpUtil::HeadersIterator i(
3340 navigation_state->start_params().extra_headers.begin(),
3341 navigation_state->start_params().extra_headers.end(), "\n");
3342 i.GetNext();) {
3343 if (LowerCaseEqualsASCII(i.name(), "referer")) {
3344 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
3345 blink::WebReferrerPolicyDefault,
3346 request.url(),
3347 WebString::fromUTF8(i.values()));
3348 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
3349 } else {
3350 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
3351 WebString::fromUTF8(i.values()));
3356 if (!render_view_->renderer_preferences_.enable_referrers)
3357 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
3360 void RenderFrameImpl::didReceiveResponse(
3361 blink::WebLocalFrame* frame,
3362 unsigned identifier,
3363 const blink::WebURLResponse& response) {
3364 DCHECK(!frame_ || frame_ == frame);
3365 // Only do this for responses that correspond to a provisional data source
3366 // of the top-most frame. If we have a provisional data source, then we
3367 // can't have any sub-resources yet, so we know that this response must
3368 // correspond to a frame load.
3369 if (!frame->provisionalDataSource() || frame->parent())
3370 return;
3372 // If we are in view source mode, then just let the user see the source of
3373 // the server's error page.
3374 if (frame->isViewSourceModeEnabled())
3375 return;
3377 DocumentState* document_state =
3378 DocumentState::FromDataSource(frame->provisionalDataSource());
3379 int http_status_code = response.httpStatusCode();
3381 // Record page load flags.
3382 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3383 if (extra_data) {
3384 document_state->set_was_fetched_via_spdy(
3385 extra_data->was_fetched_via_spdy());
3386 document_state->set_was_npn_negotiated(
3387 extra_data->was_npn_negotiated());
3388 document_state->set_npn_negotiated_protocol(
3389 extra_data->npn_negotiated_protocol());
3390 document_state->set_was_alternate_protocol_available(
3391 extra_data->was_alternate_protocol_available());
3392 document_state->set_connection_info(
3393 extra_data->connection_info());
3394 document_state->set_was_fetched_via_proxy(
3395 extra_data->was_fetched_via_proxy());
3396 document_state->set_proxy_server(
3397 extra_data->proxy_server());
3399 InternalDocumentStateData* internal_data =
3400 InternalDocumentStateData::FromDocumentState(document_state);
3401 internal_data->set_http_status_code(http_status_code);
3402 // Whether or not the http status code actually corresponds to an error is
3403 // only checked when the page is done loading, if |use_error_page| is
3404 // still true.
3405 internal_data->set_use_error_page(true);
3408 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
3409 unsigned identifier) {
3410 DCHECK(!frame_ || frame_ == frame);
3411 InternalDocumentStateData* internal_data =
3412 InternalDocumentStateData::FromDataSource(frame->dataSource());
3413 if (!internal_data->use_error_page())
3414 return;
3416 // Do not show error page when DevTools is attached.
3417 RenderFrameImpl* localRoot = this;
3418 while (localRoot->frame_ && localRoot->frame_->parent() &&
3419 localRoot->frame_->parent()->isWebLocalFrame()) {
3420 localRoot = RenderFrameImpl::FromWebFrame(localRoot->frame_->parent());
3421 DCHECK(localRoot);
3423 if (localRoot->devtools_agent_ && localRoot->devtools_agent_->IsAttached())
3424 return;
3426 // Display error page, if appropriate.
3427 std::string error_domain = "http";
3428 int http_status_code = internal_data->http_status_code();
3429 if (GetContentClient()->renderer()->HasErrorPage(
3430 http_status_code, &error_domain)) {
3431 WebURLError error;
3432 error.unreachableURL = frame->document().url();
3433 error.domain = WebString::fromUTF8(error_domain);
3434 error.reason = http_status_code;
3435 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
3439 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3440 blink::WebLocalFrame* frame,
3441 const blink::WebURLRequest& request,
3442 const blink::WebURLResponse& response) {
3443 DCHECK(!frame_ || frame_ == frame);
3444 // The recipients of this message have no use for data: URLs: they don't
3445 // affect the page's insecure content list and are not in the disk cache. To
3446 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3447 // filter them out here.
3448 GURL url(request.url());
3449 if (url.SchemeIs(url::kDataScheme))
3450 return;
3452 // Let the browser know we loaded a resource from the memory cache. This
3453 // message is needed to display the correct SSL indicators.
3454 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3455 render_view_->GetRoutingID(),
3456 url,
3457 response.securityInfo(),
3458 request.httpMethod().utf8(),
3459 response.mimeType().utf8(),
3460 WebURLRequestToResourceType(request)));
3463 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3464 DCHECK(!frame_ || frame_ == frame);
3465 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
3466 render_view_->GetRoutingID()));
3469 void RenderFrameImpl::didRunInsecureContent(
3470 blink::WebLocalFrame* frame,
3471 const blink::WebSecurityOrigin& origin,
3472 const blink::WebURL& target) {
3473 DCHECK(!frame_ || frame_ == frame);
3474 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
3475 render_view_->GetRoutingID(),
3476 origin.toString().utf8(),
3477 target));
3480 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3481 DCHECK(!frame_ || frame_ == frame);
3482 #if defined(ENABLE_PLUGINS)
3483 if (frame != render_view_->webview()->mainFrame())
3484 return;
3485 PluginChannelHost::Broadcast(
3486 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3487 #endif
3490 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3491 v8::Handle<v8::Context> context,
3492 int extension_group,
3493 int world_id) {
3494 DCHECK(!frame_ || frame_ == frame);
3496 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
3497 DidCreateScriptContext(context, extension_group, world_id));
3500 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3501 v8::Handle<v8::Context> context,
3502 int world_id) {
3503 DCHECK(!frame_ || frame_ == frame);
3505 FOR_EACH_OBSERVER(RenderFrameObserver,
3506 observers_,
3507 WillReleaseScriptContext(context, world_id));
3510 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3511 blink::WebLocalFrame* frame) {
3512 DCHECK(!frame_ || frame_ == frame);
3513 if (frame->parent())
3514 return;
3516 InternalDocumentStateData* data =
3517 InternalDocumentStateData::FromDataSource(frame->dataSource());
3518 data->set_did_first_visually_non_empty_layout(true);
3520 #if defined(OS_ANDROID)
3521 GetRenderWidget()->DidChangeBodyBackgroundColor(
3522 render_view_->webwidget_->backgroundColor());
3523 #endif
3525 GetRenderWidget()->QueueMessage(
3526 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3527 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3530 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3531 DCHECK(!frame_ || frame_ == frame);
3532 // TODO(nasko): Move implementation here. Needed methods:
3533 // * StartNavStateSyncTimerIfNecessary
3534 render_view_->didChangeScrollOffset(frame);
3536 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeScrollOffset());
3539 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3540 DCHECK(!frame_ || frame_ == frame);
3541 if (!frame->parent()) {
3542 render_view_->Send(new ViewHostMsg_WillInsertBody(
3543 render_view_->GetRoutingID()));
3547 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3548 int count,
3549 bool final_update) {
3550 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3551 if (!count)
3552 active_match_ordinal = 0;
3554 render_view_->Send(new ViewHostMsg_Find_Reply(
3555 render_view_->GetRoutingID(), request_id, count,
3556 gfx::Rect(), active_match_ordinal, final_update));
3559 void RenderFrameImpl::reportFindInPageSelection(
3560 int request_id,
3561 int active_match_ordinal,
3562 const blink::WebRect& selection_rect) {
3563 render_view_->Send(new ViewHostMsg_Find_Reply(
3564 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3565 active_match_ordinal, false));
3568 void RenderFrameImpl::requestStorageQuota(
3569 blink::WebLocalFrame* frame,
3570 blink::WebStorageQuotaType type,
3571 unsigned long long requested_size,
3572 blink::WebStorageQuotaCallbacks callbacks) {
3573 DCHECK(!frame_ || frame_ == frame);
3574 WebSecurityOrigin origin = frame->document().securityOrigin();
3575 if (origin.isUnique()) {
3576 // Unique origins cannot store persistent state.
3577 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3578 return;
3580 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3581 render_view_->GetRoutingID(),
3582 GURL(origin.toString()),
3583 static_cast<storage::StorageType>(type),
3584 requested_size,
3585 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3588 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3589 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3590 impl->set_render_frame_id(routing_id_);
3593 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3594 if (!geolocation_dispatcher_)
3595 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3596 return geolocation_dispatcher_;
3599 blink::WebPresentationClient* RenderFrameImpl::presentationClient() {
3600 if (!presentation_dispatcher_)
3601 presentation_dispatcher_ = new PresentationDispatcher(this);
3602 return presentation_dispatcher_;
3605 blink::WebPushClient* RenderFrameImpl::pushClient() {
3606 if (!push_messaging_dispatcher_)
3607 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3608 return push_messaging_dispatcher_;
3611 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3612 blink::WebLocalFrame* frame,
3613 blink::WebRTCPeerConnectionHandler* handler) {
3614 DCHECK(!frame_ || frame_ == frame);
3615 #if defined(ENABLE_WEBRTC)
3616 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3617 #endif
3620 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3621 if (!web_user_media_client_)
3622 InitializeUserMediaClient();
3623 return web_user_media_client_;
3626 blink::WebEncryptedMediaClient* RenderFrameImpl::encryptedMediaClient() {
3627 if (!web_encrypted_media_client_) {
3628 web_encrypted_media_client_.reset(new media::WebEncryptedMediaClientImpl(
3629 GetCdmFactory(), GetMediaPermission()));
3631 return web_encrypted_media_client_.get();
3634 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3635 if (!midi_dispatcher_)
3636 midi_dispatcher_ = new MidiDispatcher(this);
3637 return midi_dispatcher_;
3640 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3641 blink::WebLocalFrame* source_frame,
3642 blink::WebFrame* target_frame,
3643 blink::WebSecurityOrigin target_origin,
3644 blink::WebDOMMessageEvent event) {
3645 DCHECK(!frame_ || frame_ == target_frame);
3647 // Currently, a postMessage that targets a cross-process frame can be plumbed
3648 // either through this function or RenderFrameProxy::postMessageEvent. This
3649 // function is used when the target cross-process frame is a top-level frame
3650 // which has been swapped out. In that case, the corresponding WebLocalFrame
3651 // currently remains in the frame tree even in site-per-process mode (see
3652 // OnSwapOut). RenderFrameProxy::postMessageEvent is used in
3653 // --site-per-process mode for all other cases.
3655 // TODO(alexmos, nasko): When swapped-out:// disappears, this should be
3656 // cleaned up so that RenderFrameProxy::postMessageEvent is the only path for
3657 // cross-process postMessages.
3658 if (!is_swapped_out_)
3659 return false;
3661 // It is possible to get here on a swapped-out frame without a
3662 // |render_frame_proxy_|. This happens when:
3663 // - This process only has one active RenderView and is about to go away
3664 // (e.g., due to cross-process navigation).
3665 // - The top frame has a subframe with an unload handler.
3666 // - The subframe sends a postMessage to the top-level frame in its unload
3667 // handler.
3668 // See https://crbug.com/475651 for details. We return false here, since we
3669 // don't want to deliver the message to the new process in this case.
3670 if (!render_frame_proxy_)
3671 return false;
3673 render_frame_proxy_->postMessageEvent(
3674 source_frame, render_frame_proxy_->web_frame(), target_origin, event);
3675 return true;
3678 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3679 const blink::WebURL& url) {
3680 DCHECK(!frame_ || frame_ == frame);
3681 std::string user_agent_override_for_url =
3682 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3683 if (!user_agent_override_for_url.empty())
3684 return WebString::fromUTF8(user_agent_override_for_url);
3686 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3687 render_view_->renderer_preferences_.user_agent_override.empty()) {
3688 return blink::WebString();
3691 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3692 // associated with it, so the checks below are not valid. Temporarily
3693 // return early and fix properly as part of https://crbug.com/426555.
3694 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3695 return blink::WebString();
3697 // If we're in the middle of committing a load, the data source we need
3698 // will still be provisional.
3699 WebFrame* main_frame = render_view_->webview()->mainFrame();
3700 WebDataSource* data_source = NULL;
3701 if (main_frame->provisionalDataSource())
3702 data_source = main_frame->provisionalDataSource();
3703 else
3704 data_source = main_frame->dataSource();
3706 InternalDocumentStateData* internal_data = data_source ?
3707 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3708 if (internal_data && internal_data->is_overriding_user_agent())
3709 return WebString::fromUTF8(
3710 render_view_->renderer_preferences_.user_agent_override);
3711 return blink::WebString();
3714 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3715 DCHECK(!frame_ || frame_ == frame);
3716 if (render_view_->renderer_preferences_.enable_do_not_track)
3717 return WebString::fromUTF8("1");
3718 return WebString();
3721 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3722 bool default_value) {
3723 DCHECK(!frame_ || frame_ == frame);
3724 if (!default_value)
3725 return false;
3727 bool blocked = true;
3728 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3729 render_view_->GetRoutingID(),
3730 GURL(frame->top()->document().securityOrigin().toString()),
3731 THREE_D_API_TYPE_WEBGL,
3732 &blocked));
3733 return !blocked;
3736 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3737 int arb_robustness_status_code) {
3738 DCHECK(!frame_ || frame_ == frame);
3739 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3740 GURL(frame->top()->document().securityOrigin().toString()),
3741 THREE_D_API_TYPE_WEBGL,
3742 arb_robustness_status_code));
3745 blink::WebScreenOrientationClient*
3746 RenderFrameImpl::webScreenOrientationClient() {
3747 if (!screen_orientation_dispatcher_)
3748 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3749 return screen_orientation_dispatcher_;
3752 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3753 ServiceWorkerNetworkProvider* provider =
3754 ServiceWorkerNetworkProvider::FromDocumentState(
3755 DocumentState::FromDataSource(&data_source));
3756 return provider->context()->controller_handle_id() !=
3757 kInvalidServiceWorkerHandleId;
3760 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3761 ServiceWorkerNetworkProvider* provider =
3762 ServiceWorkerNetworkProvider::FromDocumentState(
3763 DocumentState::FromDataSource(&data_source));
3765 if (provider->context()->controller())
3766 return provider->context()->controller()->version_id();
3767 return kInvalidServiceWorkerVersionId;
3770 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3771 blink::WebAXEvent event) {
3772 HandleWebAccessibilityEvent(obj, event);
3775 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3776 int identifier,
3777 int match_index,
3778 const blink::WebAXObject& start_object,
3779 int start_offset,
3780 const blink::WebAXObject& end_object,
3781 int end_offset) {
3782 if (renderer_accessibility_) {
3783 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3784 identifier, match_index, start_object, start_offset,
3785 end_object, end_offset);
3789 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame) {
3790 DCHECK(!frame_ || frame_ == frame);
3792 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3795 void RenderFrameImpl::didChangeDefaultPresentation(
3796 blink::WebLocalFrame* frame) {
3797 DCHECK(!frame_ || frame_ == frame);
3799 FOR_EACH_OBSERVER(
3800 RenderFrameObserver, observers_, DidChangeDefaultPresentation());
3803 bool RenderFrameImpl::enterFullscreen() {
3804 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, true));
3805 return true;
3808 bool RenderFrameImpl::exitFullscreen() {
3809 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, false));
3810 return true;
3813 blink::WebPermissionClient* RenderFrameImpl::permissionClient() {
3814 if (!permission_client_)
3815 permission_client_.reset(new PermissionDispatcher(GetServiceRegistry()));
3817 return permission_client_.get();
3820 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3821 Send(new FrameHostMsg_MediaPlayingNotification(
3822 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3823 player->hasAudio(), player->isRemote()));
3826 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3827 Send(new FrameHostMsg_MediaPausedNotification(
3828 routing_id_, reinterpret_cast<int64>(player)));
3831 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3832 DidPause(player);
3835 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3836 observers_.AddObserver(observer);
3839 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3840 observer->RenderFrameGone();
3841 observers_.RemoveObserver(observer);
3844 void RenderFrameImpl::OnStop() {
3845 DCHECK(frame_);
3846 frame_->stopLoading();
3847 if (!frame_->parent())
3848 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3850 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3853 void RenderFrameImpl::WasHidden() {
3854 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3857 void RenderFrameImpl::WasShown() {
3858 // TODO(kenrb): Need to figure out how to do this better. Should
3859 // VisibilityState remain a page-level concept or move to frames?
3860 // The semantics of 'Show' might have to change here.
3861 if (render_widget_) {
3862 static_cast<blink::WebFrameWidget*>(render_widget_->webwidget())->
3863 setVisibilityState(blink::WebPageVisibilityStateVisible, false);
3865 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3868 void RenderFrameImpl::WidgetWillClose() {
3869 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WidgetWillClose());
3872 bool RenderFrameImpl::IsHidden() {
3873 return GetRenderWidget()->is_hidden();
3876 // Tell the embedding application that the URL of the active page has changed.
3877 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3878 blink::WebFrame* frame,
3879 blink::WebHistoryCommitType commit_type) {
3880 DCHECK(!frame_ || frame_ == frame);
3881 WebDataSource* ds = frame->dataSource();
3882 DCHECK(ds);
3884 const WebURLRequest& request = ds->request();
3885 const WebURLResponse& response = ds->response();
3887 DocumentState* document_state = DocumentState::FromDataSource(ds);
3888 NavigationStateImpl* navigation_state =
3889 static_cast<NavigationStateImpl*>(document_state->navigation_state());
3890 InternalDocumentStateData* internal_data =
3891 InternalDocumentStateData::FromDocumentState(document_state);
3893 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3894 params.http_status_code = response.httpStatusCode();
3895 params.url_is_unreachable = ds->hasUnreachableURL();
3896 params.is_post = false;
3897 params.post_id = -1;
3898 params.page_id = render_view_->page_id_;
3899 // We need to track the RenderViewHost routing_id because of downstream
3900 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3901 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3902 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3903 // based on the ID stored in the resource requests. Once those dependencies
3904 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3905 // client to be based on the routing_id of the RenderFrameHost.
3906 params.render_view_routing_id = render_view_->routing_id();
3907 params.socket_address.set_host(response.remoteIPAddress().utf8());
3908 params.socket_address.set_port(response.remotePort());
3909 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3910 if (extra_data)
3911 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3912 params.was_within_same_page = navigation_state->WasWithinSamePage();
3913 params.security_info = response.securityInfo();
3915 // Set the URL to be displayed in the browser UI to the user.
3916 params.url = GetLoadingUrl();
3917 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3919 // Set the origin of the frame. This will be replicated to the corresponding
3920 // RenderFrameProxies in other processes.
3921 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3922 // to https://crbug.com/439608 and will be replicated as unique origins.
3923 if (!is_swapped_out_) {
3924 WebString serialized_origin(frame->document().securityOrigin().toString());
3925 if (GURL(serialized_origin).IsStandard())
3926 params.origin = url::Origin(serialized_origin.utf8());
3929 if (frame->document().baseURL() != params.url)
3930 params.base_url = frame->document().baseURL();
3932 GetRedirectChain(ds, &params.redirects);
3933 params.should_update_history = !ds->hasUnreachableURL() &&
3934 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3936 params.searchable_form_url = internal_data->searchable_form_url();
3937 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3939 params.gesture = render_view_->navigation_gesture_;
3940 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3942 // Make navigation state a part of the DidCommitProvisionalLoad message so
3943 // that committed entry has it at all times.
3944 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3945 if (entry)
3946 params.page_state = HistoryEntryToPageState(entry);
3947 else
3948 params.page_state = PageState::CreateFromURL(request.url());
3950 if (!frame->parent()) {
3951 // Top-level navigation.
3953 // Reset the zoom limits in case a plugin had changed them previously. This
3954 // will also call us back which will cause us to send a message to
3955 // update WebContentsImpl.
3956 render_view_->webview()->zoomLimitsChanged(
3957 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3958 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3960 // Set zoom level, but don't do it for full-page plugin since they don't use
3961 // the same zoom settings.
3962 HostZoomLevels::iterator host_zoom =
3963 render_view_->host_zoom_levels_.find(GURL(request.url()));
3964 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3965 // Reset the zoom levels for plugins.
3966 render_view_->webview()->setZoomLevel(0);
3967 } else {
3968 // If the zoom level is not found, then do nothing. In-page navigation
3969 // relies on not changing the zoom level in this case.
3970 if (host_zoom != render_view_->host_zoom_levels_.end())
3971 render_view_->webview()->setZoomLevel(host_zoom->second);
3974 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3975 // This zoom level was merely recorded transiently for this load. We can
3976 // erase it now. If at some point we reload this page, the browser will
3977 // send us a new, up-to-date zoom level.
3978 render_view_->host_zoom_levels_.erase(host_zoom);
3981 // Update contents MIME type for main frame.
3982 params.contents_mime_type = ds->response().mimeType().utf8();
3984 params.transition = navigation_state->GetTransitionType();
3985 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3986 // If the main frame does a load, it should not be reported as a subframe
3987 // navigation. This can occur in the following case:
3988 // 1. You're on a site with frames.
3989 // 2. You do a subframe navigation. This is stored with transition type
3990 // MANUAL_SUBFRAME.
3991 // 3. You navigate to some non-frame site, say, google.com.
3992 // 4. You navigate back to the page from step 2. Since it was initially
3993 // MANUAL_SUBFRAME, it will be that same transition type here.
3994 // We don't want that, because any navigation that changes the toplevel
3995 // frame should be tracked as a toplevel navigation (this allows us to
3996 // update the URL bar, etc).
3997 params.transition = ui::PAGE_TRANSITION_LINK;
4000 // If the page contained a client redirect (meta refresh, document.loc...),
4001 // set the referrer and transition appropriately.
4002 if (ds->isClientRedirect()) {
4003 params.referrer =
4004 Referrer(params.redirects[0], ds->request().referrerPolicy());
4005 params.transition = ui::PageTransitionFromInt(
4006 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
4007 } else {
4008 params.referrer = RenderViewImpl::GetReferrerFromRequest(
4009 frame, ds->request());
4012 base::string16 method = request.httpMethod();
4013 if (EqualsASCII(method, "POST")) {
4014 params.is_post = true;
4015 params.post_id = ExtractPostId(entry);
4018 // Send the user agent override back.
4019 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
4021 // Track the URL of the original request. We use the first entry of the
4022 // redirect chain if it exists because the chain may have started in another
4023 // process.
4024 params.original_request_url = GetOriginalRequestURL(ds);
4026 params.history_list_was_cleared =
4027 navigation_state->request_params().should_clear_history_list;
4029 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
4030 frame->dataSource()->request().inputPerfMetricReportPolicy());
4031 params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD(
4032 frame->dataSource()->request().uiStartTime());
4034 // Save some histogram data so we can compute the average memory used per
4035 // page load of the glyphs.
4036 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
4037 blink::WebGlyphCache::pageCount());
4039 // This message needs to be sent before any of allowScripts(),
4040 // allowImages(), allowPlugins() is called for the new page, so that when
4041 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
4042 // after the FrameHostMsg_DidCommitProvisionalLoad message.
4043 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4044 } else {
4045 // Subframe navigation: the type depends on whether this navigation
4046 // generated a new session history entry. When they do generate a session
4047 // history entry, it means the user initiated the navigation and we should
4048 // mark it as such.
4049 if (commit_type == blink::WebStandardCommit)
4050 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
4051 else
4052 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
4054 DCHECK(!navigation_state->request_params().should_clear_history_list);
4055 params.history_list_was_cleared = false;
4056 params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT;
4058 // Don't send this message while the subframe is swapped out.
4059 if (!is_swapped_out())
4060 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
4063 // If we end up reusing this WebRequest (for example, due to a #ref click),
4064 // we don't want the transition type to persist. Just clear it.
4065 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
4068 void RenderFrameImpl::didStartLoading(bool to_different_document) {
4069 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
4070 "id", routing_id_);
4071 render_view_->FrameDidStartLoading(frame_);
4072 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
4075 void RenderFrameImpl::didStopLoading() {
4076 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
4077 "id", routing_id_);
4078 render_view_->FrameDidStopLoading(frame_);
4079 Send(new FrameHostMsg_DidStopLoading(routing_id_));
4082 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
4083 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
4086 void RenderFrameImpl::HandleWebAccessibilityEvent(
4087 const blink::WebAXObject& obj, blink::WebAXEvent event) {
4088 if (renderer_accessibility_)
4089 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
4092 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
4093 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FocusedNodeChanged(node));
4096 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) {
4097 if (renderer_accessibility())
4098 renderer_accessibility()->AccessibilityFocusedNodeChanged(node);
4101 // PlzNavigate
4102 void RenderFrameImpl::OnCommitNavigation(
4103 const ResourceResponseHead& response,
4104 const GURL& stream_url,
4105 const CommonNavigationParams& common_params,
4106 const RequestNavigationParams& request_params) {
4107 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4108 switches::kEnableBrowserSideNavigation));
4109 bool is_reload = false;
4110 bool is_history_navigation = request_params.page_state.IsValid();
4111 WebURLRequest::CachePolicy cache_policy =
4112 WebURLRequest::UseProtocolCachePolicy;
4113 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4114 common_params.url, is_history_navigation, request_params, &is_reload,
4115 &cache_policy)) {
4116 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4117 return;
4120 GetContentClient()->SetActiveURL(common_params.url);
4122 pending_navigation_params_.reset(new NavigationParams(
4123 common_params, StartNavigationParams(), request_params));
4125 if (!common_params.base_url_for_data_url.is_empty() ||
4126 common_params.url.SchemeIs(url::kDataScheme)) {
4127 LoadDataURL(common_params, frame_);
4128 return;
4131 // Create a WebURLRequest that blink can use to get access to the body of the
4132 // response through a stream in the browser. Blink will then commit the
4133 // navigation.
4134 // TODO(clamy): Have the navigation commit directly, without going through
4135 // loading a WebURLRequest.
4136 scoped_ptr<StreamOverrideParameters> stream_override(
4137 new StreamOverrideParameters());
4138 stream_override->stream_url = stream_url;
4139 stream_override->response = response;
4140 WebURLRequest request =
4141 CreateURLRequestForNavigation(common_params,
4142 stream_override.Pass(),
4143 frame_->isViewSourceModeEnabled());
4145 // Make sure that blink loader will not try to use browser side navigation for
4146 // this request (since it already went to the browser).
4147 request.setCheckForBrowserSideNavigation(false);
4149 // Record this before starting the load. A lower bound of this time is needed
4150 // to sanitize the navigationStart override set below.
4151 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
4152 frame_->loadRequest(request);
4153 UpdateFrameNavigationTiming(frame_, request_params.browser_navigation_start,
4154 renderer_navigation_start);
4157 void RenderFrameImpl::OnFailedNavigation(
4158 const CommonNavigationParams& common_params,
4159 const RequestNavigationParams& request_params,
4160 bool has_stale_copy_in_cache,
4161 int error_code) {
4162 bool is_reload = IsReload(common_params.navigation_type);
4163 bool is_history_navigation = request_params.page_state.IsValid();
4164 WebURLRequest::CachePolicy cache_policy =
4165 WebURLRequest::UseProtocolCachePolicy;
4166 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
4167 common_params.url, is_history_navigation, request_params, &is_reload,
4168 &cache_policy)) {
4169 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4170 return;
4173 GetContentClient()->SetActiveURL(common_params.url);
4175 pending_navigation_params_.reset(new NavigationParams(
4176 common_params, StartNavigationParams(), request_params));
4178 // Inform the browser of the start of the provisional load. This is needed so
4179 // that the load is properly tracked by the WebNavigation API.
4180 // TODO(clamy): Properly set is_transition_navigation.
4181 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
4182 routing_id_, common_params.url, false));
4184 // Send the provisional load failure.
4185 blink::WebURLError error =
4186 CreateWebURLError(common_params.url, has_stale_copy_in_cache, error_code);
4187 WebURLRequest failed_request = CreateURLRequestForNavigation(
4188 common_params, scoped_ptr<StreamOverrideParameters>(),
4189 frame_->isViewSourceModeEnabled());
4190 SendFailedProvisionalLoad(failed_request, error, frame_);
4192 if (!ShouldDisplayErrorPageForFailedLoad(error_code, common_params.url)) {
4193 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
4194 return;
4197 // Make sure errors are not shown in view source mode.
4198 frame_->enableViewSourceMode(false);
4200 // Replace the current history entry in reloads, history navigations and loads
4201 // of the same url. This corresponds to Blink's notion of a standard
4202 // commit.
4203 // TODO(clamy): see if initial commits in subframes should be handled
4204 // separately.
4205 bool replace = is_reload || is_history_navigation ||
4206 common_params.url == GetLoadingUrl();
4207 LoadNavigationErrorPage(failed_request, error, replace);
4210 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
4211 RenderFrame* render_frame,
4212 const NavigationPolicyInfo& info) {
4213 #ifdef OS_ANDROID
4214 // The handlenavigation API is deprecated and will be removed once
4215 // crbug.com/325351 is resolved.
4216 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
4217 GetContentClient()->renderer()->HandleNavigation(
4218 render_frame,
4219 static_cast<DocumentState*>(info.extraData),
4220 render_view_->opener_id_,
4221 info.frame,
4222 info.urlRequest,
4223 info.navigationType,
4224 info.defaultPolicy,
4225 info.isRedirect)) {
4226 return blink::WebNavigationPolicyIgnore;
4228 #endif
4230 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
4231 info.urlRequest));
4232 const base::CommandLine& command_line =
4233 *base::CommandLine::ForCurrentProcess();
4235 bool is_subframe = !!info.frame->parent();
4237 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe) {
4238 // There's no reason to ignore navigations on subframes, since the swap out
4239 // logic no longer applies.
4240 } else {
4241 if (is_swapped_out_) {
4242 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
4243 // Targeted links may try to navigate a swapped out frame. Allow the
4244 // browser process to navigate the tab instead. Note that it is also
4245 // possible for non-targeted navigations (from this view) to arrive
4246 // here just after we are swapped out. It's ok to send them to the
4247 // browser, as long as they're for the top level frame.
4248 // TODO(creis): Ensure this supports targeted form submissions when
4249 // fixing http://crbug.com/101395.
4250 if (info.frame->parent() == NULL) {
4251 OpenURL(info.frame, info.urlRequest.url(), referrer,
4252 info.defaultPolicy);
4253 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4256 // We should otherwise ignore in-process iframe navigations, if they
4257 // arrive just after we are swapped out.
4258 return blink::WebNavigationPolicyIgnore;
4261 // Allow kSwappedOutURL to complete.
4262 return info.defaultPolicy;
4266 // Webkit is asking whether to navigate to a new URL.
4267 // This is fine normally, except if we're showing UI from one security
4268 // context and they're trying to navigate to a different context.
4269 const GURL& url = info.urlRequest.url();
4271 // A content initiated navigation may have originated from a link-click,
4272 // script, drag-n-drop operation, etc.
4273 DocumentState* document_state = static_cast<DocumentState*>(info.extraData);
4274 bool is_content_initiated =
4275 document_state->navigation_state()->IsContentInitiated();
4277 // Experimental:
4278 // If --enable-strict-site-isolation is enabled, send all top-level
4279 // navigations to the browser to let it swap processes when crossing site
4280 // boundaries. This is currently expected to break some script calls and
4281 // navigations, such as form submissions.
4282 bool force_swap_due_to_flag =
4283 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
4284 if (force_swap_due_to_flag &&
4285 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
4286 WebString origin_str = info.frame->document().securityOrigin().toString();
4287 GURL frame_url(origin_str.utf8().data());
4288 // TODO(cevans): revisit whether this site check is still necessary once
4289 // crbug.com/101395 is fixed.
4290 bool same_domain_or_host =
4291 net::registry_controlled_domains::SameDomainOrHost(
4292 frame_url,
4293 url,
4294 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
4295 // Only keep same-site (domain + scheme) and data URLs in the same process.
4296 bool is_same_site =
4297 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
4298 url.SchemeIs(url::kDataScheme);
4299 if (!is_same_site) {
4300 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4301 return blink::WebNavigationPolicyIgnore;
4305 // If the browser is interested, then give it a chance to look at the request.
4306 if (is_content_initiated) {
4307 bool is_form_post =
4308 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
4309 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
4310 EqualsASCII(info.urlRequest.httpMethod(), "POST");
4311 bool browser_handles_request =
4312 render_view_->renderer_preferences_
4313 .browser_handles_non_local_top_level_requests
4314 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
4315 is_form_post);
4316 if (!browser_handles_request) {
4317 browser_handles_request = IsTopLevelNavigation(info.frame) &&
4318 render_view_->renderer_preferences_
4319 .browser_handles_all_top_level_requests;
4322 if (browser_handles_request) {
4323 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4324 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4328 // Use the frame's original request's URL rather than the document's URL for
4329 // subsequent checks. For a popup, the document's URL may become the opener
4330 // window's URL if the opener has called document.write().
4331 // See http://crbug.com/93517.
4332 GURL old_url(info.frame->dataSource()->request().url());
4334 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4335 // an extension or app origin, leaving a WebUI page, etc). We only care about
4336 // top-level navigations (not iframes). But we sometimes navigate to
4337 // about:blank to clear a tab, and we want to still allow that.
4339 // Note: this is known to break POST submissions when crossing process
4340 // boundaries until http://crbug.com/101395 is fixed. This is better for
4341 // security than loading a WebUI, extension or app page in the wrong process.
4342 // POST requests don't work because this mechanism does not preserve form
4343 // POST data. We will need to send the request's httpBody data up to the
4344 // browser process, and issue a special POST navigation in WebKit (via
4345 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4346 // for examples of how to send the httpBody data.
4347 if (!info.frame->parent() && is_content_initiated &&
4348 !url.SchemeIs(url::kAboutScheme)) {
4349 bool send_referrer = false;
4351 // All navigations to or from WebUI URLs or within WebUI-enabled
4352 // RenderProcesses must be handled by the browser process so that the
4353 // correct bindings and data sources can be registered.
4354 // Similarly, navigations to view-source URLs or within ViewSource mode
4355 // must be handled by the browser process (except for reloads - those are
4356 // safe to leave within the renderer).
4357 // Lastly, access to file:// URLs from non-file:// URL pages must be
4358 // handled by the browser so that ordinary renderer processes don't get
4359 // blessed with file permissions.
4360 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
4361 bool is_initial_navigation = render_view_->page_id_ == -1;
4362 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
4363 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
4364 url.SchemeIs(kViewSourceScheme) ||
4365 (info.frame->isViewSourceModeEnabled() &&
4366 info.navigationType != blink::WebNavigationTypeReload);
4368 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
4369 // Fork non-file to file opens. Check the opener URL if this is the
4370 // initial navigation in a newly opened window.
4371 GURL source_url(old_url);
4372 if (is_initial_navigation && source_url.is_empty() &&
4373 info.frame->opener())
4374 source_url = info.frame->opener()->top()->document().url();
4375 DCHECK(!source_url.is_empty());
4376 should_fork = !source_url.SchemeIs(url::kFileScheme);
4379 if (!should_fork) {
4380 // Give the embedder a chance.
4381 should_fork = GetContentClient()->renderer()->ShouldFork(
4382 info.frame, url, info.urlRequest.httpMethod().utf8(),
4383 is_initial_navigation, info.isRedirect, &send_referrer);
4386 if (should_fork) {
4387 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
4388 info.defaultPolicy);
4389 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4393 // Detect when a page is "forking" a new tab that can be safely rendered in
4394 // its own process. This is done by sites like Gmail that try to open links
4395 // in new windows without script connections back to the original page. We
4396 // treat such cases as browser navigations (in which we will create a new
4397 // renderer for a cross-site navigation), rather than WebKit navigations.
4399 // We use the following heuristic to decide whether to fork a new page in its
4400 // own process:
4401 // The parent page must open a new tab to about:blank, set the new tab's
4402 // window.opener to null, and then redirect the tab to a cross-site URL using
4403 // JavaScript.
4405 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4406 // (see below).
4407 bool is_fork =
4408 // Must start from a tab showing about:blank, which is later redirected.
4409 old_url == GURL(url::kAboutBlankURL) &&
4410 // Must be the first real navigation of the tab.
4411 render_view_->historyBackListCount() < 1 &&
4412 render_view_->historyForwardListCount() < 1 &&
4413 // The parent page must have set the child's window.opener to null before
4414 // redirecting to the desired URL.
4415 info.frame->opener() == NULL &&
4416 // Must be a top-level frame.
4417 info.frame->parent() == NULL &&
4418 // Must not have issued the request from this page.
4419 is_content_initiated &&
4420 // Must be targeted at the current tab.
4421 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
4422 // Must be a JavaScript navigation, which appears as "other".
4423 info.navigationType == blink::WebNavigationTypeOther;
4425 if (is_fork) {
4426 // Open the URL via the browser, not via WebKit.
4427 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
4428 return blink::WebNavigationPolicyIgnore;
4431 // PlzNavigate: send the request to the browser if needed.
4432 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4433 switches::kEnableBrowserSideNavigation) &&
4434 info.urlRequest.checkForBrowserSideNavigation()) {
4435 BeginNavigation(&info.urlRequest);
4436 return blink::WebNavigationPolicyIgnore;
4439 return info.defaultPolicy;
4442 void RenderFrameImpl::OpenURL(WebFrame* frame,
4443 const GURL& url,
4444 const Referrer& referrer,
4445 WebNavigationPolicy policy) {
4446 DCHECK_EQ(frame_, frame);
4448 FrameHostMsg_OpenURL_Params params;
4449 params.url = url;
4450 params.referrer = referrer;
4451 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
4452 WebDataSource* ds = frame->provisionalDataSource();
4453 if (ds) {
4454 DocumentState* document_state = DocumentState::FromDataSource(ds);
4455 NavigationStateImpl* navigation_state =
4456 static_cast<NavigationStateImpl*>(document_state->navigation_state());
4457 if (navigation_state->IsContentInitiated()) {
4458 params.should_replace_current_entry =
4459 ds->replacesCurrentHistoryItem() &&
4460 render_view_->history_list_length_;
4461 } else {
4462 // This is necessary to preserve the should_replace_current_entry value on
4463 // cross-process redirects, in the event it was set by a previous process.
4465 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4466 // NavigationState::should_replace_current_entry().
4467 params.should_replace_current_entry =
4468 navigation_state->start_params().should_replace_current_entry;
4470 } else {
4471 params.should_replace_current_entry = false;
4473 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
4474 if (GetContentClient()->renderer()->AllowPopup())
4475 params.user_gesture = true;
4477 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
4478 policy == blink::WebNavigationPolicyNewForegroundTab ||
4479 policy == blink::WebNavigationPolicyNewWindow ||
4480 policy == blink::WebNavigationPolicyNewPopup) {
4481 WebUserGestureIndicator::consumeUserGesture();
4484 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4487 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4488 const std::string& encoding_name) {
4489 // Only update main frame's encoding_name.
4490 if (!frame->parent())
4491 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4494 void RenderFrameImpl::SyncSelectionIfRequired() {
4495 base::string16 text;
4496 size_t offset;
4497 gfx::Range range;
4498 #if defined(ENABLE_PLUGINS)
4499 if (render_view_->focused_pepper_plugin_) {
4500 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4501 offset = 0; // Pepper API does not support offset reporting.
4502 // TODO(kinaba): cut as needed.
4503 } else
4504 #endif
4506 size_t location, length;
4507 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4508 &location, &length)) {
4509 return;
4512 range = gfx::Range(location, location + length);
4514 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4515 blink::WebTextInputTypeNone) {
4516 // If current focused element is editable, we will send 100 more chars
4517 // before and after selection. It is for input method surrounding text
4518 // feature.
4519 if (location > kExtraCharsBeforeAndAfterSelection)
4520 offset = location - kExtraCharsBeforeAndAfterSelection;
4521 else
4522 offset = 0;
4523 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4524 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4525 if (!webrange.isNull())
4526 text = webrange.toPlainText();
4527 } else {
4528 offset = location;
4529 text = frame_->selectionAsText();
4530 // http://crbug.com/101435
4531 // In some case, frame->selectionAsText() returned text's length is not
4532 // equal to the length returned from webwidget()->caretOrSelectionRange().
4533 // So we have to set the range according to text.length().
4534 range.set_end(range.start() + text.length());
4538 // Sometimes we get repeated didChangeSelection calls from webkit when
4539 // the selection hasn't actually changed. We don't want to report these
4540 // because it will cause us to continually claim the X clipboard.
4541 if (selection_text_offset_ != offset ||
4542 selection_range_ != range ||
4543 selection_text_ != text) {
4544 selection_text_ = text;
4545 selection_text_offset_ = offset;
4546 selection_range_ = range;
4547 SetSelectedText(text, offset, range);
4549 GetRenderWidget()->UpdateSelectionBounds();
4552 void RenderFrameImpl::InitializeUserMediaClient() {
4553 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4554 return;
4556 #if defined(OS_ANDROID)
4557 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4558 switches::kDisableWebRTC))
4559 return;
4560 #endif
4562 #if defined(ENABLE_WEBRTC)
4563 DCHECK(!web_user_media_client_);
4564 web_user_media_client_ = new UserMediaClientImpl(
4565 this,
4566 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4567 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4568 #endif
4571 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4572 const blink::WebURL& url,
4573 WebMediaPlayerClient* client) {
4574 #if defined(ENABLE_WEBRTC)
4575 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4576 bool found_neon =
4577 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4578 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4579 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4580 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4581 new RenderMediaLog(),
4582 CreateRendererFactory());
4583 #else
4584 return NULL;
4585 #endif // defined(ENABLE_WEBRTC)
4588 scoped_ptr<MediaStreamRendererFactory>
4589 RenderFrameImpl::CreateRendererFactory() {
4590 #if defined(ENABLE_WEBRTC)
4591 return scoped_ptr<MediaStreamRendererFactory>(
4592 new MediaStreamRendererFactory());
4593 #else
4594 return scoped_ptr<MediaStreamRendererFactory>(
4595 static_cast<MediaStreamRendererFactory*>(NULL));
4596 #endif
4599 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4600 const GURL& url,
4601 bool is_history_navigation,
4602 const RequestNavigationParams& request_params,
4603 bool* is_reload,
4604 WebURLRequest::CachePolicy* cache_policy) {
4605 MaybeHandleDebugURL(url);
4606 if (!render_view_->webview())
4607 return false;
4609 FOR_EACH_OBSERVER(
4610 RenderViewObserver, render_view_->observers_, Navigate(url));
4612 // If this is a stale back/forward (due to a recent navigation the browser
4613 // didn't know about), ignore it. Only check if swapped in because if the
4614 // frame is swapped out, it won't commit before asking the browser.
4615 if (!render_view_->is_swapped_out() && is_history_navigation &&
4616 render_view_->history_list_offset_ !=
4617 request_params.current_history_list_offset) {
4618 return false;
4621 render_view_->history_list_offset_ =
4622 request_params.current_history_list_offset;
4623 render_view_->history_list_length_ =
4624 request_params.current_history_list_length;
4625 if (request_params.should_clear_history_list) {
4626 CHECK_EQ(-1, render_view_->history_list_offset_);
4627 CHECK_EQ(0, render_view_->history_list_length_);
4630 if (!is_swapped_out_ || frame_->parent())
4631 return true;
4633 // This is a swapped out main frame, so swap the renderer back in.
4634 // We marked the view as hidden when swapping the view out, so be sure to
4635 // reset the visibility state before navigating to the new URL.
4636 render_view_->webview()->setVisibilityState(
4637 render_view_->visibilityState(), false);
4639 // If this is an attempt to reload while we are swapped out, we should not
4640 // reload swappedout://, but the previous page, which is stored in
4641 // params.state. Setting is_reload to false will treat this like a back
4642 // navigation to accomplish that.
4643 *is_reload = false;
4644 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4646 // We refresh timezone when a view is swapped in since timezone
4647 // can get out of sync when the system timezone is updated while
4648 // the view is swapped out.
4649 RenderThreadImpl::NotifyTimezoneChange();
4651 render_view_->SetSwappedOut(false);
4652 is_swapped_out_ = false;
4653 return true;
4656 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4657 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4658 switches::kEnableBrowserSideNavigation));
4659 DCHECK(request);
4660 // TODO(clamy): Execute the beforeunload event.
4662 // Note: At this stage, the goal is to apply all the modifications the
4663 // renderer wants to make to the request, and then send it to the browser, so
4664 // that the actual network request can be started. Ideally, all such
4665 // modifications should take place in willSendRequest, and in the
4666 // implementation of willSendRequest for the various InspectorAgents
4667 // (devtools).
4669 // TODO(clamy): Apply devtools override.
4670 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4671 // else in blink.
4672 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4674 // TODO(clamy): Same-document navigations should not be sent back to the
4675 // browser.
4676 // TODO(clamy): Data urls should not be sent back to the browser either.
4677 Send(new FrameHostMsg_DidStartLoading(routing_id_, true));
4678 Send(new FrameHostMsg_BeginNavigation(
4679 routing_id_, MakeCommonNavigationParams(request),
4680 BeginNavigationParams(request->httpMethod().latin1(),
4681 GetWebURLRequestHeaders(*request),
4682 GetLoadFlagsForWebURLRequest(*request),
4683 request->hasUserGesture()),
4684 GetRequestBodyForWebURLRequest(*request)));
4687 void RenderFrameImpl::LoadDataURL(const CommonNavigationParams& params,
4688 WebFrame* frame) {
4689 // A loadData request with a specified base URL.
4690 std::string mime_type, charset, data;
4691 if (net::DataURL::Parse(params.url, &mime_type, &charset, &data)) {
4692 const GURL base_url = params.base_url_for_data_url.is_empty() ?
4693 params.url : params.base_url_for_data_url;
4694 frame->loadData(
4695 WebData(data.c_str(), data.length()),
4696 WebString::fromUTF8(mime_type),
4697 WebString::fromUTF8(charset),
4698 base_url,
4699 params.history_url_for_data_url,
4700 false);
4701 } else {
4702 CHECK(false) << "Invalid URL passed: "
4703 << params.url.possibly_invalid_spec();
4707 void RenderFrameImpl::SendFailedProvisionalLoad(
4708 const blink::WebURLRequest& request,
4709 const blink::WebURLError& error,
4710 blink::WebLocalFrame* frame) {
4711 bool show_repost_interstitial = (error.reason == net::ERR_CACHE_MISS &&
4712 EqualsASCII(request.httpMethod(), "POST"));
4714 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
4715 params.error_code = error.reason;
4716 GetContentClient()->renderer()->GetNavigationErrorStrings(
4717 render_view_.get(), frame, request, error, NULL,
4718 &params.error_description);
4719 params.url = error.unreachableURL;
4720 params.showing_repost_interstitial = show_repost_interstitial;
4721 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(routing_id_, params));
4724 bool RenderFrameImpl::ShouldDisplayErrorPageForFailedLoad(
4725 int error_code,
4726 const GURL& unreachable_url) {
4727 // Don't display an error page if this is simply a cancelled load. Aside
4728 // from being dumb, Blink doesn't expect it and it will cause a crash.
4729 if (error_code == net::ERR_ABORTED)
4730 return false;
4732 // Don't display "client blocked" error page if browser has asked us not to.
4733 if (error_code == net::ERR_BLOCKED_BY_CLIENT &&
4734 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
4735 return false;
4738 // Allow the embedder to suppress an error page.
4739 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(
4740 this, unreachable_url)) {
4741 return false;
4744 if (RenderThreadImpl::current() &&
4745 RenderThreadImpl::current()->layout_test_mode()) {
4746 return false;
4749 return true;
4752 GURL RenderFrameImpl::GetLoadingUrl() const {
4753 WebDataSource* ds = frame_->dataSource();
4754 if (ds->hasUnreachableURL())
4755 return ds->unreachableURL();
4757 const WebURLRequest& request = ds->request();
4758 return request.url();
4761 void RenderFrameImpl::PopulateDocumentStateFromPending(
4762 DocumentState* document_state) {
4763 document_state->set_request_time(
4764 pending_navigation_params_->request_params.request_time);
4766 InternalDocumentStateData* internal_data =
4767 InternalDocumentStateData::FromDocumentState(document_state);
4769 if (!pending_navigation_params_->common_params.url.SchemeIs(
4770 url::kJavaScriptScheme) &&
4771 pending_navigation_params_->common_params.navigation_type ==
4772 FrameMsg_Navigate_Type::RESTORE) {
4773 // We're doing a load of a page that was restored from the last session. By
4774 // default this prefers the cache over loading (LOAD_PREFERRING_CACHE) which
4775 // can result in stale data for pages that are set to expire. We explicitly
4776 // override that by setting the policy here so that as necessary we load
4777 // from the network.
4779 // TODO(davidben): Remove this in favor of passing a cache policy to the
4780 // loadHistoryItem call in OnNavigate. That requires not overloading
4781 // UseProtocolCachePolicy to mean both "normal load" and "determine cache
4782 // policy based on load type, etc".
4783 internal_data->set_cache_policy_override(
4784 WebURLRequest::UseProtocolCachePolicy);
4787 if (IsReload(pending_navigation_params_->common_params.navigation_type))
4788 document_state->set_load_type(DocumentState::RELOAD);
4789 else if (pending_navigation_params_->request_params.page_state.IsValid())
4790 document_state->set_load_type(DocumentState::HISTORY_LOAD);
4791 else
4792 document_state->set_load_type(DocumentState::NORMAL_LOAD);
4794 internal_data->set_is_overriding_user_agent(
4795 pending_navigation_params_->request_params.is_overriding_user_agent);
4796 internal_data->set_must_reset_scroll_and_scale_state(
4797 pending_navigation_params_->common_params.navigation_type ==
4798 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
4799 document_state->set_can_load_local_resources(
4800 pending_navigation_params_->request_params.can_load_local_resources);
4803 NavigationState* RenderFrameImpl::CreateNavigationStateFromPending() {
4804 // A navigation resulting from loading a javascript URL should not be treated
4805 // as a browser initiated event. Instead, we want it to look as if the page
4806 // initiated any load resulting from JS execution.
4807 if (!pending_navigation_params_->common_params.url.SchemeIs(
4808 url::kJavaScriptScheme)) {
4809 return NavigationStateImpl::CreateBrowserInitiated(
4810 pending_navigation_params_->common_params,
4811 pending_navigation_params_->start_params,
4812 pending_navigation_params_->request_params);
4814 return NavigationStateImpl::CreateContentInitiated();
4817 #if defined(OS_ANDROID)
4819 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4820 const blink::WebURL& url,
4821 WebMediaPlayerClient* client,
4822 media::MediaPermission* media_permission,
4823 blink::WebContentDecryptionModule* initial_cdm) {
4824 GpuChannelHost* gpu_channel_host =
4825 RenderThreadImpl::current()->EstablishGpuChannelSync(
4826 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4827 if (!gpu_channel_host) {
4828 LOG(ERROR) << "Failed to establish GPU channel for media player";
4829 return NULL;
4832 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4833 if (SynchronousCompositorFactory* factory =
4834 SynchronousCompositorFactory::GetInstance()) {
4835 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4836 } else {
4837 scoped_refptr<cc_blink::ContextProviderWebContext> context_provider =
4838 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4840 if (!context_provider.get()) {
4841 LOG(ERROR) << "Failed to get context3d for media player";
4842 return NULL;
4845 stream_texture_factory = StreamTextureFactoryImpl::Create(
4846 context_provider, gpu_channel_host, routing_id_);
4849 return new WebMediaPlayerAndroid(
4850 frame_, client, weak_factory_.GetWeakPtr(), GetMediaPlayerManager(),
4851 GetCdmFactory(), media_permission, initial_cdm, stream_texture_factory,
4852 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4853 new RenderMediaLog());
4856 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4857 if (!media_player_manager_)
4858 media_player_manager_ = new RendererMediaPlayerManager(this);
4859 return media_player_manager_;
4862 #endif // defined(OS_ANDROID)
4864 media::MediaPermission* RenderFrameImpl::GetMediaPermission() {
4865 if (!media_permission_dispatcher_)
4866 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
4867 return media_permission_dispatcher_;
4870 media::CdmFactory* RenderFrameImpl::GetCdmFactory() {
4871 #if defined(ENABLE_BROWSER_CDMS)
4872 if (!cdm_manager_)
4873 cdm_manager_ = new RendererCdmManager(this);
4874 #endif // defined(ENABLE_BROWSER_CDMS)
4876 if (!cdm_factory_) {
4877 DCHECK(frame_);
4878 cdm_factory_ = new RenderCdmFactory(
4879 #if defined(ENABLE_PEPPER_CDMS)
4880 base::Bind(&PepperCdmWrapperImpl::Create, frame_),
4881 #elif defined(ENABLE_BROWSER_CDMS)
4882 cdm_manager_,
4883 #endif
4884 this);
4887 return cdm_factory_;
4890 } // namespace content