XMPP和同源政策问题

时间:2011-08-05 13:21:18

标签: ajax same-origin-policy

我正在使用OpenFire服务器和JSJaC客户端库构建聊天应用程序。 页面从http://staging.mysite.com加载,XMPP在http://xmpp.mysite.com上运行。如您所见,它们共享同一个域。所以我在页面加载时使用以下代码。

function OnPageLoad (){
    document.domain = "mysite.com";
    DoLogin();
}

无论如何,它引发了我的异常,说我违反了安全措施。为什么document.domain不起作用?它应该工作还是只是为了“美丽”?如果是,在这种特定情况下可以做些什么?

我无法访问库中的XMLHttpRequest对象,也无法控制它。

1 个答案:

答案 0 :(得分:0)

反正。我不得不深入挖掘JSJaC库并对代码进行了一些注入。但首先我做了一些解决方法。基本上我将以下标题添加到响应中

Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, *

通常,这允许使用本机xhr进行跨域请求。但事实证明它只适用于现代浏览器。例如它在IE8中不起作用,任何版本的Opera都拒绝这个标题。 然后我用了基于flash的解决方案。我使用flXHR并修改了jsjac.uncompressed.js。

XmlHttp.create = function () {
    //  try {
    //    if (window.XMLHttpRequest) {
    //      var req = new XMLHttpRequest();
    //     
    //      // some versions of Moz do not support the readyState property
    //      // and the onreadystate event so we patch it!
    //      if (req.readyState == null) {
    //  req.readyState = 1;
    //  req.addEventListener("load", function () {
    //                 req.readyState = 4;
    //                 if (typeof req.onreadystatechange == "function")
    //               req.onreadystatechange();
    //               }, false);
    //      }
    //     
    //      return req;
    //    }
    //    if (window.ActiveXObject) {
    //      return new ActiveXObject(XmlHttp.getPrefix() + ".XmlHttp");
    //    }
    //  }
    //  catch (ex) {}
    //  // fell through
    //  throw new Error("Your browser does not support XmlHttp objects");
    var AsyncClient = new flensed.flXHR({
        "autoUpdatePlayer": true,
        "instanceId": "myproxy" + _xhrpf.toString(),
        // This is important because the library uses the response xml of the object to manipulate the data
        "xmlResponseText": true,
        "onreadystatechange": function () { }
    });
    // counter for giving a unique id for the flash xhr object.
    _xhrpf++;
    return AsyncClient;
};


var _xhrpf = 1;

然后我在目标域的根目录中添加了crossdomain.xml。现在,如果浏览器具有Flash插件,它将完美运行。
如果没有flash插件,我想制作一些检测机制,只需制作一个原生的xhr,并希望浏览器支持跨域请求的标题。

相关问题