user31782
user31782

Reputation: 7589

Why doesn't onload event work on a tab opened with window.open?

I open a new blank tab. Now from this tab I need to open a website in a new tab. I do this as following. In its console I write:

var wild = window.open("https://css-tricks.com/", "mywin", '');

That works fine. Now I have the access of this new window with wild.document. Now I wish to execute some code on that page after its dom will have been loaded. I use the onload event as:

function foo(){
    var mytext = wild.document.body.textContent;
    alert( mytext );
}
wild.addEventListener("load", foo);

But unfortunately the alert doesn't happen. I also tried putting the event listener in anonymous self calling function as explained in this answer, but that didn't work too. I also tried ondomload event but unfortunately that didn't work too.

Why doesn't onload event work on a tab opened with window.open? And how to get it working properly?

Upvotes: 8

Views: 16531

Answers (5)

gaetanoM
gaetanoM

Reputation: 42044

As described in Detecting the onload event of a window opened with window.open the following demo works fine:

var wild;

window.addEventListener('DOMContentLoaded', function(e) {
  wild = window.open("myLocalStaticPage.html", "mywin", '');
  wild[wild.addEventListener ? 'addEventListener' : 'attachEvent'](
    (wild.attachEvent ? 'on' : '') + 'load', function (e) {
      alert("loaded")
    }, false);
});

// the following handler only used for test purposes
document.addEventListener('click', function(e) {
  try {
    alert(wild);
  } catch(err) {
    alert(err);
  }
}, false);

I added a listener on the source page so that you can test the value of the wild variable simply clicking on the page.

For a static page there is no problem.

But, if you need to open the classic "http://google.com/" page you will see, clicking on the starting page the following errors:

enter image description here

and, from the debugging environment:

enter image description here

What does they mean? When you open the google page, google redirects by itself and this is out of your control.

Why does this happen? To avoid scraping..... just for instance and more.

Is it possible to add such a listener (load)? Yes, but the only way I know is creating a chrome extension, or FF extension or IE..... because the extension api (javascript) offers you the possibility to do this with no pain.

If you are interested in Chrome api you may take a look to manifest and more in detail to a section called "content_scripts" like:

"content_scripts": [{
    "matches":    ["*://*/*"],
    "js":         ["content.js"],
    "run_at": "document_end",
    "all_frames": true
}],

where the "run_at" parameter:

Controls when the files in js are injected. Can be "document_start", "document_end", or "document_idle". Defaults to "document_idle".

Upvotes: 6

Panu Logic
Panu Logic

Reputation: 2263

You wrote: "In its console I write: ....". Does that mean you open it interactively? If so then that window opens. If you then AFTER that add a load-listener to it that will probably do nothing because the DOM has already loaded. Adding an event-handler does not react to events that have already happened.

I struggled with the same problem of wondering why I did not see the onload-event happen when I programmatically open a new tab. What I did differently was log a message on the console. That is a more reliable way of getting information about what is going on. Alert-popups can be prevented for many reasons but console messages should not be.

But I didn't see a message on the console about the new window load-event, even though the window did open properly. It was very confusing and I thought (wrongly) that the load-event simply didn't happen because I saw nothing about it on the console. I thought perhaps because I was loading the same URL in the other tab the content of that was already cached by the browser so it did not have to be "loaded" (from the server) and thus did not cause the onload-event, since it had been already loaded earlier.

But turns out the explanation was simpler. The load-event DID happen, but I did not see a console-message about it because ... I was looking at the console of the OPENER-window/tab! I was NOT looking at the console of the tab that was opened.

Each tab/window has its own debugger (-window). Messages from a tab only show in the console of its own debugger window, not on the consoles of others tabs. You can have multiple debugger-windows open, one per tab. That can get confusing because it is then hard to know which debugger-window belongs to which browser window.

So after opening the same URL in a new tab, I had to focus on that tab and THEN OPEN a NEW debugger-window while looking at that tab. THEN I could see the message about the load-event handler in that new console. It took me some time to figure this out, so hopefully this can help others who wonder why they don't see the onload -event. If the window opens, the event probably does happen, you are just looking at the wrong console.

What caused my confusion? It was probably that we always talk about "THE console". That seems to imply that there is (a single) "the" console. But there can be MULTIPLE consoles, open at the same or different times, showing different messages.

This of course can apply to any other event as well. Just because you don't see a log-entry for it on the console you are looking at, does not necessarily mean it didn't happen.

Upvotes: 0

tsb
tsb

Reputation: 189

window.onload event fires when every document loaded.

var wild=null;

      function load() {
            if(wild !=null)
            {
               alert("load event detected!  :"+wild.location.hostname+wild.location.pathname);
             }
             else
               alert("not yet loaded");
          }
      window.onload = load;

      wild = window.open("https://www.google.co.in/", "mywin", ''); // Security Exception raise due to Cross orgin security enabled google.co.in
     // wild = window.open("https://localhost:5555/test.html", "mywin", ''); //This will  work when same origin policy
     console.log("After Loading ...");

Upvotes: 0

kag359six
kag359six

Reputation: 2253

You're loading an external site, so you should be getting a cross-origin frame error (I did when I tested your code in the Chrome console).When I test it in Firefox, the window object is null. In Safari, the object is undefined.

Even with setTimeout the objects are null or the error is thrown, so if you say it worked using setTimeout I would share that code. You aren't allowed to access the document of another window unless the origin is identical (so the same page). At least that is my understanding.

I would have one script on the first page that opens the other window:

<body>
 <script type="text/javascript">
   window.open('http://www.linktoyourotherpage.com/', 'mywin', '');
 </script>
</body>

And a script for the other page that manipulates the document

<body onload="foo()">
  <script type="text/javascript">
    function foo() {
      var mytext = document.body.textContent;
      alert( mytext );
    }
  </script>
</body>

Upvotes: 1

Lumi Lu
Lumi Lu

Reputation: 3305

Please try this,

function foo() {
    var wild = window.open("http://google.com/", "mywin", '');
    wild.addEventListener("load", function(){
        var mytext = wild.document.body.textContent;
        alert( mytext );        
    });
}

Upvotes: 0

Related Questions