【问题标题】:XMPP and Same origin policy problemXMPP 和同源策略问题
【发布时间】:2011-09-07 18:50:10
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: ajax same-origin-policy


    【解决方案1】:

    无论如何。我不得不更深入地挖掘 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 都简单地拒绝了此标头。 然后我使用了基于闪存的解决方案。我使用了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,希望浏览器支持跨域请求的headers。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-07
      • 2012-02-20
      • 2011-04-24
      • 2018-01-27
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多