window.onload not working chrome dev console

2k Views Asked by At

window.onload doesn't seem to run the specified function in the chrome console and I can't seem to find anyone with the same problem.

Code:

function preStart() {
    console.log("Hello");
}
window.location = 'https://www.google.com/';
window.onload = preStart;

When ran the window.location successfully runs but "preStart" does not. Any help with this would me much appreciated.

Edit - Ben Hanna says .onload will not activate because the page is changed which is fine but is there a solution to this? (where the function runs after the page changes)

1

There are 1 best solutions below

3
Ben Hanna On

This code will never hit the onload event if you're changing the location to navigate away to another page.

Update: You could do something like this.

function preStart() {
   // You can run a function like this before navigating
   console.log("Hello");
   window.location = 'https://www.google.com/';
   // You can't run a function once you've navigated to Google
   // because you can't execute arbitrary scripts on pages/domains
   // that you don't own.
}

// preStart will be executed when the `onload` event fires
window.onload = preStart;