3

I have very simple code but it does not trigger any of the load events - window opens page loads but events are not triggered.

var ref = window.open('http://localhost:3000/#/login','_blank','location=no'); 

ref.addEventListener('loadstart', function(event) {
    log.info('in loadstart ');
});

ref.addEventListener('loadstop', function(event){
    log.info('in loadstop ');
});

https://plnkr.co/edit/ubEk8UN6SGXkYV7PgFZZ?p=preview - Plunkr code to see what is the problem and suggest solution.

Simple 10-15 lines of code but ate all my weekend to figure out what went wrong

Amol Ghotankar
  • 1,558
  • 4
  • 21
  • 40

1 Answers1

2

From the docs for window.open:

Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

So try wrapping your event listeners in a window.setTimeout

function openInApp(){
    var ref = window.open('http://google.com/','_blank','location=no'); 
    window.setTimeout(function(){
      ref.addEventListener('loadstart', function(event) {
          console.log('in loadstart ');
          alert('start: ' + event.url);
      });
    }, 1000);
}

Assuming you have no same-origin problems, that should now work.

horyd
  • 1,334
  • 10
  • 12
  • thanks but it does not work tried it - https://plnkr.co/edit/ubEk8UN6SGXkYV7PgFZZ?p=preview - throws permission denied – Amol Ghotankar Jul 29 '16 at 19:00
  • 1
    That's because of the same-origin policy, from the [docs](https://developer.mozilla.org/en-US/docs/Web/API/Window/open): "A reference to the newly created window. If the call failed, it will be null. The reference can be used to access properties and methods of the new window provided it complies with Same origin policy security requirements." Try testing it locally, where I'm assuming you are calling the code from localhost, and opening the new window at localhost too – horyd Jul 29 '16 at 21:29
  • I changed origin to same domain, just opened plunkr itself using window.open but still same issues https://plnkr.co/edit/ubEk8UN6SGXkYV7PgFZZ?p=preview – Amol Ghotankar Aug 10 '16 at 16:58
  • You'll still see the error in the console and it shows you why, the request comes from "https://run.plnkr.co", and you are trying to access a frame with origin "https://plnkr.co". Try this experiment on your localhost if you can :) – horyd Aug 10 '16 at 17:29