gpt4 book ai didi

javascript - 使用 postmessage 发回消息

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:46:18 28 4
gpt4 key购买 nike

我目前正在制作一个需要在两个域之间发送信息的应用程序(将在加载页面时)。

网站 1:创建 iFrame >向网站 2 发送 Postmessage

window.onload =  function () {

iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "WEBSITE 2");
iframe.style.width = "200px";
iframe.style.height = "200px";
iframe.style.border = "none"; //please do not show the iframe JS.
iframe.id = "lol";
document.body.appendChild(iframe);
document.getElementById("test").innerHTML = "Test!"
window.addEventListener("message", listener, false);

window.setTimeout(sendMessage,100)
}
function sendMessage(e) {
var receiver = document.getElementById('lol').contentWindow;
receiver.postMessage('Hello Treehouse!', 'WEBSITE 2');
}

function listener(event){
if ( event.origin !== "WEBSITE 2" )
return //website isn't ours bro

document.getElementById("test").innerHTML = event.data

}

网站 2从网站 1 > 获取 Postmessage创建 iFrame (?) >向网站 1 (?) 发送 Postmessage

window.onload =  function createiframe() {
window.addEventListener("message", listener, false);
}

function listener(event){
if ( event.origin !== "WEBSITE 1" )
return //website isn't ours bro

document.getElementById("test").innerHTML = event.data

window.setTimeout(createiFrame,1000)
}
function createiFrame() {
iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "WEBSITE 1");
iframe.style.width = "230px";
iframe.style.height = "203px";
iframe.style.border = "none"; //please do not show the iframe JS.
iframe.id = "lol";
document.body.appendChild(iframe);
document.getElementById("test").innerHTML = "Test!"
window.setTimeout(sendMessage,1000)
}
function sendMessage(e) {
var receiver = document.getElementById('lol').contentWindow;
receiver.postMessage('Hello ', 'WEBSITE 1');
console.log('Message sent')
}

iFrame 在网站 2 上创建,然后与网站 1 和网站 2 进行循环,但是从网站 2 发送到网站 1 的 Postmessage 显示在额外的 iFrame 中,是否可以发回消息到在浏览器中打开的网站 1?

显示的示例:

测试! 测试! 你好 测试!

谢谢!

最佳答案

要响应 Event.origin 域,您可以随意处置 messageEvent.source

// Child website:
window.addEventListener("message", evt => {
// if (evt.origin !== "http://example.com") return;

console.log(evt.data) // "Question!"
evt.source.postMessage("Response!", evt.origin);
});

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#The_dispatched_event

source
A reference to the window object that sent the message; you can use this to establish two-way communication between two windows with different origins.

关于javascript - 使用 postmessage 发回消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25162918/

28 4 0