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?
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:
and, from the debugging environment:
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With