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 "apps/ui/web_contents_sizer.h"
12 #include "base/bind.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/history/history_tab_helper.h"
16 #include "chrome/browser/history/history_types.h"
17 #include "chrome/browser/prerender/prerender_field_trial.h"
18 #include "chrome/browser/prerender/prerender_final_status.h"
19 #include "chrome/browser/prerender/prerender_handle.h"
20 #include "chrome/browser/prerender/prerender_manager.h"
21 #include "chrome/browser/prerender/prerender_manager_factory.h"
22 #include "chrome/browser/prerender/prerender_resource_throttle.h"
23 #include "chrome/browser/prerender/prerender_tracker.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/ui/browser.h"
26 #include "chrome/browser/ui/tab_helpers.h"
27 #include "chrome/common/prerender_messages.h"
28 #include "chrome/common/render_messages.h"
29 #include "chrome/common/url_constants.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 "content/public/common/page_transition_types.h"
42 #include "ui/gfx/rect.h"
44 using content::DownloadItem
;
45 using content::OpenURLParams
;
46 using content::RenderViewHost
;
47 using content::ResourceRedirectDetails
;
48 using content::SessionStorageNamespace
;
49 using content::WebContents
;
55 // Internal cookie event.
56 // Whenever a prerender interacts with the cookie store, either sending
57 // existing cookies that existed before the prerender started, or when a cookie
58 // is changed, we record these events for histogramming purposes.
59 enum InternalCookieEvent
{
60 INTERNAL_COOKIE_EVENT_MAIN_FRAME_SEND
= 0,
61 INTERNAL_COOKIE_EVENT_MAIN_FRAME_CHANGE
= 1,
62 INTERNAL_COOKIE_EVENT_OTHER_SEND
= 2,
63 INTERNAL_COOKIE_EVENT_OTHER_CHANGE
= 3,
64 INTERNAL_COOKIE_EVENT_MAX
67 // Indicates whether existing cookies were sent, and if they were third party
68 // cookies, and whether they were for blocking resources.
69 // Each value may be inclusive of previous values. We only care about the
70 // value with the highest index that has ever occurred in the course of a
73 COOKIE_SEND_TYPE_NONE
= 0,
74 COOKIE_SEND_TYPE_FIRST_PARTY
= 1,
75 COOKIE_SEND_TYPE_THIRD_PARTY
= 2,
76 COOKIE_SEND_TYPE_THIRD_PARTY_BLOCKING_RESOURCE
= 3,
81 std::vector
<base::WeakPtr
<PrerenderResourceThrottle
> > throttles
) {
82 for (size_t i
= 0; i
< throttles
.size(); i
++) {
84 throttles
[i
]->Resume();
91 const int PrerenderContents::kNumCookieStatuses
=
92 (1 << INTERNAL_COOKIE_EVENT_MAX
);
95 const int PrerenderContents::kNumCookieSendTypes
= COOKIE_SEND_TYPE_MAX
;
97 class PrerenderContentsFactoryImpl
: public PrerenderContents::Factory
{
99 virtual PrerenderContents
* CreatePrerenderContents(
100 PrerenderManager
* prerender_manager
, Profile
* profile
,
101 const GURL
& url
, const content::Referrer
& referrer
,
102 Origin origin
, uint8 experiment_id
) OVERRIDE
{
103 return new PrerenderContents(prerender_manager
, profile
,
104 url
, referrer
, origin
, experiment_id
);
108 // WebContentsDelegateImpl -----------------------------------------------------
110 class PrerenderContents::WebContentsDelegateImpl
111 : public content::WebContentsDelegate
{
113 explicit WebContentsDelegateImpl(PrerenderContents
* prerender_contents
)
114 : prerender_contents_(prerender_contents
) {
117 // content::WebContentsDelegate implementation:
118 virtual WebContents
* OpenURLFromTab(WebContents
* source
,
119 const OpenURLParams
& params
) OVERRIDE
{
120 // |OpenURLFromTab| is typically called when a frame performs a navigation
121 // that requires the browser to perform the transition instead of WebKit.
122 // Examples include prerendering a site that redirects to an app URL,
123 // or if --enable-strict-site-isolation is specified and the prerendered
124 // frame redirects to a different origin.
125 // TODO(cbentzel): Consider supporting this if it is a common case during
127 prerender_contents_
->Destroy(FINAL_STATUS_OPEN_URL
);
131 virtual void CloseContents(content::WebContents
* contents
) OVERRIDE
{
132 prerender_contents_
->Destroy(FINAL_STATUS_CLOSED
);
135 virtual void CanDownload(
136 RenderViewHost
* render_view_host
,
138 const std::string
& request_method
,
139 const base::Callback
<void(bool)>& callback
) OVERRIDE
{
140 prerender_contents_
->Destroy(FINAL_STATUS_DOWNLOAD
);
141 // Cancel the download.
145 virtual bool ShouldCreateWebContents(
146 WebContents
* web_contents
,
148 WindowContainerType window_container_type
,
149 const base::string16
& frame_name
,
150 const GURL
& target_url
,
151 const std::string
& partition_id
,
152 SessionStorageNamespace
* session_storage_namespace
) OVERRIDE
{
153 // Since we don't want to permit child windows that would have a
154 // window.opener property, terminate prerendering.
155 prerender_contents_
->Destroy(FINAL_STATUS_CREATE_NEW_WINDOW
);
160 virtual bool OnGoToEntryOffset(int offset
) OVERRIDE
{
161 // This isn't allowed because the history merge operation
162 // does not work if there are renderer issued challenges.
163 // TODO(cbentzel): Cancel in this case? May not need to do
164 // since render-issued offset navigations are not guaranteed,
165 // but indicates that the page cares about the history.
169 virtual bool ShouldSuppressDialogs() OVERRIDE
{
170 // We still want to show the user the message when they navigate to this
171 // page, so cancel this prerender.
172 prerender_contents_
->Destroy(FINAL_STATUS_JAVASCRIPT_ALERT
);
173 // Always suppress JavaScript messages if they're triggered by a page being
178 virtual void RegisterProtocolHandler(WebContents
* web_contents
,
179 const std::string
& protocol
,
181 bool user_gesture
) OVERRIDE
{
182 // TODO(mmenke): Consider supporting this if it is a common case during
184 prerender_contents_
->Destroy(FINAL_STATUS_REGISTER_PROTOCOL_HANDLER
);
187 virtual gfx::Size
GetSizeForNewRenderView(
188 WebContents
* web_contents
) const OVERRIDE
{
189 // Have to set the size of the RenderView on initialization to be sure it is
190 // set before the RenderView is hidden on all platforms (esp. Android).
191 return prerender_contents_
->size_
;
195 PrerenderContents
* prerender_contents_
;
198 void PrerenderContents::Observer::OnPrerenderStopLoading(
199 PrerenderContents
* contents
) {
202 void PrerenderContents::Observer::OnPrerenderDomContentLoaded(
203 PrerenderContents
* contents
) {
206 void PrerenderContents::Observer::OnPrerenderCreatedMatchCompleteReplacement(
207 PrerenderContents
* contents
, PrerenderContents
* replacement
) {
210 PrerenderContents::Observer::Observer() {
213 PrerenderContents::Observer::~Observer() {
216 PrerenderContents::PrerenderContents(
217 PrerenderManager
* prerender_manager
,
220 const content::Referrer
& referrer
,
223 : prerendering_has_started_(false),
224 session_storage_namespace_id_(-1),
225 prerender_manager_(prerender_manager
),
230 has_stopped_loading_(false),
231 has_finished_loading_(false),
232 final_status_(FINAL_STATUS_MAX
),
233 match_complete_status_(MATCH_COMPLETE_DEFAULT
),
234 prerendering_has_been_cancelled_(false),
238 experiment_id_(experiment_id
),
239 creator_child_id_(-1),
242 cookie_send_type_(COOKIE_SEND_TYPE_NONE
),
244 DCHECK(prerender_manager
!= NULL
);
247 PrerenderContents
* PrerenderContents::CreateMatchCompleteReplacement() {
248 PrerenderContents
* new_contents
= prerender_manager_
->CreatePrerenderContents(
249 prerender_url(), referrer(), origin(), experiment_id());
251 new_contents
->load_start_time_
= load_start_time_
;
252 new_contents
->session_storage_namespace_id_
= session_storage_namespace_id_
;
253 new_contents
->set_match_complete_status(
254 PrerenderContents::MATCH_COMPLETE_REPLACEMENT_PENDING
);
256 const bool did_init
= new_contents
->Init();
258 DCHECK_EQ(alias_urls_
.front(), new_contents
->alias_urls_
.front());
259 DCHECK_EQ(1u, new_contents
->alias_urls_
.size());
260 new_contents
->alias_urls_
= alias_urls_
;
261 // Erase all but the first alias URL; the replacement has adopted the
262 // remainder without increasing the renderer-side reference count.
263 alias_urls_
.resize(1);
264 new_contents
->set_match_complete_status(
265 PrerenderContents::MATCH_COMPLETE_REPLACEMENT
);
266 NotifyPrerenderCreatedMatchCompleteReplacement(new_contents
);
270 bool PrerenderContents::Init() {
271 return AddAliasURL(prerender_url_
);
275 PrerenderContents::Factory
* PrerenderContents::CreateFactory() {
276 return new PrerenderContentsFactoryImpl();
280 PrerenderContents
* PrerenderContents::FromWebContents(
281 content::WebContents
* web_contents
) {
284 PrerenderManager
* prerender_manager
= PrerenderManagerFactory::GetForProfile(
285 Profile::FromBrowserContext(web_contents
->GetBrowserContext()));
286 if (!prerender_manager
)
288 return prerender_manager
->GetPrerenderContents(web_contents
);
291 void PrerenderContents::StartPrerendering(
292 int creator_child_id
,
293 const gfx::Size
& size
,
294 SessionStorageNamespace
* session_storage_namespace
) {
295 DCHECK(profile_
!= NULL
);
296 DCHECK(!size
.IsEmpty());
297 DCHECK(!prerendering_has_started_
);
298 DCHECK(prerender_contents_
.get() == NULL
);
299 DCHECK_EQ(-1, creator_child_id_
);
300 DCHECK(size_
.IsEmpty());
301 DCHECK_EQ(1U, alias_urls_
.size());
303 creator_child_id_
= creator_child_id
;
304 session_storage_namespace_id_
= session_storage_namespace
->id();
307 DCHECK(load_start_time_
.is_null());
308 load_start_time_
= base::TimeTicks::Now();
309 start_time_
= base::Time::Now();
311 // Everything after this point sets up the WebContents object and associated
312 // RenderView for the prerender page. Don't do this for members of the
314 if (prerender_manager_
->IsControlGroup(experiment_id()))
317 if (origin_
== ORIGIN_LOCAL_PREDICTOR
&&
318 IsLocalPredictorPrerenderAlwaysControlEnabled()) {
322 prerendering_has_started_
= true;
324 alias_session_storage_namespace
= session_storage_namespace
->CreateAlias();
325 prerender_contents_
.reset(
326 CreateWebContents(alias_session_storage_namespace
.get()));
327 TabHelpers::AttachTabHelpers(prerender_contents_
.get());
328 content::WebContentsObserver::Observe(prerender_contents_
.get());
330 web_contents_delegate_
.reset(new WebContentsDelegateImpl(this));
331 prerender_contents_
.get()->SetDelegate(web_contents_delegate_
.get());
332 // Set the size of the prerender WebContents.
333 apps::ResizeWebContents(prerender_contents_
.get(), size_
);
335 child_id_
= GetRenderViewHost()->GetProcess()->GetID();
336 route_id_
= GetRenderViewHost()->GetRoutingID();
338 // Log transactions to see if we could merge session storage namespaces in
339 // the event of a mismatch.
340 alias_session_storage_namespace
->AddTransactionLogProcessId(child_id_
);
342 NotifyPrerenderStart();
344 // Close ourselves when the application is shutting down.
345 notification_registrar_
.Add(this, chrome::NOTIFICATION_APP_TERMINATING
,
346 content::NotificationService::AllSources());
348 // Register to inform new RenderViews that we're prerendering.
349 notification_registrar_
.Add(
350 this, content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
,
351 content::Source
<WebContents
>(prerender_contents_
.get()));
353 // Transfer over the user agent override.
354 prerender_contents_
.get()->SetUserAgentOverride(
355 prerender_manager_
->config().user_agent_override
);
357 content::NavigationController::LoadURLParams
load_url_params(
359 load_url_params
.referrer
= referrer_
;
360 load_url_params
.transition_type
= content::PAGE_TRANSITION_LINK
;
361 if (origin_
== ORIGIN_OMNIBOX
) {
362 load_url_params
.transition_type
= content::PageTransitionFromInt(
363 content::PAGE_TRANSITION_TYPED
|
364 content::PAGE_TRANSITION_FROM_ADDRESS_BAR
);
365 } else if (origin_
== ORIGIN_INSTANT
) {
366 load_url_params
.transition_type
= content::PageTransitionFromInt(
367 content::PAGE_TRANSITION_GENERATED
|
368 content::PAGE_TRANSITION_FROM_ADDRESS_BAR
);
370 load_url_params
.override_user_agent
=
371 prerender_manager_
->config().is_overriding_user_agent
?
372 content::NavigationController::UA_OVERRIDE_TRUE
:
373 content::NavigationController::UA_OVERRIDE_FALSE
;
374 prerender_contents_
.get()->GetController().LoadURLWithParams(load_url_params
);
377 bool PrerenderContents::GetChildId(int* child_id
) const {
379 DCHECK_GE(child_id_
, -1);
380 *child_id
= child_id_
;
381 return child_id_
!= -1;
384 bool PrerenderContents::GetRouteId(int* route_id
) const {
386 DCHECK_GE(route_id_
, -1);
387 *route_id
= route_id_
;
388 return route_id_
!= -1;
391 void PrerenderContents::SetFinalStatus(FinalStatus final_status
) {
392 DCHECK_GE(final_status
, FINAL_STATUS_USED
);
393 DCHECK_LT(final_status
, FINAL_STATUS_MAX
);
395 DCHECK_EQ(FINAL_STATUS_MAX
, final_status_
);
397 final_status_
= final_status
;
400 PrerenderContents::~PrerenderContents() {
401 DCHECK_NE(FINAL_STATUS_MAX
, final_status());
403 prerendering_has_been_cancelled() || final_status() == FINAL_STATUS_USED
);
404 DCHECK_NE(ORIGIN_MAX
, origin());
405 // Since a lot of prerenders terminate before any meaningful cookie action
406 // would have happened, only record the cookie status for prerenders who
407 // were used, cancelled, or timed out.
408 if (prerendering_has_started_
&& final_status() == FINAL_STATUS_USED
) {
409 prerender_manager_
->RecordCookieStatus(origin(), experiment_id(),
411 prerender_manager_
->RecordCookieSendType(origin(), experiment_id(),
414 prerender_manager_
->RecordFinalStatusWithMatchCompleteStatus(
415 origin(), experiment_id(), match_complete_status(), final_status());
417 bool used
= final_status() == FINAL_STATUS_USED
||
418 final_status() == FINAL_STATUS_WOULD_HAVE_BEEN_USED
;
419 prerender_manager_
->RecordNetworkBytes(used
, network_bytes_
);
421 // Broadcast the removal of aliases.
422 for (content::RenderProcessHost::iterator host_iterator
=
423 content::RenderProcessHost::AllHostsIterator();
424 !host_iterator
.IsAtEnd();
425 host_iterator
.Advance()) {
426 content::RenderProcessHost
* host
= host_iterator
.GetCurrentValue();
427 host
->Send(new PrerenderMsg_OnPrerenderRemoveAliases(alias_urls_
));
430 // If we still have a WebContents, clean up anything we need to and then
432 if (prerender_contents_
.get())
433 delete ReleasePrerenderContents();
436 void PrerenderContents::AddObserver(Observer
* observer
) {
437 DCHECK_EQ(FINAL_STATUS_MAX
, final_status_
);
438 observer_list_
.AddObserver(observer
);
441 void PrerenderContents::RemoveObserver(Observer
* observer
) {
442 observer_list_
.RemoveObserver(observer
);
445 void PrerenderContents::Observe(int type
,
446 const content::NotificationSource
& source
,
447 const content::NotificationDetails
& details
) {
449 // TODO(davidben): Try to remove this in favor of relying on
450 // FINAL_STATUS_PROFILE_DESTROYED.
451 case chrome::NOTIFICATION_APP_TERMINATING
:
452 Destroy(FINAL_STATUS_APP_TERMINATING
);
455 case content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED
: {
456 if (prerender_contents_
.get()) {
457 DCHECK_EQ(content::Source
<WebContents
>(source
).ptr(),
458 prerender_contents_
.get());
460 content::Details
<RenderViewHost
> new_render_view_host(details
);
461 OnRenderViewHostCreated(new_render_view_host
.ptr());
463 // Make sure the size of the RenderViewHost has been passed to the new
464 // RenderView. Otherwise, the size may not be sent until the
465 // RenderViewReady event makes it from the render process to the UI
466 // thread of the browser process. When the RenderView receives its
467 // size, is also sets itself to be visible, which would then break the
469 new_render_view_host
->WasResized();
470 prerender_contents_
->WasHidden();
476 NOTREACHED() << "Unexpected notification sent.";
481 void PrerenderContents::OnRenderViewHostCreated(
482 RenderViewHost
* new_render_view_host
) {
485 WebContents
* PrerenderContents::CreateWebContents(
486 SessionStorageNamespace
* session_storage_namespace
) {
487 // TODO(ajwong): Remove the temporary map once prerendering is aware of
488 // multiple session storage namespaces per tab.
489 content::SessionStorageNamespaceMap session_storage_namespace_map
;
490 session_storage_namespace_map
[std::string()] = session_storage_namespace
;
491 return WebContents::CreateWithSessionStorage(
492 WebContents::CreateParams(profile_
), session_storage_namespace_map
);
495 void PrerenderContents::NotifyPrerenderStart() {
496 DCHECK_EQ(FINAL_STATUS_MAX
, final_status_
);
497 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnPrerenderStart(this));
500 void PrerenderContents::NotifyPrerenderStopLoading() {
501 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnPrerenderStopLoading(this));
504 void PrerenderContents::NotifyPrerenderDomContentLoaded() {
505 FOR_EACH_OBSERVER(Observer
, observer_list_
,
506 OnPrerenderDomContentLoaded(this));
509 void PrerenderContents::NotifyPrerenderStop() {
510 DCHECK_NE(FINAL_STATUS_MAX
, final_status_
);
511 FOR_EACH_OBSERVER(Observer
, observer_list_
, OnPrerenderStop(this));
512 observer_list_
.Clear();
515 void PrerenderContents::NotifyPrerenderCreatedMatchCompleteReplacement(
516 PrerenderContents
* replacement
) {
517 FOR_EACH_OBSERVER(Observer
, observer_list_
,
518 OnPrerenderCreatedMatchCompleteReplacement(this,
522 bool PrerenderContents::OnMessageReceived(const IPC::Message
& message
) {
524 // The following messages we do want to consume.
525 IPC_BEGIN_MESSAGE_MAP(PrerenderContents
, message
)
526 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CancelPrerenderForPrinting
,
527 OnCancelPrerenderForPrinting
)
528 IPC_MESSAGE_UNHANDLED(handled
= false)
529 IPC_END_MESSAGE_MAP()
534 bool PrerenderContents::CheckURL(const GURL
& url
) {
535 if (!url
.SchemeIsHTTPOrHTTPS()) {
536 DCHECK_NE(MATCH_COMPLETE_REPLACEMENT_PENDING
, match_complete_status_
);
537 Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME
);
540 if (match_complete_status_
!= MATCH_COMPLETE_REPLACEMENT_PENDING
&&
541 prerender_manager_
->HasRecentlyBeenNavigatedTo(origin(), url
)) {
542 Destroy(FINAL_STATUS_RECENTLY_VISITED
);
548 bool PrerenderContents::AddAliasURL(const GURL
& url
) {
552 alias_urls_
.push_back(url
);
554 for (content::RenderProcessHost::iterator host_iterator
=
555 content::RenderProcessHost::AllHostsIterator();
556 !host_iterator
.IsAtEnd();
557 host_iterator
.Advance()) {
558 content::RenderProcessHost
* host
= host_iterator
.GetCurrentValue();
559 host
->Send(new PrerenderMsg_OnPrerenderAddAlias(url
));
565 bool PrerenderContents::Matches(
567 const SessionStorageNamespace
* session_storage_namespace
) const {
568 if (session_storage_namespace
&&
569 session_storage_namespace_id_
!= session_storage_namespace
->id()) {
572 return std::count_if(alias_urls_
.begin(), alias_urls_
.end(),
573 std::bind2nd(std::equal_to
<GURL
>(), url
)) != 0;
576 void PrerenderContents::RenderProcessGone(base::TerminationStatus status
) {
577 Destroy(FINAL_STATUS_RENDERER_CRASHED
);
580 void PrerenderContents::RenderFrameCreated(
581 content::RenderFrameHost
* render_frame_host
) {
582 // When a new RenderFrame is created for a prerendering WebContents, tell the
583 // new RenderFrame it's being used for prerendering before any navigations
584 // occur. Note that this is always triggered before the first navigation, so
585 // there's no need to send the message just after the WebContents is created.
586 render_frame_host
->Send(new PrerenderMsg_SetIsPrerendering(
587 render_frame_host
->GetRoutingID(), true));
590 void PrerenderContents::DidStopLoading(
591 content::RenderViewHost
* render_view_host
) {
592 has_stopped_loading_
= true;
593 NotifyPrerenderStopLoading();
596 void PrerenderContents::DocumentLoadedInFrame(
598 RenderViewHost
* render_view_host
) {
599 if (frame_id
== main_frame_id_
)
600 NotifyPrerenderDomContentLoaded();
603 void PrerenderContents::DidStartProvisionalLoadForFrame(
605 int64 parent_frame_id
,
607 const GURL
& validated_url
,
609 bool is_iframe_srcdoc
,
610 RenderViewHost
* render_view_host
) {
612 if (!CheckURL(validated_url
))
615 // Usually, this event fires if the user clicks or enters a new URL.
616 // Neither of these can happen in the case of an invisible prerender.
617 // So the cause is: Some JavaScript caused a new URL to be loaded. In that
618 // case, the spinner would start again in the browser, so we must reset
619 // has_stopped_loading_ so that the spinner won't be stopped.
620 has_stopped_loading_
= false;
621 has_finished_loading_
= false;
625 void PrerenderContents::DidCommitProvisionalLoadForFrame(
627 const base::string16
& frame_unique_name
,
630 content::PageTransition transition_type
,
631 RenderViewHost
* render_view_host
) {
633 main_frame_id_
= frame_id
;
637 void PrerenderContents::DidFinishLoad(int64 frame_id
,
638 const GURL
& validated_url
,
640 RenderViewHost
* render_view_host
) {
642 has_finished_loading_
= true;
645 void PrerenderContents::DidNavigateMainFrame(
646 const content::LoadCommittedDetails
& details
,
647 const content::FrameNavigateParams
& params
) {
648 // If the prerender made a second navigation entry, abort the prerender. This
649 // avoids having to correctly implement a complex history merging case (this
650 // interacts with location.replace) and correctly synchronize with the
651 // renderer. The final status may be monitored to see we need to revisit this
652 // decision. This does not affect client redirects as those do not push new
653 // history entries. (Calls to location.replace, navigations before onload, and
654 // <meta http-equiv=refresh> with timeouts under 1 second do not create
655 // entries in Blink.)
656 if (prerender_contents_
->GetController().GetEntryCount() > 1) {
657 Destroy(FINAL_STATUS_NEW_NAVIGATION_ENTRY
);
661 // Add each redirect as an alias. |params.url| is included in
662 // |params.redirects|.
664 // TODO(davidben): We do not correctly patch up history for renderer-initated
665 // navigations which add history entries. http://crbug.com/305660.
666 for (size_t i
= 0; i
< params
.redirects
.size(); i
++) {
667 if (!AddAliasURL(params
.redirects
[i
]))
672 void PrerenderContents::DidGetRedirectForResourceRequest(
673 RenderViewHost
* render_view_host
,
674 const content::ResourceRedirectDetails
& details
) {
675 // DidGetRedirectForResourceRequest can come for any resource on a page. If
676 // it's a redirect on the top-level resource, the name needs to be remembered
677 // for future matching, and if it redirects to an https resource, it needs to
678 // be canceled. If a subresource is redirected, nothing changes.
679 if (details
.resource_type
!= ResourceType::MAIN_FRAME
)
681 CheckURL(details
.new_url
);
684 void PrerenderContents::Destroy(FinalStatus final_status
) {
685 DCHECK_NE(final_status
, FINAL_STATUS_USED
);
687 if (prerendering_has_been_cancelled_
)
690 SetFinalStatus(final_status
);
692 prerendering_has_been_cancelled_
= true;
693 prerender_manager_
->AddToHistory(this);
694 prerender_manager_
->MoveEntryToPendingDelete(this, final_status
);
696 // Note that if this PrerenderContents was made into a MatchComplete
697 // replacement by MoveEntryToPendingDelete, NotifyPrerenderStop will
698 // not reach the PrerenderHandle. Rather
699 // OnPrerenderCreatedMatchCompleteReplacement will propogate that
700 // information to the referer.
701 if (!prerender_manager_
->IsControlGroup(experiment_id()) &&
702 (prerendering_has_started() ||
703 match_complete_status() == MATCH_COMPLETE_REPLACEMENT
)) {
704 NotifyPrerenderStop();
708 base::ProcessMetrics
* PrerenderContents::MaybeGetProcessMetrics() {
709 if (process_metrics_
.get() == NULL
) {
710 // If a PrenderContents hasn't started prerending, don't be fully formed.
711 if (!GetRenderViewHost() || !GetRenderViewHost()->GetProcess())
713 base::ProcessHandle handle
= GetRenderViewHost()->GetProcess()->GetHandle();
714 if (handle
== base::kNullProcessHandle
)
716 #if !defined(OS_MACOSX)
717 process_metrics_
.reset(base::ProcessMetrics::CreateProcessMetrics(handle
));
719 process_metrics_
.reset(base::ProcessMetrics::CreateProcessMetrics(
721 content::BrowserChildProcessHost::GetPortProvider()));
725 return process_metrics_
.get();
728 void PrerenderContents::DestroyWhenUsingTooManyResources() {
729 base::ProcessMetrics
* metrics
= MaybeGetProcessMetrics();
733 size_t private_bytes
, shared_bytes
;
734 if (metrics
->GetMemoryBytes(&private_bytes
, &shared_bytes
) &&
735 private_bytes
> prerender_manager_
->config().max_bytes
) {
736 Destroy(FINAL_STATUS_MEMORY_LIMIT_EXCEEDED
);
740 WebContents
* PrerenderContents::ReleasePrerenderContents() {
741 prerender_contents_
->SetDelegate(NULL
);
742 content::WebContentsObserver::Observe(NULL
);
743 if (alias_session_storage_namespace
)
744 alias_session_storage_namespace
->RemoveTransactionLogProcessId(child_id_
);
745 return prerender_contents_
.release();
748 RenderViewHost
* PrerenderContents::GetRenderViewHostMutable() {
749 return const_cast<RenderViewHost
*>(GetRenderViewHost());
752 const RenderViewHost
* PrerenderContents::GetRenderViewHost() const {
753 if (!prerender_contents_
.get())
755 return prerender_contents_
->GetRenderViewHost();
758 void PrerenderContents::DidNavigate(
759 const history::HistoryAddPageArgs
& add_page_args
) {
760 add_page_vector_
.push_back(add_page_args
);
763 void PrerenderContents::CommitHistory(WebContents
* tab
) {
764 HistoryTabHelper
* history_tab_helper
= HistoryTabHelper::FromWebContents(tab
);
765 for (size_t i
= 0; i
< add_page_vector_
.size(); ++i
)
766 history_tab_helper
->UpdateHistoryForNavigation(add_page_vector_
[i
]);
769 base::Value
* PrerenderContents::GetAsValue() const {
770 if (!prerender_contents_
.get())
772 base::DictionaryValue
* dict_value
= new base::DictionaryValue();
773 dict_value
->SetString("url", prerender_url_
.spec());
774 base::TimeTicks current_time
= base::TimeTicks::Now();
775 base::TimeDelta duration
= current_time
- load_start_time_
;
776 dict_value
->SetInteger("duration", duration
.InSeconds());
777 dict_value
->SetBoolean("is_loaded", prerender_contents_
&&
778 !prerender_contents_
->IsLoading());
782 bool PrerenderContents::IsCrossSiteNavigationPending() const {
783 if (!prerender_contents_
)
785 return (prerender_contents_
->GetSiteInstance() !=
786 prerender_contents_
->GetPendingSiteInstance());
789 void PrerenderContents::PrepareForUse() {
790 SetFinalStatus(FINAL_STATUS_USED
);
792 if (prerender_contents_
.get()) {
793 prerender_contents_
->SendToAllFrames(
794 new PrerenderMsg_SetIsPrerendering(MSG_ROUTING_NONE
, false));
797 NotifyPrerenderStop();
799 content::BrowserThread::PostTask(
800 content::BrowserThread::IO
,
802 base::Bind(&ResumeThrottles
, resource_throttles_
));
803 resource_throttles_
.clear();
806 SessionStorageNamespace
* PrerenderContents::GetSessionStorageNamespace() const {
807 if (!prerender_contents())
809 return prerender_contents()->GetController().
810 GetDefaultSessionStorageNamespace();
813 void PrerenderContents::OnCancelPrerenderForPrinting() {
814 Destroy(FINAL_STATUS_WINDOW_PRINT
);
817 void PrerenderContents::RecordCookieEvent(CookieEvent event
,
818 bool is_main_frame_http_request
,
819 bool is_third_party_cookie
,
820 bool is_for_blocking_resource
,
821 base::Time earliest_create_date
) {
822 // We don't care about sent cookies that were created after this prerender
824 // The reason is that for the purpose of the histograms emitted, we only care
825 // about cookies that existed before the prerender was started, but not
826 // about cookies that were created as part of the prerender. Using the
827 // earliest creation timestamp of all cookies provided by the cookie monster
828 // is a heuristic that yields the desired result pretty closely.
829 // In particular, we pretend no other WebContents make changes to the cookies
830 // relevant to the prerender, which may not actually always be the case, but
831 // hopefully most of the times.
832 if (event
== COOKIE_EVENT_SEND
&& earliest_create_date
> start_time_
)
835 InternalCookieEvent internal_event
= INTERNAL_COOKIE_EVENT_MAX
;
837 if (is_main_frame_http_request
) {
838 if (event
== COOKIE_EVENT_SEND
) {
839 internal_event
= INTERNAL_COOKIE_EVENT_MAIN_FRAME_SEND
;
841 internal_event
= INTERNAL_COOKIE_EVENT_MAIN_FRAME_CHANGE
;
844 if (event
== COOKIE_EVENT_SEND
) {
845 internal_event
= INTERNAL_COOKIE_EVENT_OTHER_SEND
;
847 internal_event
= INTERNAL_COOKIE_EVENT_OTHER_CHANGE
;
851 DCHECK_GE(internal_event
, 0);
852 DCHECK_LT(internal_event
, INTERNAL_COOKIE_EVENT_MAX
);
854 cookie_status_
|= (1 << internal_event
);
856 DCHECK_GE(cookie_status_
, 0);
857 DCHECK_LT(cookie_status_
, kNumCookieStatuses
);
859 CookieSendType send_type
= COOKIE_SEND_TYPE_NONE
;
860 if (event
== COOKIE_EVENT_SEND
) {
861 if (!is_third_party_cookie
) {
862 send_type
= COOKIE_SEND_TYPE_FIRST_PARTY
;
864 if (is_for_blocking_resource
) {
865 send_type
= COOKIE_SEND_TYPE_THIRD_PARTY_BLOCKING_RESOURCE
;
867 send_type
= COOKIE_SEND_TYPE_THIRD_PARTY
;
871 DCHECK_GE(send_type
, 0);
872 DCHECK_LT(send_type
, COOKIE_SEND_TYPE_MAX
);
874 if (cookie_send_type_
< send_type
)
875 cookie_send_type_
= send_type
;
878 void PrerenderContents::AddResourceThrottle(
879 const base::WeakPtr
<PrerenderResourceThrottle
>& throttle
) {
880 resource_throttles_
.push_back(throttle
);
883 void PrerenderContents::AddNetworkBytes(int64 bytes
) {
884 network_bytes_
+= bytes
;
887 } // namespace prerender