Javascript redirect loop - javascript

I'm doing some old url redirection with javascript.
My old urls in Google index are something like domain.com/#!about/c3g8. My new url for about us page is like domain.com/#about since I have change my site to one paged site.
My old site has had 4 pages without including root page. Each page has had a unique ending. They are -
/c3g8
/cjg9
/cee5
/cce3
The redirections cannot be done in .htaccess because they contain hash(#) character in them. Therefore, I have no choice but javascript. My current redirect js code is as follow
if(document.URL.indexOf(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/)) {
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/,'');
window.location = url_new;
break;
}
All inner pages redirect properly but home page became a redirect loop and until I press Esc key twice.
I have this $('a[href^=#]').bind("click", function(event){.... code in my js too. How can I redirect without leading to a redirect loop?
Thanks in advance!

You're mixing regex matching and indexOf. The if condition is always going to evaluate to -1 which is truthy, so the the redirect always happens.
Use regex.test() instead, and use the g modifier to tell it to replace all instances...
if(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/.test(document.URL)) {
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/g,'');
window.location = url_new;
break;
}

Try this:
var url_new = document.URL.replace(/!|\/c3g8|\/cjg9|\/cee5|\/cce3/,'');
if(document.URL !== url_new){
window.location = url_new;
}

Related

Trying to redirect a page depending on what is in the URL with Javascript

I am looking to redirect a webpage if the URL is a certain URL. I can only edit the header script (which is in every webpage), but I only need to redirect the one page, so I chose to go this route.
For example, if the URL is /blog I want it to redirect to /blog-home. The problem I am having is that /blog/blogpost is also redirecting to /blog-home. I only want the one page (/blog) to redirect.
Right now I have:
if(document.URL.indexOf("/blog") >= 0){
window.stop();
window.location.href = "/blog-home";
}
With this code, /blog redirects fine to /blog-home.
You can use endsWith to make sure that '/blog' is the last part of the URL.
if(document.URL.endsWith("/blog")){
window.stop();
window.location.href = "/blog-home";
}
You can check it using a regex, consider also that it might be an additional trailing / after the url, it might end for example with /blog or /blog/:
if(document.URL.match(/\/blog\/?$/) !== null){
window.stop();
window.location.href = "/blog-home";
}
Split the URL on / characters and use an equality test on the last part.
var split = document.URL.split("/");
if (split[split.length-1] == "blog") {
window.stop();
window.location.href = "/blog-home";
}
window.location gives you the current url path
window.location.origin gives you the base path thus you do the following :
if(window.location === window.location.origin +"/blog" ) {
window.stop();
window.location.href = "/blog-home"
}

Attempting window.location or window.location.href redirect which is causing a loop

I'm attempting to use javascript to determine if the user is using a certain language and if they're not using english then for the page to load a different page BUT with the params of which I've grabbed from the url.
I have been able to load the page with the params but I keep falling into a loop reloading the page, even after skimming through the countless other examples, such as: this or this.
function locateUserLanguage() {
var languageValue = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)).split('-');
var url = window.location.href.split('?');
var baseUrl = url[0];
var urlParams = url[1];
if (languageValue[0] === 'en') {
console.log('no redirect needed, stay here.');
} else {
// I tried to set location into a variable but also wasn't working.
// var newURL = window.location.href.replace(window.location.href, 'https://www.mysite.dog/?' + urlParams);
window.location.href = 'https://www.mysite.dog/?' + urlParams
}
} locateUserLanguage();
I've attempted to place a return true; as well as return false; but neither stop the loop.
I've tried window.location.replace(); and setting the window.location.href straight to what I need, but it's continuing to loop.
There is a possibility that the script in which this function is written is executed in both of your pages (english and non-english) on load. So, as soon as the page is loaded, locateUserLanguage function is executed in both english and non-english website causing the infinite loop.
You need to put a check before you call locateUserLanguage function.
Suppose english website has url = "www.myside.com" and non-english website has url "www.myside.aus". So the condition needs to be
if (window.location.host === "www.myside.com") { locateUserLanguage() }
This will make sure that locateUserLanguage is called only in english website.
Or other apporach can be to load this script only in english website which will avoid the usage of conditional statement.
Hope it helps. Revert for any doubts.

Redirect on mobile *only* if specific anchor is present? (my current code redirects but ignores conditional)

