Is it a bug of web speech API? - javascript

I wrote the code to speak the text of current page.
Here is my code :
$('#speak').on('click', function () {
if(!('speechSynthesis' in window)){
alert('This browser doesn\'t support this feature.\n Try again with Chrome browser');
return;
}
navigator.browserInfo= (function(){
var ua= navigator.userAgent, tem,
iOS = !!ua.match(/ip(ad|od|hone)/i),
webkit = !!ua.match(/Webkit/i),
iOSChrome = iOS && webkit && !ua.match(/Version/i) && ua.match(/CriOS/i) && !ua.match(/EdgeOS/i) && !ua.match(/OPiOS/i),
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(iOSChrome){
return {'browser': 'Chrome'};
}
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge?)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera').replace('Edg ', 'Edge ');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return {'browser': M[0], 'version': M[1]};
})();
if(navigator.browserInfo.browser != 'Chrome'){
alert('Try again with Chrome browser.');
return;
}
if ($(this).attr('data-opt') == 'cancel') {
timer(1);
window.speechSynthesis.cancel();
$(this).attr('data-opt', 'speak');
return;
}
var text = '';
if(currentPage == 1)
text = '';
else
text = currentPage >= 35? $('.page' + (currentPage + 1))[0].innerText : $('.page' + currentPage)[0].innerText;
if (text.trim() == null || text.trim() == '') {
text = 'There is no text to speak.';
}
speak(text);
});
function timer(end) {
if (end != null) {
clearTimeout(myTimeout);
return;
}
window.speechSynthesis.pause();
window.speechSynthesis.resume();
myTimeout = setTimeout(timer, 10000);
}
function speak(text) {
if (window.speechSynthesis.speaking) {
console.error('speechSynthesis.speaking');
return;
}
window.speechSynthesis.cancel();
if(navigator.userAgent.search('Android') == -1)
myTimeout = setTimeout(timer, 10000);
var msg = new SpeechSynthesisUtterance(text);
msg.pitch = 1;
msg.rate = 1;
for (var i = 0; i < window.speechSynthesis.getVoices().length; i++) {
if (window.speechSynthesis.getVoices()[i].lang == 'ko-KR') {
msg.voice = window.speechSynthesis.getVoices()[i];
break;
}
}
msg.onend = function () {
timer(1);
$('#speak').attr('data-opt', 'speak');
};
msg.onerror = function(event){
if(navigator.userAgent.search('Mobile') == -1){
alert('An error has occurred with the speech synthesis: ' + event.error);
}else{
console.log('An error has occurred with the speech synthesis: ' + event.error);
}
timer(1);
window.speechSynthesis.cancel();
$('#speak').attr('data-opt', 'speak');
};
$.when(window.speechSynthesis.speak(msg)).then(function () {
$('#speak').attr('data-opt', 'cancel');
});
}
A brief explanation of my code : When you click the #speak button first of all the callback function start to filter if this browser support web speech API and if this browser is chrome after passing all the filtering it gets text from the current page's innerText property and finally speak the text.
It seems it works fine in the most case perfectly working on desktop.
The problem i'm facing is it just stops working on mobile especially iOS after speaking all the text or sometimes random, i don't know why it stops so suddenly without any errors..
Since i wrote the timer function i don't think it's the typical problem that appears with long text.
Any help it would be appreciated thank you in advance.

Related

Speech Recognition result double in mobile

I have tried this code work fine on pc desktop windows. But this not work on mobile devices, they result multiple sentences on textarea.
speechRecognition.onresult = (event) => {
var teks_transkrip= "";
var transkrip_akhir = "";
// Ulangi hasil dari objek pengenalan suara.
for (let i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
transkrip_akhir+= event.results[i][0].transcript;
} else {
teks_transkrip+= event.results[i][0].transcript;
$("#pratinjau").val(teks_transkrip);
}}
$("#artikel").insertIntoTextArea(transkrip_akhir);
transkrip_akhir = "";
};
$.fn.insertIntoTextArea = function(textToInsert) {
var data = $("#artikel").val();
if (textToInsert.trim() == "titik"){
$("#artikel").val(data + ".");
return;
}
if (textToInsert.trim() == "baris baru"){
$("#artikel").val(data + "\n");
return;
}
if (textToInsert.trim() == "paragraf baru"){
$("#artikel").val(data + "\n\n");
return;
}
if (textToInsert.trim() == "titik koma"){
$("#artikel").val(data + ";");
return;
}
if (textToInsert.trim() == "koma"){
$("#artikel").val(data + ",");
return;
}
$("#artikel").val(data + textToInsert);
}
I've read this article speech recognition onresult called twice on mobile and tablet deveices and it doesn't help at all.
i want speech reccognition worked on al devices that using chrome

How to remove end space when firefox double click selected text

