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

Rub*_*bix 21 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

我的示例代码 - 不会产生所需的结果 - 从以下URL运行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>
Run Code Online (Sandbox Code Playgroud)

此代码的输出:

Result:
Error loading page: 0

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

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

Mic*_*Mic 23

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>
Run Code Online (Sandbox Code Playgroud)

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