Finding previous URL from window.history

2019-08-08 10:45发布

问题:

I've hosts file blocking so time to time, I get these "Page not found" errors browsing thru deals.

Since I got tired of copying the target url, unescaping, replacing it in address bar and hitting enter, I wrote a handy bookmarklet to automate this:

(function () {
    var href = window.location.href;
    var loc = href.indexOf('url=');
    if (loc > 0) {
        var endLoc = href.indexOf('&', loc + 4);
        endLoc = endLoc > 0 ? endLoc : href.length;
        window.location.href = unescape(href.substring(loc + 4, endLoc));
    }
})()

Now the problem is that Chrome, internally redirects and unreachable page to its own bounce.php which produces the following error page.

Since it supports history API, the URL in browser address bar doesn't change, as evident from the following data:

> JSON.stringify(window.history)  
{"state":null,"length":2}

Now the problem is, my bookmarklet doesn't work since window.location.href points to "data:text/html,chromewebdata" once this happens.

I've looked at this question How do you get the previous url in Javascript? whose accepted answer is blissfully incorrect. Rightfully so, document.referrer is empty in my case.

So is there a way to find the previous URL from window.history? window.history.previous is non-standard and doesn't work on Chrome anyway.

回答1:

Found a way (at least while it lasts!)

Chrome sets the entire URL in document.title, so querying it is all that's needed. Here's the modified code if anyone's interested:

(function () {
    var href = document.title;
    var loc = href.lastIndexOf('http');
    if (loc > 0) {
        var endLoc = href.indexOf(' is not available', loc);
        endLoc = endLoc > 0 ? endLoc : href.length;
        window.location.href = unescape(unescape(href.substring(loc, endLoc)))
    }
})()

Note: The double unescape is needed for links coming via Google Ads.