Firefox double click selected text with next space. How to remove end space on screen with javascript.
Thank you so much.
Here's solution that does remove trailing whitespace character selected on doubleclick in Windows browsers, somewhat emulating Firefox about:config setting layout.word_select.eat_space_to_next_word being set to "false".
Does it "On screen, not in variable".
Tested in Chrome 60.0.3112.113, Firefox 55.0.3, IE8 and IE Edge(14).
It's still sometimes visible as selection shrinks from that extra space but nothing can be done about that.
Works for both arbitrary text and input/textareas(those need completely different approaches).
Uses jQuery
(function() {
var lastSelEvent = null;
var lastSelInputEvent = null;
var lastDblClickEvent = null;
var selchangeModTs = null;
$(document).on('selectstart selectionchange', function (e) //not input/textarea case
{
fixEventTS(e);
lastSelEvent = e;
if (( selchangeModTs != null) && (new Date().getTime() - selchangeModTs < 50)) //without this we get infinite loop in IE11+ as changing selection programmatically apparently generates event itself...
return;
handleSelEvent(e);
});
$(document).on('select', function (e) //input/textarea
{
fixEventTS(e);
lastSelInputEvent = e;
handleSelEvent(e);
});
$(document).on('dblclick',function(e)
{
fixEventTS(e);
lastDblClickEvent = e;
handleSelEvent(e);
});
function fixEventTS(e)
{
if (typeof e.timeStamp == 'undefined') //IE 8 no timestamps for events...
{
e.timeStamp = new Date().getTime();
}
}
function handleSelEvent(e)
{
if (lastDblClickEvent===null)
return;
if ( ((e.type==='selectstart') || (e.type==='selectionchange') || (e.type==='dblclick')) && (lastSelEvent != null) && (Math.abs(lastDblClickEvent.timeStamp - lastSelEvent.timeStamp) < 1000) ) // different browsers have different event order so take abs to be safe...
{
switch (lastSelEvent.type)
{
case 'selectstart':
setTimeout(handleSelChange,50); //IE8 etc fix, selectionchange is actually only change, not selection "creation"
break;
case 'selectionchange':
handleSelChange();
break;
}
}
if ( ((e.type==='select') || (e.type==='dblclick')) && (lastSelInputEvent != null) && (Math.abs(lastDblClickEvent.timeStamp - lastSelInputEvent.timeStamp) < 1000) ){
handleSel(lastSelInputEvent);
}
}
function handleSel(e)
{
//right whitespace
while (/\s$/.test(e.target.value.substr(e.target.selectionEnd - 1, 1)) && e.target.selectionEnd > 0) {
e.target.selectionEnd -= 1;
}
//left whitespace
while (/\s$/.test(e.target.value.substr(e.target.selectionStart, 1)) && e.target.selectionStart > 0) {
e.target.selectionStart += 1;
}
}
function handleSelChange() {
var sel = null;
if (typeof window.getSelection == 'function') // modern browsers
sel = window.getSelection();
else if (typeof document.getSelection == 'function')
sel = document.getSelection();
if (sel && !sel.isCollapsed) {
var range = sel.getRangeAt(0); //have to use range instead of more direct selection.expand/selection.modify as otherwise have to consider selection's direction in non-doubleclick cases
if (range.endOffset > 0 && (range.endContainer.nodeType===3) && (range.endContainer.textContent != ''/*otherwise rightside pictures get deleted*/))
{
//right whitespaces
while ( /[\s\S]+\s$/.test(range.endContainer.textContent.substr(0,range.endOffset)) ) { //have to use instead of range.toString() for IE11+ as it auto-trims whitespaces there and in selection.toString()
selchangeModTs = new Date().getTime();
range.setEnd(range.endContainer, range.endOffset - 1);
}
}
if ((range.startContainer.nodeType===3) && (range.startContainer.textContent != '') && (range.startOffset < range.startContainer.textContent.length)) {
//left whitespaces
while (/^\s[\s\S]+/.test(range.startContainer.textContent.substr(range.startOffset))) {
selchangeModTs = new Date().getTime();
range.setStart(range.startContainer, range.startOffset + 1);
}
}
selchangeModTs = new Date().getTime();
sel.removeAllRanges(); //IE11+ fix, in Firefox/Chrome changes to range apply to selection automatically
sel.addRange(range);
}
else if (typeof document.selection != 'undefined') //IE 10 and lower case
{
var range = document.selection.createRange();
if (range && range.text && range.text.toString()) {
while ((range.text != '') && /[\s\S]+\s$/.test(range.text.toString())) {
selchangeModTs = new Date().getTime();
range.moveEnd('character', -1);
range.select();
}
while ((range.text != '') && /^\s[\s\S]+/.test(range.text.toString())) {
selchangeModTs = new Date().getTime();
range.moveStart('character', 1);
range.select();
}
}
}
}
})();
If you don't need old IE support & limitint to doubleclick-only removal it can be greatly simplified and only needs to handle selectchange and select events to respective functions.(but then you actually can't select stuff with keyboard)
Edit:
Using Rangy lib(https://github.com/timdown/rangy) Core + TextRange for non-input elements selection trimming is way better than my basic attempt that only works if endContainer happens to be a text node. Basic action of selection trimming is
rangy.getSelection().trim()
Minimal includes are
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/rangy/1.3.0/rangy-core.min.js
https://cdnjs.cloudflare.com/ajax/libs/rangy/1.3.0/rangy-textrange.min.js
Rangy implementation additionally supporting triple-click whole-line selection trimming
(function() {
var lastSelEvent = null;
var lastSelInputEvent = null;
var lastDblClickEvent = null;
var selchangeModTs = null;
var tripleclickFixBound = false;
var selStartTimout = null;
$(document).on('selectstart selectionchange', function (e) //non-inputs
{
fixEventTS(e);
lastSelEvent = e;
if ( ( selchangeModTs != null) && (new Date().getTime() - selchangeModTs < 50) ) //ie11+ fix otherwise get self-loop with our selection changes generating this event
return;
handleSelEvent(e);
});
if ('onselect' in document.documentElement) {
$(document).on('select', function (e) //input/textarea
{
fixEventTS(e);
lastSelInputEvent = e;
handleSelEvent(e);
});
}
$(document).on('click',function(e){
if (typeof e.originalEvent.detail !== 'undefined')
{
multiclickHandlerfunction(e);
}
else
{
fixEventTS(e);
if (!tripleclickFixBound) {
$(document).on('dblclick', function (e) {
fixEventTS(e);
selchangeModTs = null;
lastDblClickEvent = e;
handleSelEvent(e);
});
tripleclickFixBound=true;
}
if ( (lastDblClickEvent != null) && (e.timeStamp - lastDblClickEvent.timeStamp < 300))
{
lastDblClickEvent = e;
selchangeModTs = null;
handleSelEvent(e);
}
}
});
function multiclickHandlerfunction(e) {
if (e.originalEvent.detail === 2 || e.originalEvent.detail === 3) {
fixEventTS(e);
selchangeModTs = null;
lastDblClickEvent = e;
handleSelEvent(e);
}
}
function fixEventTS(e)
{
if (typeof e.timeStamp == 'undefined') //IE 8
{
e.timeStamp = new Date().getTime();
}
}
function handleSelEvent(e)
{
if (lastDblClickEvent===null)
return;
if ( ((e.type==='selectstart') || (e.type==='selectionchange') || (e.type==='dblclick') || (e.type==='click')) && (lastSelEvent != null) && (Math.abs(lastDblClickEvent.timeStamp - lastSelEvent.timeStamp) < 1000) ) // different order of events in different browsers...
{
switch (lastSelEvent.type)
{
case 'selectstart':
case 'selectionchange':
clearTimeout(selStartTimout);
selStartTimout = setTimeout(handleSelChange,(/msie\s|trident\/|edge\//i.test(window.navigator.userAgent)?150:0));
break;
}
}
if ( ((e.type==='select') || (e.type==='dblclick') || (e.type==='click')) && (lastSelInputEvent != null) && (Math.abs(lastDblClickEvent.timeStamp - lastSelInputEvent.timeStamp) < 1000) )
{
handleSel(lastSelInputEvent);
}
}
function handleSel(e)
{
if (typeof(e.target.selectionEnd) != 'undefined') {
//left whitespace
while (/\s$/.test(e.target.value.substr(e.target.selectionEnd - 1, 1)) && e.target.selectionEnd > 0) {
e.target.selectionEnd -= 1;
}
//right whitespace
while (/^s/.test(e.target.value.substr(e.target.selectionStart - 1, 1)) && e.target.selectionStart > 0) {
e.target.selectionStart += 1;
}
}
}
function handleSelChange() {
var sel = rangy.getSelection();
if (sel && !sel.isCollapsed) {
selchangeModTs = new Date().getTime();
sel.trim();
}
else if (typeof document.selection != 'undefined') //IE 10- input/textArea case
{
var range = document.selection.createRange();
if (range && range.text && range.text.toString()) {
while ((range.text != '') && /[\s\S]+\s$/.test(range.text.toString())) {
selchangeModTs = new Date().getTime();
range.moveEnd('character', -1);
range.select();
}
while ((range.text != '') && /^\s[\s\S]+/.test(range.text.toString())) {
selchangeModTs = new Date().getTime();
range.moveStart('character', 1);
range.select();
}
}
}
}
})($,window);
CodePen demo
One thing I tried was to use range.setEnd() using the selection focus and anchor node and offset but -1.
Please excuse the lack of checks for browser compatibility.
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var selected = range.toString();
if (!selection.isCollapsed) {
if (/\s+$/.test(selected)) {
if (selection.focusOffset > selection.anchorOffset) {
range.setEnd(selection.focusNode, selection.focusOffset - 1);
} else {
range.setEnd(selection.anchorNode, selection.anchorOffset - 1);
}
}
}
I am unsure if it works in IE/Edge but Chrome seems happy with it.
You must be using a Windows machine. And so you are seeing this issue. It doesnt exists on ubuntu machine.
Also if you need to remove the trailing space with Js
Try something like this.
document.ondblclick = function () {
var sel = (document.selection && document.selection.createRange().text) ||
(window.getSelection && window.getSelection().toString());
var selection = window.getSelection();
$('#new_word').text(sel.trim());
};
Check this jsFiddle http://jsfiddle.net/shinde87sagar/FvkwV/
Thanks to #James Bellaby
It worked for me using Chrome 83, this is the code for removing leading and trailing spaces from the selected range.
function fix_selection(range) {
var selection = window.getSelection();
var selected = range.toString();
range = selection.getRangeAt(0);
let start = selection.anchorOffset;
let end = selection.focusOffset;
if (!selection.isCollapsed) {
if (/\s+$/.test(selected)) { // Removes leading spaces
if (start > end) {
range.setEnd(selection.focusNode, --start);
} else {
range.setEnd(selection.anchorNode, --end);
}
}
if (/^\s+/.test(selected)) { // Removes trailing spaces
if (start > end) {
range.setStart(selection.anchorNode, ++end);
} else {
range.setStart(selection.focusNode, ++start);
}
}
}
return range
}
just put the text inside a label and the problem will be solved
Javascript has a trim() method which trims tailing (end) and leading spaces.
e.g.
var str = " Hello World! ";
str = str.trim(); // returns "Hello World"
Ref: http://www.w3schools.com/jsref/jsref_trim_string.asp

How to detect Acrobat X Pro installed on machine using javascript

How can I detect if Acrobat X Pro is installed on a machine using javascript. I have code that works for Adobe Reader. but now I have upgrdaed my adobe version to Acrobat X Pro. But it is not working for Acrobat X Pro using IE8.
var perform_acrobat_detection = function()
{
//
// The returned object
//
var browser_info = {
name: null,
acrobat : null,
acrobat_ver : null
};
if(navigator && (navigator.userAgent.toLowerCase()).indexOf("chrome") > -1)
browser_info.name = "chrome";
else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("msie") > -1)
browser_info.name = "ie";
else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("firefox") > -1)
browser_info.name = "firefox";
else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("msie") > -1)
browser_info.name = "other";
try {
if(browser_info.name == "ie") {
var control = null;
//
// load the activeX control
//
try {
// AcroPDF.PDF is used by version 7 and later
control = new ActiveXObject('AcroPDF.PDF');
}
catch (e){}
if (!control) {
try {
// PDF.PdfCtrl is used by version 6 and earlier
control = new ActiveXObject('PDF.PdfCtrl');
}
catch (e) {}
}
if(!control) {
browser_info.acrobat == null;
return browser_info;
}
version = control.GetVersions().split(',');
version = version[0].split('=');
browser_info.acrobat = "installed";
browser_info.acrobat_ver = parseFloat(version[1]);
}
else if(browser_info.name == "chrome") {
for(key in navigator.plugins)
{
if(navigator.plugins[key].name == "Chrome PDF Viewer" || navigator.plugins[key].name == "Adobe Acrobat") {
browser_info.acrobat = "installed";
browser_info.acrobat_ver = parseInt(navigator.plugins[key].version) || "Chome PDF Viewer";
}
}
}
//
// NS3+, Opera3+, IE5+ Mac, Safari (support plugin array): check for Acrobat plugin in plugin array
//
else if(navigator.plugins != null)
{
var acrobat = navigator.plugins['Adobe Acrobat'];
if(acrobat == null)
{
browser_info.acrobat = null;
return browser_info;
}
browser_info.acrobat = "installed";
browser_info.acrobat_ver = parseInt(acrobat.version[0]);
}
}
catch(e)
{
browser_info.acrobat_ver = null;
}
return browser_info;
};
var browser_info = perform_acrobat_detection();

