How to allow language change even after detecting country? - javascript

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.

Related

Why window.history.pushState updates my content but not the URL

I want to be able to switch the language on my client-only React app without page reload. I was able to achieve that, but my url is not changing as it was before.
I have 2 languages - French - /fr, English - /en
This is the URL language method I tried with window.history.pushState
function generateUrlSwitch(lang) {
const location = window.location.pathname;
if (location.length > 3) {
const actualPath = location.substr(4, location.length);
const url = `/${lang}/${actualPath}`;
return window.history.pushState(null, null, url);
} else {
return '/' + lang;
}
}
Current Behaviour:
Content update to chosen language without reload - url stays the same, but I can see the parameter is switching in milliseconds between en/fr and also when I console.log both options are in console.
Expected Behaviour:
Content updated based on chosen language without page reload + url update based on chosen language
Language Switcher is just calling the function:
href={generateUrlSwitch('en')}
href={generateUrlSwitch('fr')}
What am I doing wrong ?

Pattern matching never terminates

I have this javascript for pattern matching. When I open the HTML file and the scripts run, it never ends. The page loads forever. The logs inside the if and else never print out. I am unable to find the problem.
var link="https://www.google.co.uk/search?source=hp&ei=EUtVWuX5JpGRkwWW_py4Cg&q=testing+for+schools&oq=testing&gs_l=psy-ab.1.1.0i131k1j0l9.7269.8065.0.9955.7.7.0.0.0.0.175.755.4j3.7.0....0...1.1.64.psy-ab..0.7.754...0i3k1.0.TglIEkPkeIU";
var pattern = "(https:\\/\\/)(.*\\.)*(google.co.uk)(\\/.*)*(\\/)*";
if(link.search(pattern) == 0)
{
console.log("inside if");
console.log("Match");
}
else
{
console.log("inside else");
console.log("Not Match");
}
EDIT:
I need a RegEx that represents almost any URL starts with https. The only thing that is variable is the domain name, e.g. google.co.uk. I thought my RegEx was perfect but it could not handle this case.
EDIT2:
The logic for the patter I need is: (any-sub-domain.)*(domain-name)(/something)* (/)*
EDIT3:
Sorry the previous edit corrected now. It was wrong because I did not put it in code.
Instead of using a regex to parse the whole URL, I suggest first using the URL object of JavaScript to extract the relevant parts of the URL. Then you can check attributes of the URL such as hostname and protocol using if:
var link = "https://www.google.co.uk/search?source=hp&ei=EUtVWuX5JpGRkwWW_py4Cg&q=testing+for+schools&oq=testing&gs_l=psy-ab.1.1.0i131k1j0l9.7269.8065.0.9955.7.7.0.0.0.0.175.755.4j3.7.0....0...1.1.64.psy-ab..0.7.754...0i3k1.0.TglIEkPkeIU";
var urlObject = new URL(link);
console.log(urlObject.hostname); // "www.google.co.uk"
console.log(urlObject.protocol); // "https:"
if (urlObject.protocol === "https:") {
if (urlObject.hostname.endsWith('google.co.uk')) {
console.log("this page is on Google UK");
} else {
console.log("this page is on some other HTTPS web site");
}
} else {
console.log("this page is not secured by HTTPS");
}

Javascript - Create own bookmark website with prompt?

I just started to learn Javascript and basically I wanted to create a bookmark on Google Chrome where I basically just want to do:
"www.hello" + i + ".com"
so basically open up a prompt where I myself enter what I want "i" to be and then it should then add up so etc:
i = world
end: www.helloworld.com (Automatic open it up).
I assume this is beginner level but I have just learned and I just know how to open up a prompt at this moment.
javascript:(()=>{let i=prompt("Enter "i" for website ,")
and now I dont know how to continue to make it add for a website.
That's very simple..
Just copy paste the code below and save it in your bookmark and give it a try..
javascript:var websiteName = prompt("Enter \"i\" for website..");var url = "http://www.hello"+websiteName+".com";window.location.href = url;
Note that javascript: at the front will be automatically removed when you copy and paste the code manually in url bar. So save it once in bookmark and use.
You can pretty much use whatever you would normally put between <script> tags on your page. So this:
var i = prompt("Enter website:", "");
if (i == null || i == "") {
//add whatever action you would like when user cancels
} else {
window.open("https://www."+ i +".com");
}
Becomes this (minus the comments):
javascript: var i = prompt("Enter website:", ""); if (i == null || i == "") { } else { window.open("https://www."+ i +".com"); }

Relative URLs for POSTS with Javascript/Jquery - concise

I have a c# MVC project with some jQuery driven interface. Some actions are performed with a $.post().
Sometimes, the site would be deployed to the root of the domain (e.g. www.mydomain.com) and sometimes it would be deployed in a folder (e.g. www.mydomain.com/Super).
I want to make posts to controllers relative to the location of the view that the user is accessing. However, the user may access the view both with and without an ending /, so i need to cater for both scenarios to avoid weird requests to www.mydomain.com/Super//somecontroller.
Currently, i have a function that does the following:
function getlocation() {
var loc = "";
if (location.pathname != "/") {
loc = (window.location.href.match("/$")) ? window.location.href : window.location.href + "/";
}
return loc;
}
Ultimately, this looks pretty ugly to me. Besides, every time i want to make a post or insert a relative URL when parsing data, i have to insert the result of that function before the actual URL which contributes to tag soup.
What is the best way to approach this?
I think your code is not ugly, but you can look to Backbone.js code:
url: function() {
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
},
This is a case of me not asking the question correctly.
The problem as i had it is best solved using Url.Action() method from the UrlHelper.

Problem with document.location.href

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.

Categories