1 // Copyright (c) 2012 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 "chrome/browser/prerender/prerender_contents.h"
11 #include "base/bind.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/history/history_tab_helper.h"
15 #include "chrome/browser/prerender/prerender_field_trial.h"
16 #include "chrome/browser/prerender/prerender_final_status.h"
17 #include "chrome/browser/prerender/prerender_handle.h"
18 #include "chrome/browser/prerender/prerender_manager.h"
19 #include "chrome/browser/prerender/prerender_manager_factory.h"
20 #include "chrome/browser/prerender/prerender_resource_throttle.h"
21 #include "chrome/browser/prerender/prerender_tracker.h"
22 #include "chrome/browser/profiles/profile.h"
23 #include "chrome/browser/ui/browser.h"
24 #include "chrome/browser/ui/tab_helpers.h"
25 #include "chrome/browser/ui/web_contents_sizer.h"
26 #include "chrome/common/prerender_messages.h"
27 #include "chrome/common/render_messages.h"
28 #include "chrome/common/url_constants.h"
29 #include "components/history/core/browser/history_types.h"
30 #include "content/public/browser/browser_child_process_host.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/render_frame_host.h"
34 #include "content/public/browser/render_process_host.h"
35 #include "content/public/browser/render_view_host.h"
36 #include "content/public/browser/resource_request_details.h"
37 #include "content/public/browser/session_storage_namespace.h"
38 #include "content/public/browser/web_contents.h"
39 #include "content/public/browser/web_contents_delegate.h"
40 #include "content/public/common/frame_navigate_params.h"
41 #include "net/url_request/url_request_context_getter.h"
42 #include "ui/base/page_transition_types.h"
43 #include "ui/gfx/rect.h"
45 using content::BrowserThread
;
46 using content::DownloadItem
;
47 using content::OpenURLParams
;
48 using content::RenderViewHost
;
49 using content::ResourceRedirectDetails
;
50 using content::ResourceType
;
51 using content::SessionStorageNamespace
;
52 using content::WebContents
;
58 // Internal cookie event.
59 // Whenever a prerender interacts with the cookie store, either sending
60 // existing cookies that existed before the prerender started, or when a cookie
61 // is changed, we record these events for histogramming purposes.
62 enum InternalCookieEvent
{
63 INTERNAL_COOKIE_EVENT_MAIN_FRAME_SEND
= 0,
64 INTERNAL_COOKIE_EVENT_MAIN_FRAME_CHANGE
= 1,
65 INTERNAL_COOKIE_EVENT_OTHER_SEND
= 2,
66 INTERNAL_COOKIE_EVENT_OTHER_CHANGE
= 3,
67 INTERNAL_COOKIE_EVENT_MAX
70 // Indicates whether existing cookies were sent, and if they were third party
71 // cookies, and whether they were for blocking resources.
72 // Each value may be inclusive of previous values. We only care about the
73 // value with the highest index that has ever occurred in the course of a
76 COOKIE_SEND_TYPE_NONE
= 0,
77 COOKIE_SEND_TYPE_FIRST_PARTY
= 1,
78 COOKIE_SEND_TYPE_THIRD_PARTY
= 2,
79 COOKIE_SEND_TYPE_THIRD_PARTY_BLOCKING_RESOURCE
= 3,
84 std::vector
<base::WeakPtr
<PrerenderResourceThrottle
> > throttles
) {
85 for (size_t i
= 0; i
< throttles
.size(); i
++) {
87 throttles
[i
]->Resume();
94 const int PrerenderContents::kNumCookieStatuses
=
95 (1 << INTERNAL_COOKIE_EVENT_MAX
);
98 const int PrerenderContents::kNumCookieSendTypes
= COOKIE_SEND_TYPE_MAX
;
100 class PrerenderContentsFactoryImpl
: public PrerenderContents::Factory
{
102 PrerenderContents
* CreatePrerenderContents(
103 PrerenderManager
* prerender_manager
,
106 const content::Referrer
& referrer
,
108 uint8 experiment_id
) override
{
109 return new PrerenderContents(prerender_manager
, profile
,
110 url
, referrer
, origin
, experiment_id
);
114 // WebContentsDelegateImpl -----------------------------------------------------
116 class PrerenderContents::WebContentsDelegateImpl
117 : public content::WebContentsDelegate
{
119 explicit WebContentsDelegateImpl(PrerenderContents
* prerender_contents
)
120 : prerender_contents_(prerender_contents
) {
123 // content::WebContentsDelegate implementation:
124 WebContents
* OpenURLFromTab(WebContents
* source
,
125 const OpenURLParams
& params
) override
{
126 // |OpenURLFromTab| is typically called when a frame performs a navigation
127 // that requires the browser to perform the transition instead of WebKit.
128 // Examples include prerendering a site that redirects to an app URL,
129 // or if --enable-strict-site-isolation is specified and the prerendered
130 // frame redirects to a different origin.
131 // TODO(cbentzel): Consider supporting this if it is a common case during
133 prerender_contents_
->Destroy(FINAL_STATUS_OPEN_URL
);
137 void CloseContents(content::WebContents
* contents
) override
{
138 prerender_contents_
->Destroy(FINAL_STATUS_CLOSED
);
141 void CanDownload(RenderViewHost
* render_view_host
,
143 const std::string
& request_method
,
144 const base::Callback
<void(bool)>& callback
) override
{
145 prerender_contents_
->Destroy(FINAL_STATUS_DOWNLOAD
);
146 // Cancel the download.
150 bool ShouldCreateWebContents(
151 WebContents
* web_contents
,
153 WindowContainerType window_container_type
,
154 const base::string16
& frame_name
,
155 const GURL
& target_url
,
156 const std::string
& partition_id
,
157 SessionStorageNamespace
* session_storage_namespace
) override
{
158 // Since we don't want to permit child windows that would have a
159 // window.opener property, terminate prerendering.
160 prerender_contents_
->Destroy(FINAL_STATUS_CREATE_NEW_WINDOW
);
165 bool OnGoToEntryOffset(int offset
) override
{
166 // This isn't allowed because the history merge operation
167 // does not work if there are renderer issued challenges.
168 // TODO(cbentzel): Cancel in this case? May not need to do
169 // since render-issued offset navigations are not guaranteed,
170 // but indicates that the page cares about the history.
174 bool ShouldSuppressDialogs(WebContents
* source
) override
{
175 // We still want to show the user the message when they navigate to this
176 // page, so cancel this prerender.
177 prerender_contents_
->Destroy(FINAL_STATUS_JAVASCRIPT_ALERT
);
178 // Always suppress JavaScript messages if they're triggered by a page being
183 void RegisterProtocolHandler(WebContents
* web_contents
,
184 const std::string
& protocol
,
186 bool user_gesture
) override
{
187 // TODO(mmenke): Consider supporting this if it is a common case during
189 prerender_contents_
->Destroy(FINAL_STATUS_REGISTER_PROTOCOL_HANDLER
);
192 gfx::Size
GetSizeForNewRenderView(WebContents
* web_contents
) const override
{
193 // Have to set the size of the RenderView on initialization to be sure it is
194 // set before the RenderView is hidden on all platforms (esp. Android).
195 return prerender_contents_
->size_
;
199 PrerenderContents
* prerender_contents_
;
202 void PrerenderContents::Observer::OnPrerenderStopLoading(
203 PrerenderContents
* contents
) {
206 void PrerenderContents::Observer::OnPrerenderDomContentLoaded(
207 PrerenderContents
* contents
) {
210 void PrerenderContents::Observer::OnPrerenderCreatedMatchCompleteReplacement(
211 PrerenderContents
* contents
, PrerenderContents
* replacement
) {
214 PrerenderContents::Observer::Observer() {
217 PrerenderContents::Observer::~Observer() {
220 PrerenderContents::PrerenderContents(
221 PrerenderManager
* prerender_manager
,
224 const content::Referrer
& referrer
,
227 : prerendering_has_started_(false),
228 session_storage_namespace_id_(-1),
229 prerender_manager_(prerender_manager
),
234 has_stopped_loading_(false),
235 has_finished_loading_(false),
236 final_status_(FINAL_STATUS_MAX
),
237 match_complete_status_(MATCH_COMPLETE_DEFAULT
),
238 prerendering_has_been_cancelled_(false),
242 experiment_id_(experiment_id
),
243 creator_child_id_(-1),
245 cookie_send_type_(COOKIE_SEND_TYPE_NONE
),
247 DCHECK(prerender_manager
!= NULL
);
250 PrerenderContents
* PrerenderContents::CreateMatchCompleteReplacement() {
251 PrerenderContents
* new_contents
= prerender_manager_
->CreatePrerenderContents(
252 prerender_url(), referrer(), origin(), experiment_id());
254 new_contents
->load_start_time_
= load_start_time_
;
255 new_contents
->session_storage_namespace_id_
= session_storage_namespace_id_
;
256 new_contents
->set_match_complete_status(
257 PrerenderContents::MATCH_COMPLETE_REPLACEMENT_PENDING
);
259 const bool did_init
= new_contents
->Init();
261 DCHECK_EQ(alias_urls_
.front(), new_contents
->alias_urls_
.front());
262 DCHECK_EQ(1u, new_contents
->alias_urls_
.size());
263 new_contents
->alias_urls_
= alias_urls_
;
264 // Erase all but the first alias URL; the replacement has adopted the
265 // remainder without increasing the renderer-side reference count.
266 alias_urls_
.resize(1);
267 new_contents
->set_match_complete_status(
268 PrerenderContents::MATCH_COMPLETE_REPLACEMENT
);
269 NotifyPrerenderCreatedMatchCompleteReplacement(new_contents
);
273 bool PrerenderContents::Init() {
274 return AddAliasURL(prerender_url_
);
278 PrerenderContents::Factory
* PrerenderContents::CreateFactory() {
279 return new PrerenderContentsFactoryImpl();
283 PrerenderContents
* PrerenderContents::FromWebContents(
284 content::WebContents
* web_contents
) {
287 PrerenderManager
* prerender_manager
= PrerenderManagerFactory::GetForProfile(
288 Profile::FromBrowserContext(web_contents
->GetBrowserContext()));
289 if (!prerender_manager
)
291 return prerender_manager
->GetPrerenderContents(web_contents
);
294 void PrerenderContents::StartPrerendering(
295 int creator_child_id
,
296 const gfx::Size
& size
,
297 SessionStorageNamespace
* session_storage_namespace
,
298 net::URLRequestContextGetter
* request_context
) {
299 DCHECK(profile_
!= NULL
);
300 DCHECK(!size
.IsEmpty());
301 DCHECK(!prerendering_has_started_
);
302 DCHECK(prerender_contents_
.get() == NULL
);
303 DCHECK_EQ(-1, creator_child_id_
);
304 DCHECK(size_
.IsEmpty());
305 DCHECK_EQ(1U, alias_urls_
.size());
307 creator_child_id_
= creator_child_id
;
308 session_storage_namespace_id_
= session_storage_namespace
->id();
311 DCHECK(load_start_time_
.is_null());
312 load_start_time_
= base::TimeTicks::Now();
313 start_time_
= base::Time::Now();
315 // Everything after this point sets up the WebContents object and associated
316 // RenderView for the prerender page. Don't do this for members of the
318 if (prerender_manager_
->IsControlGroup(experiment_id()))
321 if (origin_
== ORIGIN_LOCAL_PREDICTOR
&&
322 IsLocalPredictorPrerenderAlwaysControlEnabled()) {
326 prerendering_has_started_
= true;
328 alias_session_storage_namespace
= session_storage_namespace
->CreateAlias();
329 prerender_contents_
.reset(
330 CreateWebContents(alias_session_storage_namespace
.get()));
331 TabHelpers::AttachTabHelpers(prerender_contents_
.get());
332 content::WebContentsObserver::Observe(prerender_contents_
.get());
334 web_contents_delegate_
.reset(new WebContentsDelegateImpl(this));
335 prerender_contents_
.get()->SetDelegate(web_contents_delegate_
.get());
336 // Set the size of the prerender WebContents.
337 ResizeWebContents(prerender_contents_
.get(), size_
);
339 child_id_
= GetRenderViewHost()->GetProcess()->GetID();
340 route_id_
= GetRenderViewHost()->GetRoutingID();
342 // Log transactions to see if we could merge session storage namespaces in
343 // the event of a mismatch.
344 alias_session_storage_namespace
->AddTransactionLogProcessId(child_id_
);
346 // Add the RenderProcessHost to the Prerender Manager.
347 prerender_manager()->AddPrerenderProcessHost(
348 GetRenderViewHost()->GetProcess());
350 // In the prerender tracker, create a Prerender Cookie Store to keep track of
351 // cookie changes performed by the prerender. Once the prerender is shown,
352 // the cookie changes will be committed to the actual cookie store,
353 // otherwise, they will be discarded.
354 // If |request_context| is NULL, the feature must be disabled, so the
355 // operation will not be performed.
356 if (request_context
) {
357 BrowserThread::PostTask(
358 BrowserThread::IO
, FROM_HERE
,
359 base::Bind(&PrerenderTracker::AddPrerenderCookieStoreOnIOThread
,
360 base::Unretained(prerender_manager()->prerender_tracker()),
361 GetRenderViewHost()->GetProcess()->GetID(),
362 make_scoped_refptr(request_context
),
363 base::Bind(&PrerenderContents::Destroy
,
365 FINAL_STATUS_COOKIE_CONFLICT
)));
368 NotifyPrerenderStart();
370 // Close ourselves when the application is shutting down.
371 notification_registrar_
.Add(this, chrome::NOTIFICATION_APP_TERMINATING
,
372 content::NotificationService::AllSources());
374 // Register to inform new RenderViews that we're prerendering.
375 notification_registrar_
.Add(
376 this, content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
377 content::Source
<WebContents
>(prerender_contents_
.get()));
379 // Transfer over the user agent override.
380 prerender_contents_
.get()->SetUserAgentOverride(
381 prerender_manager_
->config().user_agent_override
);
383 content::NavigationController::LoadURLParams
load_url_params(
385 load_url_params
.referrer
= referrer_
;
386 load_url_params
.transition_type
= ui::PAGE_TRANSITION_LINK
;
387 if (origin_
== ORIGIN_OMNIBOX
) {
388 load_url_params
.transition_type
= ui::PageTransitionFromInt(
389 ui::PAGE_TRANSITION_TYPED
|
390 ui::PAGE_TRANSITION_FROM_ADDRESS_BAR
);
391 } else if (origin_
== ORIGIN_INSTANT
) {
392 load_url_params
.transition_type
= ui::PageTransitionFromInt(
393 ui::PAGE_TRANSITION_GENERATED
|
394 ui::PAGE_TRANSITION_FROM_ADDRESS_BAR
);
396 load_url_params
.override_user_agent
=
397 prerender_manager_
->config().is_overriding_user_agent
?
398 content::NavigationController::UA_OVERRIDE_TRUE
:
399 content::NavigationController::UA_OVERRIDE_FALSE
;
400 prerender_contents_
.get()->GetController().LoadURLWithParams(load_url_params
);
403 bool PrerenderContents::GetChildId(int* child_id
) const {
405 DCHECK_GE(child_id_
, -1);
406 *child_id
= child_id_
;
407 return child_id_
!= -1;
410 bool PrerenderContents::GetRouteId(int* route_id
) const {
412 DCHECK_GE(route_id_
, -1);
413 *route_id
= route_id_
;
414 return route_id_
!= -1;
417 void PrerenderContents::SetFinalStatus(FinalStatus final_status
) {
418 DCHECK_GE(final_status
, FINAL_STATUS_USED
);
419 DCHECK_LT(final_status
, FINAL_STATUS_MAX
);
421 DCHECK_EQ(FINAL_STATUS_MAX
, final_status_
);
423 final_status_
= final_status
;
426 PrerenderContents::~PrerenderContents() {
427 DCHECK_NE(FINAL_STATUS_MAX
, final_status());
429 prerendering_has_been_cancelled() || final_status() == FINAL_STATUS_USED
);
430 DCHECK_NE(ORIGIN_MAX
, origin());
431 // Since a lot of prerenders terminate before any meaningful cookie action
432 // would have happened, only record the cookie status for prerenders who
433 // were used, cancelled, or timed out.
434 if (prerendering_has_started_
&& final_status() == FINAL_STATUS_USED
) {
435 prerender_manager_
->RecordCookieStatus(origin(), experiment_id(),
437 prerender_manager_
->RecordCookieSendType(origin(), experiment_id(),
440 prerender_manager_
->RecordFinalStatusWithMatchCompleteStatus(
441 origin(), experiment_id(), match_complete_status(), final_status());
443 bool used
= final_status() == FINAL_STATUS_USED
||
444 final_status() == FINAL_STATUS_WOULD_HAVE_BEEN_USED
;
445 prerender_manager_
->RecordNetworkBytes(origin(), used
, network_bytes_
);
447 // Broadcast the removal of aliases.
448 for (content::RenderProcessHost::iterator host_iterator
=
449 content::RenderProcessHost::AllHostsIterator();
450 !host_iterator
.IsAtEnd();
451 host_iterator
.Advance()) {
452 content::RenderProcessHost
* host
= host_iterator
.GetCurrentValue();
453 host
->Send(new PrerenderMsg_OnPrerenderRemoveAliases(alias_urls_
));
456 // If we still have a WebContents, clean up anything we need to and then
458 if (prerender_contents_
.get())
459 delete ReleasePrerenderContents();
462 void PrerenderContents::AddObserver(Observer
* observer
) {
463 DCHECK_EQ(FINAL_STATUS_MAX
, final_status_
);
464 observer_list_
.AddObserver(observer
);
467 void PrerenderContents::RemoveObserver(Observer
* observer
) {
468 observer_list_
.RemoveObserver(observer
);
471 void PrerenderContents::Observe(int type
,
472 const content::NotificationSource
& source
,
473 const content::NotificationDetails
& details
) {
475 // TODO(davidben): Try to remove this in favor of relying on
476 // FINAL_STATUS_PROFILE_DESTROYED.
477 case chrome::NOTIFICATION_APP_TERMINATING
:
478 Destroy(FINAL_STATUS_APP_TERMINATING
);
481 case content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
: {
482 if (prerender_contents_
.get()) {
483 DCHECK_EQ(content::Source
<WebContents
>(source
).ptr(),
484 prerender_contents_
.get());
486 content::Details
<RenderViewHost
> new_render_view_host(details
);
487 OnRenderViewHostCreated(new_render_view_host
.ptr());
489 // Make sure the size of the RenderViewHost has been passed to the new
490 // RenderView. Otherwise, the size may not be sent until the
491 // RenderViewReady event makes it from the render process to the UI
492 // thread of the browser process. When the RenderView receives its
493 // size, is also sets itself to be visible, which would then break the
495 new_render_view_host
->WasResized();
496 prerender_contents_
->WasHidden();
502 NOTREACHED() << "Unexpected notification sent.";
507 void PrerenderContents::OnRenderViewHostCreated(
508 RenderViewHost
* new_render_view_host
) {
511 WebContents
* PrerenderContents::CreateWebContents(
512 SessionStorageNamespace
* session_storage_namespace
) {
513 // TODO(ajwong): Remove the temporary map once prerendering is aware of
514 // multiple session storage namespaces per tab.
515 content::SessionStorageNamespaceMap session_storage_namespace_map
;
516 session_storage_namespace_map
[std::string()] = session_storage_namespace
;
517 return WebContents::CreateWithSessionStorage(
518 WebContents::CreateParams(profile_
), session_storage_namespace_map
);
521 void PrerenderContents::NotifyPrerenderStart() {
522 DCHECK_EQ(FINAL_STATUS_MAX
, final_status_
);
523 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnPrerenderStart(this));
526 void PrerenderContents::NotifyPrerenderStopLoading() {
527 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnPrerenderStopLoading(this));
530 void PrerenderContents::NotifyPrerenderDomContentLoaded() {
531 FOR_EACH_OBSERVER(Observer
, observer_list_
,
532 OnPrerenderDomContentLoaded(this));
535 void PrerenderContents::NotifyPrerenderStop() {
536 DCHECK_NE(FINAL_STATUS_MAX
, final_status_
);
537 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnPrerenderStop(this));
538 observer_list_
.Clear();
541 void PrerenderContents::NotifyPrerenderCreatedMatchCompleteReplacement(
542 PrerenderContents
* replacement
) {
543 FOR_EACH_OBSERVER(Observer
, observer_list_
,
544 OnPrerenderCreatedMatchCompleteReplacement(this,
548 bool PrerenderContents::OnMessageReceived(const IPC::Message
& message
) {
550 // The following messages we do want to consume.
551 IPC_BEGIN_MESSAGE_MAP(PrerenderContents
, message
)
552 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CancelPrerenderForPrinting
,
553 OnCancelPrerenderForPrinting
)
554 IPC_MESSAGE_UNHANDLED(handled
= false)
555 IPC_END_MESSAGE_MAP()
560 bool PrerenderContents::CheckURL(const GURL
& url
) {
561 if (!url
.SchemeIsHTTPOrHTTPS()) {
562 DCHECK_NE(MATCH_COMPLETE_REPLACEMENT_PENDING
, match_complete_status_
);
563 Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME
);
566 if (match_complete_status_
!= MATCH_COMPLETE_REPLACEMENT_PENDING
&&
567 prerender_manager_
->HasRecentlyBeenNavigatedTo(origin(), url
)) {
568 Destroy(FINAL_STATUS_RECENTLY_VISITED
);
574 bool PrerenderContents::AddAliasURL(const GURL
& url
) {
578 alias_urls_
.push_back(url
);
580 for (content::RenderProcessHost::iterator host_iterator
=
581 content::RenderProcessHost::AllHostsIterator();
582 !host_iterator
.IsAtEnd();
583 host_iterator
.Advance()) {
584 content::RenderProcessHost
* host
= host_iterator
.GetCurrentValue();
585 host
->Send(new PrerenderMsg_OnPrerenderAddAlias(url
));
591 bool PrerenderContents::Matches(
593 const SessionStorageNamespace
* session_storage_namespace
) const {
594 if (session_storage_namespace
&&
595 session_storage_namespace_id_
!= session_storage_namespace
->id()) {
598 return std::count_if(alias_urls_
.begin(), alias_urls_
.end(),
599 std::bind2nd(std::equal_to
<GURL
>(), url
)) != 0;
602 void PrerenderContents::RenderProcessGone(base::TerminationStatus status
) {
603 Destroy(FINAL_STATUS_RENDERER_CRASHED
);
606 void PrerenderContents::RenderFrameCreated(
607 content::RenderFrameHost
* render_frame_host
) {
608 // When a new RenderFrame is created for a prerendering WebContents, tell the
609 // new RenderFrame it's being used for prerendering before any navigations
610 // occur. Note that this is always triggered before the first navigation, so
611 // there's no need to send the message just after the WebContents is created.
612 render_frame_host
->Send(new PrerenderMsg_SetIsPrerendering(
613 render_frame_host
->GetRoutingID(), true));
616 void PrerenderContents::DidStopLoading(
617 content::RenderViewHost
* render_view_host
) {
618 has_stopped_loading_
= true;
619 NotifyPrerenderStopLoading();
622 void PrerenderContents::DocumentLoadedInFrame(
623 content::RenderFrameHost
* render_frame_host
) {
624 if (!render_frame_host
->GetParent())
625 NotifyPrerenderDomContentLoaded();
628 void PrerenderContents::DidStartProvisionalLoadForFrame(
629 content::RenderFrameHost
* render_frame_host
,
630 const GURL
& validated_url
,
632 bool is_iframe_srcdoc
) {
633 if (!render_frame_host
->GetParent()) {
634 if (!CheckURL(validated_url
))
637 // Usually, this event fires if the user clicks or enters a new URL.
638 // Neither of these can happen in the case of an invisible prerender.
639 // So the cause is: Some JavaScript caused a new URL to be loaded. In that
640 // case, the spinner would start again in the browser, so we must reset
641 // has_stopped_loading_ so that the spinner won't be stopped.
642 has_stopped_loading_
= false;
643 has_finished_loading_
= false;
647 void PrerenderContents::DidFinishLoad(
648 content::RenderFrameHost
* render_frame_host
,
649 const GURL
& validated_url
) {
650 if (!render_frame_host
->GetParent())
651 has_finished_loading_
= true;
654 void PrerenderContents::DidNavigateMainFrame(
655 const content::LoadCommittedDetails
& details
,
656 const content::FrameNavigateParams
& params
) {
657 // If the prerender made a second navigation entry, abort the prerender. This
658 // avoids having to correctly implement a complex history merging case (this
659 // interacts with location.replace) and correctly synchronize with the
660 // renderer. The final status may be monitored to see we need to revisit this
661 // decision. This does not affect client redirects as those do not push new
662 // history entries. (Calls to location.replace, navigations before onload, and
663 // <meta http-equiv=refresh> with timeouts under 1 second do not create
664 // entries in Blink.)
665 if (prerender_contents_
->GetController().GetEntryCount() > 1) {
666 Destroy(FINAL_STATUS_NEW_NAVIGATION_ENTRY
);
670 // Add each redirect as an alias. |params.url| is included in
671 // |params.redirects|.
673 // TODO(davidben): We do not correctly patch up history for renderer-initated
674 // navigations which add history entries. http://crbug.com/305660.
675 for (size_t i
= 0; i
< params
.redirects
.size(); i
++) {
676 if (!AddAliasURL(params
.redirects
[i
]))
681 void PrerenderContents::DidGetRedirectForResourceRequest(
682 content::RenderFrameHost
* render_frame_host
,
683 const content::ResourceRedirectDetails
& details
) {
684 // DidGetRedirectForResourceRequest can come for any resource on a page. If
685 // it's a redirect on the top-level resource, the name needs to be remembered
686 // for future matching, and if it redirects to an https resource, it needs to
687 // be canceled. If a subresource is redirected, nothing changes.
688 if (details
.resource_type
!= content::RESOURCE_TYPE_MAIN_FRAME
)
690 CheckURL(details
.new_url
);
693 void PrerenderContents::Destroy(FinalStatus final_status
) {
694 DCHECK_NE(final_status
, FINAL_STATUS_USED
);
696 if (prerendering_has_been_cancelled_
)
699 SetFinalStatus(final_status
);
701 prerendering_has_been_cancelled_
= true;
702 prerender_manager_
->AddToHistory(this);
703 prerender_manager_
->MoveEntryToPendingDelete(this, final_status
);
705 // Note that if this PrerenderContents was made into a MatchComplete
706 // replacement by MoveEntryToPendingDelete, NotifyPrerenderStop will
707 // not reach the PrerenderHandle. Rather
708 // OnPrerenderCreatedMatchCompleteReplacement will propogate that
709 // information to the referer.
710 if (!prerender_manager_
->IsControlGroup(experiment_id()) &&
711 (prerendering_has_started() ||
712 match_complete_status() == MATCH_COMPLETE_REPLACEMENT
)) {
713 NotifyPrerenderStop();
717 base::ProcessMetrics
* PrerenderContents::MaybeGetProcessMetrics() {
718 if (process_metrics_
.get() == NULL
) {
719 // If a PrenderContents hasn't started prerending, don't be fully formed.
720 if (!GetRenderViewHost() || !GetRenderViewHost()->GetProcess())
722 base::ProcessHandle handle
= GetRenderViewHost()->GetProcess()->GetHandle();
723 if (handle
== base::kNullProcessHandle
)
725 #if !defined(OS_MACOSX)
726 process_metrics_
.reset(base::ProcessMetrics::CreateProcessMetrics(handle
));
728 process_metrics_
.reset(base::ProcessMetrics::CreateProcessMetrics(
730 content::BrowserChildProcessHost::GetPortProvider()));
734 return process_metrics_
.get();
737 void PrerenderContents::DestroyWhenUsingTooManyResources() {
738 base::ProcessMetrics
* metrics
= MaybeGetProcessMetrics();
742 size_t private_bytes
, shared_bytes
;
743 if (metrics
->GetMemoryBytes(&private_bytes
, &shared_bytes
) &&
744 private_bytes
> prerender_manager_
->config().max_bytes
) {
745 Destroy(FINAL_STATUS_MEMORY_LIMIT_EXCEEDED
);
749 WebContents
* PrerenderContents::ReleasePrerenderContents() {
750 prerender_contents_
->SetDelegate(NULL
);
751 content::WebContentsObserver::Observe(NULL
);
752 if (alias_session_storage_namespace
.get())
753 alias_session_storage_namespace
->RemoveTransactionLogProcessId(child_id_
);
754 return prerender_contents_
.release();
757 RenderViewHost
* PrerenderContents::GetRenderViewHostMutable() {
758 return const_cast<RenderViewHost
*>(GetRenderViewHost());
761 const RenderViewHost
* PrerenderContents::GetRenderViewHost() const {
762 if (!prerender_contents_
.get())
764 return prerender_contents_
->GetRenderViewHost();
767 void PrerenderContents::DidNavigate(
768 const history::HistoryAddPageArgs
& add_page_args
) {
769 add_page_vector_
.push_back(add_page_args
);
772 void PrerenderContents::CommitHistory(WebContents
* tab
) {
773 HistoryTabHelper
* history_tab_helper
= HistoryTabHelper::FromWebContents(tab
);
774 for (size_t i
= 0; i
< add_page_vector_
.size(); ++i
)
775 history_tab_helper
->UpdateHistoryForNavigation(add_page_vector_
[i
]);
778 base::Value
* PrerenderContents::GetAsValue() const {
779 if (!prerender_contents_
.get())
781 base::DictionaryValue
* dict_value
= new base::DictionaryValue();
782 dict_value
->SetString("url", prerender_url_
.spec());
783 base::TimeTicks current_time
= base::TimeTicks::Now();
784 base::TimeDelta duration
= current_time
- load_start_time_
;
785 dict_value
->SetInteger("duration", duration
.InSeconds());
786 dict_value
->SetBoolean("is_loaded", prerender_contents_
&&
787 !prerender_contents_
->IsLoading());
791 bool PrerenderContents::IsCrossSiteNavigationPending() const {
792 if (!prerender_contents_
)
794 return (prerender_contents_
->GetSiteInstance() !=
795 prerender_contents_
->GetPendingSiteInstance());
798 void PrerenderContents::PrepareForUse() {
799 SetFinalStatus(FINAL_STATUS_USED
);
801 if (prerender_contents_
.get()) {
802 prerender_contents_
->SendToAllFrames(
803 new PrerenderMsg_SetIsPrerendering(MSG_ROUTING_NONE
, false));
806 NotifyPrerenderStop();
808 BrowserThread::PostTask(
811 base::Bind(&ResumeThrottles
, resource_throttles_
));
812 resource_throttles_
.clear();
815 SessionStorageNamespace
* PrerenderContents::GetSessionStorageNamespace() const {
816 if (!prerender_contents())
818 return prerender_contents()->GetController().
819 GetDefaultSessionStorageNamespace();
822 void PrerenderContents::OnCancelPrerenderForPrinting() {
823 Destroy(FINAL_STATUS_WINDOW_PRINT
);
826 void PrerenderContents::RecordCookieEvent(CookieEvent event
,
827 bool is_main_frame_http_request
,
828 bool is_third_party_cookie
,
829 bool is_for_blocking_resource
,
830 base::Time earliest_create_date
) {
831 // We don't care about sent cookies that were created after this prerender
833 // The reason is that for the purpose of the histograms emitted, we only care
834 // about cookies that existed before the prerender was started, but not
835 // about cookies that were created as part of the prerender. Using the
836 // earliest creation timestamp of all cookies provided by the cookie monster
837 // is a heuristic that yields the desired result pretty closely.
838 // In particular, we pretend no other WebContents make changes to the cookies
839 // relevant to the prerender, which may not actually always be the case, but
840 // hopefully most of the times.
841 if (event
== COOKIE_EVENT_SEND
&& earliest_create_date
> start_time_
)
844 InternalCookieEvent internal_event
= INTERNAL_COOKIE_EVENT_MAX
;
846 if (is_main_frame_http_request
) {
847 if (event
== COOKIE_EVENT_SEND
) {
848 internal_event
= INTERNAL_COOKIE_EVENT_MAIN_FRAME_SEND
;
850 internal_event
= INTERNAL_COOKIE_EVENT_MAIN_FRAME_CHANGE
;
853 if (event
== COOKIE_EVENT_SEND
) {
854 internal_event
= INTERNAL_COOKIE_EVENT_OTHER_SEND
;
856 internal_event
= INTERNAL_COOKIE_EVENT_OTHER_CHANGE
;
860 DCHECK_GE(internal_event
, 0);
861 DCHECK_LT(internal_event
, INTERNAL_COOKIE_EVENT_MAX
);
863 cookie_status_
|= (1 << internal_event
);
865 DCHECK_GE(cookie_status_
, 0);
866 DCHECK_LT(cookie_status_
, kNumCookieStatuses
);
868 CookieSendType send_type
= COOKIE_SEND_TYPE_NONE
;
869 if (event
== COOKIE_EVENT_SEND
) {
870 if (!is_third_party_cookie
) {
871 send_type
= COOKIE_SEND_TYPE_FIRST_PARTY
;
873 if (is_for_blocking_resource
) {
874 send_type
= COOKIE_SEND_TYPE_THIRD_PARTY_BLOCKING_RESOURCE
;
876 send_type
= COOKIE_SEND_TYPE_THIRD_PARTY
;
880 DCHECK_GE(send_type
, 0);
881 DCHECK_LT(send_type
, COOKIE_SEND_TYPE_MAX
);
883 if (cookie_send_type_
< send_type
)
884 cookie_send_type_
= send_type
;
887 void PrerenderContents::AddResourceThrottle(
888 const base::WeakPtr
<PrerenderResourceThrottle
>& throttle
) {
889 resource_throttles_
.push_back(throttle
);
892 void PrerenderContents::AddNetworkBytes(int64 bytes
) {
893 network_bytes_
+= bytes
;
896 } // namespace prerender