Enable right clicking on the applist doodle web contents and log the data.
[chromium-blink-merge.git] / content / renderer / render_frame_impl.cc
blobb3bca5aff559363f8665610ff4391643f6a73c87
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/kill.h"
18 #include "base/process/process.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "content/child/appcache/appcache_dispatcher.h"
23 #include "content/child/plugin_messages.h"
24 #include "content/child/quota_dispatcher.h"
25 #include "content/child/request_extra_data.h"
26 #include "content/child/service_worker/service_worker_handle_reference.h"
27 #include "content/child/service_worker/service_worker_network_provider.h"
28 #include "content/child/service_worker/service_worker_provider_context.h"
29 #include "content/child/service_worker/web_service_worker_provider_impl.h"
30 #include "content/child/v8_value_converter_impl.h"
31 #include "content/child/web_url_loader_impl.h"
32 #include "content/child/web_url_request_util.h"
33 #include "content/child/webmessageportchannel_impl.h"
34 #include "content/child/websocket_bridge.h"
35 #include "content/child/weburlresponse_extradata_impl.h"
36 #include "content/common/clipboard_messages.h"
37 #include "content/common/frame_messages.h"
38 #include "content/common/frame_replication_state.h"
39 #include "content/common/input_messages.h"
40 #include "content/common/service_worker/service_worker_types.h"
41 #include "content/common/swapped_out_messages.h"
42 #include "content/common/view_messages.h"
43 #include "content/public/common/bindings_policy.h"
44 #include "content/public/common/content_constants.h"
45 #include "content/public/common/content_switches.h"
46 #include "content/public/common/context_menu_params.h"
47 #include "content/public/common/page_state.h"
48 #include "content/public/common/resource_response.h"
49 #include "content/public/common/url_constants.h"
50 #include "content/public/common/url_utils.h"
51 #include "content/public/renderer/browser_plugin_delegate.h"
52 #include "content/public/renderer/content_renderer_client.h"
53 #include "content/public/renderer/context_menu_client.h"
54 #include "content/public/renderer/document_state.h"
55 #include "content/public/renderer/navigation_state.h"
56 #include "content/public/renderer/render_frame_observer.h"
57 #include "content/public/renderer/renderer_ppapi_host.h"
58 #include "content/renderer/accessibility/renderer_accessibility.h"
59 #include "content/renderer/browser_plugin/browser_plugin.h"
60 #include "content/renderer/browser_plugin/browser_plugin_manager.h"
61 #include "content/renderer/child_frame_compositing_helper.h"
62 #include "content/renderer/context_menu_params_builder.h"
63 #include "content/renderer/devtools/devtools_agent.h"
64 #include "content/renderer/dom_automation_controller.h"
65 #include "content/renderer/dom_utils.h"
66 #include "content/renderer/external_popup_menu.h"
67 #include "content/renderer/geolocation_dispatcher.h"
68 #include "content/renderer/history_controller.h"
69 #include "content/renderer/history_serialization.h"
70 #include "content/renderer/image_loading_helper.h"
71 #include "content/renderer/ime_event_guard.h"
72 #include "content/renderer/internal_document_state_data.h"
73 #include "content/renderer/manifest/manifest_manager.h"
74 #include "content/renderer/media/audio_renderer_mixer_manager.h"
75 #include "content/renderer/media/crypto/render_cdm_factory.h"
76 #include "content/renderer/media/media_permission_dispatcher.h"
77 #include "content/renderer/media/media_stream_dispatcher.h"
78 #include "content/renderer/media/media_stream_renderer_factory.h"
79 #include "content/renderer/media/midi_dispatcher.h"
80 #include "content/renderer/media/render_media_log.h"
81 #include "content/renderer/media/user_media_client_impl.h"
82 #include "content/renderer/media/webmediaplayer_ms.h"
83 #include "content/renderer/mojo/service_registry_js_wrapper.h"
84 #include "content/renderer/notification_permission_dispatcher.h"
85 #include "content/renderer/npapi/plugin_channel_host.h"
86 #include "content/renderer/pepper/plugin_instance_throttler_impl.h"
87 #include "content/renderer/presentation/presentation_dispatcher.h"
88 #include "content/renderer/push_messaging/push_messaging_dispatcher.h"
89 #include "content/renderer/render_frame_proxy.h"
90 #include "content/renderer/render_process.h"
91 #include "content/renderer/render_thread_impl.h"
92 #include "content/renderer/render_view_impl.h"
93 #include "content/renderer/render_widget_fullscreen_pepper.h"
94 #include "content/renderer/renderer_webapplicationcachehost_impl.h"
95 #include "content/renderer/renderer_webcolorchooser_impl.h"
96 #include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
97 #include "content/renderer/shared_worker_repository.h"
98 #include "content/renderer/websharedworker_proxy.h"
99 #include "gin/modules/module_registry.h"
100 #include "media/base/audio_renderer_mixer_input.h"
101 #include "media/base/media_log.h"
102 #include "media/blink/webencryptedmediaclient_impl.h"
103 #include "media/blink/webmediaplayer_impl.h"
104 #include "media/blink/webmediaplayer_params.h"
105 #include "media/filters/gpu_video_accelerator_factories.h"
106 #include "net/base/data_url.h"
107 #include "net/base/net_errors.h"
108 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
109 #include "net/http/http_util.h"
110 #include "third_party/WebKit/public/platform/WebStorageQuotaCallbacks.h"
111 #include "third_party/WebKit/public/platform/WebString.h"
112 #include "third_party/WebKit/public/platform/WebURL.h"
113 #include "third_party/WebKit/public/platform/WebURLError.h"
114 #include "third_party/WebKit/public/platform/WebURLResponse.h"
115 #include "third_party/WebKit/public/platform/WebVector.h"
116 #include "third_party/WebKit/public/web/WebColorSuggestion.h"
117 #include "third_party/WebKit/public/web/WebDocument.h"
118 #include "third_party/WebKit/public/web/WebFrameWidget.h"
119 #include "third_party/WebKit/public/web/WebGlyphCache.h"
120 #include "third_party/WebKit/public/web/WebLocalFrame.h"
121 #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h"
122 #include "third_party/WebKit/public/web/WebNavigationPolicy.h"
123 #include "third_party/WebKit/public/web/WebPlugin.h"
124 #include "third_party/WebKit/public/web/WebPluginParams.h"
125 #include "third_party/WebKit/public/web/WebPluginPlaceholder.h"
126 #include "third_party/WebKit/public/web/WebRange.h"
127 #include "third_party/WebKit/public/web/WebScriptSource.h"
128 #include "third_party/WebKit/public/web/WebSearchableFormData.h"
129 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
130 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
131 #include "third_party/WebKit/public/web/WebSurroundingText.h"
132 #include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
133 #include "third_party/WebKit/public/web/WebView.h"
134 #include "third_party/mojo/src/mojo/edk/js/core.h"
135 #include "third_party/mojo/src/mojo/edk/js/support.h"
137 #if defined(ENABLE_PLUGINS)
138 #include "content/renderer/npapi/webplugin_impl.h"
139 #include "content/renderer/pepper/pepper_browser_connection.h"
140 #include "content/renderer/pepper/pepper_plugin_instance_impl.h"
141 #include "content/renderer/pepper/pepper_webplugin_impl.h"
142 #include "content/renderer/pepper/plugin_module.h"
143 #endif
145 #if defined(ENABLE_WEBRTC)
146 #include "content/renderer/media/rtc_peer_connection_handler.h"
147 #endif
149 #if defined(OS_ANDROID)
150 #include <cpu-features.h>
152 #include "content/common/gpu/client/context_provider_command_buffer.h"
153 #include "content/renderer/android/synchronous_compositor_factory.h"
154 #include "content/renderer/java/gin_java_bridge_dispatcher.h"
155 #include "content/renderer/media/android/renderer_media_player_manager.h"
156 #include "content/renderer/media/android/stream_texture_factory_impl.h"
157 #include "content/renderer/media/android/webmediaplayer_android.h"
158 #else
159 #include "cc/blink/context_provider_web_context.h"
160 #endif
162 #if defined(ENABLE_PEPPER_CDMS)
163 #include "content/renderer/media/crypto/pepper_cdm_wrapper_impl.h"
164 #elif defined(ENABLE_BROWSER_CDMS)
165 #include "content/renderer/media/crypto/renderer_cdm_manager.h"
166 #endif
168 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
169 #include "content/renderer/media/media_renderer_service_provider.h"
170 #include "media/mojo/services/mojo_renderer_factory.h"
171 #else
172 #include "media/renderers/default_renderer_factory.h"
173 #endif
175 using blink::WebContextMenuData;
176 using blink::WebData;
177 using blink::WebDataSource;
178 using blink::WebDocument;
179 using blink::WebElement;
180 using blink::WebExternalPopupMenu;
181 using blink::WebExternalPopupMenuClient;
182 using blink::WebFrame;
183 using blink::WebHistoryItem;
184 using blink::WebHTTPBody;
185 using blink::WebLocalFrame;
186 using blink::WebMediaPlayer;
187 using blink::WebMediaPlayerClient;
188 using blink::WebNavigationPolicy;
189 using blink::WebNavigationType;
190 using blink::WebNode;
191 using blink::WebPluginParams;
192 using blink::WebPopupMenuInfo;
193 using blink::WebRange;
194 using blink::WebReferrerPolicy;
195 using blink::WebScriptSource;
196 using blink::WebSearchableFormData;
197 using blink::WebSecurityOrigin;
198 using blink::WebSecurityPolicy;
199 using blink::WebServiceWorkerProvider;
200 using blink::WebStorageQuotaCallbacks;
201 using blink::WebString;
202 using blink::WebURL;
203 using blink::WebURLError;
204 using blink::WebURLRequest;
205 using blink::WebURLResponse;
206 using blink::WebUserGestureIndicator;
207 using blink::WebVector;
208 using blink::WebView;
209 using base::Time;
210 using base::TimeDelta;
212 namespace content {
214 namespace {
216 const char kDefaultAcceptHeader[] =
217 "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/"
218 "*;q=0.8";
219 const char kAcceptHeader[] = "Accept";
221 const size_t kExtraCharsBeforeAndAfterSelection = 100;
223 typedef std::map<int, RenderFrameImpl*> RoutingIDFrameMap;
224 static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
225 LAZY_INSTANCE_INITIALIZER;
227 typedef std::map<blink::WebFrame*, RenderFrameImpl*> FrameMap;
228 base::LazyInstance<FrameMap> g_frame_map = LAZY_INSTANCE_INITIALIZER;
230 int64 ExtractPostId(HistoryEntry* entry) {
231 if (!entry)
232 return -1;
234 const WebHistoryItem& item = entry->root();
235 if (item.isNull() || item.httpBody().isNull())
236 return -1;
238 return item.httpBody().identifier();
241 WebURLResponseExtraDataImpl* GetExtraDataFromResponse(
242 const WebURLResponse& response) {
243 return static_cast<WebURLResponseExtraDataImpl*>(response.extraData());
246 void GetRedirectChain(WebDataSource* ds, std::vector<GURL>* result) {
247 // Replace any occurrences of swappedout:// with about:blank.
248 const WebURL& blank_url = GURL(url::kAboutBlankURL);
249 WebVector<WebURL> urls;
250 ds->redirectChain(urls);
251 result->reserve(urls.size());
252 for (size_t i = 0; i < urls.size(); ++i) {
253 if (urls[i] != GURL(kSwappedOutURL))
254 result->push_back(urls[i]);
255 else
256 result->push_back(blank_url);
260 // Returns the original request url. If there is no redirect, the original
261 // url is the same as ds->request()->url(). If the WebDataSource belongs to a
262 // frame was loaded by loadData, the original url will be ds->unreachableURL()
263 GURL GetOriginalRequestURL(WebDataSource* ds) {
264 // WebDataSource has unreachable URL means that the frame is loaded through
265 // blink::WebFrame::loadData(), and the base URL will be in the redirect
266 // chain. However, we never visited the baseURL. So in this case, we should
267 // use the unreachable URL as the original URL.
268 if (ds->hasUnreachableURL())
269 return ds->unreachableURL();
271 std::vector<GURL> redirects;
272 GetRedirectChain(ds, &redirects);
273 if (!redirects.empty())
274 return redirects.at(0);
276 return ds->originalRequest().url();
279 NOINLINE void CrashIntentionally() {
280 // NOTE(shess): Crash directly rather than using NOTREACHED() so
281 // that the signature is easier to triage in crash reports.
282 volatile int* zero = NULL;
283 *zero = 0;
286 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
287 NOINLINE void MaybeTriggerAsanError(const GURL& url) {
288 // NOTE(rogerm): We intentionally perform an invalid heap access here in
289 // order to trigger an Address Sanitizer (ASAN) error report.
290 const char kCrashDomain[] = "crash";
291 const char kHeapOverflow[] = "/heap-overflow";
292 const char kHeapUnderflow[] = "/heap-underflow";
293 const char kUseAfterFree[] = "/use-after-free";
294 #if defined(SYZYASAN)
295 const char kCorruptHeapBlock[] = "/corrupt-heap-block";
296 const char kCorruptHeap[] = "/corrupt-heap";
297 #endif
299 if (!url.DomainIs(kCrashDomain, sizeof(kCrashDomain) - 1))
300 return;
302 if (!url.has_path())
303 return;
305 std::string crash_type(url.path());
306 if (crash_type == kHeapOverflow) {
307 base::debug::AsanHeapOverflow();
308 } else if (crash_type == kHeapUnderflow ) {
309 base::debug::AsanHeapUnderflow();
310 } else if (crash_type == kUseAfterFree) {
311 base::debug::AsanHeapUseAfterFree();
312 #if defined(SYZYASAN)
313 } else if (crash_type == kCorruptHeapBlock) {
314 base::debug::AsanCorruptHeapBlock();
315 } else if (crash_type == kCorruptHeap) {
316 base::debug::AsanCorruptHeap();
317 #endif
320 #endif // ADDRESS_SANITIZER || SYZYASAN
322 void MaybeHandleDebugURL(const GURL& url) {
323 if (!url.SchemeIs(kChromeUIScheme))
324 return;
325 if (url == GURL(kChromeUICrashURL)) {
326 CrashIntentionally();
327 } else if (url == GURL(kChromeUIDumpURL)) {
328 // This URL will only correctly create a crash dump file if content is
329 // hosted in a process that has correctly called
330 // base::debug::SetDumpWithoutCrashingFunction. Refer to the documentation
331 // of base::debug::DumpWithoutCrashing for more details.
332 base::debug::DumpWithoutCrashing();
333 } else if (url == GURL(kChromeUIKillURL)) {
334 base::KillProcess(base::GetCurrentProcessHandle(), 1, false);
335 } else if (url == GURL(kChromeUIHangURL)) {
336 for (;;) {
337 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(1));
339 } else if (url == GURL(kChromeUIShorthangURL)) {
340 base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(20));
343 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
344 MaybeTriggerAsanError(url);
345 #endif // ADDRESS_SANITIZER || SYZYASAN
348 // Returns false unless this is a top-level navigation.
349 bool IsTopLevelNavigation(WebFrame* frame) {
350 return frame->parent() == NULL;
353 // Returns false unless this is a top-level navigation that crosses origins.
354 bool IsNonLocalTopLevelNavigation(const GURL& url,
355 WebFrame* frame,
356 WebNavigationType type,
357 bool is_form_post) {
358 if (!IsTopLevelNavigation(frame))
359 return false;
361 // Navigations initiated within Webkit are not sent out to the external host
362 // in the following cases.
363 // 1. The url scheme is not http/https
364 // 2. The origin of the url and the opener is the same in which case the
365 // opener relationship is maintained.
366 // 3. Reloads/form submits/back forward navigations
367 if (!url.SchemeIs(url::kHttpScheme) && !url.SchemeIs(url::kHttpsScheme))
368 return false;
370 if (type != blink::WebNavigationTypeReload &&
371 type != blink::WebNavigationTypeBackForward && !is_form_post) {
372 // The opener relationship between the new window and the parent allows the
373 // new window to script the parent and vice versa. This is not allowed if
374 // the origins of the two domains are different. This can be treated as a
375 // top level navigation and routed back to the host.
376 blink::WebFrame* opener = frame->opener();
377 if (!opener)
378 return true;
380 if (url.GetOrigin() != GURL(opener->document().url()).GetOrigin())
381 return true;
383 return false;
386 WebURLRequest CreateURLRequestForNavigation(
387 const CommonNavigationParams& common_params,
388 scoped_ptr<StreamOverrideParameters> stream_override,
389 bool is_view_source_mode_enabled) {
390 WebURLRequest request(common_params.url);
391 if (is_view_source_mode_enabled)
392 request.setCachePolicy(WebURLRequest::ReturnCacheDataElseLoad);
394 if (common_params.referrer.url.is_valid()) {
395 WebString web_referrer = WebSecurityPolicy::generateReferrerHeader(
396 common_params.referrer.policy,
397 common_params.url,
398 WebString::fromUTF8(common_params.referrer.url.spec()));
399 if (!web_referrer.isEmpty())
400 request.setHTTPReferrer(web_referrer, common_params.referrer.policy);
403 RequestExtraData* extra_data = new RequestExtraData();
404 extra_data->set_stream_override(stream_override.Pass());
405 request.setExtraData(extra_data);
407 // Set the ui timestamp for this navigation. Currently the timestamp here is
408 // only non empty when the navigation was triggered by an Android intent. The
409 // timestamp is converted to a double version supported by blink. It will be
410 // passed back to the browser in the DidCommitProvisionalLoad and the
411 // DocumentLoadComplete IPCs.
412 base::TimeDelta ui_timestamp = common_params.ui_timestamp - base::TimeTicks();
413 request.setUiStartTime(ui_timestamp.InSecondsF());
414 request.setInputPerfMetricReportPolicy(
415 static_cast<WebURLRequest::InputToLoadPerfMetricReportPolicy>(
416 common_params.report_type));
417 return request;
420 void UpdateFrameNavigationTiming(WebFrame* frame,
421 base::TimeTicks browser_navigation_start,
422 base::TimeTicks renderer_navigation_start) {
423 // The browser provides the navigation_start time to bootstrap the
424 // Navigation Timing information for the browser-initiated navigations. In
425 // case of cross-process navigations, this carries over the time of
426 // finishing the onbeforeunload handler of the previous page.
427 DCHECK(!browser_navigation_start.is_null());
428 if (frame->provisionalDataSource()) {
429 // |browser_navigation_start| is likely before this process existed, so we
430 // can't use InterProcessTimeTicksConverter. We need at least to ensure
431 // that the browser-side navigation start we set is not later than the one
432 // on the renderer side.
433 base::TimeTicks navigation_start = std::min(
434 browser_navigation_start, renderer_navigation_start);
435 double navigation_start_seconds =
436 (navigation_start - base::TimeTicks()).InSecondsF();
437 frame->provisionalDataSource()->setNavigationStartTime(
438 navigation_start_seconds);
439 // TODO(clamy): We need to provide additional timing values for the
440 // Navigation Timing API to work with browser-side navigations.
444 // PlzNavigate
445 CommonNavigationParams MakeCommonNavigationParams(
446 blink::WebURLRequest* request) {
447 const RequestExtraData kEmptyData;
448 const RequestExtraData* extra_data =
449 static_cast<RequestExtraData*>(request->extraData());
450 if (!extra_data)
451 extra_data = &kEmptyData;
452 CommonNavigationParams params;
453 params.url = request->url();
454 params.referrer = Referrer(
455 GURL(request->httpHeaderField(WebString::fromUTF8("Referer")).latin1()),
456 request->referrerPolicy());
457 params.transition = extra_data->transition_type();
459 // Set the ui timestamp for this navigation. Currently the timestamp here is
460 // only non empty when the navigation was triggered by an Android intent, or
461 // by the user clicking on a link. The timestamp is converted from a double
462 // version supported by blink. It will be passed back to the renderer in the
463 // CommitNavigation IPC, and then back to the browser again in the
464 // DidCommitProvisionalLoad and the DocumentLoadComplete IPCs.
465 params.ui_timestamp =
466 base::TimeTicks() + base::TimeDelta::FromSecondsD(request->uiStartTime());
467 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
468 request->inputPerfMetricReportPolicy());
469 return params;
472 #if !defined(OS_ANDROID)
473 media::Context3D GetSharedMainThreadContext3D() {
474 cc::ContextProvider* provider =
475 RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
476 if (!provider)
477 return media::Context3D();
478 return media::Context3D(provider->ContextGL(), provider->GrContext());
480 #endif
482 RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl =
483 nullptr;
485 #define STATIC_ASSERT_MATCHING_ENUMS(content_name, blink_name) \
486 static_assert( \
487 static_cast<int>(content_name) == static_cast<int>(blink_name), \
488 "enum values must match")
490 // Check that blink::WebSandboxFlags is kept in sync with
491 // content::SandboxFlags.
492 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NONE,
493 blink::WebSandboxFlags::None);
494 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::NAVIGATION,
495 blink::WebSandboxFlags::Navigation);
496 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::PLUGINS,
497 blink::WebSandboxFlags::Plugins);
498 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIGIN,
499 blink::WebSandboxFlags::Origin);
500 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::FORMS,
501 blink::WebSandboxFlags::Forms);
502 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::SCRIPTS,
503 blink::WebSandboxFlags::Scripts);
504 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::TOP_NAVIGATION,
505 blink::WebSandboxFlags::TopNavigation);
506 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POPUPS,
507 blink::WebSandboxFlags::Popups);
508 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::AUTOMATIC_FEATURES,
509 blink::WebSandboxFlags::AutomaticFeatures);
510 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::POINTER_LOCK,
511 blink::WebSandboxFlags::PointerLock);
512 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::DOCUMENT_DOMAIN,
513 blink::WebSandboxFlags::DocumentDomain);
514 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ORIENTATION_LOCK,
515 blink::WebSandboxFlags::OrientationLock);
516 STATIC_ASSERT_MATCHING_ENUMS(SandboxFlags::ALL,
517 blink::WebSandboxFlags::All);
519 } // namespace
521 // static
522 RenderFrameImpl* RenderFrameImpl::Create(RenderViewImpl* render_view,
523 int32 routing_id) {
524 DCHECK(routing_id != MSG_ROUTING_NONE);
526 if (g_create_render_frame_impl)
527 return g_create_render_frame_impl(render_view, routing_id);
528 else
529 return new RenderFrameImpl(render_view, routing_id);
532 // static
533 RenderFrameImpl* RenderFrameImpl::FromRoutingID(int32 routing_id) {
534 RoutingIDFrameMap::iterator iter =
535 g_routing_id_frame_map.Get().find(routing_id);
536 if (iter != g_routing_id_frame_map.Get().end())
537 return iter->second;
538 return NULL;
541 // static
542 void RenderFrameImpl::CreateFrame(
543 int routing_id,
544 int parent_routing_id,
545 int proxy_routing_id,
546 const FrameReplicationState& replicated_state,
547 CompositorDependencies* compositor_deps,
548 const FrameMsg_NewFrame_WidgetParams& widget_params) {
549 // TODO(nasko): For now, this message is only sent for subframes, as the
550 // top level frame is created when the RenderView is created through the
551 // ViewMsg_New IPC.
552 CHECK_NE(MSG_ROUTING_NONE, parent_routing_id);
554 blink::WebLocalFrame* web_frame;
555 RenderFrameImpl* render_frame;
556 if (proxy_routing_id == MSG_ROUTING_NONE) {
557 RenderFrameProxy* parent_proxy =
558 RenderFrameProxy::FromRoutingID(parent_routing_id);
559 // If the browser is sending a valid parent routing id, it should already
560 // be created and registered.
561 CHECK(parent_proxy);
562 blink::WebRemoteFrame* parent_web_frame = parent_proxy->web_frame();
564 // Create the RenderFrame and WebLocalFrame, linking the two.
565 render_frame =
566 RenderFrameImpl::Create(parent_proxy->render_view(), routing_id);
567 web_frame = parent_web_frame->createLocalChild(
568 WebString::fromUTF8(replicated_state.name),
569 ContentToWebSandboxFlags(replicated_state.sandbox_flags), render_frame);
570 } else {
571 RenderFrameProxy* proxy =
572 RenderFrameProxy::FromRoutingID(proxy_routing_id);
573 CHECK(proxy);
574 render_frame = RenderFrameImpl::Create(proxy->render_view(), routing_id);
575 web_frame = blink::WebLocalFrame::create(render_frame);
576 render_frame->proxy_routing_id_ = proxy_routing_id;
577 web_frame->initializeToReplaceRemoteFrame(proxy->web_frame());
579 render_frame->SetWebFrame(web_frame);
581 if (widget_params.routing_id != MSG_ROUTING_NONE) {
582 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
583 switches::kSitePerProcess));
584 render_frame->render_widget_ = RenderWidget::CreateForFrame(
585 widget_params.routing_id, widget_params.surface_id,
586 widget_params.hidden, render_frame->render_view_->screen_info(),
587 compositor_deps, web_frame);
588 // TODO(kenrb): Observing shouldn't be necessary when we sort out
589 // WasShown and WasHidden, separating page-level visibility from
590 // frame-level visibility.
591 render_frame->render_widget_->RegisterRenderFrame(render_frame);
594 render_frame->Initialize();
597 // static
598 RenderFrame* RenderFrame::FromWebFrame(blink::WebFrame* web_frame) {
599 return RenderFrameImpl::FromWebFrame(web_frame);
602 // static
603 RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) {
604 FrameMap::iterator iter = g_frame_map.Get().find(web_frame);
605 if (iter != g_frame_map.Get().end())
606 return iter->second;
607 return NULL;
610 // static
611 void RenderFrameImpl::InstallCreateHook(
612 CreateRenderFrameImplFunction create_render_frame_impl) {
613 CHECK(!g_create_render_frame_impl);
614 g_create_render_frame_impl = create_render_frame_impl;
617 // static
618 content::SandboxFlags RenderFrameImpl::WebToContentSandboxFlags(
619 blink::WebSandboxFlags flags) {
620 return static_cast<content::SandboxFlags>(flags);
623 // static
624 blink::WebSandboxFlags RenderFrameImpl::ContentToWebSandboxFlags(
625 content::SandboxFlags flags) {
626 return static_cast<blink::WebSandboxFlags>(flags);
629 // RenderFrameImpl ----------------------------------------------------------
630 RenderFrameImpl::RenderFrameImpl(RenderViewImpl* render_view, int routing_id)
631 : frame_(NULL),
632 render_view_(render_view->AsWeakPtr()),
633 routing_id_(routing_id),
634 is_swapped_out_(false),
635 render_frame_proxy_(NULL),
636 is_detaching_(false),
637 proxy_routing_id_(MSG_ROUTING_NONE),
638 #if defined(ENABLE_PLUGINS)
639 plugin_power_saver_helper_(NULL),
640 #endif
641 cookie_jar_(this),
642 selection_text_offset_(0),
643 selection_range_(gfx::Range::InvalidRange()),
644 handling_select_range_(false),
645 notification_permission_dispatcher_(NULL),
646 web_user_media_client_(NULL),
647 media_permission_dispatcher_(NULL),
648 midi_dispatcher_(NULL),
649 #if defined(OS_ANDROID)
650 media_player_manager_(NULL),
651 #endif
652 #if defined(ENABLE_BROWSER_CDMS)
653 cdm_manager_(NULL),
654 #endif
655 #if defined(VIDEO_HOLE)
656 contains_media_player_(false),
657 #endif
658 geolocation_dispatcher_(NULL),
659 push_messaging_dispatcher_(NULL),
660 presentation_dispatcher_(NULL),
661 screen_orientation_dispatcher_(NULL),
662 manifest_manager_(NULL),
663 accessibility_mode_(AccessibilityModeOff),
664 renderer_accessibility_(NULL),
665 weak_factory_(this) {
666 std::pair<RoutingIDFrameMap::iterator, bool> result =
667 g_routing_id_frame_map.Get().insert(std::make_pair(routing_id_, this));
668 CHECK(result.second) << "Inserting a duplicate item.";
670 RenderThread::Get()->AddRoute(routing_id_, this);
672 render_view_->RegisterRenderFrame(this);
674 // Everything below subclasses RenderFrameObserver and is automatically
675 // deleted when the RenderFrame gets deleted.
676 #if defined(OS_ANDROID)
677 new GinJavaBridgeDispatcher(this);
678 #endif
680 #if defined(ENABLE_PLUGINS)
681 plugin_power_saver_helper_ = new PluginPowerSaverHelper(this);
682 #endif
684 manifest_manager_ = new ManifestManager(this);
687 RenderFrameImpl::~RenderFrameImpl() {
688 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, RenderFrameGone());
689 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnDestruct());
691 #if defined(VIDEO_HOLE)
692 if (contains_media_player_)
693 render_view_->UnregisterVideoHoleFrame(this);
694 #endif
696 if (render_frame_proxy_)
697 delete render_frame_proxy_;
699 render_view_->UnregisterRenderFrame(this);
700 g_routing_id_frame_map.Get().erase(routing_id_);
701 RenderThread::Get()->RemoveRoute(routing_id_);
704 void RenderFrameImpl::SetWebFrame(blink::WebLocalFrame* web_frame) {
705 DCHECK(!frame_);
707 std::pair<FrameMap::iterator, bool> result = g_frame_map.Get().insert(
708 std::make_pair(web_frame, this));
709 CHECK(result.second) << "Inserting a duplicate item.";
711 frame_ = web_frame;
714 void RenderFrameImpl::Initialize() {
715 #if defined(ENABLE_PLUGINS)
716 new PepperBrowserConnection(this);
717 #endif
718 new SharedWorkerRepository(this);
720 if (!frame_->parent())
721 new ImageLoadingHelper(this);
723 // We delay calling this until we have the WebFrame so that any observer or
724 // embedder can call GetWebFrame on any RenderFrame.
725 GetContentClient()->renderer()->RenderFrameCreated(this);
728 RenderWidget* RenderFrameImpl::GetRenderWidget() {
729 return render_view_.get();
732 #if defined(ENABLE_PLUGINS)
733 void RenderFrameImpl::PepperPluginCreated(RendererPpapiHost* host) {
734 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
735 DidCreatePepperPlugin(host));
736 if (host->GetPluginName() == kFlashPluginName) {
737 RenderThread::Get()->RecordAction(
738 base::UserMetricsAction("FrameLoadWithFlash"));
742 void RenderFrameImpl::PepperDidChangeCursor(
743 PepperPluginInstanceImpl* instance,
744 const blink::WebCursorInfo& cursor) {
745 // Update the cursor appearance immediately if the requesting plugin is the
746 // one which receives the last mouse event. Otherwise, the new cursor won't be
747 // picked up until the plugin gets the next input event. That is bad if, e.g.,
748 // the plugin would like to set an invisible cursor when there isn't any user
749 // input for a while.
750 if (instance == render_view_->pepper_last_mouse_event_target())
751 GetRenderWidget()->didChangeCursor(cursor);
754 void RenderFrameImpl::PepperDidReceiveMouseEvent(
755 PepperPluginInstanceImpl* instance) {
756 render_view_->set_pepper_last_mouse_event_target(instance);
759 void RenderFrameImpl::PepperTextInputTypeChanged(
760 PepperPluginInstanceImpl* instance) {
761 if (instance != render_view_->focused_pepper_plugin())
762 return;
764 GetRenderWidget()->UpdateTextInputType();
766 FocusedNodeChangedForAccessibility(WebNode());
769 void RenderFrameImpl::PepperCaretPositionChanged(
770 PepperPluginInstanceImpl* instance) {
771 if (instance != render_view_->focused_pepper_plugin())
772 return;
773 GetRenderWidget()->UpdateSelectionBounds();
776 void RenderFrameImpl::PepperCancelComposition(
777 PepperPluginInstanceImpl* instance) {
778 if (instance != render_view_->focused_pepper_plugin())
779 return;
780 Send(new InputHostMsg_ImeCancelComposition(render_view_->GetRoutingID()));;
781 #if defined(OS_MACOSX) || defined(USE_AURA)
782 GetRenderWidget()->UpdateCompositionInfo(true);
783 #endif
786 void RenderFrameImpl::PepperSelectionChanged(
787 PepperPluginInstanceImpl* instance) {
788 if (instance != render_view_->focused_pepper_plugin())
789 return;
790 SyncSelectionIfRequired();
793 RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer(
794 PepperPluginInstanceImpl* plugin) {
795 GURL active_url;
796 if (render_view_->webview() && render_view_->webview()->mainFrame())
797 active_url = GURL(render_view_->webview()->mainFrame()->document().url());
798 RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create(
799 GetRenderWidget()->routing_id(), GetRenderWidget()->compositor_deps(),
800 plugin, active_url, GetRenderWidget()->screenInfo());
801 widget->show(blink::WebNavigationPolicyIgnore);
802 return widget;
805 bool RenderFrameImpl::IsPepperAcceptingCompositionEvents() const {
806 if (!render_view_->focused_pepper_plugin())
807 return false;
808 return render_view_->focused_pepper_plugin()->
809 IsPluginAcceptingCompositionEvents();
812 void RenderFrameImpl::PluginCrashed(const base::FilePath& plugin_path,
813 base::ProcessId plugin_pid) {
814 // TODO(jam): dispatch this IPC in RenderFrameHost and switch to use
815 // routing_id_ as a result.
816 Send(new FrameHostMsg_PluginCrashed(routing_id_, plugin_path, plugin_pid));
819 void RenderFrameImpl::SimulateImeSetComposition(
820 const base::string16& text,
821 const std::vector<blink::WebCompositionUnderline>& underlines,
822 int selection_start,
823 int selection_end) {
824 render_view_->OnImeSetComposition(
825 text, underlines, selection_start, selection_end);
828 void RenderFrameImpl::SimulateImeConfirmComposition(
829 const base::string16& text,
830 const gfx::Range& replacement_range) {
831 render_view_->OnImeConfirmComposition(text, replacement_range, false);
834 void RenderFrameImpl::OnImeSetComposition(
835 const base::string16& text,
836 const std::vector<blink::WebCompositionUnderline>& underlines,
837 int selection_start,
838 int selection_end) {
839 // When a PPAPI plugin has focus, we bypass WebKit.
840 if (!IsPepperAcceptingCompositionEvents()) {
841 pepper_composition_text_ = text;
842 } else {
843 // TODO(kinaba) currently all composition events are sent directly to
844 // plugins. Use DOM event mechanism after WebKit is made aware about
845 // plugins that support composition.
846 // The code below mimics the behavior of WebCore::Editor::setComposition.
848 // Empty -> nonempty: composition started.
849 if (pepper_composition_text_.empty() && !text.empty()) {
850 render_view_->focused_pepper_plugin()->HandleCompositionStart(
851 base::string16());
853 // Nonempty -> empty: composition canceled.
854 if (!pepper_composition_text_.empty() && text.empty()) {
855 render_view_->focused_pepper_plugin()->HandleCompositionEnd(
856 base::string16());
858 pepper_composition_text_ = text;
859 // Nonempty: composition is ongoing.
860 if (!pepper_composition_text_.empty()) {
861 render_view_->focused_pepper_plugin()->HandleCompositionUpdate(
862 pepper_composition_text_, underlines, selection_start,
863 selection_end);
868 void RenderFrameImpl::OnImeConfirmComposition(
869 const base::string16& text,
870 const gfx::Range& replacement_range,
871 bool keep_selection) {
872 // When a PPAPI plugin has focus, we bypass WebKit.
873 // Here, text.empty() has a special meaning. It means to commit the last
874 // update of composition text (see
875 // RenderWidgetHost::ImeConfirmComposition()).
876 const base::string16& last_text = text.empty() ? pepper_composition_text_
877 : text;
879 // last_text is empty only when both text and pepper_composition_text_ is.
880 // Ignore it.
881 if (last_text.empty())
882 return;
884 if (!IsPepperAcceptingCompositionEvents()) {
885 base::i18n::UTF16CharIterator iterator(&last_text);
886 int32 i = 0;
887 while (iterator.Advance()) {
888 blink::WebKeyboardEvent char_event;
889 char_event.type = blink::WebInputEvent::Char;
890 char_event.timeStampSeconds = base::Time::Now().ToDoubleT();
891 char_event.modifiers = 0;
892 char_event.windowsKeyCode = last_text[i];
893 char_event.nativeKeyCode = last_text[i];
895 const int32 char_start = i;
896 for (; i < iterator.array_pos(); ++i) {
897 char_event.text[i - char_start] = last_text[i];
898 char_event.unmodifiedText[i - char_start] = last_text[i];
901 if (GetRenderWidget()->webwidget())
902 GetRenderWidget()->webwidget()->handleInputEvent(char_event);
904 } else {
905 // Mimics the order of events sent by WebKit.
906 // See WebCore::Editor::setComposition() for the corresponding code.
907 render_view_->focused_pepper_plugin()->HandleCompositionEnd(last_text);
908 render_view_->focused_pepper_plugin()->HandleTextInput(last_text);
910 pepper_composition_text_.clear();
912 #endif // defined(ENABLE_PLUGINS)
914 MediaStreamDispatcher* RenderFrameImpl::GetMediaStreamDispatcher() {
915 if (!web_user_media_client_)
916 InitializeUserMediaClient();
917 return web_user_media_client_ ?
918 web_user_media_client_->media_stream_dispatcher() : NULL;
921 bool RenderFrameImpl::Send(IPC::Message* message) {
922 if (is_detaching_) {
923 delete message;
924 return false;
926 if (is_swapped_out_) {
927 if (!SwappedOutMessages::CanSendWhileSwappedOut(message)) {
928 delete message;
929 return false;
933 return RenderThread::Get()->Send(message);
936 #if defined(OS_MACOSX) || defined(OS_ANDROID)
937 void RenderFrameImpl::DidHideExternalPopupMenu() {
938 // We need to clear external_popup_menu_ as soon as ExternalPopupMenu::close
939 // is called. Otherwise, createExternalPopupMenu() for new popup will fail.
940 external_popup_menu_.reset();
942 #endif
944 bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) {
945 // TODO(kenrb): document() should not be null, but as a transitional step
946 // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages
947 // to this method. This happens for a top-level remote frame, where a
948 // document-less RenderFrame is replaced by a RenderFrameProxy but kept
949 // around and is still able to receive messages.
950 if (!frame_->document().isNull())
951 GetContentClient()->SetActiveURL(frame_->document().url());
953 ObserverListBase<RenderFrameObserver>::Iterator it(observers_);
954 RenderFrameObserver* observer;
955 while ((observer = it.GetNext()) != NULL) {
956 if (observer->OnMessageReceived(msg))
957 return true;
960 bool handled = true;
961 IPC_BEGIN_MESSAGE_MAP(RenderFrameImpl, msg)
962 IPC_MESSAGE_HANDLER(FrameMsg_Navigate, OnNavigate)
963 IPC_MESSAGE_HANDLER(FrameMsg_BeforeUnload, OnBeforeUnload)
964 IPC_MESSAGE_HANDLER(FrameMsg_SwapOut, OnSwapOut)
965 IPC_MESSAGE_HANDLER(FrameMsg_Stop, OnStop)
966 IPC_MESSAGE_HANDLER(FrameMsg_ContextMenuClosed, OnContextMenuClosed)
967 IPC_MESSAGE_HANDLER(FrameMsg_CustomContextMenuAction,
968 OnCustomContextMenuAction)
969 IPC_MESSAGE_HANDLER(InputMsg_Undo, OnUndo)
970 IPC_MESSAGE_HANDLER(InputMsg_Redo, OnRedo)
971 IPC_MESSAGE_HANDLER(InputMsg_Cut, OnCut)
972 IPC_MESSAGE_HANDLER(InputMsg_Copy, OnCopy)
973 IPC_MESSAGE_HANDLER(InputMsg_Paste, OnPaste)
974 IPC_MESSAGE_HANDLER(InputMsg_PasteAndMatchStyle, OnPasteAndMatchStyle)
975 IPC_MESSAGE_HANDLER(InputMsg_Delete, OnDelete)
976 IPC_MESSAGE_HANDLER(InputMsg_SelectAll, OnSelectAll)
977 IPC_MESSAGE_HANDLER(InputMsg_SelectRange, OnSelectRange)
978 IPC_MESSAGE_HANDLER(InputMsg_Unselect, OnUnselect)
979 IPC_MESSAGE_HANDLER(InputMsg_MoveRangeSelectionExtent,
980 OnMoveRangeSelectionExtent)
981 IPC_MESSAGE_HANDLER(InputMsg_Replace, OnReplace)
982 IPC_MESSAGE_HANDLER(InputMsg_ReplaceMisspelling, OnReplaceMisspelling)
983 IPC_MESSAGE_HANDLER(InputMsg_ExtendSelectionAndDelete,
984 OnExtendSelectionAndDelete)
985 IPC_MESSAGE_HANDLER(InputMsg_SetCompositionFromExistingText,
986 OnSetCompositionFromExistingText)
987 IPC_MESSAGE_HANDLER(InputMsg_ExecuteNoValueEditCommand,
988 OnExecuteNoValueEditCommand)
989 IPC_MESSAGE_HANDLER(FrameMsg_CSSInsertRequest, OnCSSInsertRequest)
990 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequest,
991 OnJavaScriptExecuteRequest)
992 IPC_MESSAGE_HANDLER(FrameMsg_JavaScriptExecuteRequestForTests,
993 OnJavaScriptExecuteRequestForTests)
994 IPC_MESSAGE_HANDLER(FrameMsg_VisualStateRequest,
995 OnVisualStateRequest)
996 IPC_MESSAGE_HANDLER(FrameMsg_SetEditableSelectionOffsets,
997 OnSetEditableSelectionOffsets)
998 IPC_MESSAGE_HANDLER(FrameMsg_SetupTransitionView, OnSetupTransitionView)
999 IPC_MESSAGE_HANDLER(FrameMsg_BeginExitTransition, OnBeginExitTransition)
1000 IPC_MESSAGE_HANDLER(FrameMsg_RevertExitTransition, OnRevertExitTransition)
1001 IPC_MESSAGE_HANDLER(FrameMsg_HideTransitionElements,
1002 OnHideTransitionElements)
1003 IPC_MESSAGE_HANDLER(FrameMsg_ShowTransitionElements,
1004 OnShowTransitionElements)
1005 IPC_MESSAGE_HANDLER(FrameMsg_Reload, OnReload)
1006 IPC_MESSAGE_HANDLER(FrameMsg_TextSurroundingSelectionRequest,
1007 OnTextSurroundingSelectionRequest)
1008 IPC_MESSAGE_HANDLER(FrameMsg_AddStyleSheetByURL,
1009 OnAddStyleSheetByURL)
1010 IPC_MESSAGE_HANDLER(FrameMsg_SetAccessibilityMode,
1011 OnSetAccessibilityMode)
1012 IPC_MESSAGE_HANDLER(FrameMsg_DisownOpener, OnDisownOpener)
1013 IPC_MESSAGE_HANDLER(FrameMsg_CommitNavigation, OnCommitNavigation)
1014 #if defined(OS_ANDROID)
1015 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItems, OnSelectPopupMenuItems)
1016 #elif defined(OS_MACOSX)
1017 IPC_MESSAGE_HANDLER(FrameMsg_SelectPopupMenuItem, OnSelectPopupMenuItem)
1018 IPC_MESSAGE_HANDLER(InputMsg_CopyToFindPboard, OnCopyToFindPboard)
1019 #endif
1020 IPC_END_MESSAGE_MAP()
1022 return handled;
1025 void RenderFrameImpl::OnNavigate(const FrameMsg_Navigate_Params& params) {
1026 TRACE_EVENT2("navigation", "RenderFrameImpl::OnNavigate",
1027 "id", routing_id_,
1028 "url", params.common_params.url.possibly_invalid_spec());
1030 bool is_reload =
1031 RenderViewImpl::IsReload(params.common_params.navigation_type);
1032 bool is_history_navigation = params.commit_params.page_state.IsValid();
1033 WebURLRequest::CachePolicy cache_policy =
1034 WebURLRequest::UseProtocolCachePolicy;
1035 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
1036 params.common_params.url, true, is_history_navigation,
1037 params.current_history_list_offset, &is_reload, &cache_policy)) {
1038 Send(new FrameHostMsg_DidDropNavigation(routing_id_));
1039 return;
1042 render_view_->history_list_offset_ = params.current_history_list_offset;
1043 render_view_->history_list_length_ = params.current_history_list_length;
1044 if (params.should_clear_history_list) {
1045 CHECK_EQ(-1, render_view_->history_list_offset_);
1046 CHECK_EQ(0, render_view_->history_list_length_);
1049 GetContentClient()->SetActiveURL(params.common_params.url);
1051 WebFrame* frame = frame_;
1052 if (!params.frame_to_navigate.empty()) {
1053 // TODO(nasko): Move this lookup to the browser process.
1054 frame = render_view_->webview()->findFrameByName(
1055 WebString::fromUTF8(params.frame_to_navigate));
1056 CHECK(frame) << "Invalid frame name passed: " << params.frame_to_navigate;
1059 if (is_reload && !render_view_->history_controller()->GetCurrentEntry()) {
1060 // We cannot reload if we do not have any history state. This happens, for
1061 // example, when recovering from a crash.
1062 is_reload = false;
1063 cache_policy = WebURLRequest::ReloadIgnoringCacheData;
1066 render_view_->pending_navigation_params_.reset(
1067 new FrameMsg_Navigate_Params(params));
1069 // If we are reloading, then WebKit will use the history state of the current
1070 // page, so we should just ignore any given history state. Otherwise, if we
1071 // have history state, then we need to navigate to it, which corresponds to a
1072 // back/forward navigation event.
1073 if (is_reload) {
1074 bool reload_original_url =
1075 (params.common_params.navigation_type ==
1076 FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL);
1077 bool ignore_cache = (params.common_params.navigation_type ==
1078 FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE);
1080 if (reload_original_url)
1081 frame->reloadWithOverrideURL(params.common_params.url, true);
1082 else
1083 frame->reload(ignore_cache);
1084 } else if (is_history_navigation) {
1085 // We must know the page ID of the page we are navigating back to.
1086 DCHECK_NE(params.page_id, -1);
1087 scoped_ptr<HistoryEntry> entry =
1088 PageStateToHistoryEntry(params.commit_params.page_state);
1089 if (entry) {
1090 // Ensure we didn't save the swapped out URL in UpdateState, since the
1091 // browser should never be telling us to navigate to swappedout://.
1092 CHECK(entry->root().urlString() != WebString::fromUTF8(kSwappedOutURL));
1093 render_view_->history_controller()->GoToEntry(entry.Pass(), cache_policy);
1095 } else if (!params.base_url_for_data_url.is_empty()) {
1096 // A loadData request with a specified base URL.
1097 std::string mime_type, charset, data;
1098 if (net::DataURL::Parse(
1099 params.common_params.url, &mime_type, &charset, &data)) {
1100 frame->loadData(
1101 WebData(data.c_str(), data.length()),
1102 WebString::fromUTF8(mime_type),
1103 WebString::fromUTF8(charset),
1104 params.base_url_for_data_url,
1105 params.history_url_for_data_url,
1106 false);
1107 } else {
1108 CHECK(false) << "Invalid URL passed: "
1109 << params.common_params.url.possibly_invalid_spec();
1111 } else {
1112 // Navigate to the given URL.
1113 WebURLRequest request =
1114 CreateURLRequestForNavigation(params.common_params,
1115 scoped_ptr<StreamOverrideParameters>(),
1116 frame->isViewSourceModeEnabled());
1118 if (!params.extra_headers.empty()) {
1119 for (net::HttpUtil::HeadersIterator i(params.extra_headers.begin(),
1120 params.extra_headers.end(),
1121 "\n");
1122 i.GetNext();) {
1123 request.addHTTPHeaderField(WebString::fromUTF8(i.name()),
1124 WebString::fromUTF8(i.values()));
1128 if (params.is_post) {
1129 request.setHTTPMethod(WebString::fromUTF8("POST"));
1131 // Set post data.
1132 WebHTTPBody http_body;
1133 http_body.initialize();
1134 const char* data = NULL;
1135 if (params.browser_initiated_post_data.size()) {
1136 data = reinterpret_cast<const char*>(
1137 &params.browser_initiated_post_data.front());
1139 http_body.appendData(
1140 WebData(data, params.browser_initiated_post_data.size()));
1141 request.setHTTPBody(http_body);
1144 // A session history navigation should have been accompanied by state.
1145 CHECK_EQ(params.page_id, -1);
1147 // Record this before starting the load, we need a lower bound of this time
1148 // to sanitize the navigationStart override set below.
1149 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
1150 frame->loadRequest(request);
1152 UpdateFrameNavigationTiming(
1153 frame, params.commit_params.browser_navigation_start,
1154 renderer_navigation_start);
1157 // In case LoadRequest failed before DidCreateDataSource was called.
1158 render_view_->pending_navigation_params_.reset();
1161 void RenderFrameImpl::NavigateToSwappedOutURL() {
1162 // We use loadRequest instead of loadHTMLString because the former commits
1163 // synchronously. Otherwise a new navigation can interrupt the navigation
1164 // to kSwappedOutURL. If that happens to be to the page we had been
1165 // showing, then WebKit will never send a commit and we'll be left spinning.
1166 // Set the is_swapped_out_ bit to true, so IPC filtering is in effect and
1167 // the navigation to swappedout:// is not announced to the browser side.
1168 is_swapped_out_ = true;
1169 GURL swappedOutURL(kSwappedOutURL);
1170 WebURLRequest request(swappedOutURL);
1171 frame_->loadRequest(request);
1174 void RenderFrameImpl::BindServiceRegistry(
1175 mojo::InterfaceRequest<mojo::ServiceProvider> services,
1176 mojo::ServiceProviderPtr exposed_services) {
1177 service_registry_.Bind(services.Pass());
1178 service_registry_.BindRemoteServiceProvider(exposed_services.Pass());
1181 ManifestManager* RenderFrameImpl::manifest_manager() {
1182 return manifest_manager_;
1185 void RenderFrameImpl::OnBeforeUnload() {
1186 TRACE_EVENT1("navigation", "RenderFrameImpl::OnBeforeUnload",
1187 "id", routing_id_);
1188 // TODO(creis): Right now, this is only called on the main frame. Make the
1189 // browser process send dispatchBeforeUnloadEvent to every frame that needs
1190 // it.
1191 CHECK(!frame_->parent());
1193 base::TimeTicks before_unload_start_time = base::TimeTicks::Now();
1194 bool proceed = frame_->dispatchBeforeUnloadEvent();
1195 base::TimeTicks before_unload_end_time = base::TimeTicks::Now();
1196 Send(new FrameHostMsg_BeforeUnload_ACK(routing_id_, proceed,
1197 before_unload_start_time,
1198 before_unload_end_time));
1201 void RenderFrameImpl::OnSwapOut(
1202 int proxy_routing_id,
1203 bool is_loading,
1204 const FrameReplicationState& replicated_frame_state) {
1205 TRACE_EVENT1("navigation", "RenderFrameImpl::OnSwapOut", "id", routing_id_);
1206 RenderFrameProxy* proxy = NULL;
1207 bool is_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
1208 switches::kSitePerProcess);
1209 bool is_main_frame = !frame_->parent();
1211 // Only run unload if we're not swapped out yet, but send the ack either way.
1212 if (!is_swapped_out_) {
1213 // Swap this RenderFrame out so the frame can navigate to a page rendered by
1214 // a different process. This involves running the unload handler and
1215 // clearing the page. We also allow this process to exit if there are no
1216 // other active RenderFrames in it.
1218 // Send an UpdateState message before we get swapped out.
1219 render_view_->SyncNavigationState();
1221 // If we need a proxy to replace this, create it now so its routing id is
1222 // registered for receiving IPC messages.
1223 if (proxy_routing_id != MSG_ROUTING_NONE) {
1224 proxy = RenderFrameProxy::CreateProxyToReplaceFrame(this,
1225 proxy_routing_id);
1228 // Synchronously run the unload handler before sending the ACK.
1229 // TODO(creis): Call dispatchUnloadEvent unconditionally here to support
1230 // unload on subframes as well.
1231 if (is_main_frame)
1232 frame_->dispatchUnloadEvent();
1234 // Swap out and stop sending any IPC messages that are not ACKs.
1235 if (is_main_frame)
1236 render_view_->SetSwappedOut(true);
1237 is_swapped_out_ = true;
1239 // Now that we're swapped out and filtering IPC messages, stop loading to
1240 // ensure that no other in-progress navigation continues. We do this here
1241 // to avoid sending a DidStopLoading message to the browser process.
1242 // TODO(creis): Should we be stopping all frames here and using
1243 // StopAltErrorPageFetcher with RenderView::OnStop, or just stopping this
1244 // frame?
1245 OnStop();
1247 // Transfer settings such as initial drawing parameters to the remote frame,
1248 // if one is created, that will replace this frame.
1249 if (!is_main_frame && proxy)
1250 proxy->web_frame()->initializeFromFrame(frame_);
1252 // Replace the page with a blank dummy URL. The unload handler will not be
1253 // run a second time, thanks to a check in FrameLoader::stopLoading.
1254 // TODO(creis): Need to add a better way to do this that avoids running the
1255 // beforeunload handler. For now, we just run it a second time silently.
1256 if (!is_site_per_process || is_main_frame)
1257 NavigateToSwappedOutURL();
1259 // Let WebKit know that this view is hidden so it can drop resources and
1260 // stop compositing.
1261 // TODO(creis): Support this for subframes as well.
1262 if (is_main_frame) {
1263 render_view_->webview()->setVisibilityState(
1264 blink::WebPageVisibilityStateHidden, false);
1268 // It is now safe to show modal dialogs again.
1269 // TODO(creis): Deal with modal dialogs from subframes.
1270 if (is_main_frame)
1271 render_view_->suppress_dialogs_until_swap_out_ = false;
1273 Send(new FrameHostMsg_SwapOut_ACK(routing_id_));
1275 // Now that all of the cleanup is complete and the browser side is notified,
1276 // start using the RenderFrameProxy, if one is created.
1277 if (proxy) {
1278 if (!is_main_frame) {
1279 frame_->swap(proxy->web_frame());
1281 if (is_loading)
1282 proxy->OnDidStartLoading();
1284 if (is_site_per_process) {
1285 // TODO(nasko): delete the frame here, since we've replaced it with a
1286 // proxy.
1288 } else {
1289 set_render_frame_proxy(proxy);
1293 // In --site-per-process, initialize the WebRemoteFrame with the replication
1294 // state passed by the process that is now rendering the frame.
1295 // TODO(alexmos): We cannot yet do this for swapped-out main frames, because
1296 // in that case we leave the LocalFrame as the main frame visible to Blink
1297 // and don't call swap() above. Because swap() is what creates a RemoteFrame
1298 // in proxy->web_frame(), the RemoteFrame will not exist for main frames.
1299 // When we do an unconditional swap for all frames, we can remove
1300 // !is_main_frame below.
1301 if (is_site_per_process && proxy && !is_main_frame)
1302 proxy->SetReplicatedState(replicated_frame_state);
1304 // Safe to exit if no one else is using the process.
1305 if (is_main_frame)
1306 render_view_->WasSwappedOut();
1309 void RenderFrameImpl::OnContextMenuClosed(
1310 const CustomContextMenuContext& custom_context) {
1311 if (custom_context.request_id) {
1312 // External request, should be in our map.
1313 ContextMenuClient* client =
1314 pending_context_menus_.Lookup(custom_context.request_id);
1315 if (client) {
1316 client->OnMenuClosed(custom_context.request_id);
1317 pending_context_menus_.Remove(custom_context.request_id);
1319 } else {
1320 if (custom_context.link_followed.is_valid()) {
1321 frame_->sendPings(
1322 DomUtils::ExtractParentAnchorNode(context_menu_node_),
1323 custom_context.link_followed);
1325 // Internal request, forward to WebKit.
1326 context_menu_node_.reset();
1330 void RenderFrameImpl::OnCustomContextMenuAction(
1331 const CustomContextMenuContext& custom_context,
1332 unsigned action) {
1333 if (custom_context.request_id) {
1334 // External context menu request, look in our map.
1335 ContextMenuClient* client =
1336 pending_context_menus_.Lookup(custom_context.request_id);
1337 if (client)
1338 client->OnMenuAction(custom_context.request_id, action);
1339 } else {
1340 // Internal request, forward to WebKit.
1341 render_view_->webview()->performCustomContextMenuAction(action);
1345 void RenderFrameImpl::OnUndo() {
1346 frame_->executeCommand(WebString::fromUTF8("Undo"), GetFocusedElement());
1349 void RenderFrameImpl::OnRedo() {
1350 frame_->executeCommand(WebString::fromUTF8("Redo"), GetFocusedElement());
1353 void RenderFrameImpl::OnCut() {
1354 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1355 frame_->executeCommand(WebString::fromUTF8("Cut"), GetFocusedElement());
1358 void RenderFrameImpl::OnCopy() {
1359 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1360 WebNode current_node = context_menu_node_.isNull() ?
1361 GetFocusedElement() : context_menu_node_;
1362 frame_->executeCommand(WebString::fromUTF8("Copy"), current_node);
1365 void RenderFrameImpl::OnPaste() {
1366 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1367 frame_->executeCommand(WebString::fromUTF8("Paste"), GetFocusedElement());
1370 void RenderFrameImpl::OnPasteAndMatchStyle() {
1371 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1372 frame_->executeCommand(
1373 WebString::fromUTF8("PasteAndMatchStyle"), GetFocusedElement());
1376 #if defined(OS_MACOSX)
1377 void RenderFrameImpl::OnCopyToFindPboard() {
1378 // Since the find pasteboard supports only plain text, this can be simpler
1379 // than the |OnCopy()| case.
1380 if (frame_->hasSelection()) {
1381 base::string16 selection = frame_->selectionAsText();
1382 RenderThread::Get()->Send(
1383 new ClipboardHostMsg_FindPboardWriteStringAsync(selection));
1386 #endif
1388 void RenderFrameImpl::OnDelete() {
1389 frame_->executeCommand(WebString::fromUTF8("Delete"), GetFocusedElement());
1392 void RenderFrameImpl::OnSelectAll() {
1393 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1394 frame_->executeCommand(WebString::fromUTF8("SelectAll"), GetFocusedElement());
1397 void RenderFrameImpl::OnSelectRange(const gfx::Point& base,
1398 const gfx::Point& extent) {
1399 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1400 Send(new InputHostMsg_SelectRange_ACK(GetRenderWidget()->routing_id()));
1402 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1403 frame_->selectRange(base, extent);
1406 void RenderFrameImpl::OnUnselect() {
1407 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1408 frame_->executeCommand(WebString::fromUTF8("Unselect"), GetFocusedElement());
1411 void RenderFrameImpl::OnMoveRangeSelectionExtent(const gfx::Point& point) {
1412 // This IPC is dispatched by RenderWidgetHost, so use its routing id.
1413 Send(new InputHostMsg_MoveRangeSelectionExtent_ACK(
1414 GetRenderWidget()->routing_id()));
1416 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1417 frame_->moveRangeSelectionExtent(point);
1420 void RenderFrameImpl::OnReplace(const base::string16& text) {
1421 if (!frame_->hasSelection())
1422 frame_->selectWordAroundCaret();
1424 frame_->replaceSelection(text);
1427 void RenderFrameImpl::OnReplaceMisspelling(const base::string16& text) {
1428 if (!frame_->hasSelection())
1429 return;
1431 frame_->replaceMisspelledRange(text);
1434 void RenderFrameImpl::OnCSSInsertRequest(const std::string& css) {
1435 frame_->document().insertStyleSheet(WebString::fromUTF8(css));
1438 void RenderFrameImpl::OnJavaScriptExecuteRequest(
1439 const base::string16& jscript,
1440 int id,
1441 bool notify_result) {
1442 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequest",
1443 TRACE_EVENT_SCOPE_THREAD);
1445 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1446 v8::Handle<v8::Value> result =
1447 frame_->executeScriptAndReturnValue(WebScriptSource(jscript));
1449 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1452 void RenderFrameImpl::OnJavaScriptExecuteRequestForTests(
1453 const base::string16& jscript,
1454 int id,
1455 bool notify_result) {
1456 TRACE_EVENT_INSTANT0("test_tracing", "OnJavaScriptExecuteRequestForTests",
1457 TRACE_EVENT_SCOPE_THREAD);
1459 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
1460 v8::Handle<v8::Value> result =
1461 frame_->executeScriptAndReturnValueForTests(WebScriptSource(jscript));
1463 HandleJavascriptExecutionResult(jscript, id, notify_result, result);
1466 void RenderFrameImpl::HandleJavascriptExecutionResult(
1467 const base::string16& jscript,
1468 int id,
1469 bool notify_result,
1470 v8::Handle<v8::Value> result) {
1471 if (notify_result) {
1472 base::ListValue list;
1473 if (!result.IsEmpty()) {
1474 v8::Local<v8::Context> context = frame_->mainWorldScriptContext();
1475 v8::Context::Scope context_scope(context);
1476 V8ValueConverterImpl converter;
1477 converter.SetDateAllowed(true);
1478 converter.SetRegExpAllowed(true);
1479 base::Value* result_value = converter.FromV8Value(result, context);
1480 list.Set(0, result_value ? result_value : base::Value::CreateNullValue());
1481 } else {
1482 list.Set(0, base::Value::CreateNullValue());
1484 Send(new FrameHostMsg_JavaScriptExecuteResponse(routing_id_, id, list));
1488 void RenderFrameImpl::OnVisualStateRequest(uint64 id) {
1489 GetRenderWidget()->QueueMessage(
1490 new FrameHostMsg_VisualStateResponse(routing_id_, id),
1491 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
1494 void RenderFrameImpl::OnSetEditableSelectionOffsets(int start, int end) {
1495 base::AutoReset<bool> handling_select_range(&handling_select_range_, true);
1496 if (!GetRenderWidget()->ShouldHandleImeEvent())
1497 return;
1498 ImeEventGuard guard(GetRenderWidget());
1499 frame_->setEditableSelectionOffsets(start, end);
1502 void RenderFrameImpl::OnSetCompositionFromExistingText(
1503 int start, int end,
1504 const std::vector<blink::WebCompositionUnderline>& underlines) {
1505 if (!GetRenderWidget()->ShouldHandleImeEvent())
1506 return;
1507 ImeEventGuard guard(GetRenderWidget());
1508 frame_->setCompositionFromExistingText(start, end, underlines);
1511 void RenderFrameImpl::OnExecuteNoValueEditCommand(const std::string& name) {
1512 frame_->executeCommand(WebString::fromUTF8(name), GetFocusedElement());
1515 void RenderFrameImpl::OnExtendSelectionAndDelete(int before, int after) {
1516 if (!GetRenderWidget()->ShouldHandleImeEvent())
1517 return;
1518 ImeEventGuard guard(GetRenderWidget());
1519 frame_->extendSelectionAndDelete(before, after);
1522 void RenderFrameImpl::OnSetAccessibilityMode(AccessibilityMode new_mode) {
1523 if (accessibility_mode_ == new_mode)
1524 return;
1525 accessibility_mode_ = new_mode;
1526 if (renderer_accessibility_) {
1527 // Note: this isn't called automatically by the destructor because
1528 // there'd be no point in calling it in frame teardown, only if there's
1529 // an accessibility mode change but the frame is persisting.
1530 renderer_accessibility_->DisableAccessibility();
1532 delete renderer_accessibility_;
1533 renderer_accessibility_ = NULL;
1535 if (accessibility_mode_ == AccessibilityModeOff)
1536 return;
1538 if (accessibility_mode_ & AccessibilityModeFlagFullTree)
1539 renderer_accessibility_ = new RendererAccessibility(this);
1542 void RenderFrameImpl::OnDisownOpener() {
1543 // TODO(creis): We should only see this for main frames for now. To support
1544 // disowning the opener on subframes, we will need to move WebContentsImpl's
1545 // opener_ to FrameTreeNode.
1546 CHECK(!frame_->parent());
1548 if (frame_->opener())
1549 frame_->setOpener(NULL);
1552 #if defined(OS_ANDROID)
1553 void RenderFrameImpl::OnSelectPopupMenuItems(
1554 bool canceled,
1555 const std::vector<int>& selected_indices) {
1556 // It is possible to receive more than one of these calls if the user presses
1557 // a select faster than it takes for the show-select-popup IPC message to make
1558 // it to the browser UI thread. Ignore the extra-messages.
1559 // TODO(jcivelli): http:/b/5793321 Implement a better fix, as detailed in bug.
1560 if (!external_popup_menu_)
1561 return;
1563 external_popup_menu_->DidSelectItems(canceled, selected_indices);
1564 external_popup_menu_.reset();
1566 #endif
1568 #if defined(OS_MACOSX)
1569 void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) {
1570 if (external_popup_menu_ == NULL)
1571 return;
1572 external_popup_menu_->DidSelectItem(selected_index);
1573 external_popup_menu_.reset();
1575 #endif
1577 void RenderFrameImpl::OnReload(bool ignore_cache) {
1578 frame_->reload(ignore_cache);
1581 void RenderFrameImpl::OnTextSurroundingSelectionRequest(size_t max_length) {
1582 blink::WebSurroundingText surroundingText;
1583 surroundingText.initialize(frame_->selectionRange(), max_length);
1585 if (surroundingText.isNull()) {
1586 // |surroundingText| might not be correctly initialized, for example if
1587 // |frame_->selectionRange().isNull()|, in other words, if there was no
1588 // selection.
1589 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1590 routing_id_, base::string16(), 0, 0));
1591 return;
1594 Send(new FrameHostMsg_TextSurroundingSelectionResponse(
1595 routing_id_,
1596 surroundingText.textContent(),
1597 surroundingText.startOffsetInTextContent(),
1598 surroundingText.endOffsetInTextContent()));
1601 void RenderFrameImpl::OnAddStyleSheetByURL(const std::string& url) {
1602 frame_->addStyleSheetByURL(WebString::fromUTF8(url));
1605 void RenderFrameImpl::OnSetupTransitionView(const std::string& markup) {
1606 frame_->document().setIsTransitionDocument(true);
1607 frame_->navigateToSandboxedMarkup(WebData(markup.data(), markup.length()));
1610 void RenderFrameImpl::OnBeginExitTransition(const std::string& css_selector,
1611 bool exit_to_native_app) {
1612 frame_->document().setIsTransitionDocument(true);
1613 frame_->document().beginExitTransition(WebString::fromUTF8(css_selector),
1614 exit_to_native_app);
1617 void RenderFrameImpl::OnRevertExitTransition() {
1618 frame_->document().setIsTransitionDocument(false);
1619 frame_->document().revertExitTransition();
1622 void RenderFrameImpl::OnHideTransitionElements(
1623 const std::string& css_selector) {
1624 frame_->document().hideTransitionElements(WebString::fromUTF8(css_selector));
1627 void RenderFrameImpl::OnShowTransitionElements(
1628 const std::string& css_selector) {
1629 frame_->document().showTransitionElements(WebString::fromUTF8(css_selector));
1632 bool RenderFrameImpl::RunJavaScriptMessage(JavaScriptMessageType type,
1633 const base::string16& message,
1634 const base::string16& default_value,
1635 const GURL& frame_url,
1636 base::string16* result) {
1637 // Don't allow further dialogs if we are waiting to swap out, since the
1638 // PageGroupLoadDeferrer in our stack prevents it.
1639 if (render_view()->suppress_dialogs_until_swap_out_)
1640 return false;
1642 bool success = false;
1643 base::string16 result_temp;
1644 if (!result)
1645 result = &result_temp;
1647 render_view()->SendAndRunNestedMessageLoop(
1648 new FrameHostMsg_RunJavaScriptMessage(
1649 routing_id_, message, default_value, frame_url, type, &success,
1650 result));
1651 return success;
1654 void RenderFrameImpl::LoadNavigationErrorPage(
1655 const WebURLRequest& failed_request,
1656 const WebURLError& error,
1657 bool replace) {
1658 std::string error_html;
1659 GetContentClient()->renderer()->GetNavigationErrorStrings(
1660 render_view(), frame_, failed_request, error, &error_html, NULL);
1662 frame_->loadHTMLString(error_html,
1663 GURL(kUnreachableWebDataURL),
1664 error.unreachableURL,
1665 replace);
1668 void RenderFrameImpl::DidCommitCompositorFrame() {
1669 if (BrowserPluginManager::Get())
1670 BrowserPluginManager::Get()->DidCommitCompositorFrame(GetRoutingID());
1671 FOR_EACH_OBSERVER(
1672 RenderFrameObserver, observers_, DidCommitCompositorFrame());
1675 RenderView* RenderFrameImpl::GetRenderView() {
1676 return render_view_.get();
1679 int RenderFrameImpl::GetRoutingID() {
1680 return routing_id_;
1683 blink::WebLocalFrame* RenderFrameImpl::GetWebFrame() {
1684 DCHECK(frame_);
1685 return frame_;
1688 WebElement RenderFrameImpl::GetFocusedElement() const {
1689 WebDocument doc = frame_->document();
1690 if (!doc.isNull())
1691 return doc.focusedElement();
1693 return WebElement();
1696 WebPreferences& RenderFrameImpl::GetWebkitPreferences() {
1697 return render_view_->GetWebkitPreferences();
1700 int RenderFrameImpl::ShowContextMenu(ContextMenuClient* client,
1701 const ContextMenuParams& params) {
1702 DCHECK(client); // A null client means "internal" when we issue callbacks.
1703 ContextMenuParams our_params(params);
1704 our_params.custom_context.request_id = pending_context_menus_.Add(client);
1705 Send(new FrameHostMsg_ContextMenu(routing_id_, our_params));
1706 return our_params.custom_context.request_id;
1709 void RenderFrameImpl::CancelContextMenu(int request_id) {
1710 DCHECK(pending_context_menus_.Lookup(request_id));
1711 pending_context_menus_.Remove(request_id);
1714 blink::WebNode RenderFrameImpl::GetContextMenuNode() const {
1715 return context_menu_node_;
1718 blink::WebPlugin* RenderFrameImpl::CreatePlugin(
1719 blink::WebFrame* frame,
1720 const WebPluginInfo& info,
1721 const blink::WebPluginParams& params,
1722 scoped_ptr<content::PluginInstanceThrottler> throttler) {
1723 DCHECK_EQ(frame_, frame);
1724 #if defined(ENABLE_PLUGINS)
1725 if (info.type == WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN) {
1726 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1727 GetContentClient()->renderer()->CreateBrowserPluginDelegate(
1728 this, params.mimeType.utf8(), GURL(params.url)));
1729 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1730 this, browser_plugin_delegate.Pass());
1733 bool pepper_plugin_was_registered = false;
1734 scoped_refptr<PluginModule> pepper_module(PluginModule::Create(
1735 this, info, &pepper_plugin_was_registered));
1736 if (pepper_plugin_was_registered) {
1737 if (pepper_module.get()) {
1738 return new PepperWebPluginImpl(
1739 pepper_module.get(), params, this,
1740 make_scoped_ptr(
1741 static_cast<PluginInstanceThrottlerImpl*>(throttler.release())));
1744 #if defined(OS_CHROMEOS)
1745 LOG(WARNING) << "Pepper module/plugin creation failed.";
1746 return NULL;
1747 #else
1748 // TODO(jam): change to take RenderFrame.
1749 return new WebPluginImpl(frame, params, info.path, render_view_, this);
1750 #endif
1751 #else
1752 return NULL;
1753 #endif
1756 void RenderFrameImpl::LoadURLExternally(blink::WebLocalFrame* frame,
1757 const blink::WebURLRequest& request,
1758 blink::WebNavigationPolicy policy) {
1759 DCHECK(!frame_ || frame_ == frame);
1760 loadURLExternally(frame, request, policy, WebString());
1763 void RenderFrameImpl::ExecuteJavaScript(const base::string16& javascript) {
1764 OnJavaScriptExecuteRequest(javascript, 0, false);
1767 ServiceRegistry* RenderFrameImpl::GetServiceRegistry() {
1768 return &service_registry_;
1771 #if defined(ENABLE_PLUGINS)
1772 void RenderFrameImpl::RegisterPeripheralPlugin(
1773 const GURL& content_origin,
1774 const base::Closure& unthrottle_callback) {
1775 return plugin_power_saver_helper_->RegisterPeripheralPlugin(
1776 content_origin, unthrottle_callback);
1778 #endif // defined(ENABLE_PLUGINS)
1780 bool RenderFrameImpl::IsFTPDirectoryListing() {
1781 WebURLResponseExtraDataImpl* extra_data =
1782 GetExtraDataFromResponse(frame_->dataSource()->response());
1783 return extra_data ? extra_data->is_ftp_directory_listing() : false;
1786 void RenderFrameImpl::AttachGuest(int element_instance_id) {
1787 BrowserPluginManager::Get()->Attach(element_instance_id);
1790 void RenderFrameImpl::DetachGuest(int element_instance_id) {
1791 BrowserPluginManager::Get()->Detach(element_instance_id);
1794 void RenderFrameImpl::SetSelectedText(const base::string16& selection_text,
1795 size_t offset,
1796 const gfx::Range& range) {
1797 // Use the routing id of Render Widget Host.
1798 Send(new ViewHostMsg_SelectionChanged(GetRenderWidget()->routing_id(),
1799 selection_text,
1800 offset,
1801 range));
1804 void RenderFrameImpl::EnsureMojoBuiltinsAreAvailable(
1805 v8::Isolate* isolate,
1806 v8::Handle<v8::Context> context) {
1807 gin::ModuleRegistry* registry = gin::ModuleRegistry::From(context);
1808 if (registry->available_modules().count(mojo::js::Core::kModuleName))
1809 return;
1811 v8::HandleScope handle_scope(isolate);
1812 registry->AddBuiltinModule(
1813 isolate, mojo::js::Core::kModuleName, mojo::js::Core::GetModule(isolate));
1814 registry->AddBuiltinModule(isolate,
1815 mojo::js::Support::kModuleName,
1816 mojo::js::Support::GetModule(isolate));
1817 registry->AddBuiltinModule(
1818 isolate,
1819 ServiceRegistryJsWrapper::kModuleName,
1820 ServiceRegistryJsWrapper::Create(isolate, &service_registry_).ToV8());
1823 // blink::WebFrameClient implementation ----------------------------------------
1825 blink::WebPluginPlaceholder* RenderFrameImpl::createPluginPlaceholder(
1826 blink::WebLocalFrame* frame,
1827 const blink::WebPluginParams& params) {
1828 DCHECK_EQ(frame_, frame);
1829 return GetContentClient()
1830 ->renderer()
1831 ->CreatePluginPlaceholder(this, frame, params)
1832 .release();
1835 blink::WebPlugin* RenderFrameImpl::createPlugin(
1836 blink::WebLocalFrame* frame,
1837 const blink::WebPluginParams& params) {
1838 DCHECK_EQ(frame_, frame);
1839 blink::WebPlugin* plugin = NULL;
1840 if (GetContentClient()->renderer()->OverrideCreatePlugin(
1841 this, frame, params, &plugin)) {
1842 return plugin;
1845 if (base::UTF16ToUTF8(params.mimeType) == kBrowserPluginMimeType) {
1846 scoped_ptr<BrowserPluginDelegate> browser_plugin_delegate(
1847 GetContentClient()->renderer()->CreateBrowserPluginDelegate(this,
1848 kBrowserPluginMimeType, GURL(params.url)));
1849 return BrowserPluginManager::Get()->CreateBrowserPlugin(
1850 this, browser_plugin_delegate.Pass());
1853 #if defined(ENABLE_PLUGINS)
1854 WebPluginInfo info;
1855 std::string mime_type;
1856 bool found = false;
1857 Send(new FrameHostMsg_GetPluginInfo(
1858 routing_id_, params.url, frame->top()->document().url(),
1859 params.mimeType.utf8(), &found, &info, &mime_type));
1860 if (!found)
1861 return NULL;
1863 WebPluginParams params_to_use = params;
1864 params_to_use.mimeType = WebString::fromUTF8(mime_type);
1865 return CreatePlugin(frame, info, params_to_use, nullptr /* throttler */);
1866 #else
1867 return NULL;
1868 #endif // defined(ENABLE_PLUGINS)
1871 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1872 blink::WebLocalFrame* frame,
1873 const blink::WebURL& url,
1874 blink::WebMediaPlayerClient* client) {
1875 return createMediaPlayer(frame, url, client, nullptr);
1878 blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
1879 blink::WebLocalFrame* frame,
1880 const blink::WebURL& url,
1881 blink::WebMediaPlayerClient* client,
1882 blink::WebContentDecryptionModule* initial_cdm) {
1883 #if defined(VIDEO_HOLE)
1884 if (!contains_media_player_) {
1885 render_view_->RegisterVideoHoleFrame(this);
1886 contains_media_player_ = true;
1888 #endif // defined(VIDEO_HOLE)
1890 blink::WebMediaStream web_stream(
1891 blink::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));
1892 if (!web_stream.isNull())
1893 return CreateWebMediaPlayerForMediaStream(url, client);
1895 if (!media_permission_dispatcher_)
1896 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
1898 #if defined(OS_ANDROID)
1899 return CreateAndroidWebMediaPlayer(url, client, media_permission_dispatcher_,
1900 initial_cdm);
1901 #else
1902 scoped_refptr<media::MediaLog> media_log(new RenderMediaLog());
1905 RenderThreadImpl* render_thread = RenderThreadImpl::current();
1906 media::WebMediaPlayerParams params(
1907 base::Bind(&ContentRendererClient::DeferMediaLoad,
1908 base::Unretained(GetContentClient()->renderer()),
1909 static_cast<RenderFrame*>(this)),
1910 render_thread->GetAudioRendererMixerManager()->CreateInput(
1911 render_view_->routing_id_, routing_id_),
1912 media_log, render_thread->GetMediaThreadTaskRunner(),
1913 render_thread->compositor_message_loop_proxy(),
1914 base::Bind(&GetSharedMainThreadContext3D), media_permission_dispatcher_,
1915 initial_cdm);
1917 #if defined(ENABLE_PEPPER_CDMS)
1918 scoped_ptr<media::CdmFactory> cdm_factory(
1919 new RenderCdmFactory(base::Bind(&PepperCdmWrapperImpl::Create, frame)));
1920 #elif defined(ENABLE_BROWSER_CDMS)
1921 scoped_ptr<media::CdmFactory> cdm_factory(
1922 new RenderCdmFactory(GetCdmManager()));
1923 #else
1924 scoped_ptr<media::CdmFactory> cdm_factory(new RenderCdmFactory());
1925 #endif
1927 #if defined(ENABLE_MEDIA_MOJO_RENDERER)
1928 scoped_ptr<media::RendererFactory> media_renderer_factory(
1929 new media::MojoRendererFactory(make_scoped_ptr(
1930 new MediaRendererServiceProvider(GetServiceRegistry()))));
1931 #else
1932 scoped_ptr<media::RendererFactory> media_renderer_factory =
1933 GetContentClient()->renderer()->CreateMediaRendererFactory(this,
1934 media_log);
1936 if (!media_renderer_factory.get()) {
1937 media_renderer_factory.reset(new media::DefaultRendererFactory(
1938 media_log, render_thread->GetGpuFactories(),
1939 *render_thread->GetAudioHardwareConfig()));
1941 #endif // defined(ENABLE_MEDIA_MOJO_RENDERER)
1943 return new media::WebMediaPlayerImpl(
1944 frame, client, weak_factory_.GetWeakPtr(), media_renderer_factory.Pass(),
1945 cdm_factory.Pass(), params);
1946 #endif // defined(OS_ANDROID)
1949 blink::WebApplicationCacheHost* RenderFrameImpl::createApplicationCacheHost(
1950 blink::WebLocalFrame* frame,
1951 blink::WebApplicationCacheHostClient* client) {
1952 if (!frame || !frame->view())
1953 return NULL;
1954 DCHECK(!frame_ || frame_ == frame);
1955 return new RendererWebApplicationCacheHostImpl(
1956 RenderViewImpl::FromWebView(frame->view()), client,
1957 RenderThreadImpl::current()->appcache_dispatcher()->backend_proxy());
1960 blink::WebWorkerPermissionClientProxy*
1961 RenderFrameImpl::createWorkerPermissionClientProxy(
1962 blink::WebLocalFrame* frame) {
1963 if (!frame || !frame->view())
1964 return NULL;
1965 DCHECK(!frame_ || frame_ == frame);
1966 return GetContentClient()->renderer()->CreateWorkerPermissionClientProxy(
1967 this, frame);
1970 WebExternalPopupMenu* RenderFrameImpl::createExternalPopupMenu(
1971 const WebPopupMenuInfo& popup_menu_info,
1972 WebExternalPopupMenuClient* popup_menu_client) {
1973 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1974 // An IPC message is sent to the browser to build and display the actual
1975 // popup. The user could have time to click a different select by the time
1976 // the popup is shown. In that case external_popup_menu_ is non NULL.
1977 // By returning NULL in that case, we instruct Blink to cancel that new
1978 // popup. So from the user perspective, only the first one will show, and
1979 // will have to close the first one before another one can be shown.
1980 if (external_popup_menu_)
1981 return NULL;
1982 external_popup_menu_.reset(
1983 new ExternalPopupMenu(this, popup_menu_info, popup_menu_client));
1984 if (render_view_->screen_metrics_emulator_) {
1985 render_view_->SetExternalPopupOriginAdjustmentsForEmulation(
1986 external_popup_menu_.get(),
1987 render_view_->screen_metrics_emulator_.get());
1989 return external_popup_menu_.get();
1990 #else
1991 return NULL;
1992 #endif
1995 blink::WebCookieJar* RenderFrameImpl::cookieJar(blink::WebLocalFrame* frame) {
1996 DCHECK(!frame_ || frame_ == frame);
1997 return &cookie_jar_;
2000 blink::WebServiceWorkerProvider* RenderFrameImpl::createServiceWorkerProvider(
2001 blink::WebLocalFrame* frame) {
2002 DCHECK(!frame_ || frame_ == frame);
2003 // At this point we should have non-null data source.
2004 DCHECK(frame->dataSource());
2005 if (!ChildThreadImpl::current())
2006 return NULL; // May be null in some tests.
2007 ServiceWorkerNetworkProvider* provider =
2008 ServiceWorkerNetworkProvider::FromDocumentState(
2009 DocumentState::FromDataSource(frame->dataSource()));
2010 return new WebServiceWorkerProviderImpl(
2011 ChildThreadImpl::current()->thread_safe_sender(),
2012 provider ? provider->context() : NULL);
2015 void RenderFrameImpl::didAccessInitialDocument(blink::WebLocalFrame* frame) {
2016 DCHECK(!frame_ || frame_ == frame);
2017 // If the request hasn't yet committed, notify the browser process that it is
2018 // no longer safe to show the pending URL of the main frame, since a URL spoof
2019 // is now possible. (If the request has committed, the browser already knows.)
2020 if (!frame->parent()) {
2021 DocumentState* document_state =
2022 DocumentState::FromDataSource(frame->dataSource());
2023 NavigationState* navigation_state = document_state->navigation_state();
2025 if (!navigation_state->request_committed()) {
2026 Send(new FrameHostMsg_DidAccessInitialDocument(routing_id_));
2031 blink::WebFrame* RenderFrameImpl::createChildFrame(
2032 blink::WebLocalFrame* parent,
2033 const blink::WebString& name,
2034 blink::WebSandboxFlags sandbox_flags) {
2035 // Synchronously notify the browser of a child frame creation to get the
2036 // routing_id for the RenderFrame.
2037 int child_routing_id = MSG_ROUTING_NONE;
2038 Send(new FrameHostMsg_CreateChildFrame(
2039 routing_id_, base::UTF16ToUTF8(name),
2040 WebToContentSandboxFlags(sandbox_flags), &child_routing_id));
2042 // Allocation of routing id failed, so we can't create a child frame. This can
2043 // happen if this RenderFrameImpl's IPCs are being filtered when in swapped
2044 // out state or synchronous IPC message above has failed.
2045 if (child_routing_id == MSG_ROUTING_NONE) {
2046 NOTREACHED() << "Failed to allocate routing id for child frame.";
2047 return nullptr;
2050 // Create the RenderFrame and WebLocalFrame, linking the two.
2051 RenderFrameImpl* child_render_frame = RenderFrameImpl::Create(
2052 render_view_.get(), child_routing_id);
2053 blink::WebLocalFrame* web_frame = WebLocalFrame::create(child_render_frame);
2054 child_render_frame->SetWebFrame(web_frame);
2056 // Add the frame to the frame tree and initialize it.
2057 parent->appendChild(web_frame);
2058 child_render_frame->Initialize();
2060 return web_frame;
2063 void RenderFrameImpl::didDisownOpener(blink::WebLocalFrame* frame) {
2064 DCHECK(!frame_ || frame_ == frame);
2065 // We only need to notify the browser if the active, top-level frame clears
2066 // its opener. We can ignore cases where a swapped out frame clears its
2067 // opener after hearing about it from the browser, and the browser does not
2068 // (yet) care about subframe openers.
2069 if (is_swapped_out_ || frame->parent())
2070 return;
2072 // Notify WebContents and all its swapped out RenderViews.
2073 Send(new FrameHostMsg_DidDisownOpener(routing_id_));
2076 void RenderFrameImpl::frameDetached(blink::WebFrame* frame) {
2077 // NOTE: This function is called on the frame that is being detached and not
2078 // the parent frame. This is different from createChildFrame() which is
2079 // called on the parent frame.
2080 CHECK(!is_detaching_);
2081 DCHECK(!frame_ || frame_ == frame);
2083 bool is_subframe = !!frame->parent();
2085 Send(new FrameHostMsg_Detach(routing_id_));
2087 // The |is_detaching_| flag disables Send(). FrameHostMsg_Detach must be
2088 // sent before setting |is_detaching_| to true. In contrast, Observers
2089 // should only be notified afterwards so they cannot call back into here and
2090 // have IPCs fired off.
2091 is_detaching_ = true;
2093 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameDetached());
2094 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2095 FrameDetached(frame));
2097 // We need to clean up subframes by removing them from the map and deleting
2098 // the RenderFrameImpl. In contrast, the main frame is owned by its
2099 // containing RenderViewHost (so that they have the same lifetime), so only
2100 // removal from the map is needed and no deletion.
2101 FrameMap::iterator it = g_frame_map.Get().find(frame);
2102 CHECK(it != g_frame_map.Get().end());
2103 CHECK_EQ(it->second, this);
2104 g_frame_map.Get().erase(it);
2106 if (is_subframe)
2107 frame->parent()->removeChild(frame);
2109 // |frame| is invalid after here.
2110 frame->close();
2112 if (is_subframe) {
2113 delete this;
2114 // Object is invalid after this point.
2118 void RenderFrameImpl::frameFocused() {
2119 Send(new FrameHostMsg_FrameFocused(routing_id_));
2122 void RenderFrameImpl::willClose(blink::WebFrame* frame) {
2123 DCHECK(!frame_ || frame_ == frame);
2125 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FrameWillClose());
2126 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2127 FrameWillClose(frame));
2130 void RenderFrameImpl::didChangeName(blink::WebLocalFrame* frame,
2131 const blink::WebString& name) {
2132 DCHECK(!frame_ || frame_ == frame);
2133 if (!render_view_->renderer_preferences_.report_frame_name_changes)
2134 return;
2136 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeName(name));
2139 void RenderFrameImpl::didMatchCSS(
2140 blink::WebLocalFrame* frame,
2141 const blink::WebVector<blink::WebString>& newly_matching_selectors,
2142 const blink::WebVector<blink::WebString>& stopped_matching_selectors) {
2143 DCHECK(!frame_ || frame_ == frame);
2145 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2146 DidMatchCSS(frame,
2147 newly_matching_selectors,
2148 stopped_matching_selectors));
2151 bool RenderFrameImpl::shouldReportDetailedMessageForSource(
2152 const blink::WebString& source) {
2153 return GetContentClient()->renderer()->ShouldReportDetailedMessageForSource(
2154 source);
2157 void RenderFrameImpl::didAddMessageToConsole(
2158 const blink::WebConsoleMessage& message,
2159 const blink::WebString& source_name,
2160 unsigned source_line,
2161 const blink::WebString& stack_trace) {
2162 logging::LogSeverity log_severity = logging::LOG_VERBOSE;
2163 switch (message.level) {
2164 case blink::WebConsoleMessage::LevelDebug:
2165 log_severity = logging::LOG_VERBOSE;
2166 break;
2167 case blink::WebConsoleMessage::LevelLog:
2168 case blink::WebConsoleMessage::LevelInfo:
2169 log_severity = logging::LOG_INFO;
2170 break;
2171 case blink::WebConsoleMessage::LevelWarning:
2172 log_severity = logging::LOG_WARNING;
2173 break;
2174 case blink::WebConsoleMessage::LevelError:
2175 log_severity = logging::LOG_ERROR;
2176 break;
2177 default:
2178 NOTREACHED();
2181 if (shouldReportDetailedMessageForSource(source_name)) {
2182 FOR_EACH_OBSERVER(
2183 RenderFrameObserver, observers_,
2184 DetailedConsoleMessageAdded(message.text,
2185 source_name,
2186 stack_trace,
2187 source_line,
2188 static_cast<int32>(log_severity)));
2191 Send(new FrameHostMsg_AddMessageToConsole(routing_id_,
2192 static_cast<int32>(log_severity),
2193 message.text,
2194 static_cast<int32>(source_line),
2195 source_name));
2198 void RenderFrameImpl::loadURLExternally(
2199 blink::WebLocalFrame* frame,
2200 const blink::WebURLRequest& request,
2201 blink::WebNavigationPolicy policy,
2202 const blink::WebString& suggested_name) {
2203 DCHECK(!frame_ || frame_ == frame);
2204 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(frame, request));
2205 if (policy == blink::WebNavigationPolicyDownload) {
2206 render_view_->Send(new ViewHostMsg_DownloadUrl(render_view_->GetRoutingID(),
2207 request.url(), referrer,
2208 suggested_name));
2209 } else {
2210 OpenURL(frame, request.url(), referrer, policy);
2214 blink::WebNavigationPolicy RenderFrameImpl::decidePolicyForNavigation(
2215 const NavigationPolicyInfo& info) {
2216 DCHECK(!frame_ || frame_ == info.frame);
2217 return DecidePolicyForNavigation(this, info);
2220 blink::WebHistoryItem RenderFrameImpl::historyItemForNewChildFrame(
2221 blink::WebFrame* frame) {
2222 DCHECK(!frame_ || frame_ == frame);
2223 return render_view_->history_controller()->GetItemForNewChildFrame(this);
2226 void RenderFrameImpl::willSendSubmitEvent(blink::WebLocalFrame* frame,
2227 const blink::WebFormElement& form) {
2228 DCHECK(!frame_ || frame_ == frame);
2230 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSendSubmitEvent(form));
2233 void RenderFrameImpl::willSubmitForm(blink::WebLocalFrame* frame,
2234 const blink::WebFormElement& form) {
2235 DCHECK(!frame_ || frame_ == frame);
2236 DocumentState* document_state =
2237 DocumentState::FromDataSource(frame->provisionalDataSource());
2238 NavigationState* navigation_state = document_state->navigation_state();
2239 InternalDocumentStateData* internal_data =
2240 InternalDocumentStateData::FromDocumentState(document_state);
2242 if (ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2243 ui::PAGE_TRANSITION_LINK)) {
2244 navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT);
2247 // Save these to be processed when the ensuing navigation is committed.
2248 WebSearchableFormData web_searchable_form_data(form);
2249 internal_data->set_searchable_form_url(web_searchable_form_data.url());
2250 internal_data->set_searchable_form_encoding(
2251 web_searchable_form_data.encoding().utf8());
2253 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form));
2256 void RenderFrameImpl::didCreateDataSource(blink::WebLocalFrame* frame,
2257 blink::WebDataSource* datasource) {
2258 DCHECK(!frame_ || frame_ == frame);
2260 // TODO(nasko): Move implementation here. Needed state:
2261 // * pending_navigation_params_
2262 // * webview
2263 // Needed methods:
2264 // * PopulateDocumentStateFromPending
2265 // * CreateNavigationStateFromPending
2266 render_view_->didCreateDataSource(frame, datasource);
2268 // Create the serviceworker's per-document network observing object if it
2269 // does not exist (When navigation happens within a page, the provider already
2270 // exists).
2271 if (!ServiceWorkerNetworkProvider::FromDocumentState(
2272 DocumentState::FromDataSource(datasource))) {
2273 scoped_ptr<ServiceWorkerNetworkProvider>
2274 network_provider(new ServiceWorkerNetworkProvider(
2275 routing_id_, SERVICE_WORKER_PROVIDER_FOR_CONTROLLEE));
2276 ServiceWorkerNetworkProvider::AttachToDocumentState(
2277 DocumentState::FromDataSource(datasource),
2278 network_provider.Pass());
2282 void RenderFrameImpl::didStartProvisionalLoad(blink::WebLocalFrame* frame,
2283 bool is_transition_navigation,
2284 double triggering_event_time) {
2285 DCHECK(!frame_ || frame_ == frame);
2286 WebDataSource* ds = frame->provisionalDataSource();
2288 // In fast/loader/stop-provisional-loads.html, we abort the load before this
2289 // callback is invoked.
2290 if (!ds)
2291 return;
2293 TRACE_EVENT2("navigation", "RenderFrameImpl::didStartProvisionalLoad",
2294 "id", routing_id_, "url", ds->request().url().string().utf8());
2295 DocumentState* document_state = DocumentState::FromDataSource(ds);
2297 // We should only navigate to swappedout:// when is_swapped_out_ is true.
2298 CHECK((ds->request().url() != GURL(kSwappedOutURL)) ||
2299 is_swapped_out_) <<
2300 "Heard swappedout:// when not swapped out.";
2302 // Update the request time if WebKit has better knowledge of it.
2303 if (document_state->request_time().is_null() &&
2304 triggering_event_time != 0.0) {
2305 document_state->set_request_time(Time::FromDoubleT(triggering_event_time));
2308 // Start time is only set after request time.
2309 document_state->set_start_load_time(Time::Now());
2311 bool is_top_most = !frame->parent();
2312 if (is_top_most) {
2313 render_view_->set_navigation_gesture(
2314 WebUserGestureIndicator::isProcessingUserGesture() ?
2315 NavigationGestureUser : NavigationGestureAuto);
2316 } else if (ds->replacesCurrentHistoryItem()) {
2317 // Subframe navigations that don't add session history items must be
2318 // marked with AUTO_SUBFRAME. See also didFailProvisionalLoad for how we
2319 // handle loading of error pages.
2320 document_state->navigation_state()->set_transition_type(
2321 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2324 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2325 DidStartProvisionalLoad(frame));
2326 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidStartProvisionalLoad());
2328 Send(new FrameHostMsg_DidStartProvisionalLoadForFrame(
2329 routing_id_, ds->request().url(), is_transition_navigation));
2332 void RenderFrameImpl::didReceiveServerRedirectForProvisionalLoad(
2333 blink::WebLocalFrame* frame) {
2334 DCHECK(!frame_ || frame_ == frame);
2335 render_view_->history_controller()->RemoveChildrenForRedirect(this);
2338 void RenderFrameImpl::didFailProvisionalLoad(blink::WebLocalFrame* frame,
2339 const blink::WebURLError& error) {
2340 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailProvisionalLoad",
2341 "id", routing_id_);
2342 DCHECK(!frame_ || frame_ == frame);
2343 WebDataSource* ds = frame->provisionalDataSource();
2344 DCHECK(ds);
2346 const WebURLRequest& failed_request = ds->request();
2348 // Notify the browser that we failed a provisional load with an error.
2350 // Note: It is important this notification occur before DidStopLoading so the
2351 // SSL manager can react to the provisional load failure before being
2352 // notified the load stopped.
2354 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2355 DidFailProvisionalLoad(frame, error));
2356 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2357 DidFailProvisionalLoad(error));
2359 bool show_repost_interstitial =
2360 (error.reason == net::ERR_CACHE_MISS &&
2361 EqualsASCII(failed_request.httpMethod(), "POST"));
2363 FrameHostMsg_DidFailProvisionalLoadWithError_Params params;
2364 params.error_code = error.reason;
2365 GetContentClient()->renderer()->GetNavigationErrorStrings(
2366 render_view_.get(),
2367 frame,
2368 failed_request,
2369 error,
2370 NULL,
2371 &params.error_description);
2372 params.url = error.unreachableURL;
2373 params.showing_repost_interstitial = show_repost_interstitial;
2374 Send(new FrameHostMsg_DidFailProvisionalLoadWithError(
2375 routing_id_, params));
2377 // Don't display an error page if this is simply a cancelled load. Aside
2378 // from being dumb, WebCore doesn't expect it and it will cause a crash.
2379 if (error.reason == net::ERR_ABORTED)
2380 return;
2382 // Don't display "client blocked" error page if browser has asked us not to.
2383 if (error.reason == net::ERR_BLOCKED_BY_CLIENT &&
2384 render_view_->renderer_preferences_.disable_client_blocked_error_page) {
2385 return;
2388 // Allow the embedder to suppress an error page.
2389 if (GetContentClient()->renderer()->ShouldSuppressErrorPage(this,
2390 error.unreachableURL)) {
2391 return;
2394 if (RenderThreadImpl::current() &&
2395 RenderThreadImpl::current()->layout_test_mode()) {
2396 return;
2399 // Make sure we never show errors in view source mode.
2400 frame->enableViewSourceMode(false);
2402 DocumentState* document_state = DocumentState::FromDataSource(ds);
2403 NavigationState* navigation_state = document_state->navigation_state();
2405 // If this is a failed back/forward/reload navigation, then we need to do a
2406 // 'replace' load. This is necessary to avoid messing up session history.
2407 // Otherwise, we do a normal load, which simulates a 'go' navigation as far
2408 // as session history is concerned.
2410 // AUTO_SUBFRAME loads should always be treated as loads that do not advance
2411 // the page id.
2413 // TODO(davidben): This should also take the failed navigation's replacement
2414 // state into account, if a location.replace() failed.
2415 bool replace =
2416 navigation_state->pending_page_id() != -1 ||
2417 ui::PageTransitionCoreTypeIs(navigation_state->transition_type(),
2418 ui::PAGE_TRANSITION_AUTO_SUBFRAME);
2420 // If we failed on a browser initiated request, then make sure that our error
2421 // page load is regarded as the same browser initiated request.
2422 if (!navigation_state->is_content_initiated()) {
2423 render_view_->pending_navigation_params_.reset(
2424 new FrameMsg_Navigate_Params);
2425 render_view_->pending_navigation_params_->page_id =
2426 navigation_state->pending_page_id();
2427 render_view_->pending_navigation_params_->pending_history_list_offset =
2428 navigation_state->pending_history_list_offset();
2429 render_view_->pending_navigation_params_->should_clear_history_list =
2430 navigation_state->history_list_was_cleared();
2431 render_view_->pending_navigation_params_->common_params.transition =
2432 navigation_state->transition_type();
2433 render_view_->pending_navigation_params_->request_time =
2434 document_state->request_time();
2435 render_view_->pending_navigation_params_->should_replace_current_entry =
2436 replace;
2439 // Load an error page.
2440 LoadNavigationErrorPage(failed_request, error, replace);
2443 void RenderFrameImpl::didCommitProvisionalLoad(
2444 blink::WebLocalFrame* frame,
2445 const blink::WebHistoryItem& item,
2446 blink::WebHistoryCommitType commit_type) {
2447 TRACE_EVENT2("navigation", "RenderFrameImpl::didCommitProvisionalLoad",
2448 "id", routing_id_,
2449 "url", GetLoadingUrl().possibly_invalid_spec());
2450 DCHECK(!frame_ || frame_ == frame);
2451 DocumentState* document_state =
2452 DocumentState::FromDataSource(frame->dataSource());
2453 NavigationState* navigation_state = document_state->navigation_state();
2455 if (proxy_routing_id_ != MSG_ROUTING_NONE) {
2456 RenderFrameProxy* proxy =
2457 RenderFrameProxy::FromRoutingID(proxy_routing_id_);
2458 CHECK(proxy);
2459 proxy->web_frame()->swap(frame_);
2460 proxy_routing_id_ = MSG_ROUTING_NONE;
2463 // When we perform a new navigation, we need to update the last committed
2464 // session history entry with state for the page we are leaving. Do this
2465 // before updating the HistoryController state.
2466 render_view_->UpdateSessionHistory(frame);
2468 render_view_->history_controller()->UpdateForCommit(this, item, commit_type,
2469 navigation_state->was_within_same_page());
2471 InternalDocumentStateData* internal_data =
2472 InternalDocumentStateData::FromDocumentState(document_state);
2474 if (document_state->commit_load_time().is_null())
2475 document_state->set_commit_load_time(Time::Now());
2477 if (internal_data->must_reset_scroll_and_scale_state()) {
2478 render_view_->webview()->resetScrollAndScaleState();
2479 internal_data->set_must_reset_scroll_and_scale_state(false);
2481 internal_data->set_use_error_page(false);
2483 bool is_new_navigation = commit_type == blink::WebStandardCommit;
2484 if (is_new_navigation) {
2485 // We bump our Page ID to correspond with the new session history entry.
2486 render_view_->page_id_ = render_view_->next_page_id_++;
2488 // Don't update history list values for kSwappedOutURL, since
2489 // we don't want to forget the entry that was there, and since we will
2490 // never come back to kSwappedOutURL. Note that we have to call
2491 // UpdateSessionHistory and update page_id_ even in this case, so that
2492 // the current entry gets a state update and so that we don't send a
2493 // state update to the wrong entry when we swap back in.
2494 DCHECK(render_view_->history_list_length_ > 0 ||
2495 !navigation_state->should_replace_current_entry());
2496 if (GetLoadingUrl() != GURL(kSwappedOutURL) &&
2497 !navigation_state->should_replace_current_entry()) {
2498 // Advance our offset in session history, applying the length limit.
2499 // There is now no forward history.
2500 render_view_->history_list_offset_++;
2501 if (render_view_->history_list_offset_ >= kMaxSessionHistoryEntries)
2502 render_view_->history_list_offset_ = kMaxSessionHistoryEntries - 1;
2503 render_view_->history_list_length_ =
2504 render_view_->history_list_offset_ + 1;
2506 } else {
2507 // Inspect the navigation_state on this frame to see if the navigation
2508 // corresponds to a session history navigation... Note: |frame| may or
2509 // may not be the toplevel frame, but for the case of capturing session
2510 // history, the first committed frame suffices. We keep track of whether
2511 // we've seen this commit before so that only capture session history once
2512 // per navigation.
2514 // Note that we need to check if the page ID changed. In the case of a
2515 // reload, the page ID doesn't change, and UpdateSessionHistory gets the
2516 // previous URL and the current page ID, which would be wrong.
2517 if (navigation_state->pending_page_id() != -1 &&
2518 navigation_state->pending_page_id() != render_view_->page_id_ &&
2519 !navigation_state->request_committed()) {
2520 // This is a successful session history navigation!
2521 render_view_->page_id_ = navigation_state->pending_page_id();
2523 render_view_->history_list_offset_ =
2524 navigation_state->pending_history_list_offset();
2528 bool sent = Send(
2529 new FrameHostMsg_DidAssignPageId(routing_id_, render_view_->page_id_));
2530 CHECK(sent); // http://crbug.com/407376
2532 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_,
2533 DidCommitProvisionalLoad(frame, is_new_navigation));
2534 FOR_EACH_OBSERVER(RenderFrameObserver, observers_,
2535 DidCommitProvisionalLoad(is_new_navigation));
2537 if (!frame->parent()) { // Only for top frames.
2538 RenderThreadImpl* render_thread_impl = RenderThreadImpl::current();
2539 if (render_thread_impl) { // Can be NULL in tests.
2540 render_thread_impl->histogram_customizer()->
2541 RenderViewNavigatedToHost(GURL(GetLoadingUrl()).host(),
2542 RenderViewImpl::GetRenderViewCount());
2546 // Remember that we've already processed this request, so we don't update
2547 // the session history again. We do this regardless of whether this is
2548 // a session history navigation, because if we attempted a session history
2549 // navigation without valid HistoryItem state, WebCore will think it is a
2550 // new navigation.
2551 navigation_state->set_request_committed(true);
2553 SendDidCommitProvisionalLoad(frame, commit_type);
2555 // Check whether we have new encoding name.
2556 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2559 void RenderFrameImpl::didCreateNewDocument(blink::WebLocalFrame* frame) {
2560 DCHECK(!frame_ || frame_ == frame);
2562 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2563 DidCreateNewDocument(frame));
2566 void RenderFrameImpl::didClearWindowObject(blink::WebLocalFrame* frame) {
2567 DCHECK(!frame_ || frame_ == frame);
2568 // TODO(nasko): Move implementation here. Needed state:
2569 // * enabled_bindings_
2570 // * dom_automation_controller_
2571 // * stats_collection_controller_
2573 render_view_->didClearWindowObject(frame);
2575 if (render_view_->GetEnabledBindings() & BINDINGS_POLICY_DOM_AUTOMATION)
2576 DomAutomationController::Install(this, frame);
2578 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidClearWindowObject());
2581 void RenderFrameImpl::didCreateDocumentElement(blink::WebLocalFrame* frame) {
2582 DCHECK(!frame_ || frame_ == frame);
2584 // Notify the browser about non-blank documents loading in the top frame.
2585 GURL url = frame->document().url();
2586 if (url.is_valid() && url.spec() != url::kAboutBlankURL) {
2587 // TODO(nasko): Check if webview()->mainFrame() is the same as the
2588 // frame->tree()->top().
2589 blink::WebFrame* main_frame = render_view_->webview()->mainFrame();
2590 if (frame == main_frame) {
2591 // For now, don't remember plugin zoom values. We don't want to mix them
2592 // with normal web content (i.e. a fixed layout plugin would usually want
2593 // them different).
2594 render_view_->Send(new ViewHostMsg_DocumentAvailableInMainFrame(
2595 render_view_->GetRoutingID(),
2596 main_frame->document().isPluginDocument()));
2600 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2601 DidCreateDocumentElement(frame));
2604 void RenderFrameImpl::didReceiveTitle(blink::WebLocalFrame* frame,
2605 const blink::WebString& title,
2606 blink::WebTextDirection direction) {
2607 DCHECK(!frame_ || frame_ == frame);
2608 // Ignore all but top level navigations.
2609 if (!frame->parent()) {
2610 base::string16 title16 = title;
2611 base::trace_event::TraceLog::GetInstance()->UpdateProcessLabel(
2612 routing_id_, base::UTF16ToUTF8(title16));
2614 base::string16 shortened_title = title16.substr(0, kMaxTitleChars);
2615 Send(new FrameHostMsg_UpdateTitle(routing_id_,
2616 shortened_title, direction));
2619 // Also check whether we have new encoding name.
2620 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2623 void RenderFrameImpl::didChangeIcon(blink::WebLocalFrame* frame,
2624 blink::WebIconURL::Type icon_type) {
2625 DCHECK(!frame_ || frame_ == frame);
2626 // TODO(nasko): Investigate wheather implementation should move here.
2627 render_view_->didChangeIcon(frame, icon_type);
2630 void RenderFrameImpl::didFinishDocumentLoad(blink::WebLocalFrame* frame) {
2631 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishDocumentLoad",
2632 "id", routing_id_);
2633 DCHECK(!frame_ || frame_ == frame);
2634 WebDataSource* ds = frame->dataSource();
2635 DocumentState* document_state = DocumentState::FromDataSource(ds);
2636 document_state->set_finish_document_load_time(Time::Now());
2638 Send(new FrameHostMsg_DidFinishDocumentLoad(routing_id_));
2640 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2641 DidFinishDocumentLoad(frame));
2642 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishDocumentLoad());
2644 // Check whether we have new encoding name.
2645 UpdateEncoding(frame, frame->view()->pageEncoding().utf8());
2648 void RenderFrameImpl::didHandleOnloadEvents(blink::WebLocalFrame* frame) {
2649 DCHECK(!frame_ || frame_ == frame);
2650 if (!frame->parent()) {
2651 FrameMsg_UILoadMetricsReportType::Value report_type =
2652 static_cast<FrameMsg_UILoadMetricsReportType::Value>(
2653 frame->dataSource()->request().inputPerfMetricReportPolicy());
2654 base::TimeTicks ui_timestamp = base::TimeTicks() +
2655 base::TimeDelta::FromSecondsD(
2656 frame->dataSource()->request().uiStartTime());
2658 Send(new FrameHostMsg_DocumentOnLoadCompleted(
2659 routing_id_, report_type, ui_timestamp));
2663 void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame,
2664 const blink::WebURLError& error) {
2665 TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad",
2666 "id", routing_id_);
2667 DCHECK(!frame_ || frame_ == frame);
2668 // TODO(nasko): Move implementation here. No state needed.
2669 WebDataSource* ds = frame->dataSource();
2670 DCHECK(ds);
2672 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2673 DidFailLoad(frame, error));
2675 const WebURLRequest& failed_request = ds->request();
2676 base::string16 error_description;
2677 GetContentClient()->renderer()->GetNavigationErrorStrings(
2678 render_view_.get(),
2679 frame,
2680 failed_request,
2681 error,
2682 NULL,
2683 &error_description);
2684 Send(new FrameHostMsg_DidFailLoadWithError(routing_id_,
2685 failed_request.url(),
2686 error.reason,
2687 error_description));
2690 void RenderFrameImpl::didFinishLoad(blink::WebLocalFrame* frame) {
2691 TRACE_EVENT1("navigation", "RenderFrameImpl::didFinishLoad",
2692 "id", routing_id_);
2693 DCHECK(!frame_ || frame_ == frame);
2694 WebDataSource* ds = frame->dataSource();
2695 DocumentState* document_state = DocumentState::FromDataSource(ds);
2696 if (document_state->finish_load_time().is_null()) {
2697 if (!frame->parent()) {
2698 TRACE_EVENT_INSTANT0("WebCore", "LoadFinished",
2699 TRACE_EVENT_SCOPE_PROCESS);
2701 document_state->set_finish_load_time(Time::Now());
2704 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(),
2705 DidFinishLoad(frame));
2706 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidFinishLoad());
2708 // Don't send this message while the frame is swapped out.
2709 if (is_swapped_out())
2710 return;
2712 Send(new FrameHostMsg_DidFinishLoad(routing_id_,
2713 ds->request().url()));
2716 void RenderFrameImpl::didNavigateWithinPage(blink::WebLocalFrame* frame,
2717 const blink::WebHistoryItem& item,
2718 blink::WebHistoryCommitType commit_type) {
2719 TRACE_EVENT1("navigation", "RenderFrameImpl::didNavigateWithinPage",
2720 "id", routing_id_);
2721 DCHECK(!frame_ || frame_ == frame);
2722 // If this was a reference fragment navigation that we initiated, then we
2723 // could end up having a non-null pending navigation params. We just need to
2724 // update the ExtraData on the datasource so that others who read the
2725 // ExtraData will get the new NavigationState. Similarly, if we did not
2726 // initiate this navigation, then we need to take care to reset any pre-
2727 // existing navigation state to a content-initiated navigation state.
2728 // DidCreateDataSource conveniently takes care of this for us.
2729 didCreateDataSource(frame, frame->dataSource());
2731 DocumentState* document_state =
2732 DocumentState::FromDataSource(frame->dataSource());
2733 NavigationState* new_state = document_state->navigation_state();
2734 new_state->set_was_within_same_page(true);
2736 didCommitProvisionalLoad(frame, item, commit_type);
2739 void RenderFrameImpl::didUpdateCurrentHistoryItem(blink::WebLocalFrame* frame) {
2740 DCHECK(!frame_ || frame_ == frame);
2741 // TODO(nasko): Move implementation here. Needed methods:
2742 // * StartNavStateSyncTimerIfNecessary
2743 render_view_->didUpdateCurrentHistoryItem(frame);
2746 void RenderFrameImpl::addNavigationTransitionData(
2747 const blink::WebTransitionElementData& data) {
2748 FrameHostMsg_AddNavigationTransitionData_Params params;
2749 params.render_frame_id = routing_id_;
2750 params.allowed_destination_host_pattern =
2751 data.scope.utf8();
2752 params.selector = data.selector.utf8();
2753 params.markup = data.markup.utf8();
2754 params.elements.resize(data.elements.size());
2755 for (size_t i = 0; i < data.elements.size(); i++) {
2756 params.elements[i].id = data.elements[i].id.utf8();
2757 params.elements[i].rect = gfx::Rect(data.elements[i].rect);
2760 Send(new FrameHostMsg_AddNavigationTransitionData(params));
2763 void RenderFrameImpl::didChangeThemeColor() {
2764 if (frame_->parent())
2765 return;
2767 Send(new FrameHostMsg_DidChangeThemeColor(
2768 routing_id_, frame_->document().themeColor()));
2771 void RenderFrameImpl::dispatchLoad() {
2772 Send(new FrameHostMsg_DispatchLoad(routing_id_));
2775 void RenderFrameImpl::requestNotificationPermission(
2776 const blink::WebSecurityOrigin& origin,
2777 blink::WebNotificationPermissionCallback* callback) {
2778 if (!notification_permission_dispatcher_) {
2779 notification_permission_dispatcher_ =
2780 new NotificationPermissionDispatcher(this);
2783 notification_permission_dispatcher_->RequestPermission(origin, callback);
2786 void RenderFrameImpl::didChangeSelection(bool is_empty_selection) {
2787 if (!GetRenderWidget()->handling_input_event() && !handling_select_range_)
2788 return;
2790 if (is_empty_selection)
2791 selection_text_.clear();
2793 // UpdateTextInputType should be called before SyncSelectionIfRequired.
2794 // UpdateTextInputType may send TextInputTypeChanged to notify the focus
2795 // was changed, and SyncSelectionIfRequired may send SelectionChanged
2796 // to notify the selection was changed. Focus change should be notified
2797 // before selection change.
2798 GetRenderWidget()->UpdateTextInputType();
2799 SyncSelectionIfRequired();
2800 #if defined(OS_ANDROID)
2801 GetRenderWidget()->UpdateTextInputState(RenderWidget::NO_SHOW_IME,
2802 RenderWidget::FROM_NON_IME);
2803 #endif
2806 blink::WebColorChooser* RenderFrameImpl::createColorChooser(
2807 blink::WebColorChooserClient* client,
2808 const blink::WebColor& initial_color,
2809 const blink::WebVector<blink::WebColorSuggestion>& suggestions) {
2810 RendererWebColorChooserImpl* color_chooser =
2811 new RendererWebColorChooserImpl(this, client);
2812 std::vector<ColorSuggestion> color_suggestions;
2813 for (size_t i = 0; i < suggestions.size(); i++) {
2814 color_suggestions.push_back(ColorSuggestion(suggestions[i]));
2816 color_chooser->Open(static_cast<SkColor>(initial_color), color_suggestions);
2817 return color_chooser;
2820 void RenderFrameImpl::runModalAlertDialog(const blink::WebString& message) {
2821 RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_ALERT,
2822 message,
2823 base::string16(),
2824 frame_->document().url(),
2825 NULL);
2828 bool RenderFrameImpl::runModalConfirmDialog(const blink::WebString& message) {
2829 return RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_CONFIRM,
2830 message,
2831 base::string16(),
2832 frame_->document().url(),
2833 NULL);
2836 bool RenderFrameImpl::runModalPromptDialog(
2837 const blink::WebString& message,
2838 const blink::WebString& default_value,
2839 blink::WebString* actual_value) {
2840 base::string16 result;
2841 bool ok = RunJavaScriptMessage(JAVASCRIPT_MESSAGE_TYPE_PROMPT,
2842 message,
2843 default_value,
2844 frame_->document().url(),
2845 &result);
2846 if (ok)
2847 actual_value->assign(result);
2848 return ok;
2851 bool RenderFrameImpl::runModalBeforeUnloadDialog(
2852 bool is_reload,
2853 const blink::WebString& message) {
2854 // If we are swapping out, we have already run the beforeunload handler.
2855 // TODO(creis): Fix OnSwapOut to clear the frame without running beforeunload
2856 // at all, to avoid running it twice.
2857 if (is_swapped_out_)
2858 return true;
2860 // Don't allow further dialogs if we are waiting to swap out, since the
2861 // PageGroupLoadDeferrer in our stack prevents it.
2862 if (render_view()->suppress_dialogs_until_swap_out_)
2863 return false;
2865 bool success = false;
2866 // This is an ignored return value, but is included so we can accept the same
2867 // response as RunJavaScriptMessage.
2868 base::string16 ignored_result;
2869 render_view()->SendAndRunNestedMessageLoop(
2870 new FrameHostMsg_RunBeforeUnloadConfirm(
2871 routing_id_, frame_->document().url(), message, is_reload,
2872 &success, &ignored_result));
2873 return success;
2876 void RenderFrameImpl::showContextMenu(const blink::WebContextMenuData& data) {
2877 ContextMenuParams params = ContextMenuParamsBuilder::Build(data);
2878 params.source_type = GetRenderWidget()->context_menu_source_type();
2879 GetRenderWidget()->OnShowHostContextMenu(&params);
2880 if (GetRenderWidget()->has_host_context_menu_location()) {
2881 params.x = GetRenderWidget()->host_context_menu_location().x();
2882 params.y = GetRenderWidget()->host_context_menu_location().y();
2885 // Serializing a GURL longer than kMaxURLChars will fail, so don't do
2886 // it. We replace it with an empty GURL so the appropriate items are disabled
2887 // in the context menu.
2888 // TODO(jcivelli): http://crbug.com/45160 This prevents us from saving large
2889 // data encoded images. We should have a way to save them.
2890 if (params.src_url.spec().size() > GetMaxURLChars())
2891 params.src_url = GURL();
2892 context_menu_node_ = data.node;
2894 #if defined(OS_ANDROID)
2895 gfx::Rect start_rect;
2896 gfx::Rect end_rect;
2897 GetRenderWidget()->GetSelectionBounds(&start_rect, &end_rect);
2898 params.selection_start = gfx::Point(start_rect.x(), start_rect.bottom());
2899 params.selection_end = gfx::Point(end_rect.right(), end_rect.bottom());
2900 #endif
2902 Send(new FrameHostMsg_ContextMenu(routing_id_, params));
2905 void RenderFrameImpl::clearContextMenu() {
2906 context_menu_node_.reset();
2909 void RenderFrameImpl::willSendRequest(
2910 blink::WebLocalFrame* frame,
2911 unsigned identifier,
2912 blink::WebURLRequest& request,
2913 const blink::WebURLResponse& redirect_response) {
2914 DCHECK(!frame_ || frame_ == frame);
2915 // The request my be empty during tests.
2916 if (request.url().isEmpty())
2917 return;
2919 // Set the first party for cookies url if it has not been set yet (new
2920 // requests). For redirects, it is updated by WebURLLoaderImpl.
2921 if (request.firstPartyForCookies().isEmpty()) {
2922 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) {
2923 request.setFirstPartyForCookies(request.url());
2924 } else {
2925 // TODO(nasko): When the top-level frame is remote, there is no document.
2926 // This is broken and should be fixed to propagate the first party.
2927 WebFrame* top = frame->top();
2928 if (top->isWebLocalFrame()) {
2929 request.setFirstPartyForCookies(
2930 frame->top()->document().firstPartyForCookies());
2935 WebFrame* top_frame = frame->top();
2936 // TODO(nasko): Hack around asking about top-frame data source. This means
2937 // for out-of-process iframes we are treating the current frame as the
2938 // top-level frame, which is wrong.
2939 if (!top_frame || top_frame->isWebRemoteFrame())
2940 top_frame = frame;
2941 WebDataSource* provisional_data_source = top_frame->provisionalDataSource();
2942 WebDataSource* top_data_source = top_frame->dataSource();
2943 WebDataSource* data_source =
2944 provisional_data_source ? provisional_data_source : top_data_source;
2946 DocumentState* document_state = DocumentState::FromDataSource(data_source);
2947 DCHECK(document_state);
2948 InternalDocumentStateData* internal_data =
2949 InternalDocumentStateData::FromDocumentState(document_state);
2950 NavigationState* navigation_state = document_state->navigation_state();
2951 ui::PageTransition transition_type = navigation_state->transition_type();
2952 WebDataSource* frame_ds = frame->provisionalDataSource();
2953 if (frame_ds && frame_ds->isClientRedirect()) {
2954 transition_type = ui::PageTransitionFromInt(
2955 transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
2958 GURL request_url(request.url());
2959 GURL new_url;
2960 if (GetContentClient()->renderer()->WillSendRequest(
2961 frame,
2962 transition_type,
2963 request_url,
2964 request.firstPartyForCookies(),
2965 &new_url)) {
2966 request.setURL(WebURL(new_url));
2969 if (internal_data->is_cache_policy_override_set())
2970 request.setCachePolicy(internal_data->cache_policy_override());
2972 // The request's extra data may indicate that we should set a custom user
2973 // agent. This needs to be done here, after WebKit is through with setting the
2974 // user agent on its own. Similarly, it may indicate that we should set an
2975 // X-Requested-With header. This must be done here to avoid breaking CORS
2976 // checks.
2977 // PlzNavigate: there may also be a stream url associated with the request.
2978 WebString custom_user_agent;
2979 WebString requested_with;
2980 scoped_ptr<StreamOverrideParameters> stream_override;
2981 if (request.extraData()) {
2982 RequestExtraData* old_extra_data =
2983 static_cast<RequestExtraData*>(request.extraData());
2985 custom_user_agent = old_extra_data->custom_user_agent();
2986 if (!custom_user_agent.isNull()) {
2987 if (custom_user_agent.isEmpty())
2988 request.clearHTTPHeaderField("User-Agent");
2989 else
2990 request.setHTTPHeaderField("User-Agent", custom_user_agent);
2993 requested_with = old_extra_data->requested_with();
2994 if (!requested_with.isNull()) {
2995 if (requested_with.isEmpty())
2996 request.clearHTTPHeaderField("X-Requested-With");
2997 else
2998 request.setHTTPHeaderField("X-Requested-With", requested_with);
3000 stream_override = old_extra_data->TakeStreamOverrideOwnership();
3003 // Add the default accept header for frame request if it has not been set
3004 // already.
3005 if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3006 request.frameType() == blink::WebURLRequest::FrameTypeNested) &&
3007 request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) {
3008 request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader),
3009 WebString::fromUTF8(kDefaultAcceptHeader));
3012 // Add an empty HTTP origin header for non GET methods if none is currently
3013 // present.
3014 request.addHTTPOriginIfNeeded(WebString());
3016 // Attach |should_replace_current_entry| state to requests so that, should
3017 // this navigation later require a request transfer, all state is preserved
3018 // when it is re-created in the new process.
3019 bool should_replace_current_entry = false;
3020 if (navigation_state->is_content_initiated()) {
3021 should_replace_current_entry = data_source->replacesCurrentHistoryItem();
3022 } else {
3023 // If the navigation is browser-initiated, the NavigationState contains the
3024 // correct value instead of the WebDataSource.
3026 // TODO(davidben): Avoid this awkward duplication of state. See comment on
3027 // NavigationState::should_replace_current_entry().
3028 should_replace_current_entry =
3029 navigation_state->should_replace_current_entry();
3032 int provider_id = kInvalidServiceWorkerProviderId;
3033 if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel ||
3034 request.frameType() == blink::WebURLRequest::FrameTypeNested) {
3035 // |provisionalDataSource| may be null in some content::ResourceFetcher
3036 // use cases, we don't hook those requests.
3037 if (frame->provisionalDataSource()) {
3038 ServiceWorkerNetworkProvider* provider =
3039 ServiceWorkerNetworkProvider::FromDocumentState(
3040 DocumentState::FromDataSource(frame->provisionalDataSource()));
3041 provider_id = provider->provider_id();
3043 } else if (frame->dataSource()) {
3044 ServiceWorkerNetworkProvider* provider =
3045 ServiceWorkerNetworkProvider::FromDocumentState(
3046 DocumentState::FromDataSource(frame->dataSource()));
3047 provider_id = provider->provider_id();
3050 WebFrame* parent = frame->parent();
3051 int parent_routing_id = MSG_ROUTING_NONE;
3052 if (!parent) {
3053 parent_routing_id = -1;
3054 } else if (parent->isWebLocalFrame()) {
3055 parent_routing_id = FromWebFrame(parent)->GetRoutingID();
3056 } else {
3057 parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id();
3060 RequestExtraData* extra_data = new RequestExtraData();
3061 extra_data->set_visibility_state(render_view_->visibilityState());
3062 extra_data->set_custom_user_agent(custom_user_agent);
3063 extra_data->set_requested_with(requested_with);
3064 extra_data->set_render_frame_id(routing_id_);
3065 extra_data->set_is_main_frame(!parent);
3066 extra_data->set_frame_origin(
3067 GURL(frame->document().securityOrigin().toString()));
3068 extra_data->set_parent_is_main_frame(parent && !parent->parent());
3069 extra_data->set_parent_render_frame_id(parent_routing_id);
3070 extra_data->set_allow_download(navigation_state->allow_download());
3071 extra_data->set_transition_type(transition_type);
3072 extra_data->set_should_replace_current_entry(should_replace_current_entry);
3073 extra_data->set_transferred_request_child_id(
3074 navigation_state->transferred_request_child_id());
3075 extra_data->set_transferred_request_request_id(
3076 navigation_state->transferred_request_request_id());
3077 extra_data->set_service_worker_provider_id(provider_id);
3078 extra_data->set_stream_override(stream_override.Pass());
3079 request.setExtraData(extra_data);
3081 DocumentState* top_document_state =
3082 DocumentState::FromDataSource(top_data_source);
3083 if (top_document_state) {
3084 // TODO(gavinp): separate out prefetching and prerender field trials
3085 // if the rel=prerender rel type is sticking around.
3086 if (request.requestContext() == WebURLRequest::RequestContextPrefetch)
3087 top_document_state->set_was_prefetcher(true);
3090 // This is an instance where we embed a copy of the routing id
3091 // into the data portion of the message. This can cause problems if we
3092 // don't register this id on the browser side, since the download manager
3093 // expects to find a RenderViewHost based off the id.
3094 request.setRequestorID(render_view_->GetRoutingID());
3095 request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture());
3097 if (!navigation_state->extra_headers().empty()) {
3098 for (net::HttpUtil::HeadersIterator i(
3099 navigation_state->extra_headers().begin(),
3100 navigation_state->extra_headers().end(), "\n");
3101 i.GetNext(); ) {
3102 if (LowerCaseEqualsASCII(i.name(), "referer")) {
3103 WebString referrer = WebSecurityPolicy::generateReferrerHeader(
3104 blink::WebReferrerPolicyDefault,
3105 request.url(),
3106 WebString::fromUTF8(i.values()));
3107 request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault);
3108 } else {
3109 request.setHTTPHeaderField(WebString::fromUTF8(i.name()),
3110 WebString::fromUTF8(i.values()));
3115 if (!render_view_->renderer_preferences_.enable_referrers)
3116 request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault);
3119 void RenderFrameImpl::didReceiveResponse(
3120 blink::WebLocalFrame* frame,
3121 unsigned identifier,
3122 const blink::WebURLResponse& response) {
3123 DCHECK(!frame_ || frame_ == frame);
3124 // Only do this for responses that correspond to a provisional data source
3125 // of the top-most frame. If we have a provisional data source, then we
3126 // can't have any sub-resources yet, so we know that this response must
3127 // correspond to a frame load.
3128 if (!frame->provisionalDataSource() || frame->parent())
3129 return;
3131 // If we are in view source mode, then just let the user see the source of
3132 // the server's error page.
3133 if (frame->isViewSourceModeEnabled())
3134 return;
3136 DocumentState* document_state =
3137 DocumentState::FromDataSource(frame->provisionalDataSource());
3138 int http_status_code = response.httpStatusCode();
3140 // Record page load flags.
3141 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3142 if (extra_data) {
3143 document_state->set_was_fetched_via_spdy(
3144 extra_data->was_fetched_via_spdy());
3145 document_state->set_was_npn_negotiated(
3146 extra_data->was_npn_negotiated());
3147 document_state->set_npn_negotiated_protocol(
3148 extra_data->npn_negotiated_protocol());
3149 document_state->set_was_alternate_protocol_available(
3150 extra_data->was_alternate_protocol_available());
3151 document_state->set_connection_info(
3152 extra_data->connection_info());
3153 document_state->set_was_fetched_via_proxy(
3154 extra_data->was_fetched_via_proxy());
3155 document_state->set_proxy_server(
3156 extra_data->proxy_server());
3158 InternalDocumentStateData* internal_data =
3159 InternalDocumentStateData::FromDocumentState(document_state);
3160 internal_data->set_http_status_code(http_status_code);
3161 // Whether or not the http status code actually corresponds to an error is
3162 // only checked when the page is done loading, if |use_error_page| is
3163 // still true.
3164 internal_data->set_use_error_page(true);
3167 void RenderFrameImpl::didFinishResourceLoad(blink::WebLocalFrame* frame,
3168 unsigned identifier) {
3169 DCHECK(!frame_ || frame_ == frame);
3170 InternalDocumentStateData* internal_data =
3171 InternalDocumentStateData::FromDataSource(frame->dataSource());
3172 if (!internal_data->use_error_page())
3173 return;
3175 // Do not show error page when DevTools is attached.
3176 if (render_view_->devtools_agent_->IsAttached())
3177 return;
3179 // Display error page, if appropriate.
3180 std::string error_domain = "http";
3181 int http_status_code = internal_data->http_status_code();
3182 if (GetContentClient()->renderer()->HasErrorPage(
3183 http_status_code, &error_domain)) {
3184 WebURLError error;
3185 error.unreachableURL = frame->document().url();
3186 error.domain = WebString::fromUTF8(error_domain);
3187 error.reason = http_status_code;
3188 LoadNavigationErrorPage(frame->dataSource()->request(), error, true);
3192 void RenderFrameImpl::didLoadResourceFromMemoryCache(
3193 blink::WebLocalFrame* frame,
3194 const blink::WebURLRequest& request,
3195 const blink::WebURLResponse& response) {
3196 DCHECK(!frame_ || frame_ == frame);
3197 // The recipients of this message have no use for data: URLs: they don't
3198 // affect the page's insecure content list and are not in the disk cache. To
3199 // prevent large (1M+) data: URLs from crashing in the IPC system, we simply
3200 // filter them out here.
3201 GURL url(request.url());
3202 if (url.SchemeIs(url::kDataScheme))
3203 return;
3205 // Let the browser know we loaded a resource from the memory cache. This
3206 // message is needed to display the correct SSL indicators.
3207 render_view_->Send(new ViewHostMsg_DidLoadResourceFromMemoryCache(
3208 render_view_->GetRoutingID(),
3209 url,
3210 response.securityInfo(),
3211 request.httpMethod().utf8(),
3212 response.mimeType().utf8(),
3213 WebURLRequestToResourceType(request)));
3216 void RenderFrameImpl::didDisplayInsecureContent(blink::WebLocalFrame* frame) {
3217 DCHECK(!frame_ || frame_ == frame);
3218 render_view_->Send(new ViewHostMsg_DidDisplayInsecureContent(
3219 render_view_->GetRoutingID()));
3222 void RenderFrameImpl::didRunInsecureContent(
3223 blink::WebLocalFrame* frame,
3224 const blink::WebSecurityOrigin& origin,
3225 const blink::WebURL& target) {
3226 DCHECK(!frame_ || frame_ == frame);
3227 render_view_->Send(new ViewHostMsg_DidRunInsecureContent(
3228 render_view_->GetRoutingID(),
3229 origin.toString().utf8(),
3230 target));
3233 void RenderFrameImpl::didAbortLoading(blink::WebLocalFrame* frame) {
3234 DCHECK(!frame_ || frame_ == frame);
3235 #if defined(ENABLE_PLUGINS)
3236 if (frame != render_view_->webview()->mainFrame())
3237 return;
3238 PluginChannelHost::Broadcast(
3239 new PluginHostMsg_DidAbortLoading(render_view_->GetRoutingID()));
3240 #endif
3243 void RenderFrameImpl::didCreateScriptContext(blink::WebLocalFrame* frame,
3244 v8::Handle<v8::Context> context,
3245 int extension_group,
3246 int world_id) {
3247 DCHECK(!frame_ || frame_ == frame);
3248 GetContentClient()->renderer()->DidCreateScriptContext(
3249 frame, context, extension_group, world_id);
3252 void RenderFrameImpl::willReleaseScriptContext(blink::WebLocalFrame* frame,
3253 v8::Handle<v8::Context> context,
3254 int world_id) {
3255 DCHECK(!frame_ || frame_ == frame);
3257 FOR_EACH_OBSERVER(RenderFrameObserver,
3258 observers_,
3259 WillReleaseScriptContext(context, world_id));
3262 void RenderFrameImpl::didFirstVisuallyNonEmptyLayout(
3263 blink::WebLocalFrame* frame) {
3264 DCHECK(!frame_ || frame_ == frame);
3265 if (frame->parent())
3266 return;
3268 InternalDocumentStateData* data =
3269 InternalDocumentStateData::FromDataSource(frame->dataSource());
3270 data->set_did_first_visually_non_empty_layout(true);
3272 #if defined(OS_ANDROID)
3273 GetRenderWidget()->DidChangeBodyBackgroundColor(
3274 render_view_->webwidget_->backgroundColor());
3275 #endif
3277 GetRenderWidget()->QueueMessage(
3278 new FrameHostMsg_DidFirstVisuallyNonEmptyPaint(routing_id_),
3279 MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE);
3282 void RenderFrameImpl::didChangeScrollOffset(blink::WebLocalFrame* frame) {
3283 DCHECK(!frame_ || frame_ == frame);
3284 // TODO(nasko): Move implementation here. Needed methods:
3285 // * StartNavStateSyncTimerIfNecessary
3286 render_view_->didChangeScrollOffset(frame);
3288 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeScrollOffset());
3291 void RenderFrameImpl::willInsertBody(blink::WebLocalFrame* frame) {
3292 DCHECK(!frame_ || frame_ == frame);
3293 if (!frame->parent()) {
3294 render_view_->Send(new ViewHostMsg_WillInsertBody(
3295 render_view_->GetRoutingID()));
3299 void RenderFrameImpl::reportFindInPageMatchCount(int request_id,
3300 int count,
3301 bool final_update) {
3302 int active_match_ordinal = -1; // -1 = don't update active match ordinal
3303 if (!count)
3304 active_match_ordinal = 0;
3306 render_view_->Send(new ViewHostMsg_Find_Reply(
3307 render_view_->GetRoutingID(), request_id, count,
3308 gfx::Rect(), active_match_ordinal, final_update));
3311 void RenderFrameImpl::reportFindInPageSelection(
3312 int request_id,
3313 int active_match_ordinal,
3314 const blink::WebRect& selection_rect) {
3315 render_view_->Send(new ViewHostMsg_Find_Reply(
3316 render_view_->GetRoutingID(), request_id, -1, selection_rect,
3317 active_match_ordinal, false));
3320 void RenderFrameImpl::requestStorageQuota(
3321 blink::WebLocalFrame* frame,
3322 blink::WebStorageQuotaType type,
3323 unsigned long long requested_size,
3324 blink::WebStorageQuotaCallbacks callbacks) {
3325 DCHECK(!frame_ || frame_ == frame);
3326 WebSecurityOrigin origin = frame->document().securityOrigin();
3327 if (origin.isUnique()) {
3328 // Unique origins cannot store persistent state.
3329 callbacks.didFail(blink::WebStorageQuotaErrorAbort);
3330 return;
3332 ChildThreadImpl::current()->quota_dispatcher()->RequestStorageQuota(
3333 render_view_->GetRoutingID(),
3334 GURL(origin.toString()),
3335 static_cast<storage::StorageType>(type),
3336 requested_size,
3337 QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks));
3340 void RenderFrameImpl::willOpenWebSocket(blink::WebSocketHandle* handle) {
3341 WebSocketBridge* impl = static_cast<WebSocketBridge*>(handle);
3342 impl->set_render_frame_id(routing_id_);
3345 blink::WebGeolocationClient* RenderFrameImpl::geolocationClient() {
3346 if (!geolocation_dispatcher_)
3347 geolocation_dispatcher_ = new GeolocationDispatcher(this);
3348 return geolocation_dispatcher_;
3351 blink::WebPresentationClient* RenderFrameImpl::presentationClient() {
3352 if (!presentation_dispatcher_)
3353 presentation_dispatcher_ = new PresentationDispatcher(this);
3354 return presentation_dispatcher_;
3357 blink::WebPushClient* RenderFrameImpl::pushClient() {
3358 if (!push_messaging_dispatcher_)
3359 push_messaging_dispatcher_ = new PushMessagingDispatcher(this);
3360 return push_messaging_dispatcher_;
3363 void RenderFrameImpl::willStartUsingPeerConnectionHandler(
3364 blink::WebLocalFrame* frame,
3365 blink::WebRTCPeerConnectionHandler* handler) {
3366 DCHECK(!frame_ || frame_ == frame);
3367 #if defined(ENABLE_WEBRTC)
3368 static_cast<RTCPeerConnectionHandler*>(handler)->associateWithFrame(frame);
3369 #endif
3372 blink::WebUserMediaClient* RenderFrameImpl::userMediaClient() {
3373 if (!web_user_media_client_)
3374 InitializeUserMediaClient();
3375 return web_user_media_client_;
3378 blink::WebEncryptedMediaClient* RenderFrameImpl::encryptedMediaClient() {
3379 if (!web_encrypted_media_client_) {
3380 #if defined(ENABLE_PEPPER_CDMS)
3381 scoped_ptr<media::CdmFactory> cdm_factory(
3382 new RenderCdmFactory(base::Bind(PepperCdmWrapperImpl::Create, frame_)));
3383 #elif defined(ENABLE_BROWSER_CDMS)
3384 scoped_ptr<media::CdmFactory> cdm_factory(
3385 new RenderCdmFactory(GetCdmManager()));
3386 #else
3387 scoped_ptr<media::CdmFactory> cdm_factory(new RenderCdmFactory());
3388 #endif
3390 if (!media_permission_dispatcher_)
3391 media_permission_dispatcher_ = new MediaPermissionDispatcher(this);
3393 web_encrypted_media_client_.reset(new media::WebEncryptedMediaClientImpl(
3394 cdm_factory.Pass(), media_permission_dispatcher_));
3396 return web_encrypted_media_client_.get();
3399 blink::WebMIDIClient* RenderFrameImpl::webMIDIClient() {
3400 if (!midi_dispatcher_)
3401 midi_dispatcher_ = new MidiDispatcher(this);
3402 return midi_dispatcher_;
3405 bool RenderFrameImpl::willCheckAndDispatchMessageEvent(
3406 blink::WebLocalFrame* source_frame,
3407 blink::WebFrame* target_frame,
3408 blink::WebSecurityOrigin target_origin,
3409 blink::WebDOMMessageEvent event) {
3410 DCHECK(!frame_ || frame_ == target_frame);
3412 if (!is_swapped_out_)
3413 return false;
3415 ViewMsg_PostMessage_Params params;
3416 params.is_data_raw_string = false;
3417 params.data = event.data().toString();
3418 params.source_origin = event.origin();
3419 if (!target_origin.isNull())
3420 params.target_origin = target_origin.toString();
3422 blink::WebMessagePortChannelArray channels = event.releaseChannels();
3423 if (!channels.isEmpty()) {
3424 std::vector<int> message_port_ids(channels.size());
3425 // Extract the port IDs from the channel array.
3426 for (size_t i = 0; i < channels.size(); ++i) {
3427 WebMessagePortChannelImpl* webchannel =
3428 static_cast<WebMessagePortChannelImpl*>(channels[i]);
3429 message_port_ids[i] = webchannel->message_port_id();
3430 webchannel->QueueMessages();
3431 DCHECK_NE(message_port_ids[i], MSG_ROUTING_NONE);
3433 params.message_port_ids = message_port_ids;
3436 // Include the routing ID for the source frame (if one exists), which the
3437 // browser process will translate into the routing ID for the equivalent
3438 // frame in the target process.
3439 params.source_routing_id = MSG_ROUTING_NONE;
3440 if (source_frame) {
3441 RenderViewImpl* source_view =
3442 RenderViewImpl::FromWebView(source_frame->view());
3443 if (source_view)
3444 params.source_routing_id = source_view->routing_id();
3447 Send(new ViewHostMsg_RouteMessageEvent(render_view_->routing_id_, params));
3448 return true;
3451 blink::WebString RenderFrameImpl::userAgentOverride(blink::WebLocalFrame* frame,
3452 const blink::WebURL& url) {
3453 DCHECK(!frame_ || frame_ == frame);
3454 std::string user_agent_override_for_url =
3455 GetContentClient()->renderer()->GetUserAgentOverrideForURL(GURL(url));
3456 if (!user_agent_override_for_url.empty())
3457 return WebString::fromUTF8(user_agent_override_for_url);
3459 if (!render_view_->webview() || !render_view_->webview()->mainFrame() ||
3460 render_view_->renderer_preferences_.user_agent_override.empty()) {
3461 return blink::WebString();
3464 // TODO(nasko): When the top-level frame is remote, there is no WebDataSource
3465 // associated with it, so the checks below are not valid. Temporarily
3466 // return early and fix properly as part of https://crbug.com/426555.
3467 if (render_view_->webview()->mainFrame()->isWebRemoteFrame())
3468 return blink::WebString();
3470 // If we're in the middle of committing a load, the data source we need
3471 // will still be provisional.
3472 WebFrame* main_frame = render_view_->webview()->mainFrame();
3473 WebDataSource* data_source = NULL;
3474 if (main_frame->provisionalDataSource())
3475 data_source = main_frame->provisionalDataSource();
3476 else
3477 data_source = main_frame->dataSource();
3479 InternalDocumentStateData* internal_data = data_source ?
3480 InternalDocumentStateData::FromDataSource(data_source) : NULL;
3481 if (internal_data && internal_data->is_overriding_user_agent())
3482 return WebString::fromUTF8(
3483 render_view_->renderer_preferences_.user_agent_override);
3484 return blink::WebString();
3487 blink::WebString RenderFrameImpl::doNotTrackValue(blink::WebLocalFrame* frame) {
3488 DCHECK(!frame_ || frame_ == frame);
3489 if (render_view_->renderer_preferences_.enable_do_not_track)
3490 return WebString::fromUTF8("1");
3491 return WebString();
3494 bool RenderFrameImpl::allowWebGL(blink::WebLocalFrame* frame,
3495 bool default_value) {
3496 DCHECK(!frame_ || frame_ == frame);
3497 if (!default_value)
3498 return false;
3500 bool blocked = true;
3501 render_view_->Send(new ViewHostMsg_Are3DAPIsBlocked(
3502 render_view_->GetRoutingID(),
3503 GURL(frame->top()->document().securityOrigin().toString()),
3504 THREE_D_API_TYPE_WEBGL,
3505 &blocked));
3506 return !blocked;
3509 void RenderFrameImpl::didLoseWebGLContext(blink::WebLocalFrame* frame,
3510 int arb_robustness_status_code) {
3511 DCHECK(!frame_ || frame_ == frame);
3512 render_view_->Send(new ViewHostMsg_DidLose3DContext(
3513 GURL(frame->top()->document().securityOrigin().toString()),
3514 THREE_D_API_TYPE_WEBGL,
3515 arb_robustness_status_code));
3518 blink::WebScreenOrientationClient*
3519 RenderFrameImpl::webScreenOrientationClient() {
3520 if (!screen_orientation_dispatcher_)
3521 screen_orientation_dispatcher_ = new ScreenOrientationDispatcher(this);
3522 return screen_orientation_dispatcher_;
3525 bool RenderFrameImpl::isControlledByServiceWorker(WebDataSource& data_source) {
3526 ServiceWorkerNetworkProvider* provider =
3527 ServiceWorkerNetworkProvider::FromDocumentState(
3528 DocumentState::FromDataSource(&data_source));
3529 return provider->context()->controller_handle_id() !=
3530 kInvalidServiceWorkerHandleId;
3533 int64_t RenderFrameImpl::serviceWorkerID(WebDataSource& data_source) {
3534 ServiceWorkerNetworkProvider* provider =
3535 ServiceWorkerNetworkProvider::FromDocumentState(
3536 DocumentState::FromDataSource(&data_source));
3538 if (provider->context()->controller())
3539 return provider->context()->controller()->version_id();
3540 return kInvalidServiceWorkerVersionId;
3543 void RenderFrameImpl::postAccessibilityEvent(const blink::WebAXObject& obj,
3544 blink::WebAXEvent event) {
3545 HandleWebAccessibilityEvent(obj, event);
3548 void RenderFrameImpl::handleAccessibilityFindInPageResult(
3549 int identifier,
3550 int match_index,
3551 const blink::WebAXObject& start_object,
3552 int start_offset,
3553 const blink::WebAXObject& end_object,
3554 int end_offset) {
3555 if (renderer_accessibility_) {
3556 renderer_accessibility_->HandleAccessibilityFindInPageResult(
3557 identifier, match_index, start_object, start_offset,
3558 end_object, end_offset);
3562 void RenderFrameImpl::didChangeManifest(blink::WebLocalFrame* frame) {
3563 DCHECK(!frame_ || frame_ == frame);
3565 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, DidChangeManifest());
3568 bool RenderFrameImpl::enterFullscreen() {
3569 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, true));
3570 return true;
3573 bool RenderFrameImpl::exitFullscreen() {
3574 Send(new FrameHostMsg_ToggleFullscreen(routing_id_, false));
3575 return true;
3578 void RenderFrameImpl::suddenTerminationDisablerChanged(
3579 bool present,
3580 blink::WebFrameClient::SuddenTerminationDisablerType type) {
3581 switch (type) {
3582 case blink::WebFrameClient::BeforeUnloadHandler:
3583 Send(new FrameHostMsg_BeforeUnloadHandlersPresent(
3584 routing_id_, present));
3585 break;
3586 case blink::WebFrameClient::UnloadHandler:
3587 Send(new FrameHostMsg_UnloadHandlersPresent(
3588 routing_id_, present));
3589 break;
3590 default:
3591 NOTREACHED();
3595 void RenderFrameImpl::DidPlay(blink::WebMediaPlayer* player) {
3596 Send(new FrameHostMsg_MediaPlayingNotification(
3597 routing_id_, reinterpret_cast<int64>(player), player->hasVideo(),
3598 player->hasAudio(), player->isRemote()));
3601 void RenderFrameImpl::DidPause(blink::WebMediaPlayer* player) {
3602 Send(new FrameHostMsg_MediaPausedNotification(
3603 routing_id_, reinterpret_cast<int64>(player)));
3606 void RenderFrameImpl::PlayerGone(blink::WebMediaPlayer* player) {
3607 DidPause(player);
3610 void RenderFrameImpl::AddObserver(RenderFrameObserver* observer) {
3611 observers_.AddObserver(observer);
3614 void RenderFrameImpl::RemoveObserver(RenderFrameObserver* observer) {
3615 observer->RenderFrameGone();
3616 observers_.RemoveObserver(observer);
3619 void RenderFrameImpl::OnStop() {
3620 DCHECK(frame_);
3621 frame_->stopLoading();
3622 if (!frame_->parent())
3623 FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers_, OnStop());
3625 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, OnStop());
3628 void RenderFrameImpl::WasHidden() {
3629 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasHidden());
3632 void RenderFrameImpl::WasShown() {
3633 // TODO(kenrb): Need to figure out how to do this better. Should
3634 // VisibilityState remain a page-level concept or move to frames?
3635 // The semantics of 'Show' might have to change here.
3636 if (render_widget_) {
3637 render_view()->webview()->setVisibilityState(
3638 blink::WebPageVisibilityStateVisible, false);
3640 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WasShown());
3643 bool RenderFrameImpl::IsHidden() {
3644 return GetRenderWidget()->is_hidden();
3647 // Tell the embedding application that the URL of the active page has changed.
3648 void RenderFrameImpl::SendDidCommitProvisionalLoad(
3649 blink::WebFrame* frame,
3650 blink::WebHistoryCommitType commit_type) {
3651 DCHECK(!frame_ || frame_ == frame);
3652 WebDataSource* ds = frame->dataSource();
3653 DCHECK(ds);
3655 const WebURLRequest& request = ds->request();
3656 const WebURLResponse& response = ds->response();
3658 DocumentState* document_state = DocumentState::FromDataSource(ds);
3659 NavigationState* navigation_state = document_state->navigation_state();
3660 InternalDocumentStateData* internal_data =
3661 InternalDocumentStateData::FromDocumentState(document_state);
3663 FrameHostMsg_DidCommitProvisionalLoad_Params params;
3664 params.http_status_code = response.httpStatusCode();
3665 params.url_is_unreachable = ds->hasUnreachableURL();
3666 params.is_post = false;
3667 params.post_id = -1;
3668 params.page_id = render_view_->page_id_;
3669 // We need to track the RenderViewHost routing_id because of downstream
3670 // dependencies (crbug.com/392171 DownloadRequestHandle, SaveFileManager,
3671 // ResourceDispatcherHostImpl, MediaStreamUIProxy,
3672 // SpeechRecognitionDispatcherHost and possibly others). They look up the view
3673 // based on the ID stored in the resource requests. Once those dependencies
3674 // are unwound or moved to RenderFrameHost (crbug.com/304341) we can move the
3675 // client to be based on the routing_id of the RenderFrameHost.
3676 params.render_view_routing_id = render_view_->routing_id();
3677 params.socket_address.set_host(response.remoteIPAddress().utf8());
3678 params.socket_address.set_port(response.remotePort());
3679 WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response);
3680 if (extra_data)
3681 params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy();
3682 params.was_within_same_page = navigation_state->was_within_same_page();
3683 params.security_info = response.securityInfo();
3685 // Set the URL to be displayed in the browser UI to the user.
3686 params.url = GetLoadingUrl();
3687 DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL));
3689 // Set the origin of the frame. This will be replicated to the corresponding
3690 // RenderFrameProxies in other processes.
3691 // TODO(alexmos): Origins for URLs with non-standard schemes are excluded due
3692 // to https://crbug.com/439608 and will be replicated as unique origins.
3693 if (!is_swapped_out_) {
3694 WebString serialized_origin(frame->document().securityOrigin().toString());
3695 if (GURL(serialized_origin).IsStandard())
3696 params.origin = url::Origin(serialized_origin.utf8());
3699 if (frame->document().baseURL() != params.url)
3700 params.base_url = frame->document().baseURL();
3702 GetRedirectChain(ds, &params.redirects);
3703 params.should_update_history = !ds->hasUnreachableURL() &&
3704 !response.isMultipartPayload() && (response.httpStatusCode() != 404);
3706 params.searchable_form_url = internal_data->searchable_form_url();
3707 params.searchable_form_encoding = internal_data->searchable_form_encoding();
3709 params.gesture = render_view_->navigation_gesture_;
3710 render_view_->navigation_gesture_ = NavigationGestureUnknown;
3712 // Make navigation state a part of the DidCommitProvisionalLoad message so
3713 // that committed entry has it at all times.
3714 HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry();
3715 if (entry)
3716 params.page_state = HistoryEntryToPageState(entry);
3717 else
3718 params.page_state = PageState::CreateFromURL(request.url());
3720 if (!frame->parent()) {
3721 // Top-level navigation.
3723 // Reset the zoom limits in case a plugin had changed them previously. This
3724 // will also call us back which will cause us to send a message to
3725 // update WebContentsImpl.
3726 render_view_->webview()->zoomLimitsChanged(
3727 ZoomFactorToZoomLevel(kMinimumZoomFactor),
3728 ZoomFactorToZoomLevel(kMaximumZoomFactor));
3730 // Set zoom level, but don't do it for full-page plugin since they don't use
3731 // the same zoom settings.
3732 HostZoomLevels::iterator host_zoom =
3733 render_view_->host_zoom_levels_.find(GURL(request.url()));
3734 if (render_view_->webview()->mainFrame()->document().isPluginDocument()) {
3735 // Reset the zoom levels for plugins.
3736 render_view_->webview()->setZoomLevel(0);
3737 } else {
3738 // If the zoom level is not found, then do nothing. In-page navigation
3739 // relies on not changing the zoom level in this case.
3740 if (host_zoom != render_view_->host_zoom_levels_.end())
3741 render_view_->webview()->setZoomLevel(host_zoom->second);
3744 if (host_zoom != render_view_->host_zoom_levels_.end()) {
3745 // This zoom level was merely recorded transiently for this load. We can
3746 // erase it now. If at some point we reload this page, the browser will
3747 // send us a new, up-to-date zoom level.
3748 render_view_->host_zoom_levels_.erase(host_zoom);
3751 // Update contents MIME type for main frame.
3752 params.contents_mime_type = ds->response().mimeType().utf8();
3754 params.transition = navigation_state->transition_type();
3755 if (!ui::PageTransitionIsMainFrame(params.transition)) {
3756 // If the main frame does a load, it should not be reported as a subframe
3757 // navigation. This can occur in the following case:
3758 // 1. You're on a site with frames.
3759 // 2. You do a subframe navigation. This is stored with transition type
3760 // MANUAL_SUBFRAME.
3761 // 3. You navigate to some non-frame site, say, google.com.
3762 // 4. You navigate back to the page from step 2. Since it was initially
3763 // MANUAL_SUBFRAME, it will be that same transition type here.
3764 // We don't want that, because any navigation that changes the toplevel
3765 // frame should be tracked as a toplevel navigation (this allows us to
3766 // update the URL bar, etc).
3767 params.transition = ui::PAGE_TRANSITION_LINK;
3770 // If the page contained a client redirect (meta refresh, document.loc...),
3771 // set the referrer and transition appropriately.
3772 if (ds->isClientRedirect()) {
3773 params.referrer =
3774 Referrer(params.redirects[0], ds->request().referrerPolicy());
3775 params.transition = ui::PageTransitionFromInt(
3776 params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT);
3777 } else {
3778 params.referrer = RenderViewImpl::GetReferrerFromRequest(
3779 frame, ds->request());
3782 base::string16 method = request.httpMethod();
3783 if (EqualsASCII(method, "POST")) {
3784 params.is_post = true;
3785 params.post_id = ExtractPostId(entry);
3788 // Send the user agent override back.
3789 params.is_overriding_user_agent = internal_data->is_overriding_user_agent();
3791 // Track the URL of the original request. We use the first entry of the
3792 // redirect chain if it exists because the chain may have started in another
3793 // process.
3794 params.original_request_url = GetOriginalRequestURL(ds);
3796 params.history_list_was_cleared =
3797 navigation_state->history_list_was_cleared();
3799 params.report_type = static_cast<FrameMsg_UILoadMetricsReportType::Value>(
3800 frame->dataSource()->request().inputPerfMetricReportPolicy());
3801 params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD(
3802 frame->dataSource()->request().uiStartTime());
3804 // Save some histogram data so we can compute the average memory used per
3805 // page load of the glyphs.
3806 UMA_HISTOGRAM_COUNTS_10000("Memory.GlyphPagesPerLoad",
3807 blink::WebGlyphCache::pageCount());
3809 // This message needs to be sent before any of allowScripts(),
3810 // allowImages(), allowPlugins() is called for the new page, so that when
3811 // these functions send a ViewHostMsg_ContentBlocked message, it arrives
3812 // after the FrameHostMsg_DidCommitProvisionalLoad message.
3813 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3814 } else {
3815 // Subframe navigation: the type depends on whether this navigation
3816 // generated a new session history entry. When they do generate a session
3817 // history entry, it means the user initiated the navigation and we should
3818 // mark it as such.
3819 if (commit_type == blink::WebStandardCommit)
3820 params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME;
3821 else
3822 params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME;
3824 DCHECK(!navigation_state->history_list_was_cleared());
3825 params.history_list_was_cleared = false;
3826 params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT;
3828 // Don't send this message while the subframe is swapped out.
3829 if (!is_swapped_out())
3830 Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params));
3833 // If we end up reusing this WebRequest (for example, due to a #ref click),
3834 // we don't want the transition type to persist. Just clear it.
3835 navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK);
3838 void RenderFrameImpl::didStartLoading(bool to_different_document) {
3839 TRACE_EVENT1("navigation", "RenderFrameImpl::didStartLoading",
3840 "id", routing_id_);
3841 render_view_->FrameDidStartLoading(frame_);
3842 Send(new FrameHostMsg_DidStartLoading(routing_id_, to_different_document));
3845 void RenderFrameImpl::didStopLoading() {
3846 TRACE_EVENT1("navigation", "RenderFrameImpl::didStopLoading",
3847 "id", routing_id_);
3848 render_view_->FrameDidStopLoading(frame_);
3849 Send(new FrameHostMsg_DidStopLoading(routing_id_));
3852 void RenderFrameImpl::didChangeLoadProgress(double load_progress) {
3853 Send(new FrameHostMsg_DidChangeLoadProgress(routing_id_, load_progress));
3856 void RenderFrameImpl::HandleWebAccessibilityEvent(
3857 const blink::WebAXObject& obj, blink::WebAXEvent event) {
3858 if (renderer_accessibility_)
3859 renderer_accessibility_->HandleWebAccessibilityEvent(obj, event);
3862 void RenderFrameImpl::FocusedNodeChanged(const WebNode& node) {
3863 FOR_EACH_OBSERVER(RenderFrameObserver, observers_, FocusedNodeChanged(node));
3866 void RenderFrameImpl::FocusedNodeChangedForAccessibility(const WebNode& node) {
3867 if (renderer_accessibility())
3868 renderer_accessibility()->AccessibilityFocusedNodeChanged(node);
3871 // PlzNavigate
3872 void RenderFrameImpl::OnCommitNavigation(
3873 const ResourceResponseHead& response,
3874 const GURL& stream_url,
3875 const CommonNavigationParams& common_params,
3876 const CommitNavigationParams& commit_params) {
3877 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
3878 switches::kEnableBrowserSideNavigation));
3879 bool is_reload = false;
3880 bool is_history_navigation = commit_params.page_state.IsValid();
3881 WebURLRequest::CachePolicy cache_policy =
3882 WebURLRequest::UseProtocolCachePolicy;
3883 if (!RenderFrameImpl::PrepareRenderViewForNavigation(
3884 common_params.url, false /* check_for_stale_navigation */,
3885 is_history_navigation, -1 /* current_history_list_offset; TODO(clamy)*/,
3886 &is_reload, &cache_policy)) {
3887 return;
3890 GetContentClient()->SetActiveURL(common_params.url);
3892 // Create a WebURLRequest that blink can use to get access to the body of the
3893 // response through a stream in the browser. Blink will then commit the
3894 // navigation.
3895 // TODO(clamy): Have the navigation commit directly, without going through
3896 // loading a WebURLRequest.
3897 scoped_ptr<StreamOverrideParameters> stream_override(
3898 new StreamOverrideParameters());
3899 stream_override->stream_url = stream_url;
3900 stream_override->response = response;
3901 WebURLRequest request =
3902 CreateURLRequestForNavigation(common_params,
3903 stream_override.Pass(),
3904 frame_->isViewSourceModeEnabled());
3906 // Make sure that blink loader will not try to use browser side navigation for
3907 // this request (since it already went to the browser).
3908 request.setCheckForBrowserSideNavigation(false);
3910 // Record this before starting the load. A lower bound of this time is needed
3911 // to sanitize the navigationStart override set below.
3912 base::TimeTicks renderer_navigation_start = base::TimeTicks::Now();
3913 frame_->loadRequest(request);
3914 UpdateFrameNavigationTiming(
3915 frame_, commit_params.browser_navigation_start,
3916 renderer_navigation_start);
3919 WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation(
3920 RenderFrame* render_frame,
3921 const NavigationPolicyInfo& info) {
3922 #ifdef OS_ANDROID
3923 // The handlenavigation API is deprecated and will be removed once
3924 // crbug.com/325351 is resolved.
3925 if (info.urlRequest.url() != GURL(kSwappedOutURL) &&
3926 GetContentClient()->renderer()->HandleNavigation(
3927 render_frame,
3928 static_cast<DocumentState*>(info.extraData),
3929 render_view_->opener_id_,
3930 info.frame,
3931 info.urlRequest,
3932 info.navigationType,
3933 info.defaultPolicy,
3934 info.isRedirect)) {
3935 return blink::WebNavigationPolicyIgnore;
3937 #endif
3939 Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame,
3940 info.urlRequest));
3941 const base::CommandLine& command_line =
3942 *base::CommandLine::ForCurrentProcess();
3944 bool is_subframe = !!info.frame->parent();
3946 if (command_line.HasSwitch(switches::kSitePerProcess) && is_subframe) {
3947 // There's no reason to ignore navigations on subframes, since the swap out
3948 // logic no longer applies.
3949 } else {
3950 if (is_swapped_out_) {
3951 if (info.urlRequest.url() != GURL(kSwappedOutURL)) {
3952 // Targeted links may try to navigate a swapped out frame. Allow the
3953 // browser process to navigate the tab instead. Note that it is also
3954 // possible for non-targeted navigations (from this view) to arrive
3955 // here just after we are swapped out. It's ok to send them to the
3956 // browser, as long as they're for the top level frame.
3957 // TODO(creis): Ensure this supports targeted form submissions when
3958 // fixing http://crbug.com/101395.
3959 if (info.frame->parent() == NULL) {
3960 OpenURL(info.frame, info.urlRequest.url(), referrer,
3961 info.defaultPolicy);
3962 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
3965 // We should otherwise ignore in-process iframe navigations, if they
3966 // arrive just after we are swapped out.
3967 return blink::WebNavigationPolicyIgnore;
3970 // Allow kSwappedOutURL to complete.
3971 return info.defaultPolicy;
3975 // Webkit is asking whether to navigate to a new URL.
3976 // This is fine normally, except if we're showing UI from one security
3977 // context and they're trying to navigate to a different context.
3978 const GURL& url = info.urlRequest.url();
3980 // A content initiated navigation may have originated from a link-click,
3981 // script, drag-n-drop operation, etc.
3982 bool is_content_initiated = static_cast<DocumentState*>(info.extraData)->
3983 navigation_state()->is_content_initiated();
3985 // Experimental:
3986 // If --enable-strict-site-isolation is enabled, send all top-level
3987 // navigations to the browser to let it swap processes when crossing site
3988 // boundaries. This is currently expected to break some script calls and
3989 // navigations, such as form submissions.
3990 bool force_swap_due_to_flag =
3991 command_line.HasSwitch(switches::kEnableStrictSiteIsolation);
3992 if (force_swap_due_to_flag &&
3993 !info.frame->parent() && (is_content_initiated || info.isRedirect)) {
3994 WebString origin_str = info.frame->document().securityOrigin().toString();
3995 GURL frame_url(origin_str.utf8().data());
3996 // TODO(cevans): revisit whether this site check is still necessary once
3997 // crbug.com/101395 is fixed.
3998 bool same_domain_or_host =
3999 net::registry_controlled_domains::SameDomainOrHost(
4000 frame_url,
4001 url,
4002 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
4003 // Only keep same-site (domain + scheme) and data URLs in the same process.
4004 bool is_same_site =
4005 (same_domain_or_host && frame_url.scheme() == url.scheme()) ||
4006 url.SchemeIs(url::kDataScheme);
4007 if (!is_same_site) {
4008 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4009 return blink::WebNavigationPolicyIgnore;
4013 // If the browser is interested, then give it a chance to look at the request.
4014 if (is_content_initiated) {
4015 bool is_form_post =
4016 ((info.navigationType == blink::WebNavigationTypeFormSubmitted) ||
4017 (info.navigationType == blink::WebNavigationTypeFormResubmitted)) &&
4018 EqualsASCII(info.urlRequest.httpMethod(), "POST");
4019 bool browser_handles_request =
4020 render_view_->renderer_preferences_
4021 .browser_handles_non_local_top_level_requests
4022 && IsNonLocalTopLevelNavigation(url, info.frame, info.navigationType,
4023 is_form_post);
4024 if (!browser_handles_request) {
4025 browser_handles_request = IsTopLevelNavigation(info.frame) &&
4026 render_view_->renderer_preferences_
4027 .browser_handles_all_top_level_requests;
4030 if (browser_handles_request) {
4031 OpenURL(info.frame, url, referrer, info.defaultPolicy);
4032 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4036 // Use the frame's original request's URL rather than the document's URL for
4037 // subsequent checks. For a popup, the document's URL may become the opener
4038 // window's URL if the opener has called document.write().
4039 // See http://crbug.com/93517.
4040 GURL old_url(info.frame->dataSource()->request().url());
4042 // Detect when we're crossing a permission-based boundary (e.g. into or out of
4043 // an extension or app origin, leaving a WebUI page, etc). We only care about
4044 // top-level navigations (not iframes). But we sometimes navigate to
4045 // about:blank to clear a tab, and we want to still allow that.
4047 // Note: this is known to break POST submissions when crossing process
4048 // boundaries until http://crbug.com/101395 is fixed. This is better for
4049 // security than loading a WebUI, extension or app page in the wrong process.
4050 // POST requests don't work because this mechanism does not preserve form
4051 // POST data. We will need to send the request's httpBody data up to the
4052 // browser process, and issue a special POST navigation in WebKit (via
4053 // FrameLoader::loadFrameRequest). See ResourceDispatcher and WebURLLoaderImpl
4054 // for examples of how to send the httpBody data.
4055 if (!info.frame->parent() && is_content_initiated &&
4056 !url.SchemeIs(url::kAboutScheme)) {
4057 bool send_referrer = false;
4059 // All navigations to or from WebUI URLs or within WebUI-enabled
4060 // RenderProcesses must be handled by the browser process so that the
4061 // correct bindings and data sources can be registered.
4062 // Similarly, navigations to view-source URLs or within ViewSource mode
4063 // must be handled by the browser process (except for reloads - those are
4064 // safe to leave within the renderer).
4065 // Lastly, access to file:// URLs from non-file:// URL pages must be
4066 // handled by the browser so that ordinary renderer processes don't get
4067 // blessed with file permissions.
4068 int cumulative_bindings = RenderProcess::current()->GetEnabledBindings();
4069 bool is_initial_navigation = render_view_->page_id_ == -1;
4070 bool should_fork = HasWebUIScheme(url) || HasWebUIScheme(old_url) ||
4071 (cumulative_bindings & BINDINGS_POLICY_WEB_UI) ||
4072 url.SchemeIs(kViewSourceScheme) ||
4073 (info.frame->isViewSourceModeEnabled() &&
4074 info.navigationType != blink::WebNavigationTypeReload);
4076 if (!should_fork && url.SchemeIs(url::kFileScheme)) {
4077 // Fork non-file to file opens. Check the opener URL if this is the
4078 // initial navigation in a newly opened window.
4079 GURL source_url(old_url);
4080 if (is_initial_navigation && source_url.is_empty() &&
4081 info.frame->opener())
4082 source_url = info.frame->opener()->top()->document().url();
4083 DCHECK(!source_url.is_empty());
4084 should_fork = !source_url.SchemeIs(url::kFileScheme);
4087 if (!should_fork) {
4088 // Give the embedder a chance.
4089 should_fork = GetContentClient()->renderer()->ShouldFork(
4090 info.frame, url, info.urlRequest.httpMethod().utf8(),
4091 is_initial_navigation, info.isRedirect, &send_referrer);
4094 if (should_fork) {
4095 OpenURL(info.frame, url, send_referrer ? referrer : Referrer(),
4096 info.defaultPolicy);
4097 return blink::WebNavigationPolicyIgnore; // Suppress the load here.
4101 // Detect when a page is "forking" a new tab that can be safely rendered in
4102 // its own process. This is done by sites like Gmail that try to open links
4103 // in new windows without script connections back to the original page. We
4104 // treat such cases as browser navigations (in which we will create a new
4105 // renderer for a cross-site navigation), rather than WebKit navigations.
4107 // We use the following heuristic to decide whether to fork a new page in its
4108 // own process:
4109 // The parent page must open a new tab to about:blank, set the new tab's
4110 // window.opener to null, and then redirect the tab to a cross-site URL using
4111 // JavaScript.
4113 // TODO(creis): Deprecate this logic once we can rely on rel=noreferrer
4114 // (see below).
4115 bool is_fork =
4116 // Must start from a tab showing about:blank, which is later redirected.
4117 old_url == GURL(url::kAboutBlankURL) &&
4118 // Must be the first real navigation of the tab.
4119 render_view_->historyBackListCount() < 1 &&
4120 render_view_->historyForwardListCount() < 1 &&
4121 // The parent page must have set the child's window.opener to null before
4122 // redirecting to the desired URL.
4123 info.frame->opener() == NULL &&
4124 // Must be a top-level frame.
4125 info.frame->parent() == NULL &&
4126 // Must not have issued the request from this page.
4127 is_content_initiated &&
4128 // Must be targeted at the current tab.
4129 info.defaultPolicy == blink::WebNavigationPolicyCurrentTab &&
4130 // Must be a JavaScript navigation, which appears as "other".
4131 info.navigationType == blink::WebNavigationTypeOther;
4133 if (is_fork) {
4134 // Open the URL via the browser, not via WebKit.
4135 OpenURL(info.frame, url, Referrer(), info.defaultPolicy);
4136 return blink::WebNavigationPolicyIgnore;
4139 // PlzNavigate: send the request to the browser if needed.
4140 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4141 switches::kEnableBrowserSideNavigation) &&
4142 info.urlRequest.checkForBrowserSideNavigation()) {
4143 BeginNavigation(&info.urlRequest);
4144 return blink::WebNavigationPolicyIgnore;
4147 return info.defaultPolicy;
4150 void RenderFrameImpl::OpenURL(WebFrame* frame,
4151 const GURL& url,
4152 const Referrer& referrer,
4153 WebNavigationPolicy policy) {
4154 DCHECK_EQ(frame_, frame);
4156 FrameHostMsg_OpenURL_Params params;
4157 params.url = url;
4158 params.referrer = referrer;
4159 params.disposition = RenderViewImpl::NavigationPolicyToDisposition(policy);
4160 WebDataSource* ds = frame->provisionalDataSource();
4161 if (ds) {
4162 DocumentState* document_state = DocumentState::FromDataSource(ds);
4163 NavigationState* navigation_state = document_state->navigation_state();
4164 if (navigation_state->is_content_initiated()) {
4165 params.should_replace_current_entry =
4166 ds->replacesCurrentHistoryItem() &&
4167 render_view_->history_list_length_;
4168 } else {
4169 // This is necessary to preserve the should_replace_current_entry value on
4170 // cross-process redirects, in the event it was set by a previous process.
4172 // TODO(davidben): Avoid this awkward duplication of state. See comment on
4173 // NavigationState::should_replace_current_entry().
4174 params.should_replace_current_entry =
4175 navigation_state->should_replace_current_entry();
4177 } else {
4178 params.should_replace_current_entry = false;
4180 params.user_gesture = WebUserGestureIndicator::isProcessingUserGesture();
4181 if (GetContentClient()->renderer()->AllowPopup())
4182 params.user_gesture = true;
4184 if (policy == blink::WebNavigationPolicyNewBackgroundTab ||
4185 policy == blink::WebNavigationPolicyNewForegroundTab ||
4186 policy == blink::WebNavigationPolicyNewWindow ||
4187 policy == blink::WebNavigationPolicyNewPopup) {
4188 WebUserGestureIndicator::consumeUserGesture();
4191 Send(new FrameHostMsg_OpenURL(routing_id_, params));
4194 void RenderFrameImpl::UpdateEncoding(WebFrame* frame,
4195 const std::string& encoding_name) {
4196 // Only update main frame's encoding_name.
4197 if (!frame->parent())
4198 Send(new FrameHostMsg_UpdateEncoding(routing_id_, encoding_name));
4201 void RenderFrameImpl::SyncSelectionIfRequired() {
4202 base::string16 text;
4203 size_t offset;
4204 gfx::Range range;
4205 #if defined(ENABLE_PLUGINS)
4206 if (render_view_->focused_pepper_plugin_) {
4207 render_view_->focused_pepper_plugin_->GetSurroundingText(&text, &range);
4208 offset = 0; // Pepper API does not support offset reporting.
4209 // TODO(kinaba): cut as needed.
4210 } else
4211 #endif
4213 size_t location, length;
4214 if (!GetRenderWidget()->webwidget()->caretOrSelectionRange(
4215 &location, &length)) {
4216 return;
4219 range = gfx::Range(location, location + length);
4221 if (GetRenderWidget()->webwidget()->textInputInfo().type !=
4222 blink::WebTextInputTypeNone) {
4223 // If current focused element is editable, we will send 100 more chars
4224 // before and after selection. It is for input method surrounding text
4225 // feature.
4226 if (location > kExtraCharsBeforeAndAfterSelection)
4227 offset = location - kExtraCharsBeforeAndAfterSelection;
4228 else
4229 offset = 0;
4230 length = location + length - offset + kExtraCharsBeforeAndAfterSelection;
4231 WebRange webrange = WebRange::fromDocumentRange(frame_, offset, length);
4232 if (!webrange.isNull())
4233 text = webrange.toPlainText();
4234 } else {
4235 offset = location;
4236 text = frame_->selectionAsText();
4237 // http://crbug.com/101435
4238 // In some case, frame->selectionAsText() returned text's length is not
4239 // equal to the length returned from webwidget()->caretOrSelectionRange().
4240 // So we have to set the range according to text.length().
4241 range.set_end(range.start() + text.length());
4245 // Sometimes we get repeated didChangeSelection calls from webkit when
4246 // the selection hasn't actually changed. We don't want to report these
4247 // because it will cause us to continually claim the X clipboard.
4248 if (selection_text_offset_ != offset ||
4249 selection_range_ != range ||
4250 selection_text_ != text) {
4251 selection_text_ = text;
4252 selection_text_offset_ = offset;
4253 selection_range_ = range;
4254 SetSelectedText(text, offset, range);
4256 GetRenderWidget()->UpdateSelectionBounds();
4259 void RenderFrameImpl::InitializeUserMediaClient() {
4260 if (!RenderThreadImpl::current()) // Will be NULL during unit tests.
4261 return;
4263 #if defined(OS_ANDROID)
4264 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
4265 switches::kDisableWebRTC))
4266 return;
4267 #endif
4269 #if defined(ENABLE_WEBRTC)
4270 DCHECK(!web_user_media_client_);
4271 web_user_media_client_ = new UserMediaClientImpl(
4272 this,
4273 RenderThreadImpl::current()->GetPeerConnectionDependencyFactory(),
4274 make_scoped_ptr(new MediaStreamDispatcher(this)).Pass());
4275 #endif
4278 WebMediaPlayer* RenderFrameImpl::CreateWebMediaPlayerForMediaStream(
4279 const blink::WebURL& url,
4280 WebMediaPlayerClient* client) {
4281 #if defined(ENABLE_WEBRTC)
4282 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4283 bool found_neon =
4284 (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
4285 UMA_HISTOGRAM_BOOLEAN("Platform.WebRtcNEONFound", found_neon);
4286 #endif // defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
4287 return new WebMediaPlayerMS(frame_, client, weak_factory_.GetWeakPtr(),
4288 new RenderMediaLog(),
4289 CreateRendererFactory());
4290 #else
4291 return NULL;
4292 #endif // defined(ENABLE_WEBRTC)
4295 scoped_ptr<MediaStreamRendererFactory>
4296 RenderFrameImpl::CreateRendererFactory() {
4297 #if defined(ENABLE_WEBRTC)
4298 return scoped_ptr<MediaStreamRendererFactory>(
4299 new MediaStreamRendererFactory());
4300 #else
4301 return scoped_ptr<MediaStreamRendererFactory>(
4302 static_cast<MediaStreamRendererFactory*>(NULL));
4303 #endif
4306 bool RenderFrameImpl::PrepareRenderViewForNavigation(
4307 const GURL& url,
4308 bool check_for_stale_navigation,
4309 bool is_history_navigation,
4310 int current_history_list_offset,
4311 bool* is_reload,
4312 WebURLRequest::CachePolicy* cache_policy) {
4313 MaybeHandleDebugURL(url);
4314 if (!render_view_->webview())
4315 return false;
4317 FOR_EACH_OBSERVER(
4318 RenderViewObserver, render_view_->observers_, Navigate(url));
4320 // If this is a stale back/forward (due to a recent navigation the browser
4321 // didn't know about), ignore it. Only check if swapped in because if the
4322 // frame is swapped out, it won't commit before asking the browser.
4323 // TODO(clamy): remove check_for_stale_navigation
4324 if (check_for_stale_navigation &&
4325 !render_view_->is_swapped_out() && is_history_navigation &&
4326 render_view_->history_list_offset_ != current_history_list_offset) {
4327 return false;
4330 if (!is_swapped_out_ || frame_->parent())
4331 return true;
4333 // This is a swapped out main frame, so swap the renderer back in.
4334 // We marked the view as hidden when swapping the view out, so be sure to
4335 // reset the visibility state before navigating to the new URL.
4336 render_view_->webview()->setVisibilityState(
4337 render_view_->visibilityState(), false);
4339 // If this is an attempt to reload while we are swapped out, we should not
4340 // reload swappedout://, but the previous page, which is stored in
4341 // params.state. Setting is_reload to false will treat this like a back
4342 // navigation to accomplish that.
4343 *is_reload = false;
4344 *cache_policy = WebURLRequest::ReloadIgnoringCacheData;
4346 // We refresh timezone when a view is swapped in since timezone
4347 // can get out of sync when the system timezone is updated while
4348 // the view is swapped out.
4349 RenderThreadImpl::NotifyTimezoneChange();
4351 render_view_->SetSwappedOut(false);
4352 is_swapped_out_ = false;
4353 return true;
4356 void RenderFrameImpl::BeginNavigation(blink::WebURLRequest* request) {
4357 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
4358 switches::kEnableBrowserSideNavigation));
4359 DCHECK(request);
4360 // TODO(clamy): Execute the beforeunload event.
4362 // Note: At this stage, the goal is to apply all the modifications the
4363 // renderer wants to make to the request, and then send it to the browser, so
4364 // that the actual network request can be started. Ideally, all such
4365 // modifications should take place in willSendRequest, and in the
4366 // implementation of willSendRequest for the various InspectorAgents
4367 // (devtools).
4369 // TODO(clamy): Apply devtools override.
4370 // TODO(clamy): Make sure that navigation requests are not modified somewhere
4371 // else in blink.
4372 willSendRequest(frame_, 0, *request, blink::WebURLResponse());
4374 // TODO(clamy): Same-document navigations should not be sent back to the
4375 // browser.
4376 // TODO(clamy): Data urls should not be sent back to the browser either.
4377 Send(new FrameHostMsg_DidStartLoading(routing_id_, true));
4378 Send(new FrameHostMsg_BeginNavigation(
4379 routing_id_, MakeCommonNavigationParams(request),
4380 BeginNavigationParams(request->httpMethod().latin1(),
4381 GetWebURLRequestHeaders(*request),
4382 GetLoadFlagsForWebURLRequest(*request),
4383 request->hasUserGesture()),
4384 GetRequestBodyForWebURLRequest(*request)));
4387 GURL RenderFrameImpl::GetLoadingUrl() const {
4388 WebDataSource* ds = frame_->dataSource();
4389 if (ds->hasUnreachableURL())
4390 return ds->unreachableURL();
4392 const WebURLRequest& request = ds->request();
4393 return request.url();
4396 #if defined(OS_ANDROID)
4398 WebMediaPlayer* RenderFrameImpl::CreateAndroidWebMediaPlayer(
4399 const blink::WebURL& url,
4400 WebMediaPlayerClient* client,
4401 media::MediaPermission* media_permission,
4402 blink::WebContentDecryptionModule* initial_cdm) {
4403 GpuChannelHost* gpu_channel_host =
4404 RenderThreadImpl::current()->EstablishGpuChannelSync(
4405 CAUSE_FOR_GPU_LAUNCH_VIDEODECODEACCELERATOR_INITIALIZE);
4406 if (!gpu_channel_host) {
4407 LOG(ERROR) << "Failed to establish GPU channel for media player";
4408 return NULL;
4411 scoped_refptr<StreamTextureFactory> stream_texture_factory;
4412 if (SynchronousCompositorFactory* factory =
4413 SynchronousCompositorFactory::GetInstance()) {
4414 stream_texture_factory = factory->CreateStreamTextureFactory(routing_id_);
4415 } else {
4416 scoped_refptr<cc_blink::ContextProviderWebContext> context_provider =
4417 RenderThreadImpl::current()->SharedMainThreadContextProvider();
4419 if (!context_provider.get()) {
4420 LOG(ERROR) << "Failed to get context3d for media player";
4421 return NULL;
4424 stream_texture_factory = StreamTextureFactoryImpl::Create(
4425 context_provider, gpu_channel_host, routing_id_);
4428 return new WebMediaPlayerAndroid(
4429 frame_,
4430 client,
4431 weak_factory_.GetWeakPtr(),
4432 GetMediaPlayerManager(),
4433 GetCdmManager(),
4434 media_permission,
4435 initial_cdm,
4436 stream_texture_factory,
4437 RenderThreadImpl::current()->GetMediaThreadTaskRunner(),
4438 new RenderMediaLog());
4441 RendererMediaPlayerManager* RenderFrameImpl::GetMediaPlayerManager() {
4442 if (!media_player_manager_)
4443 media_player_manager_ = new RendererMediaPlayerManager(this);
4444 return media_player_manager_;
4447 #endif // defined(OS_ANDROID)
4449 #if defined(ENABLE_BROWSER_CDMS)
4450 RendererCdmManager* RenderFrameImpl::GetCdmManager() {
4451 if (!cdm_manager_)
4452 cdm_manager_ = new RendererCdmManager(this);
4453 return cdm_manager_;
4455 #endif // defined(ENABLE_BROWSER_CDMS)
4457 } // namespace content