0

I'm seeing unexpected behavior when setting window.location.href. My understanding is that the current page will be navigated away from immediately -- effectively ignoring subsequent JavaScript in the containing script. However, this is not what I'm seeing in practice (Firefox, Chrome and mobile Safari). I'm setting window.location.href when I encounter an error condition (e.g. missing some data) and yet the script continues to run and spew a bunch of errors because of said error condition. (This also applies to window.location.assign.)

Example:

function handleError() {
    window.location.href = "https://example.com"
}

function doWork(id) {
    if (!id) {
        handleError();
    }
    var oops = id.split("-");
    // a bunch of errors spill into the console, onerror listeners, etc.
}
pdoherty926
  • 9,895
  • 4
  • 37
  • 68
  • Hm, but why set `window.location.href` instead of just `window.location` itself? That said, any page JS keeps running until the current page gets unloaded, which doesn't happen on window.location _assignment_, but after the browser tries to load the URL and has something to swap in (be that a new page, an error page, or whatever else) – Mike 'Pomax' Kamermans Sep 20 '21 at 22:42
  • It doesn't, so don't count on it - so adjust your control flow accordingly. – CertainPerformance Sep 20 '21 at 22:43
  • Are you calling this doWork() function through a submit button? – Dula Sep 20 '21 at 22:59
  • Why not document.body.innerHTML = ""; throw new Error(""); and immediate catch prior to handleError? If handleError is on the stack of events, but doesn't terminate propagation, everything will fire anyway. – Evil Sep 21 '21 at 04:36

1 Answers1

0

Why not simply add a return after the guard clause?

function handleError() {
    window.location.href = "https://example.com"
}

function doWork(id) {
    if (!id) {
        handleError();
        return 
    }
    var oops = id.split("-");
    // a bunch of errors spill into the console, onerror listeners, etc.
}
Jaybeecave
  • 827
  • 2
  • 8
  • 17
  • I'm doing more/less that, but I was hoping to find a definitive, documented answer describing how this is expected to work. – pdoherty926 Sep 20 '21 at 22:57
  • 1
    Well you've tested the behaviour, which imo is better than documentation, take a look at this post also. https://stackoverflow.com/questions/37521172/is-javascript-location-href-call-asynchronous – Jaybeecave Sep 20 '21 at 22:59