0

I have a scenario where I wanted to check if the browser can go back to previous page via history.back(). For this purpose, I followed this answer https://stackoverflow.com/a/24056766/2948305, the code for which I am pasting below

function historyBackWFallback(fallbackUrl) {
    fallbackUrl = fallbackUrl || '/';
    var prevPage = window.location.href;

    window.history.go(-1);

    setTimeout(function(){ 
        if (window.location.href == prevPage) {
            window.location.href = fallbackUrl; 
        }
    }, 500);
}

When window.history.go(-1) is executed, what will window.location.href resolve to ? Will it resolve current page or the previous page(history -1) .

console.log(window.location.href);

prints the current page URL. Does this mean, until the previous page is completely loaded, window.location.href will resolve to the current page.

Or until this function is fully executed(with/without the setTimeout), it will always point to current page URL.

To be specific, when exactly will window.location.href get updated?

techriften
  • 421
  • 2
  • 16

1 Answers1

0

When a user changes location of the tab, a new window will be created for that session.

That code doesn't even get executed because window changes completely and that is also being lost.

I believe this code can prove what I said.

```

const foo = 'foo';
const oldWindow = window;

window.history.go(-1);
window = oldWindow;

foo // ReferenceError

```

window doesn't point to previous window. Using setTimeout doesn't change the result.

Also tried this but seems like no change

`

const foo = 'foo';
const oldWin = Object.create(window);

window.history.go(-1)

setTimeout(() => {
    window = oldWin;
}, 500)

`

Ertan Kara
  • 308
  • 3
  • 12