jQuery load and append issue

im getting a little issue here. I have a wordpress theme that i need to add an infinite scroll effect. Ok, its working, but it doesnt look work properly. I set the current page and the number of pages, but it keeps adding the second page every time i reach the bottom.
What im doing wrong?
Ps.: I have tried the inifite-scroll plugin for wordpress, and it dont works with my template. Thanks!
$(function() {
var currentPage = 1;
var numPages = Math.ceil(pages / 4);
var browserName = "";
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("opera") != -1) {
browserName = "opera";
} else if (ua.indexOf("msie") != -1) {
browserName = "msie";
} else if (ua.indexOf("safari") != -1) {
browserName = "safari";
} else if (ua.indexOf("mozilla") != -1) {
if (ua.indexOf("firefox") != -1) {
browserName = "firefox";
} else {
browserName = "mozilla";
}
}
$(window).scroll(function() {
if (browserName != "safari") {
var curScrollPos = $('html').scrollTop();
}
else {
var curScrollPos = $('body').scrollTop();
}
if (curScrollPos > 218) {
$("#sidebar").addClass("open");
}
if (curScrollPos < 218) {
$("#sidebar").removeClass("open");
}
var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
if (scrollBottom == 0) {
if (currentPage < numPages) {
$("<div>").load("page/" + (currentPage + 1), function() {
var newPosts = $(this).find("#content").html();
$("#content").append(newPosts);
});
currentPage++;
}
else {
}
}
});
// Infinite Scroll
});​
Possibly try this:
$("<div>").load("page/"+(currentPage+1), function() {
var newPosts = $(this).find("#content").html();
$("#content").append(newPosts);
currentPage++;
});
And remove the currentPage++;

