Detect Google Chrome page prefetch

China☆狼群 提交于 2020-01-02 05:39:09

问题


I am building a simple tool that tracks and increases the number of visits of a website. It's something simple as:

When the server receives a GET request, it will increase the counter in database for that website by 1.

However, I am running to a bit problem with Google Chrome's pre-render engine ("Predict network actions to improve page load performance").

The website is www.domain.com, and as soon as you type the domain name www.domain.com into the browser's address bar (without pressing Enter), Chrome sends a GET request to prefetch the page, resulting in the server logging that visit and increasing the counter in database by 1. After that, if the user presses Enter and actually loads the webpage, the server will see another GET request coming in, thus increasing the counter, again. This result in 2 duplicate visits logged in the database. As far as I understand, Google Chrome only downloads the page but doesn't execute it, but as soon as my server gets a GET requests, the counter is increased.

Question: Is there any way to work around this? Preferably, I would like to detect whether or not it is a prefetch or an actual user that visits the website.


回答1:


It appears that this is undetectable server side.

An issue was opened for this for the Chromium project. It's marked as "won't fix" (Prerendering does not have any distinguishing HTTP headers). The prefetch request doesn't show up in the Dev Tools "Network" tab, so you can't easily confirm this by look at the headers. I checked them using Wireshark, and unfortunately there was no difference distinguishing pre-render requests from "normal" requests.

Workaround:

You can check for prefetched pages client-side using the Page Visibility API. It's a bit more work than server side tracking, but you can insert a script tag in your page that checks if it's a prerender request. If that's the case, send an AJAX request which somehow identifies which page it was, and use that to increment the counter in your database.

if (document.visibilityState !== 'prerender')
{
    //ajax call registering page hit
}

Just watch out that the AJAX request doesn't return a result from cache, preventing it from arriving at the server.



来源:https://stackoverflow.com/questions/34562427/detect-google-chrome-page-prefetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!