【问题标题】:Override document.location.href is it possible in javascript?覆盖 document.location.href 是否可以在 javascript 中使用?
【发布时间】:2011-01-03 19:25:39
【问题描述】:

是否可以以某种方式覆盖 document.location.href ?

需要覆盖 getter,例如:alert(document.location.href);应该返回让我们说“www.example.com”,而真正的文档位置是 www.stackoverflow.com...

不知道有没有可能..

【问题讨论】:

  • 也许如果你告诉我们你真正想要达到的目标,一个解决方案可能即将到来。执行您似乎要求的最佳方法是 alert("www.example.com");
  • 我相信他的网站使用了插件,应该无法访问网址。

标签: javascript


【解决方案1】:

不,但是……

在 Ecmascript 5 中,支持 getter/setter,如果从重新定义它的范围内访问,您可以欺骗 document 引用。

证明:

(function (document) {
    alert(document);        // -> "spoofed document" 
})("spoofed document");

结合accessors可以替换文档对象。 (访问者需要 Javascript 1.5。)

【讨论】:

  • 请注意,使用内部执行eval() 或直接使用eval() 的各种命令仍然很容易突破此沙箱。有关示例,请参见此处:jsbin.com/esula/edit
【解决方案2】:

没有。出于安全原因,这是不可能的。

【讨论】:

  • gs:您可以设置一个虚假的 Facebook 登录页面并更改 URL onload。
  • 这实际上取决于浏览器。某些浏览器将允许您替换位置对象并伪造此 API 的返回。网站不应依赖此对象作为保护免受攻击的手段。
  • javascript 变量和 URL 之间没有关联。从document.location返回错误数据不会影响浏览器的URL字段。
【解决方案3】:

正如其他人已经指出的那样,如果不重新加载页面,就无法更改 URL。

请注意,您可以使用 document.location.hash 更改片段标识符,即哈希 (#) 之后的 URL 部分,但这可能对您来说不够好。

【讨论】:

    【解决方案4】:

    将“文档”换成另一个变量,对其进行编辑,然后将其换回。

    var d = {}
    for (var k in document) {
        d[k] = document[k];
    }
    d["location"]="out of this world";
    document = d;
    

    【讨论】:

    • 分配给document 无效(除非你var document,但无论如何这不是你想要的)。
    【解决方案5】:

    您可以在 IE7 或 IE8 中通过使用独立的脚本标签来覆盖它(但在现代 Firefox 或 IE9+ 中不行):

    <!DOCTYPE html>
    <html><head>
    <title>Some title</title>
    </head>
    <body>
    <script>
    var _oldDoc = document; // IE < 9 won't work with the code below unless we place it here in its own script tag
    </script>
    <script>
    var document = {};
    for (var k in _oldDoc) {
        if (navigator.appName == 'Microsoft Internet Explorer' || 
            !k.match(/^(location|domain|body)$/) // Cause problems or errors in Mozilla, but Mozilla isn't really creating a new document object anyways
        ) {
            document[k] = _oldDoc[k];
        }
    }
    
    // Causes problems in Mozilla as we can't get Mozilla to actually overwrite the object
    document["location"] = {
        href: "out of this world",
        toString: function () {
            return this.href;
        }
    };
    alert(document.location.href); // "out of this world" in IE < 9
    alert(document.location); // "out of this world" in IE < 9
    alert(document.title); // 'Some title'
    </script>
    <script>
    alert(document.location.href); // also "out of this world" in IE < 9
    alert(document.location); // also gives "out of this world" in IE < 9
    alert(document.title); // also 'Some title'
    </script>
    
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2014-01-07
      • 2019-06-20
      • 2017-10-22
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多