使用来自不同窗口的变量

Using a variable from a different window

本文关键字:窗口 变量      更新时间:2023-09-26

我想在JavaScript中打开一个新窗口,并从打开器窗口显示一些数据。根据我读到的一些东西,我做了这个:

MainWindow.html

<html>
<head>
<script>
function OpenNewWindow()
{
    this.MainWindowData = 123123;
    document.write(this.MainWindowData);
    var wnd = window.open("NewWindow.html");
    wnd.NewWindowData = 787878;
}
</script>
</head>
<body>
<input type="button" value="Open Window" onclick="OpenNewWindow()">
</body>
</html>

NewWindow.html:

<html>
<head>
<script>
function ShowData()
{
    document.write("NewWindowData: " + this.NewWindowData + "<br />");
    document.write("MainWindowData: " + window.opener.MainWindowData);
}
</script>
</head>
<body>
<input type="button" value="Show Data" onclick="ShowData()">
</body>
</html>


问题是这两个变量都没有定义。
提前感谢您的帮助

问题不在于你正在创建的变量,而是当你在初始渲染期间以外的任何时间调用它时,document.write会删除窗口的内容,因此在创建它们之后会删除你正在创建的变量。所以你不想在初始渲染后使用它。

如果您将document.write调用更改为(例如)document.getElementById('someid').innerHTML = ...;或使用document.createElement,您将获得更成功的结果。

这是你的页面,只是改变document.write使用document.createElement,这使他们工作。

主窗口:Live Copy | Source

<html>
<head>
<script>
function OpenNewWindow()
{
    this.MainWindowData = 123123;
    var wnd = window.open("http://jsbin.com/uvocos/1");
    wnd.NewWindowData = 787878;
}
</script>
</head>
<body>
<input type="button" value="Open Window" onclick="OpenNewWindow()">
</body>
</html>

弹出窗口:Live Copy |来源

<html>
<head>
<script>
function ShowData()
{
    display("NewWindowData: " + this.NewWindowData);
    display("MainWindowData: " + window.opener.MainWindowData);
}
function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p)
}
</script>
</head>
<body>
<input type="button" value="Show Data" onclick="ShowData()">
</body>
</html>

createElement是在display函数我添加到弹出。

单独:我可能会使用window而不是this来创建变量。this实际上会 window的方式,你调用你的函数,所以它工作,但有其他的方式调用函数,它不会工作,使用window.foo = ...;会。

最后:我不确定你在打开它(你的NewWindowData)后立即把变量放在弹出窗口将可靠地工作,尽管它在上面(对我来说)。通常,而不是那样,我有弹出窗口拉的数据从打开器(您的MainWindowData变量)和/或通过查询字符串传递数据到弹出窗口。

您的尝试实际上非常接近,但使用this.可能会导致问题。

在父窗口,使用:

var newWindowVariable = 'Something';

在新窗口中使用:

var myVariable = window.opener.newWindowVariable;

这可能是完成你想做的事情的最简单的方法。

使用LocalStorage

 /* Page A */
  window.localStorage.setItem("NewWindowData ", "787878");
  /* Page B */
  var stringValue = window.localStorage.getItem("NewWindowData");

然后你可以把它转换成int,或者任何你想转换成的类型

如果你想从父窗口获取值,你可以在弹出窗口中使用。

 window.opener.document.getElementById('idOfelement').value
示例