【问题标题】:Finding previous URL from window.history从 window.history 中查找上一个 URL
【发布时间】:2013-06-10 18:03:42
【问题描述】:

我有 hosts file blocking 时常在浏览交易时收到这些“找不到页面”错误。

由于我厌倦了复制目标网址、取消转义、在地址栏中替换它并按回车,我编写了一个方便的书签来自动执行此操作:

(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));
    }
})()

现在的问题是 Chrome 在内部重定向和无法访问的页面到它自己的 bounce.php,这会产生以下错误页面。

由于支持history API,浏览器地址栏中的URL不会改变,如下数据所示:

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

现在的问题是,我的书签不起作用,因为一旦发生这种情况,window.location.href 就会指向 "data:text/html,chromewebdata"

我看过这个问题How do you get the previous url in Javascript?,其接受的答案非常不正确。没错,document.referrer 在我的情况下是空的。

那么有没有办法从window.history 中找到上一个URL? window.history.previous 是非标准的,无论如何都不能在 Chrome 上运行。

【问题讨论】:

  • 您是否考虑过创建 Chrome 扩展程序而不是使用小书签?
  • 我的想法是一样的,虽然不确定我是否可以通过那个访问...
  • chrome.webRequest API 可用于检测网络错误。对于您的特定用例,只需监视 main_frame 上的错误。这是一个示例:stackoverflow.com/questions/8514883/…。在尝试创建 Chrome 扩展程序之前,您是否已经查看了错误页面的生成源?确定在里面找不到原网址吗?
  • 是的!已经看过了。此外,不能依赖查看源,因为它可能不适用于任何站点。 chrome.webRequest 听起来可行 - 只是我现在必须走大路...... :)

标签: javascript google-chrome browser-history


【解决方案1】:

找到了一种方法(至少在它持续的时候!)

Chrome 将整个 URL 设置为 document.title,因此只需查询即可。如果有人感兴趣,这是修改后的代码:

(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)))
    }
})()

注意:来自 Google Ads 的链接需要双精度 unescape

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多