如何使用postMessage传递JavaScript对象

时间:2015-06-28 10:10:06

标签: javascript html messaging postmessage

我一直在玩HTML postMessage并设法在我的网页和它打开的弹出窗口之间传递消息。

的index.html:

var popup;
window.onload = function () {
    console.log("window.onload");
    var btn = document.getElementById('signin');
    btn.addEventListener('click', signin);
};

var pollTimer;

function signin(e) {
    console.log("window.onload - signin");
    popup = window.open("http://www.olcayertas.com/testqa/redirect.html", "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=10, left=700, width=600, height=600");

    pollTimer = window.setInterval(function () {

        if (popup.closed !== false) { // !== is required for compatibility with Opera
            window.clearInterval(pollTimer);
            document.getElementById('signin').style.visibility = 'hidden';
        }

        e.preventDefault();
        popup.postMessage('message', 'http://www.olcayertas.com/testqa/index.html');
        console.log("sendMessage - Message sent!!!");

    }, 500);
}

function receiveMessage(event){
    window.clearInterval(pollTimer);
}

window.addEventListener("message", receiveMessage, false);

popup.html:

console.log("script");
window.onload = first();
var messageEle;

function receiveMessage(e) {
    console.log("receiveMessage");
    messageEle = document.getElementById('message');
    messageEle.innerHTML = "Message Received: " + e.data;
    e.source.postMessage("Mesaj alındı!", e.origin);
}

function first() {
    console.log("first");
    window.addEventListener('message', receiveMessage);
}

我需要的是通过在弹出窗口中设置top.location参数将用户重定向到其他页面,并将e.source参数传递给此页面,以便它还可以向index.html发送消息。由于我不知道e函数的receiveMessage(e)参数是如何通过的,所以我被卡住了。

我该怎么做?

提前致谢。

0 个答案:

没有答案