简体   繁体   中英

JavaScript - get content of popup window

I'm trying to read the contents of a document that is loaded via window.open :

<!DOCTYPE html>
<html>
    <body>
        <button onclick="openWin()">Open "newWindow" and read its content</button>

        <script>
            var myWindow;

            function openWin() {
                myWindow = window.open("http://www.google.com/", 
                    "myWindow", "width=400, height=400");

                myWindow.opener.document.write(myWindow.document.body.innerHTML);
            }
        </script>
    </body>
</html>

How can I read the contents of a document after loading it via window.open ? I've tried this with setTimeout function but it didn't work. This is working :

myWindow.opener.document.write("Done!!");

You can't do that if the document you're opening in a new window is from a different domain (for example, yoursite.com opening a new window that loads google.com ). This is a security restriction known as same-origin policy . More information: Same-origin policy (MDN) .

Hope this clarifies things a bit for you.

It can sometimes pay to try a few things.

My isp recently added a time stamp to their login form which prevented me using my local post form with preloaded name and password.

I looked for ways of downloading their login page and copying the time stamp to my local form. This would have been easy with almost any script except JavaScript.

Frames failed as they use the X-Frame-Option set to 'Deny'.

To my surprise I was able to copy the time stamp to my local form from a pop-up window containing their form. This now works well. The only slight imperfection was having to use a fixed timeout rather than detecting pop-up page fully loaded.

Here is the disguised full solution:

<html>
<head>
<base href='https://www.isp.net'>
<title>isp</title>
</head>
<body onload="w=window.open('login'); setTimeout('document.f.time-stamp.value=w.document.forms[0].time-stamp.value; document.f.submit(); w.close()',2000)">
<form name=f action='login' method=post>
<input type=hidden name='user-name' value='my-name'>
<input type=hidden name='password' value='my-password'>
<input type=hidden name='time-stamp' value=''>
</form>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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