On mobile, I'd to redirect to the subdomain store.website.com only if the url is website.com/#store. If the url is not that, I'd to do redirect to the subdomain m.website.com. The following always redirects to the store subdomain if the url is simply website.com, store anchor or not:
var url = "http://website.com/#store";
var hash = url.substring(url.indexOf("#")+1);
if (hash == "store") {
window.location.replace("http://store.website.com");
} else if (window.location.href == "http://website.com") {
window.location.replace("http://m.website.com");
}
I get the same result if I replace the 'else if' statement with a simple 'else' statement, or if I drop the else statement altogether. It always redirects to store.website.com in any case. Is there a slight adjustment I should make here to get the code to work as intended, or perhaps an altogether different method that should do the trick? Thanks
That's because the variable url is always set to http://website.com/#store
var url = "http://website.com/#store";
Change this to:
var url = window.location.href;
window.location.href will retrieve the current address. Then the hash should be correct.
or learn from this code using location.hash instead:
var hash = window.location.hash;
if (hash == "#store")
{
window.location.replace("http://store.website.com");
}
else if (window.location.hostname == "website.com")
{
window.location.replace("http://m.website.com");
}
Fist we use window.location.hash to get the hash part and match it. If it doesn't pass check the host name. don't use the full url. If someone enters using HTTPS instead of HTTP it won't pass. So use window.location.hostname to match the domain name instead.
Be aware this code is going to affect not just mobile devices unless you check if a mobile device is been used otherwise desktop users are going to be redirected to m.website.com too.
In the code above, you are always updating the location because hash is always equal to 'store'. You never get to the second if.
Maybe you should read the hash from window.location.href instead of the variable url.
Your URL is always a fixed String. You should check against window.location.href instead.
var url = window.location.href;
var hash = url.substring(url.indexOf("#")+1);
if (hash == "store") {
window.location.replace("http://store.website.com");
} else if (url == "http://website.com") {
window.location.replace("http://m.website.com");
}
This small script would you :
var hash = window.location.hash
hash && hash === "#store" ? window.location.replace("http://store.website.com") : window.location.replace("http://m.website.com")

Browser does not replace an include file by its including file

I am an absolute beginner in JS.
1) What I'm trying to do:
My web pages are composed of an index.php which is the same for all the files of a directory and one of a set of content.inc, like this: index.php?open=content.inc. This is done by a PHP snippet in the index.php and works well.
However, Google indexes all the content.inc files. The user's browser then displays the content.inc without the framing index.php. This I want to avoid. I therefore add a modest script at the beginning of each content.inc (which I would convert into a function once it runs) to tell the browser that instead of displaying the content.inc, it should display index.php?open=content.inc.
2) My unworkable solution:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
if (filename.indexOf("index.php") = -1)
{ var frame_name = "index.php?open="+filename;
window.location.replace(frame_name);
};
The browser (Firefox 60) ignores this; it displays content.inc. (I also have versions of this script which get the browser into an endless loop.)
What is wrong here? Please help!
PS: Please be assured that I have done extensive web search on this problem and found many pages of complaints about location.replace getting into an infinite loop; but none matches my situation. However, I gratefully accept a helpful link as an answer.
For starters, you have an error in this line:
if (filename.indexOf("index.php") = -1)
That's an assignment and will always evaluate to true, you need to use == or === (which should be more performant).
The guilty line is on your test case (see JP de la Torre answer). And to improve, here's a snippet to demo how to analyze the url with a regular expression :
function redirect(url) {
if(url && url.indexOf('.inc') >= 0) {
return url.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
return url;
}
let urls = [
window.location.href,
'http://google.fr',
'http://example.com/index.php?open=wazaa',
'http://example.com/wazza.inc'
];
urls.forEach(url => {
console.log(url, ' => ', redirect(url));
});
The regexp will capture any text between a / and .inc. You can use it then as replacement value with the $1.
And applied to your case, you simply need :
if(window.location.href.indexOf('.inc') >= 0) {
window.location.href = window.location.href.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
You can also use .htaccess server side to redirect request for .inc files on your index.php if mod_rewrite is enabled.
The solution to the problem of including an INC file called separately is the one proposed by Bertrand in his second code snippet above. It presupposes (correctly) that the inc extension is omitted in the replacement.
As I reported above, Firefox may get into an endless loop if it opens a PHP file directly, i.e. without involving the local host (with its php module).

Redirecting to a page in a domain using greasemonkey

Basically i want to access site http://www.domain.com
what i want to do is that upon logging in, it should directly take me to
http://www.domain.com/access.aspx
But I have very little knowledge of java script, so far i made it but its continuely redirecting in in a loop like
http://www.domain.com/access.aspx/access.aspx/access.aspx/access.aspx/access.aspx/access.aspx
Why is it redirecting again and again, i just want it to redirect it once.
This is my existing code
var loc = window.location.href; var a = loc +"access.aspx"; window.open(a);
I am using a separate script for logging in, and separate for redirecting.
You don't seem to be checking if redirection is required so I suspect that your redirection logic is being applied even when you're already on the page you want to be on. Consider one of the following:
Add an exclude rule which will cause your script to be not be executed on the access.aspx page.
#exclude http://www.domain.com/access.aspx.
Check before you redirect, something like
var loc = window.location.href;
if(loc != 'http://www.domain.com/access.aspx'){
var a = loc +"access.aspx";
window.open(a);
}

Categories

Resources