Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't onload event work on a tab opend 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. So,

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

like image 337
user31782 Avatar asked Jul 29 '16 11:07

user31782


1 Answers

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".

like image 93
gaetanoM Avatar answered Oct 05 '22 07:10

gaetanoM