Redirect AND reload even if same page

11,122

This method uses jQuery but the principle is, read the attribute we're about to update, and if no change would be incurred, reload instead of setting the attribute.

// current value of the location href attribute
let currentURL = $(location).attr("href");

// value we intend to change it to
let redirectURL = "https://yellow.brick.road/"

if (currentURL !== redirectURL) {
    $(location).attr("href", redirectURL);
} else {
    location.reload();
}
Share:
11,122
COMisHARD
Author by

COMisHARD

Updated on June 26, 2022

Comments

  • COMisHARD
    COMisHARD about 2 years

    What is the easiest/best way to ensure that a page redirects to another page and to ensure that the page refreshes even if the destination page is the current page.

    I have some function on page www.website.com that redirects users to the URL www.website.com/#tag. I then have an onload even that checks the url for #tag and does something if that tag exists.

    However, the program breaks if the user was already on page www.website.com/#tag. What is the best way to ensure that the user is always redirected to www.website.com/#tag through this function, as though they were arriving to the website freshly form some other page (lets say www.google.com).

    I'm currently redirecting with:

    window.location.replace(www.website.com/#tag);
    

    I'm aware there are a million ways to reload the page. I've been using:

    location.reload();