Reputation: 3
Managed to use an answer from someone else's question 11 years ago (How can you detect the version of a browser?) to retrieve the browser name and version that is being used and tie it into an if statement for displaying an alert message for out of date browsers (my if statement copied below).
What I'm wondering is if there is a simpler way for notating version <= Safari 12 so that Safari 11, 10, 9, etc. would get detected instead of doing the string of or || conditionals one after another.
if (navigator.sayswho === 'Safari 12' || navigator.sayswho === 'Safari 11' || navigator.sayswho === 'Safari 10' || navigator.sayswho === 'Safari 9') {
alert('Your browser ('+ navigator.sayswho +') is out of date, some features of our website may not work with your browser version.\r\n Please update your browser to ensure compatibility with our online product forms.\r\n\r\n');
}
It works, but I'm trying to learn how to make it a bit more elegant and slimmed down code wise. Thanks for any input you can provide. Stackoverflow has made my journey into development and website management a lot more productive and enjoyable for the last year. Cheers all.
Upvotes: 0
Views: 35
Reputation: 1551
I would recommend changing the check to:
const browser_list = [
'Safari 12',
'Safari 11',
'Safari 10',
'Safari 9'
];
if (browser_list.includes(navigator.sayswho)) {
// etc.
}
This is readable, maintainable, and can easily be changed in the future for new browsers and versions.
Upvotes: 0
Reputation: 370779
A regular expression test will do the trick.
if (/Safari (?:12|11|10|9)/.test(navigator.sayswho)) {
Another approach would be to match the trailing digits, then check if they're in the range.
const match = navigator.sayswho.match(/Safari (\d+)/);
const num = match ? Number(match[1]) : 0;
if (num <= 12 && num > 9) {
Upvotes: 1