Context: I’m trying to programmatically detect (via an injected script) if an arbitrary page (not coded by me) has a window.onload
function set (via window.onload=foo
, not addEventListener
).
I thought that I could simply check if typeof window.onload === "function"
, but that is true for this case:
<script>
function onload() {
console.log('onload called'); // this is *not* triggered on page load
}
typeof window.onload === "function"; // is true
window.onload === onload; // is`true`
window.hasOwnProperty("onload"); // is`true`
</script>
And yet that function is not automatically called during page load. I’ve tested in latest versions of Chrome and Firefox.
I thought that would be ~equivalent to this:
<script>
window.onload = function() {
console.log('onload called'); // this *is* triggered on page load
};
</script>
But it seems that’s not the case. The browser is seems to have a setter (or something like that) which is triggered when explicitly assigning window.onload
, versus the case where a global variable is implicitly accessible via the window object.
How can I robustly detect (via an injected script) whether an arbitrary page has an actual window.onload
set (one that is triggered on page load, I mean), and not just e.g. a global function called onload
?
2
Answers
On a (mostly) "pure" Chrome (with just a very few extensions, etc), this:
shows this:
The
"onload called"
appears after the whole script has been run and the page has already been loaded, which is OK. And the comparison works well for me, detecting when thewindow.onload()
exists.document.body.onload
is an alias forwindow.onlaod
So, the following should output
false
Whereas, using
window.onload =
, the following should outputtrue
(and also the console.log in theonload
handler