How can you detect the version of a browser?

I've been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but not the version.
How can I detect the version of a browser like this?
You can see what the browser says, and use that information for logging or testing multiple browsers.
navigator.sayswho= (function(){
var ua= navigator.userAgent;
var tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
console.log(navigator.sayswho); // outputs: `Chrome 62`
This is an improvement on Kennebec's answer.
mbrowser=function(){
this.spec_string= navigator.userAgent;
this.name= this.get_name();
this.version= this.get_version();
};
mbrowser.prototype.get_name=function(){
var spec_string=this.spec_string;
var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
// Work with the matches.
matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];
// Trident.
if(/trident/i.test(matches[1])){
var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || [];
return 'IE';
}
// Chrome.
if(matches[1]==='Chrome'){
var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
if(temp!=null) {return 'Opera';}
}
if((temp=spec_string.match(/version\/(\d+)/i))!=null){
matches.splice(1,1,temp[1]);
}
var name=matches[0];
return name;
};
mbrowser.prototype.get_version=function(){
var spec_string=this.spec_string;
var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
// Work with the matches.
matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];
// Trident.
if(/trident/i.test(matches[1])){
var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || [];
var version=(temp[1]||'');
return version;
}
// Chrome.
if(matches[1]==='Chrome'){
var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
var version=temp[1];
if(temp!=null) {return version;}
}
if((temp=spec_string.match(/version\/(\d+)/i))!=null){
matches.splice(1,1,temp[1]);
}
var version=matches[1];
return version;
};
// m=module.
var browser=new mbrowser();
console.log(browser.name); // Chrome
console.log(browser.version); // 109
This code deduces browser name and number from the spec_string (navigator.userAgent). But there are all kinds of spec_strings out there with their respective browser name and number. And I'm not in a situation to check but a tiny proportion of them. It would be great if you could post a spec_string who's resulting browser name and number you know. I can then update the code accordingly.
I would then slowly build up a list of spec_string items in the following manner.
'spec_string1'=>[name,number],
'spec_string2'=>[name,number],
Then in the future, whenever a change is made to the code it can automatically be tested on all known spec_string conversions.
We can do this together.
Here are several prominent libraries that handle browser detection as of May 2019.
Bowser by lancedikson - 3,761★s - Last updated May 26, 2019 - 4.8KB
var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
" v" + result.parsedResult.browser.version +
" on " + result.parsedResult.os.name);
<script src="https://unpkg.com/bowser#2.4.0/es5.js"></script>
*supports Edge based on Chromium
Platform.js by bestiejs - 2,250★s - Last updated Oct 30, 2018 - 5.9KB
console.log(platform);
document.write("You are using " + platform.name +
" v" + platform.version +
" on " + platform.os);
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB
console.log($.browser)
document.write("You are using " + $.browser.name +
" v" + $.browser.versionNumber +
" on " + $.browser.platform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
Detect.js (Archived) by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB
var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
" v" + result.browser.version +
" on " + result.os.family);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B
console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
" v" + BrowserDetect.version +
" on " + BrowserDetect.OS);
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
Notable Mentions:
WhichBrowser - 1,355★s - Last updated Oct 2, 2018
Modernizr - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.
Further Reading
Stack Overflow - Browser detection in JavaScript?
Stack Overflow - How to detect Safari, Chrome, IE, Firefox and Opera browser?
This combines kennebec's (K) answer with Hermann Ingjaldsson's (H) answer:
Maintains original answer's minimal code. (K)
Works with Microsoft Edge (K)
Extends the navigator object instead of creating a new variable/object. (K)
Separates browser version and name into independent child objects. (H)
 
