简体   繁体   English

无法获取window.open()的innerHTML

[英]Cannot get the innerHTML of a window.open()

HI I have some troubles when reading the text inside a window that I open with window.open() I hope you guys can help me, what I need is my parent window will read the <div> html value of my child window that the parent window called, I have this code but It doesn't works 嗨,我在用window.open()打开的窗口中阅读文本时遇到了一些麻烦,希望你们能为我提供帮助,我需要的是父窗口将读取子窗口的<div> html值,父窗口调用,我有此代码,但它不起作用

Parent Window 父窗口

<button onclick="buttonset()">Click me</button>
<script>
var myWindow ;
 function buttonset () {
         myWindow = window.open("pag1.html", "myWindow", "width=200,height=100");
    //myWindow.document.write("<div id='hola'>This is 'myWindow'</div>");
    alert(myWindow.document.getElementById("result").innerHTML);
    myWindow.close();
}
</script>

And this is my Child Window ( pag1.html ) code 这是我的子窗口( pag1.html )代码

    <body>

<div id="result">1</div>
<div id="msj">Correcto</div>

</body>

and when I run it says and just open new window but it doesn't show the message 当我运行时,它说,只是打开新窗口,但不显示消息

Cannot read property 'innerHTML' of null 无法读取null的属性“ innerHTML”

window.open() is asynchronous, you need to wait for the document to load. window.open()是异步的,您需要等待文档加载。

function buttonset () {
    var myWindow = window.open("pag1.html", "myWindow", "width=200,height=100");
    myWindow.onload = function() {
        alert(myWindow.document.getElementById("result").innerHTML);
        myWindow.close();
    };
}

Use load event of opened window 使用打开的window load事件

myWindow.onload = function() {
  // do stuff
}

The page is still loading. 该页面仍在加载中。 So you can attach an inline onload function on the body tag of pag1.html 因此,您可以在pag1.html的body标签上附加一个内联onload函数

pag1.html pag1.html

<body onload='doIt()'>   
  <div id="result">1</div>
  <div id="msj">Correcto</div>
  <script>
     function doIt() {
       alert(document.getElementById("result").innerHTML);
    }
   </script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM