I want to redirect my users to different languages/subfolders based on their IP address. To do this I use the JavaScript GeoIP API from MaxMind.
The problem: The english speaking people should stay at mydomain.com and not go to mydomain.com/en/. But when I redirect to mydomain.com the GeoIP script runs again which creates an infinite loop.
Here is my code (in index.html for mydomain.com):
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
if(country == "FR")
{
window.location = "http://mydomain.com/fr/"
}
else
{
window.location = "http://mydomain.com/";
}
</script>
In other posts I read about setting a cookie, but I wasn't able to do it in a way that solves the problem (and it would still create a loop when the user doesn't accept cookies, on mobile for example).
Another solution could be to redirect to mydomain.com/en/ and delete the /en/ folder in the URL via htaccess, but I wasn't able to get this done either.
An example of how I want it to work would be waze.com (it seems like they have the english version in the /en/ folder, but delete it from the URL).
So if anybody is able to help, I would be very grateful. Thanks a lot!
EDIT: I solved the problem myself. It's very simple: Just use the root directory for the english page and change function to "else {null;}" :-)
Your problem is not with geoip but with your code.
Try this:
var country = geoip_country_code();
var currentLocation = String(window.location);
//if geoip is equal FR and window.location is different "http://mydomain.com/fr/"
if(country === "FR" && currentLocation.indexOf("http://mydomain.com/fr/")!==0)
{
window.location = "http://mydomain.com/fr/"
}
//if geoip is different FR and window.location is equal "http://mydomain.com/fr/"
else if(currentLocation.indexOf("http://mydomain.com/fr/")===0)
{
window.location = "http://mydomain.com/";
}
To detect using multiple languages simply edit the following variables:
var defaultsLang are the languages that are supported by the main root (site.com/)
var languages languages supported by sub-pages (site.com/fr/, site.com/es/, etc.)
See code (not tested):
(function(){
var defaultsLang = ["en-us","en"];
var languages = {
"fr": true, //enable french pages
"pt": false, //tmp disable portuguese pages
"es": true //enable spanish pages
};
var country = geoip_country_code().toLowerCase(),
currentLocation = String(window.location),
detectCurrent = function(){
var a = currentLocation.replace(/^(http|https)[:]\/\//, "");
var b = a.split("\/");
b = b[1].toLowerCase();
a = null;
return b.length<5 && (/^[a-z\-]+$/).test(b) ? b : false;
};
var currentLang = detectCurrent();
defaultsLang = "|"+defaultsLang.join("|")+"|";
if(currentLang!==country && typeof languages[country] !=="undefined" && languages[country]!==false){
window.location = "http://mydomain.com/" + country + "/";
} else if(
defaultsLang.indexOf("|" + currentLang + "|")===-1 && //current page is not the same as default languague(s)
defaultsLang.indexOf("|" + country + "|")!==-1 && //geoip is in the list of default language(s)
currentLang!==false
){
window.location = "http://mydomain.com/";
}
})();
Related
The task is to write a script in javaScript/jQuery(other technologies also possible) to return the domain with a .pl extension if the user language browser is set to Polish. Otherwise, the script should return .eu domain extension
I tried to use jQuery, but I cannot find an appropriate solution.
<script type="text/javascript">
$(document).ready(function () {
var userLang = navigator.language || navigator.userLanguage;
var path = window.location.path;
var extension = window.location.hostname;
var ext = extension.split(".");
var x = ext[2];
if (userLang.startsWith("pl")) {
x = "pl";
window.location.href = extension + x + path;
else {
x = "eu"
window.location.href = extension + x + path;
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I expect www.domain.pl/file1/files2/file3.html(it is possible to have many directories by the link) if navigator.language = "pl" else href = www.domain.eu/path
Thank you in advance for any contributions.
I found the solution, maybe will be useful for someone.
Furthermore, it is possible to use the ternary operator instead of the if..else statement, to make code shorter and more readable.
Enjoy - thanks for contribution.
Greetings to the community.
<script type="text/javascript">
function myFunction(){
var userLang = navigator.language || navigator.userLanguage;
if (userLang.startsWith("pl")) {
var url = window.location.toString();
window.location = url.replace(".eu", ".pl");}
else {
url = window.location.toString();
window.location = url.replace(".pl", ".eu");
}
};
</script>
I'm trying to show different tab on chrome extension using JavaScript, but it's not working.
In this case, it redirects only to it.example.com and when I change my browser language to English or French, thats script redirects only to it.example.com.
Can someone show me how I can redirect based on the browser language?
I want to do different redirections for it and fr. Other languages should be redirected to English.
newtab.html
<head>
<title>Loading...</title>
<script type="text/javascript" src="js/newtab.js"></script>
</head>
newtab.js
if (window.navigator.language === 'it') {
window.location.href = 'https://it.example.com/';
}
if (window.navigator.language === 'fr') {
window.location.href = 'https://fr.example.com/';
}
else window.location.href = 'https://example.com/';
(function redirectToSpecificPage() {
var base = 'https://$1example.com/',
replaceLng = function(toReplace, replaceWith) {
return base.replace(toReplace, replaceWith);
},
lngPages = {
en: replaceLng(''),
it: replaceLng('it.'),
fr: replaceLng('fr.'),
es: replaceLng('es.'),
}
window.location.href = lngPages[window.navigator.language.toLowerCase().slice(0,2)] || lngPages.base;
})();
Assuming you changed all your != for === like suggested in comments...
I changed the browser language in Italian that still redirect me to example.com
It looks like none of your condition evaluated to true.
Be aware that the language identification codes often include a country "variant"... Like, for example, my browser language actually is en-US instead of just en. Here a list that looks complete, which you should have a look.
Additionnally, I suggest you to use the switch statement, instead of if/else for this particular case.
var language = window.navigator.language;
var languageFistTwo = language.substr(0,1); // To only keep the first 2 characters.
switch (languageFistTwo) {
case "en":
window.location.href = 'https://example.com/';
break;
case "it":
window.location.href = 'https://it.example.com/';
break;
case "fr":
window.location.href = 'https://fr.example.com/';
break;
case "es":
window.location.href = 'https://es.example.com/';
break;
default:
window.location.href = 'https://example.com/';
}
I found the solution. but this works only on chrome extension do not work on firefox :/
_locales/en/messages.json
"example_default_search": {
"message": "example.com",
"description": ""
}
_locales/it/messages.json
"example_default_search": {
"message": "it.example.com",
"description": ""
}
newtab.js
function localizeHtmlPage()
{
//Localize by replacing __MSG_***__ meta tags
var objects = document.getElementsByTagName('html');
for (var j = 0; j < objects.length; j++)
{
var obj = objects[j];
var valStrH = obj.innerHTML.toString();
var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function(match, v1)
{
return v1 ? chrome.i18n.getMessage(v1) : "";
});
if(valNewH != valStrH)
{
obj.innerHTML = valNewH;
}
}
}
localizeHtmlPage();
newtab.html
<head>
<title>Loading...</title>
<meta http-equiv="refresh" content="0;URL='https://__MSG_example_default_search__/'" />
<script type="text/javascript" src="js/newtab.js"></script>
</head>
i'm using JavaScript to make some small customization in default SharePoint 2013 issue tracker. When user submit an issue (default SharePoint function presave) JavaScript should redirect document to new URL. Everything works fine in Firefox in IE but from unknown reason redirection doesn't work in Chrome.
I'm used location, replace.href, assign etc - result the same - chrome just save the form without redirection. Can you give me any hint why it doesn't work?
I'm using SP 2013 online (and i don't have access to SP designer)
<script src="/sites/SiteAssets/Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/sites/SiteAssets/Scripts/sessvars.js"></script>
<script language="javascript" type="text/javascript" src="/sites/_layouts/15/clientpeoplepicker.js"></script>
<script type="text/javascript">
// Here i have small function to get email from sharepoint peoplePicker field
function getEmailFromPeoplePicker(title) {
var ppDiv = $("div[title='" + title + "']")[0];
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv.id];
var userList = peoplePicker.GetAllUserInfo();
var userInfo = userList[0];
var userEmail;
if(userInfo != null)
{
userEmail = userInfo.EntityData.Email;
}
return userEmail;
}
function PreSaveAction(){
// check if there is attachment
if ($('#onetidIOFile').get(0).files.length === 0) {
} else {
OkAttach() //attach file to form
}
//get email from field
var RequestApprover = getEmailFromPeoplePicker('Assigned To');
//create link for redirection with email at the end (ill use it latter for sending emails)
var targetUrl = '/sites/SitePages/RedirectDestination.aspx' + '#' + RequestAprover;
//window.location.href = targetUrl;
//location.replace(targetUrl);
//window.location.assign(targetUrl);
// window.top.location.href = targetUrl;
window.location.assign(targetUrl); // <---------- redirection which works in IE and FireFox but not in Chrome
//window.location.href = targetUrl;
//window.location.assign(targetUrl);
//window.parent.location.href(targetUrl);
//setTimeout(function(){location.href = targetUrl},500);
return true;
}
</script>
I believe you should have "return false;" (instead of return true;) at the end of your PreSaveAction function implementation. Looks like in Chrome redirect takes more time then in other browsers, so Sharepoint continues usual form flow (e.g. continues to PreSaveItem etc.)
I am using a JavaScript "Count down then redirect" script for my website. I want to use something like http referer in the script attached below:
<script>
<!--
/*
Count down then redirect script
By JavaScript Kit (http://javascriptkit.com)
*/
//change below target URL to your own
var targetURL="www.domain.com";
//change the second to start counting down from
var countdownfrom=20;
var currentsecond = document.redirect.redirect2.value =
countdownfrom + 1;
function countredirect() {
if (currentsecond != 1) {
currentsecond -= 1;
document.redirect.redirect2.value = currentsecond
} else {
window.location = targetURL;
return;
}
setTimeout(countredirect, 1000);
}
countredirect();
//-->
</script>
I want the script to work like:
If some one arrive from www.twitter.com, they will be redirected to www.domain.com/twitter.html after the count down.
If some one arrive from www.facebook.com, they will be redirected to www.domain.com/facebook.html after the count down.
If some one arrive from www.youtube.com, they will be redirected to www.domain.com/youtube.html after the count down.
I want to redirect 15-20 URL. Please help !! How can I do it ??
Simple:
var targetURL = /www\.xxx\.com/i.test(document.referrer) ?
"www.domain-for-xxx.com" : "www.domain-for-yyy.com";
Multiple Referrers:
var targetUrl = "http://defaulturl.com/";
if (/www\.xxx\.com/i.test(document.referrer)) {
targetUrl = "http://www.domain-for-xxx.com/";
} else if (/www\.yyy\.com/i.test(document.referrer)) {
targetUrl = "http://www.domain-for-yyy.com/";
}
...
I manage a website for an organization that has separate chapter sites. There is a membership signup form that is on the main website that each chapter links to. On the form there is a dropdown box that allows a person to choose the chapter they want to join. What I would like to do is have each chapter website use a specific link to the form that will preselect their chapter from the dropdown box.
After searching the web, I found that I will probably need to use a Javascript function to utilize a Query String. With all my searching, I still can't figure out the exact code to use. The page is a basic HTML page...no php and it is hosted on a linux server.
Any help would be greatly appreciated.
If you format your url like this:
www.myorg.com?chapter=1
You could add this script to your html head:
function getparam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
function loadform()
{
var list = document.getElementById("mychapterdropdown");
var chapter = getparam("chapter");
if (chapter>=0 && chapter < list.options.length)
{
list.selectedIndex = chapter;
}
}
The in your html body tag:
<body onload="loadform();" >
Could probably add more validation checks but that's the general idea.
It sounds like what you are looking for are GET or POST requests. For instance, if your user selects "Chapter A" from your form and hits select, you can allow redirects from another site (for instance http://www.yoursite.com/form.html?chapter=A) to allow Chapter A to be preselected. In Javascript this is done by
var chapter="";
var queryString = location.search.substring(1);
if ( queryString.length > 0 ) {
var getdata = queryString.split("&");
var keyvalues;
for(var i=0; i < getdata.length; i++){
keyvalues = getdata.split("=");
}
} else {
chapter = "Not Found";
}
document.getElementById( "ChapterID").value = keyvalues['chapter'];
This is untested, so don't hold me to it :).
maybe something using parse_url
$params = parse_url()
$query = $params['query'];
$query_pairs = explode('&',$query);
$key_val = array();
foreach($query_pairs as $key => $val){
$key_val[$key] = $val;
}
http://www.php.net/manual/en/function.parse-url.php
You would probably have to use an dynamic ajax content. Use the following javascript to read the querystring, then load the html file in that div using this javascript.