【问题标题】:How to return value from child window to parent window using window.open in Javascript?如何使用 Javascript 中的 window.open 将值从子窗口返回到父窗口?
【发布时间】:2014-05-13 03:23:35
【问题描述】:

我有一个父窗口,我正在使用 window.open 打开一个子窗口,如下所示。我想从子窗口中获取一个布尔值,在此基础上我将在父窗口中执行我的任务。

function openChildWin() 
{   
    var childWin = window.open("childWin.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no,addressbar=no); 
    if (childWin)
    {
        //some logic
    }
    else
    {
        //some logic
    }
} 

**childWin.html**



 <!DOCTYPE html>
    <html lang="en">
      <head>

        <script type="text/javascript">

            function OKClicked()
            {
                //return true; //I want to return true here
                            window.close(); //Close this child window  
            }

        </script>

      </head>
      <body>
        <button type="button" id="OKButton" onclick="OKClicked()">Click ME</button>
      </body>
     </html>

当按钮被点击时,我想从这里返回 true。但这一切都不适合我。我这里缺少语法吗?

【问题讨论】:

  • 你不能尝试使用cookies吗??
  • @AmarnathRShenoy - 在这里使用 cookie 有什么乐趣。我只是从子窗口中捕获一个布尔变量的简单要求,以便我可以在父窗口上做进一步的工作。

标签: javascript jquery html dom


【解决方案1】:

你可以这样做:

在父母中:

function openChildWin() {   
    var childWin = window.open("childWin.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no,addressbar=no"); 
}
function setValue(val1) {
   // do your logic here
}

在弹出窗口中:

function OKClicked() {
    window.opener.setValue(true);
}

【讨论】:

  • @Ashan shah - 这不起作用。 window.open 语句下面的语句会在子窗口打开后立即执行。
  • 检查已修改。您可以使用设置值来实现您的逻辑
  • @Ashan Shah - 是的,就是现在。我已经实现了这一点。感谢您的回答。
  • 有效解决方案
【解决方案2】:

使用下面的代码并将 test 替换为您的元素 ID。

var parentDoc = window.opener.document;
parentDoc.getElementById("test").value = document.getElementById("test").value;

【讨论】:

  • 您好 Abhay,我尝试了您的代码,但无法正常工作。我收到这样的错误 Cannot read properties of null (reading 'document')
【解决方案3】:

你可以使用window.opener.postMessage():

在父母中:

window.onmessage = function(m) {

  if(m.data) {
    // logic if 'OK' in child clicked
  }

}

在孩子中:

function OKClicked() {
  window.opener.postMessage(true, '*');
  window.close(); 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多