Skip to content
Advertisement

Redirect to another page JavaScript with condition

i have the following code which works just fine in redirecting.

window.onload = function() {
  setTimeout(
    function() {
window.location.replace('https://google.com/');}, 3000);
}

what i need is that the code checks the previous page (history) and if it was, for example, https://gmail.com, go to https://google.com and if it was something else go to, for example, https://facebook.com.

Advertisement

Answer

document.referrer will tell you what page the user just came from .. There is also window.history but it does not provide URLs .. Just whether or not the user can go page back or page forward

Something like this should do what you are asking.

console.log(document.referrer);  // View this to view what JS "sees" as actual referrer.

 window.onload = function () {

    if (document.referrer == 'https://gmail.com') {
        setTimeout(window.location.replace('https://google.com/'), 3000);
    } else {
        setTimeout(window.location.replace('https://facebook.com/'), 3000);
    }

}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement