【问题标题】:window.opener undefined in javascript popup after redirect重定向后,javascript 弹出窗口中的 window.opener 未定义
【发布时间】:2022-03-02 23:05:20
【问题描述】:

我的网站使用 window.open() 显示付款对话框时遇到问题。

弹出窗口中的页面重定向到重定向回结果页面的不同域。在结果页面上,我尝试在window.opener 上设置一个属性来表示付款正常。

这适用于某些用户。但是,其他用户会收到一条错误消息,指出 window.opener 未定义。

可以使用这些简单的页面重新创建问题:

index.html (打开弹出窗口)

<!DOCTYPE html>
<html lang="en">
<body>
    <input type="button" value="Popup" onclick="openPaymentWindow();" />

    <div id="result" style="background-color: silver;"/>

    <script type="text/javascript">
        function openPaymentWindow() {
            win = window.open('popup.html', 'popup');            
        }
    </script>    
</body>
</html>

popup.html (重定向到不同的域)

<!DOCTYPE html>
<html>
<body onload="document.forms[0].submit();">
    <form action="http://[other_domain]/payment.html">
    </form>
</body>
</html>

payment.html (重定向回原来的域)

<!DOCTYPE html>
<html>
<body onload="document.forms[0].submit();">
    <form action="http://[original_domain]/result.html">
    </form>    
</body>
</html>

result.html (在索引页上设置一个属性)

<!DOCTYPE html>
<html>
<body>
    <input type="button" value="Call top" onclick="callTop();" />

    <script type="text/javascript">
        function callTop() {
            // Here, window.opener (and top.opener) is undefined for some users
            window.opener.document.getElementById('result').style.background = 'green';
        }
    </script>  
</body>
</html>

由于并非所有用户都受到影响,我猜测这与一些安全设置有关。但我根本不知道在哪里可以找到它们 - 或者如何在我自己的电脑上复制错误。

【问题讨论】:

  • 我认为如果两个页面不在同一个域下,window.opener 会失败。您可以检查以下替代解决方案:stackoverflow.com/questions/6876830/…
  • window.opener 是从主窗口打开的文档的属性。如果弹出窗口本身加载了一个新文档,则它不会从主窗口加载,并且不再具有所述属性。即使域相同。
  • 请通过给定的链接http://stackoverflow.com/questions/7120534/window-opener-is-null-after-redirect
  • 我知道这应该是不可能的。但是当我自己和数百名其他用户测试它时,这仍然有效。这有点奇怪。
  • @NeerajDubey 在您所指的链接中,提问者显然通过在 PayPal 页面之前添加他自己的页面来解决它。这正是我正在做的... (stackoverflow.com/questions/7120534/…)

标签: javascript html


【解决方案1】:

有一种方法可以实现您想要的,但它可能不是很干净。 所以index.htmlresult.html 在同一个域上,index.html 中的脚本包含对弹出窗口对象的引用。这意味着如果您在result.html 中的window 对象上设置一些属性,您将能够在index.html 中的win 变量上读取该属性。唯一的问题是您不知道具体何时设置该属性,因此您必须使用 setInterval 来检查它。

Index.html

function openPaymentWindow() {
    var win = window.open('popup.html', 'popup');

    var successPoller = setInterval(function() {
        try {
            if(typeof win.PAYMENT_SUCESS !== 'undefined' && win.PAYMENT_SUCESS) {
                document.getElementById('result').style.background = 'green';
                clearInterval(successPoller);
            }
        }
        catch (error) {
            // handle error
        }
    }, 500);
}

result.html

 function callTop() {
      window.PAYMENT_SUCCESS = true;  
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多