I have this code in my header, which supposed to redirect users to another page if they have specific old browsers. I do not want this javascript code to be executed when bots are accessing the site. I have created a PHP condition for that, but my httpd access logs still shows that the bots are running this code. I know that because I am using JSNlog to log javascript errors and they trigger error when executing my code.
This is my code:
<?php
if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
//do nothing
}else{
?>
<script type="text/javascript">
function getBrowserData(nav) {
var data = {};
var ua = data.uaString = nav.userAgent;
var browserMatch = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if (browserMatch[1]) { browserMatch[1] = browserMatch[1].toLowerCase(); }
var operaMatch = browserMatch[1] === 'chrome';
if (operaMatch) { operaMatch = ua.match(/\bOPR\/([\d\.]+)/); }
if (/trident/i.test(browserMatch[1])) {
var msieMatch = /\brv[ :]+([\d\.]+)/g.exec(ua) || [];
data.name = 'msie';
data.version = msieMatch[1];
}
else if (operaMatch) {
data.name = 'opera';
data.version = operaMatch[1];
}
else if (browserMatch[1] === 'safari') {
var safariVersionMatch = ua.match(/version\/([\d\.]+)/i);
if (safariVersionMatch !== null) {
data.name = 'safari';
data.version = safariVersionMatch[1];
}
}
else {
data.name = browserMatch[1];
data.version = browserMatch[2];
}
var versionParts = [];
if (data.version) {
var versionPartsMatch = data.version.match(/(\d+)/g) || [];
for (var i=0; i < versionPartsMatch.length; i++) {
versionParts.push(versionPartsMatch[i]);
}
if (versionParts.length > 0) { data.majorVersion = versionParts[0]; }
}
data.name = data.name || '(unknown browser name)';
data.version = {
full: data.version || '(unknown full browser version)',
parts: versionParts,
major: versionParts.length > 0 ? versionParts[0] : '(unknown major browser version)'
};
return data;
};
var brData = getBrowserData(window.navigator || navigator);
if (
(brData.name == 'opera' && brData.version.major < 10) ||
(brData.name == 'msie' && brData.version.major < 10) ||
(brData.name == 'firefox' && brData.version.major < 27) ||
(brData.name == 'safari' && brData.version.major < 6)
) {
window.location = "https://www.example.com/outdated.htm";
}
// }
</script>
<?php } ?>
This is the error I see in the Apache log:
"POST /jsnlog.logger.php HTTP/1.1" 200 40 "https://www.example.com/some-url" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
Which matches my JSNlog error log:
[JSPHPLog]: {"msg":"Exception!","errorMsg":"Uncaught TypeError: Cannot read property '1' of null","url":""https://www.example.com/some-url","line number":186}
Line 186 is one of the lines from the above javascript code.
Am I doing something wrong with my condition? How can I make bots not run/see this code?