I’ve written a bit of code in JavaScript that uses the window.navigator.language and the navigator.browserLanguage objects to search through an array which contains these possible values.
What I am trying to achieve is to check through an array to see if any of the values within it match the browser language. I am aware that you can use PHP and check the HTTP header but I need to have this check performed client side. Anyway, I’ve written the code which is below but for some reason it doesn’t seem to return the values I want. I’ve written the function on the basis that each time the browser language matches a value in an array it will return true, else it will return false. However each time I run the function it just returns true! What am I doing wrong? Code is below.
JavaScript:
var langArray = new Array("en","en-GB","en-US","fr","de","en-gb","en-us");
function checkforIE() {
if (navigator.browserLanguage) { //if the navigator.browserLanguage is supported (IE only)
for(var i=0;i<langArray.length;i++) {
if(this[i] = navigator.browserLanguage) {
return true;
}
else {
return false;
}
}
}
}
function checkforFirefox() {
if (window.navigator.language) { //if the window.navigator.language is supported
for (var i=0;i<langArray.length;i++) {
if(window.navigator.language==this[i]) {
return true;
}
else {
return false;
}
}
}
}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="test-browser.js"></script>
<title>Test Browser support</title>
</head>
<body>
<h2>Test browser support</h2>
<a href="#" onclick="checkforIE(); checkforFirefox();">Click here</a>
</body>
</html>
Thanks in advance.
this[i]should belangArray[i]. You’re expectingthisto refer tolangArray, but that’s not correct.thisrefers towindow.Also, you’re not doing anything with the return values. To combine your function behaviour, use: