skip to Main Content

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


  1. On a (mostly) "pure" Chrome (with just a very few extensions, etc), this:

    <script>
      console.log (typeof window.onload === "function");
      window.onload = function() {
        console.log('onload called'); // this *is* triggered on page load
      };
      console.log (typeof window.onload === "function");
    </script>
    

    shows this:

    false
    true
    onload called
    

    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 the window.onload() exists.

    Login or Signup to reply.
  2. document.body.onload is an alias for window.onlaod

    So, the following should output false

    function onload() {
      console.log('does not fire on load');
    }
    console.log(window.onload === document.body.onload)

    Whereas, using window.onload =, the following should output true (and also the console.log in the onload handler

    window.onload = function onload() {
      console.log('does fire on load');
    }
    console.log(window.onload === document.body.onload)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search