The window object does not have the properties attached to it by the page that created it

懵懂的女人 提交于 2019-12-08 01:49:14

问题


I use the window.open(url, target) to open a url in a new tab/window. Before doing that, I set some properties on the newly opened window object with the intention of passing data from this page, the creator of the new window, to the newly created window.

In all browsers except Internet Explorer, the code works fine. The newly created page is able to read back the properties from the global window object representing its window.

However, only in Internet Explorer 11, the window object in the newly created window does not have the properties passed in by the previous page.

Below is example code demonstrating the problem.

Page1.html

<script type="text/javascript">
    function openNewPage(value1, value2)
    {
        var newWindow = window.open('Page2.html', '_blank')

        newWindow.property1 = value1;
        newWindow.property2 = value2;
    }
</script>

Page2.html

<body onload = "bodyLoadHandler()">
    <script type="text/javascript">
        function bodyLoadHandler() {

            // Both of these returned undefined
            // whether referenced explicitly
            // as window.property1 or as 
            // this.property1. I prefer the explicit
            // window.property1 way because of the screwed up
            // this pointer and its ensuing issues in JavaScript.

            // This happens only
            // in IE. The code runs fine in other browsers.
            var property1 = window.property1;
            var property2 = window.property2;
        }
    </script>
</body>

回答1:


Use window.opener, SharedWorker with postMessage or storage event

Page1.html

<script>
  function openNewPage(value1, value2) {
    var newWindow = window.open('Page2.html', '_blank')

    this.property1 = value1;
    this.property2 = value2;
  }
  openNewPage(1, 2)
</script>

Page2.html

<body onload="bodyLoadHandler()">
  <script type="text/javascript">
    function bodyLoadHandler() {
      var property1 = window.opener.property1;
      var property2 = window.opener.property2;
      console.log(property1, property2);
    }
  </script>
</body>

plnkr http://plnkr.co/edit/Gy5FFhvobFoBAbc8UnBY?p=preview

See also How can I load a shared web worker with a user-script?, Can the mechanism that loads the worker in Shared Web Workers be modified?



来源:https://stackoverflow.com/questions/46337968/the-window-object-does-not-have-the-properties-attached-to-it-by-the-page-that-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!