如何使用javascript从子窗口返回数据到父窗口,而不使用sessionStorage

How to return data from child to parent window using javascript without using sessionStorage

本文关键字:窗口 sessionStorage 数据 javascript 何使用 返回      更新时间:2023-09-26

我想让我的父窗口有打开子窗口的按钮。子窗口应该有一个输入文本框和一个按钮(名为Copy)。无论我在子窗口文本框中输入什么文本,然后点击复制按钮,子窗口应该关闭,输入的名称应该出现在父窗口。
我正在尝试下面的方法,但无法理解如何检索父上的输入值。

p>Click the button to create a window and then display the entered name on parent window.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    var myWindow = window.open("", "MsgWindow", "width=200,height=200");
    myWindow.document.write("<p>This window's name is: " + myWindow.name + "</p>");
    myWindow.document.write("<br/>");
    myWindow.document.write("<input type='text' id='txtId' />");
    myWindow.document.write("<input type='button' value='Copy'/>");
    var x = localStorage.getItem(Name);
            }
    myWindow.opener.document.write("Landed to prent");
}

最初我的方法是不正确的,我试图从父窗口访问子窗口文本框,而我应该做反向。下面是工作代码:

父窗口

<!DOCTYPE html>
<html>
<body>
<input type="text" id="txtName" readonly="readonly" />
<button onclick="myFunction()">Open</button>
<script>
function myFunction() {
var win = window.open("ChildWin.htm", "_blank", "width=200,height=200");
}
</script>
</body>
</html>

子窗口

<!DOCTYPE html>
<html>
<body>
<p>Enter name </p>  
<input type="text" id="txtbx" />
<br/><br/>
<button onclick="copyFunc()">Copy</button>
<script>
function copyFunc() {
   if (window.opener != null && !window.opener.closed) {
            var txtName = window.opener.document.getElementById("txtName");
            txtName.value = document.getElementById("txtbx").value;
        }
    window.close();
}
</script>
</body>
</html>