Reputation: 923
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();
Upvotes: 3
Views: 14582
Reputation: 498
try this for redirect on the same page.
window.location.reload(true)
Upvotes: 0
Reputation: 4431
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();
}
Upvotes: 2
Reputation: 3780
There's a case where navigating to the current location but with a new or changed #anchor
may cause the browser not to reload the page, but instead to scroll to the anchor point. Often this is actually the desired behaviour, since it enables the simple anchor-based linking that we are familiar with.
I've worked around it in at least one application by switching to the reload behaviour if the underlying path didn't change, whilst checking for a hash:
var new_path, old_path;
old_path = window.location.origin + window.location.pathname;
window.location.href = location;
new_path = window.location.origin + window.location.pathname;
if (old_path === new_path && window.location.hash.length > 0) {
window.location.reload();
}
I didn't need to deal with a query-string but window.location.search
provides if necessary.
Upvotes: 0
Reputation: 11869
try something like this:you can simply append the hash to it then reload:
if(window.location.href.indexOf("#tag") == -1){
window.location.href += "#tag";
location.reload(true);
}
Upvotes: 0