Problem with document.location.href - javascript

I am new to Javascript and Web development and I have a question regarding the document.location.href.
I am using a cookie for storing the language the user prefers and then load the english or the swedish version depending on the language.
The default language in the beginning is the same as the browser's language, and my index.jsp is the swedish one. The first time everything works fine. The problem is when the cookie exists already. The basic code is:
if (language!=null && language!=""){
if (language=="en-US" || language=="en-us")
document.location.href = "en/index.jsp";
}
else{
//Explorer
if (navigator.userLanguage)
language = navigator.userLanguage;
//other browsers
else
language = (navigator.language) ? navigator.language : navigator.userLanguage;
if (language!=null && language!=""){
setCookie('language', language, 365, '/', 'onCheck');
if (language=="en-US" || language=="en-us")
document.location.href = "en/index.jsp";
else if(language=="sv")
document.location.href="index.jsp";
}
}
When the cookie exists we enter the first "if", and there, if the language is swedish it opens the default blabla/index.jsp page. When the language is set to engish it should open the blabla/en/index.jsp but instead it opens the blabla/en/en/index.jsp which of course is wrong.
Does anyone know what I am doing wrong??
Thanks

Add a slash in the beginning, ie:
document.location.href = "/en/index.jsp";
Currently, you are redirecting using a relative path when you want to redirect using an absolute path. Slashes in the beginning always means absolute.
If you've ever used a Unix machine, you'd know that /etc/123/abc is a path that goes from the root, whereas etc/123/abc/ would be a relative path, building on the current directory. The same is true here.

If this is a commercial site and you care about your Google ranking then you should be cautious about using JavaScript redirects.
Search engine crawlers cannot follow these kinds of redirects. It would be better to process it on the server side and perform a true 301 redirect.
Also you should give some way to manually change this by clicking a button in your UI.
This code doesn't make any sense to me:
//Explorer
if (navigator.userLanguage)
language = navigator.userLanguage;
//other browsers
else
language = (navigator.language) ? navigator.language : navigator.userLanguage;
It seems to check if .userLanguage is populated and if it isnt it checks if .language is populated and if that isn't it uses .userLanguage which by this point has already been deemed as undefined.
I would refactor the code something like this:
if (IsCookieSet()) {
if (IsCookieLanguage("en-US")) {
document.location.href = "en/index.jsp";
}
}
else {
language = navigator.userLanguage ? navigator.userLanguage : navigator.language;
if (!IsCookieSet()){
setCookie('language', language, 365, '/', 'onCheck');
if (IsCookieLanguage("en-US")) {
document.location.href = "en/index.jsp";
}
else if(IsCookieLanguage("sv"))
{
document.location.href="index.jsp";
}
}
}
function IsCookieSet()
{
return language!=null && language!="";
}
function IsCookieLanguage(lang)
{
return language.toLowerCase() == lang.toLowerCase();
}
Well that code is a bit cleaner but it still doesn't make much sense because you haven't included all of your code - ie the bit that retrieves the cookie.

It seems you are already on a page in blabla/en/ then. Check that out.

Related

How to allow language change even after detecting country?

