如何使用Javascript和PostMessage将变量传递到新窗口

时间:2019-05-21 21:25:43

标签: javascript html

我的主页上有一个按钮,它会打开一个新窗口FindAPark.html。我正在尝试将变量传递给没有GET的HTML页面。

我已经在Homepage.js中尝试过此操作:

function buttonClick() {
    var newWindow = window.open('FindAPark.html');
    newWindow.my_special_setting = "Hello World";
}

然后在我的FindAPark.js中:

window.my_special_setting;
console.log(window.my_special_setting);

控制台说它是“未定义”,而不是显示“ Hello World”。可能是什么问题,什么可以解决?

编辑:现在它告诉我“未捕获的DOMException:阻止了具有原点“ null”的框架访问跨域框架。”我还没有在域上托管这些文件,但是我拥有两个HTML文件。我该怎么办?

3 个答案:

答案 0 :(得分:2)

使用window.postmessage

在打开的窗口中

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {

 console.log(event)

  // ...
}

现在从父窗口调度事件

newwindow.postMessage("The user is 'bob' and the password is 'secret'",
                  "https://secure.example.net");

答案 1 :(得分:1)

像这样使用localStorage:

function buttonClick() {
     localStorage.setItem("mySepcialSetting", "Hello World");
     window.location.href = "FindApark.html";
 }

然后您可以按以下方式访问它:

var mySpecialSetting = localStorage.getItem("mySepcialSetting");
console.log(mySpcialSetting);

答案 2 :(得分:0)

假设您打开的窗口来自同一安全域,则可以像在问题中一样传递变量,但是您应该等待新窗口完全加载。

let newWindow = window.open('FindAPark.html');
newWindow.addEventListener('load', function(){
  newWindow.my_special_setting = "Hello World";
}, false);

另一种选择是从打开新窗口的窗口中读取变量...与上述相同的安全策略同样适用。

let my_special_setting = window.opener.my_special_setting;