gpt4 book ai didi

javascript - 我如何绕过 window.opener 跨域安全

转载 作者:IT王子 更新时间:2023-10-29 03:14:44 25 4
gpt4 key购买 nike

我刚刚发现如果新 URL 是跨域的,在 IE 中,window.opener 在通过 window.open 打开的窗口中不可用。 How do I detect window opener in IE

如果窗口在我的域中启动,离开它,然后返回到我的域,就会发生这种情况。我正在尝试在弹出窗口中进行社交注册(facebook、google 等)。当它完成时,它应该关闭新窗口并重定向打开器。

我知道 Soundcloud 正在实现这一目标,但我不知道如何实现。我看到 URL 从他们的更改为 Facebook,然后关闭。

从第 3 方重定向回我的网站后,我运行此命令:

var data = {
type : 'complete',
destination : '<?= $destination; ?>'
};
if ( window.opener ) {
window.opener.postMessage( JSON.stringify( data ), '*' );
window.close();
}
else {
alert( "Unable to find window" );
}

它在 IE 中发出警报,即使该窗口最初是我的域,然后重定向到 FB,然后又重定向回我。我想可能是因为我打开我的网站并立即从 PHP 重定向,这可能是一个问题。然而,即使当我打开我的网站时,window.location.href = 'facebookssite.com' 返回时它仍然提示。

注意

iframe 中的社交注册不适用于 google、FB 等。我相信他们出于安全原因不允许他们。

最佳答案

反之亦然。从主(打开)窗口跟踪子弹出窗口的状态,您可以轻松知道子窗口何时导航回您的域,因此您可以再次与它“交谈”。但是不要自己关闭子窗口。让opener窗口从子窗口获取结果,然后关闭它。

例如,ma​​in.html:

<!DOCTYPE html>
<head>
<title>main</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
window.addEventListener("message", function(ev) {
if (ev.data.message === "deliverResult") {
alert("result: " + ev.data.result);
ev.source.close();
}
});

function Go() {
var child = window.open("child.html", "_blank", "height=200,width=200");

var leftDomain = false;
var interval = setInterval(function() {
try {
if (child.document.domain === document.domain) {
if (leftDomain && child.document.readyState === "complete") {
// we're here when the child window returned to our domain
clearInterval(interval);
alert("returned: " + child.document.URL);
child.postMessage({ message: "requestResult" }, "*");
}
}
else {
// this code should never be reached,
// as the x-site security check throws
// but just in case
leftDomain = true;
}
}
catch(e) {
// we're here when the child window has been navigated away or closed
if (child.closed) {
clearInterval(interval);
alert("closed");
return;
}
// navigated to another domain
leftDomain = true;
}
}, 500);
}
</script>
</head>
<body>
<button onclick="Go()">Go</button>
</body>

child.html:

<!DOCTYPE html>
<head>
<title>child</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
window.addEventListener("message", function(ev) {
if (ev.data.message === "requestResult") {
// ev.source is the opener
ev.source.postMessage({ message: "deliverResult", result: true }, "*");
}
});
</script>
</head>
<body>
<a href="http://www.example.com">Go to example.com</a>
Then click the browser Back button when ready.
</body>

使用 IE10 测试。

关于javascript - 我如何绕过 window.opener 跨域安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18625733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com