window.opener跨域调用使用javascript

时间:2014-06-25 12:10:04

标签: javascript cross-domain

我有一个像123.example.com这样的子域名网址,因为我正在使用谷歌或Facebook进行Oauth登录。现在的程序就像当我点击google或facebook登录时,弹出一个窗口,获取详细信息后,我想在父窗口中显示详细信息。所以我正在使用window.opener。$(“#first_name”)。val(firstName);,我收到这样的错误错误:拒绝访问属性'$'的权限。 如果它不是子域,它的工作正常。如何将值获取到主窗口。

1 个答案:

答案 0 :(得分:5)

有两种选择:

document.domain

如果两个窗口位于同一个根域,并且问题是子域,则可以使用document.domain property解决问题,例如:在123.example.com的窗口中,您可以执行以下操作:

document.domain = "example.com";

...允许它与example.com.

上的窗口交谈

网络消息

更一般(和现代)的解决方案是web messaging,它允许在SOP通常会阻止直接通信的地方进行合作的跨源通信。我们有http://parent-origin/parent.html,它想要打开并与http://child-origin/child.html进行通信。在http://parent-origin/parent.html

// Listen for messages
window.addEventListener("message", function(e) {
    // If we get a message from the child, and the message is asking for
    // us to send the info...
    if (e.origin === "http://child-origin" && e.data === "send-info") {
        // ...send it
        log("Got request from child, sending info");
        e.source.postMessage({command: "info", info: { /*...data goes here...*/ }}, e.origin);
    }
}, false);

http://child-origin/child.html

// Listen for messages
window.addEventListener("message", function(e) {
    var info;

    // If the message is from the parent and it says it has the info...
    if (e.origin === "http://parent-origin" && e.data && e.data.command === "info") {
        // Use info
        info = e.data.info;
        log("Info is " + JSON.stringify(info));
    }
}, false);

// Ask the opener to send us the info
opener.postMessage("send-info", "http://parent-origin");

您可以根据您打开孩子的方式消除孩子要求父母提供信息的部分(例如,如果父窗口有办法知道孩子满载并且准备好消息)。让孩子询问是一种很好的方法,可以确保它已准备好接收信息。

最初,Web消息传递只允许传递字符串,但现代浏览器允许传递被克隆的对象。另请注意,如果您有canvas个对象或类似对象,则可以在postMessage的第三个参数中传递它们,以便传输:发件人无法再访问它们,只是接收器。这样我们就可以避免复制大量内容(如果可能),同时避免多个线程同时访问相同数据的问题。

相关问题