在Javascript中使用document.domain的同源策略解决方法

时间:2010-03-08 21:37:34

标签: javascript same-origin-policy

我在Javascript中遇到了同源策略问题。我已经阅读了使用document.domain变量的解决方法,但我无法使解决方法起作用。解决方法是,您应该能够将document.domain设置为'example.com',这样如果您从foo.example.com运行代码,它就可以通过XHR从bar.example.com加载数据。

有关解决方法的详细信息,请访问:

https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript

我的示例代码 - 无法产生预期效果 - 来自http://foo.example.com/之类的网址:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script>
document.domain = 'example.com';
window.onload = function() {
    var req = new XMLHttpRequest();
    var url = 'http://bar.example.com/';
    req.open('GET', url, true);
    req.onreadystatechange = function (aEvt) {
        if (req.readyState == 4) {
            var elem = document.getElementById('result');
            if (req.status == 200) {
                var data = req.responseText;
            } else {
                var data = "Error loading page: " + req.status;
            }
            elem.innerHTML = data;
        }
    };
    req.send(null);
};
</script>
Result:<hr>
<div id="result"></div>
</body>
</html>

此代码的输出:

Result:
Error loading page: 0

如果我将url更改为'http://foo.example.com/',一切正常。我的示例代码中是否有错误?

我不想使用代理,因为它们速度较慢,效率较低,并且会增加我们的Web服务器上的流量。如果这种解决方法确实有效,那真的很酷。这是解决方法“天上掉馅饼”吗?

2 个答案:

答案 0 :(得分:21)

document.domain允许帧/ iframe之间的通信。不是XHR。

<body>
<iframe src="http://bar.example.com/"></iframe>
<script>
    document.domain = 'example.com';
    var ifr = document.getElementsByTagName('IFRAME')[0];
    ifr.onload = function(e){
        //will log the string "BODY" in the console
        console.log(ifr.contentWindow.document.body.tagName);
    };
</script>
</body>

如果删除document.domain行,则读取contentWindow的内容将引发同源策略错误。

答案 1 :(得分:3)

由于Mic回答了为什么它不起作用,我想我会分享“如何”使跨域工作的解决方案。请参阅我的帖子here

相关问题