简体   繁体   中英

How to get child window url from parent window using javascript


I'm launching a child window with a window reference name. I want to capture the URL of the child window when it changes each time.

    var winRef;
    var url='http://www.google.com';
    if(winRef == null || winRef.closed) 
    { 
      winRef = window.open(url, "mywindow");
      winRef.focus();
      alert(winRef.location.href); 
    }
    winRef.captureEvents(Event.CHANGE);  
    winRef.onchange=function(){
      alert('change event triggered');
      console.log(winRef.location.href);
    }


I have tried with events LOAD, CHANGE to capture the location change of the window. But the LOAD and CHANGE events gets triggered only once.

I dont want to use setinterval to check for the change in window.location.href as it may lead to performace issues.

Is there any other way around to get the child window URL?

You can't detect the event precisely, but you can do a workaround and check the URL all X milliseconds.

var self = this

var detectsUrl = setInterval(function(){
    var a = winRef.document.createElement('a');
    a.href = winRef.document.URL;
    if (a.hostname == "www.myURL.com") {
        winRef.close();
        clearInterval(detectsUrl);
        self.callback();
    };
}, 1000); // Here we check every seconds

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