I need to check and compare browser versions that are outdated. If the user's browser version is below a defined (<=) version number, a message should appear telling the user to update his/her browser. The version is defined in the following array in my html.
<script type="text/javascript" language="javascript">
var browserarr = {Name:"Chrome", ChromeVersion:52, URL:"http://www.google.com",
Name:"Firefox", FirefoxVersion:40, URL:"http://www.firefox.com",
Name:"Safari", SafariVersion:10, URL:""
};
</script>
My logic has been to code it using if statements but i want another way to do it so that i can fetch the browser family (chrome, firefox or IE) and then the corresponding outdated version and a url to go to update the browser. It should be dynamic so that I only need to add a new line to my array specifying a new browser to make the comparison in javascript.
Check browser
detectJS: function () {
b = detect.parse(navigator.userAgent);
if (b.browser.family === 'Chrome' && b.browser.major <= browserarr["ChromeVersion"]) {
document.getElementById('browserNotificationDiv').style.display = "block";
var url = 'google.com';
//document.getElementById("msgURL").innerHTML = browserarr["URL"];
}
if (b.browser.family === 'IE' && b.browser.major <= 9) {
document.getElementById('browserNotificationDiv').style.display = "block";
var url = 'ie.com';
}
if (b.browser.family === 'Safari' && b.browser.major <= browserarr["SafariVersion"]) {
document.getElementById('browserNotificationDiv').style.display = "block";
var url = 'safari.com';
}
if (b.browser.family === 'Firefox' && b.browser.major <= browserarr["FirefoxVersion"]) {
document.getElementById('browserNotificationDiv').style.display = "block";
var url = 'firefox.com';
}
browserDetect.displayInfo(
'Your current browser ' + b.browser.family + ' version ' + b.browser.major +' is outdated. </br>' +
'Please download the latest version by going to: ' + url + ' ' + 'link' +'</br>'
);
},
How shall I proceed?
There is a widget that does exactly what you are looking for, and you can configure which versions you want to mark as outdated here:
https://updatemybrowser.org/widget.html
But in terms of your current code. I would change your browser object to have a structure more like:
var browserList = {
"chrome" : {
acceptedVersion: 52,
downloadUrl: "https://www.google.com"
},
"firefox" : {
acceptedVersion: 40,
downloadUrl: "https://www.firefox.com"
},
"safari" : {
acceptedVersion: 10,
downloadUrl: "https://www.apple.com"
}
}
Then in your code you can have a switch statement that compares browser name (to lower case to make it easier), then an if statement in that switch clause that checks accepted version and acts on it appropriately.
var broswerName = b.browser.family.toLowerCase();
switch(broswerName) {
case 'chrome':
if(broswerList[broswerName].acceptedVersion > b.browser.major) {
//browser is outdated
}
break;
case 'firefox':
if(broswerList[broswerName].acceptedVersion > b.browser.major) {
//browser is outdated
}
break;
}
Related
There are a bunch of older questions and answers I've tried. I'm clearly missing it.
I have a (restartless?) FF extension with a startup function:
var domains = [ "awesomesite.awesome" ];
var addon_domains = []; // list of domains the addon added
var PREF = "media.getusermedia.screensharing.allowed_domains";
function startup(data, reason) {
if (reason === APP_STARTUP) {
return;
}
var prefs = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
var values = prefs.getCharPref(PREF).split(',');
domains.forEach(function (domain) {
if (values.indexOf(domain) === -1) {
values.push(domain);
addon_domains.push(domain);
}
});
prefs.setCharPref(PREF, values.join(','));
// Communicate extension has started when user browses to webpage via window object?
// ?!?!?!?!
}
You can see the full code here.
This just needs to work for Firefox in the last year or so.
Any suggestions? These did not work.
Thanks!
Update
Here's the extension code I ended up using:
function startup(data, reason) {
if (reason === APP_STARTUP) {
return;
}
var prefs = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
var values = prefs.getCharPref(PREF).split(',');
domains.forEach(function (domain) {
if (values.indexOf(domain) === -1) {
values.push(domain);
addon_domains.push(domain);
}
});
prefs.setCharPref(PREF, values.join(','));
// Set the cookies
var ios = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var cookieSvc = Components.classes["#mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);
domains.forEach(function (domain) {
var cookieUri = ios.newURI("http://" + domain + "/", null, null);
cookieSvc.setCookieString(cookieUri, null, "firefoxScreenSharing=ready;", null);
});
}
And on the web page:
Helpers.pluginFirefox = function() {
if (!bowser || bowser.name !== 'Firefox') return false;
// Read the cookie
return (document.cookie.indexOf('firefoxScreenSharing=ready') !== -1);
};
If you only have one domain, the domains.foreach() is superfluous.
You cant do much from your website side. What I would recommend is, from your addon, create a cookie, with the domain/host being your website. Then from your website check if that cookie exists. If it exists, then its installed. :)
Of course on uninstall/disable of your addon you should delete that cookie.
My script below is firing on Mozilla when it should only fire on IE? It works correctly with Chrome. The cookie notifies the user once per browser session that they should update IE (if it is version 10 or less). However, users on Mozilla are getting the alert aswell.
Code:
var key_value = "Cookie=true";
var foundCookie = 0;
// Get all the cookies from this site and store in an array
var cookieArray = document.cookie.split(';');
// Walk through the array
for(var i=0;i < cookieArray.length;i++)
{
var checkCookie = cookieArray[i];
// Remove any leading spaces
while (checkCookie.charAt(0)==' ')
{
checkCookie = checkCookie.substring(1,checkCookie.length);
}
// Look for cookie set by key_value
if (checkCookie.indexOf(key_value) == 0)
{
// alert("Found Cookie");
// The cookie was found so set the variable
foundCookie = 1;
}
}
// Check if a cookie has been found
if ( foundCookie == 0)
{
// The key_value cookie was not found so set it now
document.cookie = key_value;
if (GetIEVersion() < 11) {
alert("You are using an outdated version of Internet Explorer.");
}
}
function GetIEVersion() {
var sAgent = window.navigator.userAgent;
var Idx = sAgent.indexOf("MSIE");
// If IE, return version number.
if (Idx > 0) {
return parseInt(sAgent.substring(Idx + 5, sAgent.indexOf(".", Idx)));
}
// If IE 11 then look for Updated user agent string.
else if (!!navigator.userAgent.match(/Trident\/7\./)) {
return 11;
}
else {
return 0; //It is not IE
}
}
Fixed it. The last 'return 0;' was returning 0, obviously, which made the statement think it was IE Version 0: therefore triggering the alert. Changing this to a number higher than 11 fixed it.
I have the following JavaScript function which is failing in internet explorer 9 on the line which declares the variable filesattached.
function VesselDetails() {
insurancestart = $('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').val();
insuranceend = $('#ctl00_ContentPlaceHolder1_datetimepickerinsend').val();
filesattached = $("input:File")[0].files.length;
//set up JS objects
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').datetimepicker({ format: 'd/m/Y H:i a' });
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').datetimepicker({ format: 'd/m/Y H:i a' });
//subscribe to change events
$('#ctl00_ContentPlaceHolder1_datetimepickerinsstart').change(function () {
insurancestart = $("ctl00_ContentPlaceHolder1_datetimepickerinsstart").val();
});
$('#ctl00_ContentPlaceHolder1_datetimepickerinsend').change(function () {
insuranceend = $("ctl00_ContentPlaceHolder1_datetimepickerinsend").val();
});
$("input:File").change(function () {
filesattached = $("input:File")[0].files.length;
});
ins_client();
}
The ins_client method looks like this:
function ins_client(sender, e) {
if (pagemode == 'EditVessel') {
e.IsValid = true;
}
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && filesattached > 0) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
}
This all works perfectly well in chrome and ie 11 but the length property is returning an undefined for ie 9. I am using the length because I only want the page to be valid for a new vessel request once a document has been submitted, is there another way of doing this which will work in ie 9 onwards and chrome, apologies if this has already been answered elsewhere but I cannot find a workaround anywhere that enables this to continue working in the same way but in ie9 onwards and chrome.
I replaced:
filesattached = $("input:File")[0].files.length;
With:
var areFilesAttached = document.getElementById('ctl00_ContentPlaceHolder1_fuAttachment').value ? true : false;
Within the VesselDetails function.
Then replaced the if statement within ins_client with the following:
if (pagemode == 'NewVessel') {
if (insurancestart !== '' && insuranceend !== '' && areFilesAttached == true) {
e.IsValid = true;
}
else {
e.IsValid = false;
}
}
This was an alternative approach which enabled me to check whether or not a file had been provided without using the files.length property which is not compatible with IE9.
I'm afraid this can't be achieved, IE9 does not support HTML5 File API and therefore it returns undefined value for files property.
Take a look at FILE API
How can I detect which Flash version a browser is using with JavaScript?
There is a nice, lightweight JavaScript Flash Detection Library, which is smaller and more convenient than using SWFObject. You should consider it, if you only want to check if Flash is installed, but you're using different method of playing FLV movies.
SWFObject should be considered only, if you're also using it for playing Flash movies. For just checking, if Flash is installed, it is to heavy in my opinion.
There is a lot of going on in JavaScript Flash Detection Library, but it seems it can be simplified to something like this:
getFlashVer: function () {
var activeXObj, plugins, plugin, result;
if (navigator.plugins && navigator.plugins.length > 0) {
plugins = navigator.plugins;
for (var i = 0; i < plugins.length && !result; i++) {
plugin = plugins[i];
if (plugin.name.indexOf("Shockwave Flash") > -1) {
result = plugin.description.split("Shockwave Flash ")[1];
}
}
} else {
plugin = "ShockwaveFlash.ShockwaveFlash";
try {
activeXObj = new ActiveXObject(plugin + ".7"), result = activeXObj.GetVariable("$version")
} catch (e) {}
if (!result) try {
activeXObj = new ActiveXObject(plugin + ".6"), result = "WIN 6,0,21,0", activeXObj.AllowScriptAccess = "always", result = activeXObj.GetVariable("$version")
} catch (e) {}
if (!result) try {
activeXObj = new ActiveXObject(plugin), result = activeXObj.GetVariable("$version")
} catch (e) {}
result && (result = result.split(" ")[1].split(","), result = result[0] + "." + result[1] + " r" + result[2])
}
return result ? result : "-";
}
I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.
In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.
As a completion to nertzy's answer you can add the ability for detecting IE versions using this:
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;
On the other hand you have to detect user agent details on the server side, too.
Anyways browser detection is a seriously flawed strategy for writing cross-browser scripts, that's just to be used when browser feature detection fails. It's pretty easy for a user to alter his/her user agent details.
Prototype offers some flags you can check to get an idea as to which browser is running. Keep in mind that it's much better practice to check for the functionality you wish to use rather than check for a particular browser.
Here is the browser- and feature-detection portion of prototype.js currently in the source tree:
var Prototype = {
Browser: {
IE: !!(window.attachEvent &&
navigator.userAgent.indexOf('Opera') === -1),
Opera: navigator.userAgent.indexOf('Opera') > -1,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
navigator.userAgent.indexOf('KHTML') === -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
},
BrowserFeatures: {
XPath: !!document.evaluate,
SelectorsAPI: !!document.querySelector,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
document.createElement('div')['__proto__'] &&
document.createElement('div')['__proto__'] !==
document.createElement('form')['__proto__']
},
}
So you could check if the current browser is IE by investigating the value of Prototype.Browser.IE, or alternatively, be more future-compatible and check for a particular feature like XPath with Prototype.BrowserFeatures.XPath.
You're right - prototype doesn't provide a utility for ascertaining the browser name or version.
If you specifically need to get the browser info as a plugin, I would suggest adding the following (taken from directly jQuery):
var Browser = Class.create({
initialize: function() {
var userAgent = navigator.userAgent.toLowerCase();
this.version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
this.webkit = /webkit/.test( userAgent );
this.opera = /opera/.test( userAgent );
this.msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );
this.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
}
});
I use this over and above Prototype's browser definitions.
Object.extend(Prototype.Browser, {
ie6: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 6 ? true : false) : false,
ie7: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 7 ? true : false) : false,
ie8: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 8 ? true : false) : false,
ie9: (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false
});
Hope it helps!
I have prototype.js extended after:
var Prototype = { ... };
with this:
// extension
if (Prototype.Browser.IE) {
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);
}
}
Works fine for me, calling is like:
if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] == 8) { ... }
<script type="text/JavaScript">
function getBrowserVersion()
{
var msg = "Not Recognised Browser";
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
{
var ffversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ffversion == i)
{
msg = "FF" + i + "x";
break;
}
}
}
else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{
var ieversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ieversion == i)
{
msg = "IE" + i + "x";
break;
}
}
}
alert(msg); // return msg;
}
</script>