Return domain depends on user language - javascript

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>

Related

JavaScript redirect users based on browser language (Chrome Extension)

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>

javascript window.location update a get data

I have a small javascript issue; I want to reload page with a selected language option value as a get variable.
if I select EN language, the page reload with &lang=EN,
My problem is that I use concat so I get my_url&lang=EN&lang=FR&lang=SP ...
so when I select first EN then FR I want to get my_url&lang=FR not my_url&lang=EN&lang=FR
I want to replace the lang variable not only to add:
<select onchange="javascript:handleSelect(this)">
<option>DE</option>
<option>EN</option>
<option>FR</option>
<option>SP</option>
<option>NL</option>
<option>HR</option>
<option>PL</option>
<option>CZ</option>
</select>
<script type="text/javascript">
function handleSelect(elm)
{
window.location = window.location.href +"?lang="+elm.value;
}
</script>
Try this:
function handleSelect(elm)
{
var href = window.location.href;
if (href.indexOf("lang") > -1)
{
href = href.replace(/(lang)=\w+((?=[&])|)/, "lang="+elm.value);
}
else
{
var char = (href.indexOf("?") == -1 ? "?" : "&");
href+= char + "lang=" + elm.value;
}
window.location.href = href;
}
It should work with any kind of url keeping the params.
Fiddle. In the fiddle I'm using a div instead of the window.location.
try
window.location = window.location.pathname +"?lang="+elm.value;
You could use the replace function:
window.location = window.location.href.match(/lang=/) ? window.location.replace( /lang=(.*){2}/, 'lang=' + elm.value ) : window.location.href + '?lang=' + elm.value;
Reference: http://www.w3schools.com/jsref/jsref_replace.asp
If ?lang= exists, replace it with the new one.
If not, just add the lang parameter.
edit
I like the window.location.pathname solution from Dave Pile, this should be better than checking and replacing something.
edit2
var loc = 'http://test.de/?foo=bar'; // window.location.href;
var seperator = loc.match(/\?/) ? '&' : '?';
var elm = 'DE';
var url = loc.match(/lang/) ? loc.replace(/lang=(.*){2}/, 'lang' + elm ) : loc + seperator + 'lang=' + elm;
document.getElementById('result').innerHTML = url;
<div id="result"></div>
Look at this snippet, you have to change the loc so it should work, also change var url to window.location and elm to your language element.
It checks if parameters exists and change the seperator from ? to &, than if no lang is set, it will set it or if a lang is set, it will replace it.
function handleSelect(elm)
{
var href = window.location.href;
if (href.indexOf("lang") > -1)
window.location.href = href.replace(/(lang)=\w+((?=[&])|)/, "lang="+elm.value);
else
window.location = window.location.href +"&lang="+elm.value;
}
You could use
var currAddress = window.location.href;
var indexOfLang = currAddress.indexOf('lang=');
var tempAddress = currAddress.substring(indexOfLang, indexOfLang+7);
currAddress = currAddress.replace(tempAddress,'lang='+elm.value);
window.location = currAddress;
The number 7 is the length of substring - lang=EN.

GeoIP Redirect Loop - How to solve it?

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/";
}
})();

javascript split

<script language="javascript">
function frompost()
{
var string=$('#indexsearch').val();
var url=string.split('=');
if(url==""){
var url=string.split('video/');
}
var finalurl='http://watchvideos.tv/watch/'+url[1];
window.location = finalurl;
//$('#srchFrm').attr('action',finalurl);
//document.srchFrm.submit();
}
</script>
I have a problem with this script - it's Ok as long as indexsearch field contains = and fails when it's supposed to work as well - with video/ in the field
Try it like this:
function frompost()
{
var str = $('#indexsearch').val(),
url = str.split(/=|video\//),
finalurl = 'http://watchvideos.tv/watch/'+url[1];
window.location = finalurl;
}

send from javascript to actionscript IE problem

I tried to send a string from an html page (with javascript) to a swf file (action script 2).
i searched in google, found this page.
but the example code (version 1, not 2, you can find it in the source file .zip) didn't work in IE (IE said: object doesn't support this property or method)
where is the problem? (i don't want to use SWFObject.)
the action script :::
//From Evan Mullins # circlecube.com
//View post at http://blog.circlecube.com/2008/02/01/actionscript-javascript-communication/
import flash.external.*;
//Set up Javascript to Actioscript
var methodName:String = "sendTextFromHtml";
var instance:Object = null;
var method:Function = recieveTextFromHtml;
var wasSuccessful:Boolean = ExternalInterface.addCallback(methodName, instance, method);
//Actionscript to Javascript
//ExternalInterface.call("recieveTextFromFlash", _root.theText.text);
function recieveTextFromHtml(t) {
_root.theText.text = t;
}
_root.button.onRelease = function() {
ExternalInterface.call("recieveTextFromFlash", _root.theText.text);
_root.theText.text = "";
}
js:::
function recieveTextFromFlash(Txt) {
document.getElementById('htmlText').value = Txt;
}
and the onclick js code:::
getElementById('flash').sendTextFromHtml(htmlText.value); document.getElementById('htmlText').value = ''
Thank you.
give this javascript code a try?
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
function addToResults(results) { getFlashMovie("flashdemo").addToResults(results); }

Categories