我陷入了一个问题,我必须从弹出窗口重定向到另一个域并向其发布消息。 这是场景:-
如果我打开新的弹出窗口并发布消息,则能够接收消息,但在重定向的情况下却不能。这是我的代码:
function redirect(formData,popup) {
//popup=window ref object
popup.location.href="http://domain_two.com"
popup.postMessage(JSON.stringify(formData),
"http://domain_two.com");
}
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if (event.origin !== "http://domain_one.com")
return;
let data=event.data;
//....
}
答案 0 :(得分:1)
问题代码的一个问题是,在.postMessage()
上设置了新的.location.href
之后立即调用popup
,而不必等待{{1 }},
load
要获得预期的结果,您可以从原始window
('index.html')控制该过程。每个 popup.location.href="http://domain_two.com"
popup.postMessage(JSON.stringify(formData),
"http://domain_two.com");
都设置为唯一值。在window
处提交window.name
时,可以将生成的<form>
转换为"http://domain_one.com"
并传输到FormData
,然后传输到ArrayBuffer
({{ 1}})index.html
设置为popup
。在a.html
location.href
的{{1}}事件中,"http://domain_two.com"
到load
的{{1}}。然后将b.html
传递到.postMessage()
,其中name
获取最初在window
提交的index.html
。
(FormData
检查可能需要在下面的代码中进行调整。该代码已在plnkr上进行了测试,在该代码中,跨域消息传递的模拟不是1:1,尽管应该提供一种实现方法要求)。
index.html(.postMessage()
)
b.html
a.html(FormData
,b.html
)
origin
b.html(opener
,<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
// open `popup`
const popup = window.open('a.html');
// create random values to assign to `name` at `a.html` and `b.html`
const [firstName, lastName] = [...Array(2)].map(_ => new Uint32Array(16));
[firstName, lastName].forEach(buffer => window.crypto.getRandomValues(buffer));
const [decoder, encoder] = [new TextDecoder(), new TextEncoder()];
const [first, last] = [firstName, lastName].map(buffer => decoder.decode(buffer));
// set `name` of `popup` (`a.html`) to `first`
popup.name = first;
let data;
window.addEventListener("message", e => {
// check `name` of `source`
if (e.source.name === first) {
console.log(e.source.name);
// store `formData`
data = decoder.decode(e.data);
console.log(e, JSON.parse(decoder.decode(e.data)));
// set `name` of `popup` to `last`
popup.name = last;
// redirect `popup` to `b.html`
popup.location.href = "b.html";
}
// check if `name` of `source` (`b.html`) is `last`
if (e.source.name === last) {
// encode the stored `formData`
let curr = encoder.encode(data);
console.log(e.source.name, e.data);
// transfer `formData` to `b.html`
e.source.postMessage(curr.buffer, e.source.location.href, [curr.buffer]);
// data = void 0;
}
})
</script>
</body>
</html>
)
popup
答案 1 :(得分:0)
您可以使用查询字符串参数将表单数据传递到"http://domain_two.com"
,然后在第二个域的location.href
事件中解析load
的查询字符串
popup.location.href = `http://domain_two.com?${new URLSearchParams(formData.entries()).toString()}`