简体   繁体   中英

Not able to fetch the URL / location of the pop-up window

Is there a way to fetch the URL / Location of the pop-up window?

CODE:

<html>
   <head>
   <script>
   function openWin()
   {
      myWindow=window.open('http://www.google.com','','width=200,height=100');
      console.debug(myWindow.location.href);
      console.debug(window.location.href);
   }
   </script>
  </head>

  <body>
    <input type="button" value="Open window" onclick="openWin()" />
  </body>
</html>

The first console prints about:blank

While the second console prints the URL of the current page(ie URL of the above code, it does not print the URL of the pop-up window)

Why isn't the first console printing the location (ie http://www.google.com ) ?

Can anyone help me out with this?

Thanks in advance.

As @Hg3 says, you cannot access location.href for myWindow . window.open returns an empty DOMWindow .

However, you can overwrite window.open and maintain a simple array of all the windows you have opened.

//override window.open
var windows = [];
window._open = window.open;
window.open = function(url, name, params){
    windows.push(name, url);
    return window._open(url, name, params)
}
//function return href by name
function hrefByName(name) {
    var index=(windows.indexOf(name));
    return (index>-1) ? windows[index+1] : 'undefined';
}

//modified openWin function
function openWin(url, name) {
    var params='width=200,height=100';
    window.open(url, name, params);
    //test, ouput current url and the windows array
    console.log(hrefByName(name));
    console.log(windows);
}

test markup :

<input type="button" value="google" onclick="openWin('http://google.com', 'google')" />
<input type="button" value="bing" onclick="openWin('http://bing.com', 'bing')" />
<input type="button" value="stackoverflow" onclick="openWin('http://stackoverflow.com', 'stackoverflow')" />

Of course, I guess you have a setup with dynamically generated URL's - just build random names or pass an unique number as name.

Because browser security prevents you from getting the URL from any window that's not on the same domain as your script. So, if your code was running on example.com, you'd only be able to get the URL of any window that was also on example.com.

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