navigator.browserSpecs = (function(){
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE',version:(tem[1] || '')};
}
if(M[1]=== 'Chrome'){
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
}
M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem = ua.match(/version\/(\d+)/i))!= null)
M.splice(1, 1, tem[1]);
return {name:M[0], version:M[1]};
})();
console.log(navigator.browserSpecs); //Object { name: "Firefox", version: "42" }
if (navigator.browserSpecs.name == 'Firefox') {
// Do something for Firefox.
if (navigator.browserSpecs.version > 42) {
// Do something for Firefox versions greater than 42.
}
}
else {
// Do something for all other browsers.
}
The bowser JavaScript library offers this functionality.
if (bowser.msie && bowser.version <= 6) {
alert('Hello China');
}
It seems to be well maintained.
Use this: http://www.quirksmode.org/js/detect.html
alert(BrowserDetect.browser); // will say "Firefox"
alert(BrowserDetect.version); // will say "3" or "4"
I was looking for a solution for myself, since jQuery 1.9.1 and above have removed the $.browser functionality. I came up with this little function that works for me.
It does need a global variable (I've called mine _browser) in order to check which browser it is. I've written a jsfiddle to illustrate how it can be used, of course it can be expanded for other browsers by just adding a test for _browser.foo, where foo is the name of the browser. I did just the popular ones.
detectBrowser()
_browser = {};
function detectBrowser() {
var uagent = navigator.userAgent.toLowerCase(),
match = '';
_browser.chrome = /webkit/.test(uagent) && /chrome/.test(uagent) &&
!/edge/.test(uagent);
_browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);
_browser.msie = /msie/.test(uagent) || /trident/.test(uagent) ||
/edge/.test(uagent);
_browser.safari = /safari/.test(uagent) && /applewebkit/.test(uagent) &&
!/chrome/.test(uagent);
_browser.opr = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&
/chrome/.test(uagent) && /safari/.test(uagent) &&
/opr/.test(uagent);
_browser.version = '';
for (x in _browser) {
if (_browser[x]) {
match = uagent.match(
new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)")
);
if (match) {
_browser.version = match[3];
} else {
match = uagent.match(new RegExp("rv:([0-9]+)"));
_browser.version = match ? match[1] : "";
}
break;
}
}
_browser.opera = _browser.opr;
delete _browser.opr;
}
detectBrowser();
console.log(_browser)
To check if the current browser is Opera you would do
if (_browser.opera) { // Opera specific code }
Edit Fixed the formatting, fixed the detection for IE11 and Opera/Chrome, changed to browserResult from result. Now the order of the _browser keys doesn't matter. Updated jsFiddle link.
2015/08/11 Edit Added new testcase for Internet Explorer 12 (EDGE), fixed a small regexp problem. Updated jsFiddle link.
function BrowserCheck()
{
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) {M[2]=tem[1];}
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
return M;
}
This will return an array, first element is the browser name, second element is the complete version number in string format.
This is a Update on Fzs2 & kennebec For New Edge Chromium
function get_browser() {
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE',version:(tem[1]||'')};
}
if(M[1]==='Chrome'){
tem=ua.match(/\bEdg\/(\d+)/)
if(tem!=null) {return {name:'Edge(Chromium)', version:tem[1]};}
tem=ua.match(/\bOPR\/(\d+)/)
if(tem!=null) {return {name:'Opera', version:tem[1]};}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
return {
name: M[0],
version: M[1]
};
}
var browser=get_browser(); // browser.name = 'Edge(Chromium)'
// browser.version = '86'
console.log(browser);
In pure Javascript you can do a RegExp match on the navigator.userAgent to find the Firefox version:
var uMatch = navigator.userAgent.match(/Firefox\/(.*)$/),
ffVersion;
if (uMatch && uMatch.length > 1) {
ffVersion = uMatch[1];
}
ffVersion will be undefined if not a Firefox browser.
See working example →
jQuery can handle this quite nice (jQuery.browser)
var ua = $.browser;
if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
alert( "Do stuff for firefox 3" );
}
EDIT: As Joshua wrote in his comment below, jQuery.browser property is no longer supported in jQuery since version 1.9 (read jQuery 1.9 release notes for more details).
jQuery development team recommends using more complete approach like adapting UI with Modernizr library.
Look at navigator.userAgent - Firefox/xxx.xxx.xxx is specified right at the end.
<script type="text/javascript">
var version = navigator.appVersion;
alert(version);
</script>
I wrote a version detector based on Hermann Ingjaldsson's answer, but more robust and which returns an object with name/version data in it. It covers the major browsers but I don't bother with the plethora of mobile ones and minor ones:
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);
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;
};
It can then be used like this:
var brData = getBrowserData(window.navigator || navigator);
console.log('name: ' + brData.name);
console.log('major version: ' + brData.version.major);
// etc.
For this you need to check the value of navigator.appVersion or navigator.userAgent
Try using:
console.log(navigator.appVersion)
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>'
)
See the demo here..http://jsfiddle.net/hw4jM/3/
Detecting Browser and Its version
This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.
I have done few changes to detect browsers like Edge and UCBrowser
getBrowser = () => {
const userAgent = navigator.userAgent;
let browser = "unkown";
// Detect browser name
browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;
// detect browser version
switch (browser) {
case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
// IE version is mapped using trident version
// IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
default: return `unknown/0.0.0.0`;
}
}
browserVersion = (userAgent,regex) => {
return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}
console.log(getBrowser());
I have made a script in ASP code to detect browser, browser version, OS and OS version.
The reason for me to do this in ASP was because i want to store the data in a log-database.
So I had to detect the browser serverside.
Here is the code:
on error resume next
ua = lcase(Request.ServerVariables("HTTP_USER_AGENT"))
moz = instr(ua,"mozilla")
ffx = instr(ua,"firefox")
saf = instr(ua,"safari")
crm = instr(ua,"chrome")
max = instr(ua,"maxthon")
opr = instr(ua,"opera")
ie4 = instr(ua,"msie 4")
ie5 = instr(ua,"msie 5")
ie6 = instr(ua,"msie 6")
ie7 = instr(ua,"msie 7")
ie8 = instr(ua,"trident/4.0")
ie9 = instr(ua,"trident/5.0")
if moz>0 then
BrowserType = "Mozilla"
BrVer = mid(ua,moz+8,(instr(moz,ua," ")-(moz+8)))
end if
if ffx>0 then
BrowserType = "FireFox"
BrVer = mid(ua,ffx+8)
end if
if saf>0 then
BrowserType = "Safari"
BrVerPlass = instr(ua,"version")
BrVer = mid(ua,BrVerPlass+8,(instr(BrVerPlass,ua," ")-(BrVerPlass+8)))
end if
if crm>0 then
BrowserType = "Chrome"
BrVer = mid(ua,crm+7,(instr(crm,ua," ")-(crm+7)))
end if
if max>0 then
BrowserType = "Maxthon"
BrVer = mid(ua,max+8,(instr(max,ua," ")-(max+8)))
end if
if opr>0 then
BrowserType = "Opera"
BrVerPlass = instr(ua,"presto")
BrVer = mid(ua,BrVerPlass+7,(instr(BrVerPlass,ua," ")-(BrVerPlass+7)))
end if
if ie4>0 then
BrowserType = "Internet Explorer"
BrVer = "4"
end if
if ie5>0 then
BrowserType = "Internet Explorer"
BrVer = "5"
end if
if ie6>0 then
BrowserType = "Internet Explorer"
BrVer = "6"
end if
if ie7>0 then
BrowserType = "Internet Explorer"
BrVer = "7"
end if
if ie8>0 then
BrowserType = "Internet Explorer"
BrVer = "8"
if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
end if
if ie9>0 then
BrowserType = "Internet Explorer"
BrVer = "9"
if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
if ie8>0 then BrVer = BrVer & " (in IE8 compability mode)"
end if
OSSel = mid(ua,instr(ua,"(")+1,(instr(ua,";")-instr(ua,"("))-1)
OSver = mid(ua,instr(ua,";")+1,(instr(ua,")")-instr(ua,";"))-1)
if BrowserType = "Internet Explorer" then
OSStart = instr(ua,";")
OSStart = instr(OSStart+1,ua,";")
OSStopp = instr(OSStart+1,ua,";")
OSsel = mid(ua,OSStart+2,(OSStopp-OSStart)-2)
end if
Select case OSsel
case "windows nt 6.1"
OS = "Windows"
OSver = "7"
case "windows nt 6.0"
OS = "Windows"
OSver = "Vista"
case "windows nt 5.2"
OS = "Windows"
OSver = "Srv 2003 / XP x64"
case "windows nt 5.1"
OS = "Windows"
OSver = "XP"
case else
OS = OSSel
End select
Response.write "<br>" & ua & "<br>" & BrowserType & "<br>" & BrVer & "<br>" & OS & "<br>" & OSver & "<br>"
'Use the variables here for whatever you need........
This page seems to have a pretty nice snippet which only uses the appString and appVersion property as a last resort as it claims them to be unreliable with certain browsers.
The code on the page is as follows:
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera 15+, the true version is after "OPR/"
if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>'
)
Adding my own implementation of Hermann's answer. I needed OS detection so that's been added. Also includes some ES6 code (because we have a transpiler) that you might need to ES5-ify.
detectClient() {
let nav = navigator.appVersion,
os = 'unknown',
client = (() => {
let agent = navigator.userAgent,
engine = agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
build;
if(/trident/i.test(engine[1])){
build = /\brv[ :]+(\d+)/g.exec(agent) || [];
return {browser:'IE', version:(build[1] || '')};
}
if(engine[1] === 'Chrome'){
build = agent.match(/\bOPR\/(\d+)/);
if(build !== null) {
return {browser: 'Opera', version: build[1]};
}
}
engine = engine[2] ? [engine[1], engine[2]] : [navigator.appName, nav, '-?'];
if((build = agent.match(/version\/(\d+)/i)) !== null) {
engine.splice(1, 1, build[1]);
}
return {
browser: engine[0],
version: engine[1]
};
})();
switch (true) {
case nav.indexOf('Win') > -1:
os = 'Windows';
break;
case nav.indexOf('Mac') > -1:
os = 'MacOS';
break;
case nav.indexOf('X11') > -1:
os = 'UNIX';
break;
case nav.indexOf('Linux') > -1:
os = 'Linux';
break;
}
client.os = os;
return client;
}
Returns: Object {browser: "Chrome", version: "50", os: "UNIX"}
Here this has better compatibility then #kennebec snippet;
will return browser name and version (returns 72 instead of 72.0.3626.96).
Tested on Safari, Chrome, Opera, Firefox, IE, Edge, UCBrowser, also on mobile.
function browser() {
var userAgent = navigator.userAgent,
match = userAgent.match(/(opera|chrome|crios|safari|ucbrowser|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
result = {},
tem;
if (/trident/i.test(match[1])) {
tem = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
result.name = "Internet Explorer";
} else if (match[1] === "Chrome") {
tem = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
if (tem && tem[1]) {
result.name = tem[0].indexOf("Edge") === 0 ? "Edge" : "Opera";
}
}
if (!result.name) {
tem = userAgent.match(/version\/(\d+)/i); // iOS support
result.name = match[0].replace(/\/.*/, "");
if (result.name.indexOf("MSIE") === 0) {
result.name = "Internet Explorer";
}
if (userAgent.match("CriOS")) {
result.name = "Chrome";
}
}
if (tem && tem.length) {
match[match.length - 1] = tem[tem.length - 1];
}
result.version = Number(match[match.length - 1]);
return result;
}
I want to share this code I wrote for the issue I had to resolve. It was tested in most of the major browsers and works like a charm, for me!
It may seems that this code is very similar to the other answers but it modifyed so that I can use it insted of the browser object in jquery which missed for me recently, of course it is a combination from the above codes, with little improvements from my part I made:
(function($, ua){
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
tem,
res;
if(/trident/i.test(M[1])){
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
res = 'IE ' + (tem[1] || '');
}
else if(M[1] === 'Chrome'){
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem != null)
res = tem.slice(1).join(' ').replace('OPR', 'Opera');
else
res = [M[1], M[2]];
}
else {
M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
res = M;
}
res = typeof res === 'string'? res.split(' ') : res;
$.browser = {
name: res[0],
version: res[1],
msie: /msie|ie/i.test(res[0]),
firefox: /firefox/i.test(res[0]),
opera: /opera/i.test(res[0]),
chrome: /chrome/i.test(res[0]),
edge: /edge/i.test(res[0])
}
})(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);
console.log($.browser.name, $.browser.version, $.browser.msie);
// if IE 11 output is: IE 11 true
navigator.sayswho= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
console.log(navigator.sayswho); // outputs: `Chrome 62`
I use this to get de Name and number (int) of the version of the actual browser:
function getInfoBrowser() {
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return { name: 'Explorer', version: parseInt((tem[1] || '')) };
}
if (M[1] === 'Chrome') {
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if (tem != null) { let app = tem.slice(1).toString().split(','); return { name: app[0].replace('OPR', 'Opera'), version: parseInt(app[1]) }; }
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
return {
name: M[0],
version: parseInt(M[1])
};
}
function getBrowser(){
let info = getInfoBrowser();
$("#i-name").html(info.name);
$("#i-version").html(info.version);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" onclick="getBrowser();" value="Get Info Browser"/>
<hr/>
Name: <span id="i-name"></span><br/>
Version: <span id="i-version"></span>
This run in
Chrome ; Firefox ; Safari ; Internet Explorer (>= 9) ; Opera ; Edge
For me.
For any PWA application using angular you can put the code to check if browser is supported or not in body section of index.html -
<body>
<div id="browser"></div>
<script>
var operabrowser = true;
operabrowser = (navigator.userAgent.indexOf('Opera Mini') > -1);
if (operabrowser) {
txt = "<p>Browser not supported use different browser...</p>";
document.getElementById("browser").innerHTML = txt;
}
</script>
</body>
var ua = navigator.userAgent;
if (/Firefox\//.test(ua))
var Firefox = /Firefox\/([0-9\.A-z]+)/.exec(ua)[1];
I wrote this for my needs.
It get info like if is a mobile device or if has a retina display
try it
var nav = {
isMobile:function(){
return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) != null);
},
isDesktop:function(){
return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) == null);
},
isAndroid: function() {
return navigator.userAgent.match(/Android/i);
},
isBlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
isIOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
isOpera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
isWindows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
isRetina:function(){
return window.devicePixelRatio && window.devicePixelRatio > 1;
},
isIPad:function(){
isIPad = (/ipad/gi).test(navigator.platform);
return isIPad;
},
isLandscape:function(){
if(window.innerHeight < window.innerWidth){
return true;
}
return false;
},
getIOSVersion:function(){
if(this.isIOS()){
var OSVersion = navigator.appVersion.match(/OS (\d+_\d+)/i);
OSVersion = OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0;
return OSVersion;
}
else
return false;
},
isStandAlone:function(){
if(_.is(navigator.standalone))
return navigator.standalone;
return false;
},
isChrome:function(){
var isChrome = (/Chrome/gi).test(navigator.appVersion);
var isSafari = (/Safari/gi).test(navigator.appVersion)
return isChrome && isSafari;
},
isSafari:function(){
var isSafari = (/Safari/gi).test(navigator.appVersion)
var isChrome = (/Chrome/gi).test(navigator.appVersion)
return !isChrome && isSafari;
}
}
I use this piece of javascript code based on what I could find in another posts.
var browserHelper = function () {
var self = {};
/// IE 6+
self.isIEBrowser = function () {
return /*#cc_on!#*/false || !!document.documentMode;
};
/// Opera 8.0+
self.isOperaBrowser = function () {
return (!!window.opr && !!opr.addons)
|| !!window.opera
|| navigator.userAgent.indexOf(' OPR/') >= 0;
};
/// Firefox 1.0+
self.isFirefoxBrowser = function () {
return typeof InstallTrigger !== 'undefined';
};
/// Safari 3.0+
self.isSafariBrowser = function () {
return /constructor/i.test(window.HTMLElement)
|| (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
};
/// Edge 20+
self.isEdgeBrowser = function () {
return !self.isIEBrowser() && !!window.StyleMedia;
};
/// Chrome 1 - 87
self.isChromeBrowser = function () {
return (!!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime))
|| (navigator.userAgent.indexOf("Chrome") > -1) && !self.isOperaBrowser();
};
/// Edge (based on chromium)
self.isEdgeChromiumBrowser = function () {
return self.isChromeBrowser() && (navigator.userAgent.indexOf("Edg") != -1);
};
/// Blink
self.isBlinkBasedOnBrowser = function () {
return (self.isChromeBrowser() || self.isOperaBrowser()) && !!window.CSS;
};
/// Returns the name of the navigator
self.browserName = function () {
if (self.isOperaBrowser()) return "Opera";
if (self.isEdgeBrowser()) return "Edge";
if (self.isEdgeChromiumBrowser()) return "Edge (based on chromium)";
if (self.isFirefoxBrowser()) return "Firefox";
if (self.isIEBrowser()) return "Internet Explorer";
if (self.isSafariBrowser()) return "Safari";
if (self.isChromeBrowser()) return "Chrome";
return "Unknown";
};
return self;
};
var bName = document.getElementById('browserName');
bName.innerText = browserHelper().browserName();
#browserName {
font-family: Arial, Verdana;
font-size: 1.2rem;
color: #ff8000;
text-align: center;
border: 2px solid #ff8000;
border-radius: .5rem;
padding: .5rem;
max-width: 25%;
margin: auto;
}
<div id="browserName"></div>
For chromium browser is so simple.
Version : navigator.userAgentData.brands[0].version
Browser Name : navigator.userAgentData.brands[0].brand
This got me the version of Firefox,
let versionNumber = parseInt(window.navigator.userAgent.match(/Firefox\/([0-
9]+)\./)[1]);

Categories

Resources