So, I have developed a simple script:
function checkForCountry () {
let lang = ''
let loc = window.location.href
switch (code) {
case 'DE':
case 'AT':
lang = '/de/'
break
case 'IT':
lang = '/it/'
break
default:
lang = ''
}
if (loc.indexOf('.com') !== -1 && loc.indexOf(`${lang}`) !== -1) {
return
}
return window.location.replace('example.com' + language)
}
}
})
}
checkForCountry ())
Ok, so it is really simple. It will read the code it gets via API call (didn't put API call) and depending on the code it will know which language to assign.
This part:
if (loc.indexOf('.com') !== -1 && loc.indexOf(`${lang}`) !== -1) {
return
}
is to stop pilling up the lang and to break the cycle.
Now, when I want to change the language manually, in the website it reverts to the language I came. So, for example I have Italian version of site, and when user comes to the site he is automatically navigated to Italian version, ie.: example.com/it. If he tries to change the language to English, he always gets navigated back to Italian version.
How can I make this? I need to have this script, but when user navigates to English version of site for example: example.com, I want him to stay there.
Thank you.

Open window if user is not on a specified domain

I'm currently using this JavaScript popup confirmation redirect:
var answer = confirm("If you are joining us through site other than" +
"website.net, .com or .info please hit OK otherwise hit cancel!");
if(answer)
window.open('http://website.net', '_blank');
else
alert("You need to know that it will not work for you well if you don't")
I would really like a way to use this popup only if user was not on targeted page.
I think this is what you're trying to do:
var domains = ["aseanlegacy.net", "aseanlegacy.com", "aseanlegacy.info"];
if(domains.indexOf(document.location.hostname) == -1)
window.open("http://aseanlegacy.net", "_blank");
If the user is at a domain not in domains (tested with document.location.hostname), window.open will be called.
Here's a JSFiddle.
Per your request to only open the window once per session, here is the code modified to include a cookie:
var domains = ["aseanlegacy.net", "aseanlegacy.com", "aseanlegacy.info"];
if(domains.indexOf(document.location.hostname) == -1 && document.cookie.indexOf("opened=1") == -1)
{
document.cookie = "opened=1";
window.open("http://aseanlegacy.net", "_blank");
}
Here's the updated JSFiddle.
It is quite unclear what you want to achieve, but you can grab the "referrer" using:
document.referrer
Which will tell you where the user came from. I base this on your quote:
If you are joining us through site other than aseanlegacy.net...
I have absolute no idea why this would matter, and why you tell the user the website will not work well otherwise.
If you want to get the current location, simply use:
document.location.href
which returns the full URL, or
document.location.hostname
which returns the hostname.

Is there a better way to do this? (recursively resolving HTML unicode entities)

I'm parsing an untrusted URI, but its URI-hood must be honored. I'm trying to protect against javascript: links, but I feel like I need to recurse on it, since you could have:
javascriptjavascript::
and after stripping out all instances of javascript: get back our old friend javascript: once again.
My other concern is analogously-nested unicode entities. For instance, we could have:
"j&#X41vascript:alert('pwnt')"
...but we could also have:
"j&#&#X5841vascript:alert('pwnt')"
...though I seem to be doing it wrong (whereas a successful attacker obviously won't.)
function resolveEntities(uri) {
var s = document.createElement('span')
, nestTally = uri.match(/&/) ? 0 : 1
, limitReached = false;
s.innerHTML = uri;
while (s.textContent.match(/&/)) {
s.innerHTML = s.textContent;
if(nestTally++ >= 5) {
limitReached = true;
break;
}
}
return encodeURI(s.textContent);
}
Didn't you already ask almost the same question before? Anyway, my suggestion remains the same: use a proper HTML sanitizer.
The particular sanitizer I linked to strips javascript: URLs automatically, but you can also set it up to allow only certain whitelisted URL schemes like Thomas suggests. As he notes, this is a good idea, since it's much safer to only allow schemes like http and https which you know to be safe.
(In particular, whether a given obscure URL scheme is safe or not may depend not only on the user's browser, but also on their OS and on what third-party software they may have installed — a lot of programs like to register themselves as handlers for their own URL schemes.)
Rather than specifying what you want to blacklist (e.g. javascript: URIs), it's better to specify what you want to whitelist (e.g. http and https only). What about something like this:
function sanitizeUri(uri) {
if (!uri.match(/^https?:\/\//)) {
uri = "http://" + uri;
}
return uri;
}

Re-Direct with document.url.match

My goal is to redirect my website to (/2012/index.php)
ONLY IF the user goes to ( http://www.neonblackmag.com )
ELSE IF
the user goes to ( http://neonblackmag.com.s73231.gridserver.com ) they will not be re-directed... ( this way i can still work on my website and view it from this url ( the temp url )
I have tried the following script and variations, i have been unsuccessful in getting this to work thus far....
<script language="javascript">
if (document.URL.match("http://www.neonblackmag.com/")); {
location.replace("http://www.neonblackmag.com/2012"); }
</script>
This should work:
<script type="text/javascript">
if(location.href.match(/www.neonblackmag.com/)){
location.replace("http://www.neonblackmag.com/2012");
}
</script>
You should use regular expression as an argument of match (if you're not using https you can drop match for http://...
In your solution the semicolon after if should be removed - and I think that's it, mine is using location.href instead of document.URL.
You can also match subfolders using location.href.match(/www.neonblackmag.com\/subfolder/) etc
Cheers
G.
document.url doesn't appear to be settable, afaict. You probably want window.location
<script type="text/javascript">
if (window.location.hostname === "www.neonblackmag.com") {
window.location.pathname = '/2012';
}
</script>
(Don't use language="javascript". It's deprecated.)
Anyone at any time can disable JavaScript and continue viewing your site. There are better ways to do this, mostly on the server side.
To directly answer your questions, this code will do what you want. Here's a fiddle for it.
var the_url = window.location.href;
document.write(the_url);
// This is our pretend URL
// Remove this next line in production
var the_url = 'http://www.neonblackmag.com/';
if (the_url.indexOf('http://www.neonblackmag.com/') !== -1)
window.location.href = 'http://www.neonblackmag.com/2012/index.php';
else
alert('Welcome');
As I said, this can be easily bypassed. It'd be enough to stop a person who can check email and do basic Google searches.
On the server side is where you really have power. In your PHP code you can limit requests to only coming from your IP, or only any other variable factor, and no one can get in. If you don't like the request, send them somewhere else instead of giving them the page.
header('Location: /2012/index.php'); // PHP code for a redirect
There are plenty of other ways to do it, but this is one of the simpler. Others include, redirecting the entire domain, or creating a test sub domain and only allow requests to that.

Changing browser windows with window.location in javascript

I have a web site that is in two languages, English and French. now i do not know java-script, I created a code for showing different pictures using javascript depending on which language u want to use.
So if you are on the www.my-site.com/en/ you will see En_pic_ pictures same goes for the opposite.
/*These are the Popup images for the English and French portal */
var url1 = 'http://www.my-site.com/fr/';
var url2 = 'http://www.my-site.com/en/';
MagnifImage.setup(
if (window.location = 'url2'){
"En_pic_1", "/images/1.png","",
"En_pic_2", "/img/content/tracking_instructions/2.png", "",
"En_pic_3", "/img/content/tracking_instructions/3.png", "",
"En_pic_4", "/img/content/tracking_instructions/4.png", "",
}else{
"Fr_pic_1", "/img/content/tracking_instructions/1_fr.png", "",
"Fr_pic_2", "/images/mon-compte.png","",
"Fr_pic_3", "/img/content/tracking_instructions/3_fr.png","",
"Fr_pic_4", "/img/content/tracking_instructions/4_fr.png",""
}
);
Everything works but if I am on the other language page I get an alert box saying there is no Fr_pic_1 or En_pic_1.(depending on the current page I am in) The code I found to accomplish this as follows:
if( !(objRef.trigElem=document.getElementById( idParts[0] )) )
alert("There is no element with the ID:'"+idParts[0]+"'\n\nCase must match exactly\n\nElements must be located ABOVE the script initialisation.");
else
{
if(objRef.trigElem.parentNode && objRef.trigElem.parentNode.tagName=='A')
objRef.trigElem=objRef.trigElem.parentNode;
objRef.classId=idParts[1] || "MagnifImage" ;
objRef.imgObj=new Image();
objRef.imgObj.imgIndex=i;
objRef.imgObj.hasLoaded=0;
its a code I found at http://scripterlative.com?magnifimage
Please help....
You need to fix multiple things:
You must use == or === for comparison. A single = is assignment, not comparison.
You must compare to the variable name url2, not a quoted string 'url2'.
You must fix the way you pass the alternate parameters to your function MagnifImage.setup().
I switched to using window.location.href because window.location is an object and I find it better to use the actual attribute of that object you want rather than rely on an implicit conversion.
Change your code to this:
/*These are the Popup images for the English and French portal */
var url1 = 'http://www.my-site.com/fr/';
var url2 = 'http://www.my-site.com/en/';
if (window.location.href == url2) {
MagnifImage.setup("En_pic_1", "/images/1.png","",
"En_pic_2", "/img/content/tracking_instructions/2.png", "",
"En_pic_3", "/img/content/tracking_instructions/3.png", "",
"En_pic_4", "/img/content/tracking_instructions/4.png", "");
} else {
MagnifImage.setup("Fr_pic_1", "/img/content/tracking_instructions/1_fr.png", "",
"Fr_pic_2", "/images/mon-compte.png","",
"Fr_pic_3", "/img/content/tracking_instructions/3_fr.png","",
"Fr_pic_4", "/img/content/tracking_instructions/4_fr.png","");
}
Your code was likely causing many errors and thus not executing at all. You should learn how to look for javascript errors. Every browser has an error console that will show you javascript parsing or executing errors. Many browsers now have a built-in debugger than has a console in it that will also show you such information and allow you to see the exact source line causing the error. I use Chrome which has a built-in debugger which will do this. Firefox has a free add-on called Firebug that will do this.

Categories