Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect AND reload even if same page

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();
like image 942
COMisHARD Avatar asked Nov 26 '25 22:11

COMisHARD


1 Answers

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();
}
like image 108
Charney Kaye Avatar answered Nov 29 '25 13:11

Charney Kaye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!