I have a website to do for university and the teacher wants us to include code that checks what browser the user is using and if the browser isn't Firefox, they should be redirected elsewhere.
I have this so far:
function fnBrowserDetect(){
let userAgent = navigator.userAgent;
let browserName;
if(userAgent.match(/chrome|chromium|crios/i)){
browserName = "chrome";
}else if(userAgent.match(/firefox|fxios/i)){
browserName = "firefox";
} else if(userAgent.match(/safari/i)){
browserName = "safari";
}else if(userAgent.match(/opr\//i)){
browserName = "opera";
} else if(userAgent.match(/edg/i)){
browserName = "edge";
}else{
browserName="No browser detection";
}
document.querySelector("h1").innerText="You are using "+ browserName +" browser";
}
function redirect(){
if(browserName != "firefox"){
window.location.replace("www.google.com");
} else {
window.location.href = "../index.php";
}
}
Can someone help me out and let me know how can I do this correctly?
At the end of fnBrowserDetect, you can return browserName so you can use it in your other function.
Also make sure to include the protocol (https://) in your redirect URL.
function fnBrowserDetect(){
let userAgent = navigator.userAgent;
let browserName;
if(userAgent.match(/chrome|chromium|crios/i)){
browserName = "chrome";
}else if(userAgent.match(/firefox|fxios/i)){
browserName = "firefox";
} else if(userAgent.match(/safari/i)){
browserName = "safari";
}else if(userAgent.match(/opr\//i)){
browserName = "opera";
} else if(userAgent.match(/edg/i)){
browserName = "edge";
}else{
browserName="No browser detection";
}
document.querySelector("h1").innerText="You are using "+ browserName +" browser";
return browserName;
}
function redirect(){
if(fnBrowserDetect() != "firefox"){
window.location.replace("https://www.google.com");
} else {
window.location.href = "../index.php";
}
}