What is the best way to detect websocket support using Javascript? - javascript

I'm trying to use Javascript to detect if a web browser supports websockets, but using only feature-based detection, I'm getting false positives, so I added a user agent test to throw out Android devices instead, which I'm not happy about. I have a Samsung Galaxy Tab 2, and here's my detection code:
var isSupported = (("WebSocket" in window && window.WebSocket != undefined) ||
("MozWebSocket" in window));
/* This line exists because my Galaxy Tab 2 would otherwise appear to have support. */
if (isSupported && navigator.userAgent.indexOf("Android") > 0)
isSupported = false;
if (isSupported)
document.write("Your browser supports websockets");
else
document.write("Your browser does not support websockets");
This code seems to work with IE, Firefox, Safari (including iPhone/iPad), and Chrome. However, the feature-based check is returning true when I use the default browser of my Samsung Galaxy Tab 2, which is incorrect because that browser does not actually support websockets. Furthermore, I don't know how many other Android devices have this same issue, so at the moment, this is the best solution I'm aware of for detection.
Is there a better way to detect websocket support other than what I'm doing? I do realize that workarounds exist for Android, such as using a different browser, which means my user agent detection code as-is would not be a good thing. My goal is to not have to rely on the user agent in the first place.
Any suggestions?

This is the shortest solution and is used by Modernizr. Simply add this to your code
supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window;
then you can use it by running
if (supportsWebSockets) {
// run web socket code
}

I think the Modernizr library is what you are looking for: http://modernizr.com/
Once you include the library on your page, you can use a simple check like:
if(Modernizr.websockets){
// socket to me baby
}

This page comes on top in google search.
In year 2016 cutting the mustard for modern WebSockets implementation (no prefixes such as MozWebSocket) would be
if (
'WebSocket' in window && window.WebSocket.CLOSING === 2
) {
// supported
}
http://www.w3.org/TR/websockets/#the-websocket-interface

after reading #gzost's response.. I started tinkering.. since nothing else can properly detect WS's on my android phone... even websocket.org says i have it, but then fails to connect.
Anyways, try this workaround.. seems to properly detect it on/off with chrome, FF, safari and the default android browser.
var has_ws=0;
function checkWebSocket(){
try{
websocket = new WebSocket("ws:websocket.org");
websocket.close('');
}catch(e){ //throws code 15 if has socket to me babies
has_ws=1;
}
}
$(document).ready(function(){
checkWebSocket();
});

None of the above answers by itself was sufficient in my tests. The following code seems to be working fine:
function nll( o ) { return CS.undefined === typeof o || null === o; }
// ...
function check_ws_object() {
try {
var websocket = new WebSocket( "wss://echo.websocket.org" );
return true;
} catch ( e ) { ; }
return false;
}
//
function check_support() {
if ( !( WebSocket in window ) ) {
if ( nll( window.WebSocket) ) {
if ( !this.check_ws_object() ) {
alert( "This browser doesn't support HTML5 Web Sockets!" );
return false;
}
}
}
return true;
},
The above tests are sorted, so that the faster ones come first.

Related

How to detect if webkitSpeechRecognition actually works in a browser

Edge claims to support webkitSpeechRecognition, but it doesn't work (discussion here, doesn't work on websites meant for testing, like this mozilla one, with the error "Error occurred in recognition: language-not-supported" despite my US english UI).
How can I detect if webkitSpeechRecognition is actually supported? I tried to filter out Edge by looking at the user agent, but it shows up as Chrome, and I'd prefer to just use feature detection rather than looking at the user agent anyway. I'd like to check this without requesting microphone permission (if I did request microphone permission, I'd have to wait for them to accept, and then see the language-not-supported error). Is there a simple way to check this, similar to just checking the value of window["webkitSpeechRecognition"] (which is defined in Edge, despite not working)?
If you want to check the support for webkitSpeechRecognition then you can refer to the JS code example below.
if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)
{
console.log("speech recognition API supported");
}
else
{
console.log("speech recognition API not supported")
}
Output in MS Edge 88.0.705.56:
However, if you directly try to make a test using webkitSpeechRecognition then it will not work.
It looks like this feature is currently under development and to use it we need to enable it by passing the command line arguments.
I suggest you refer to the steps below.
Create a shortcut of the Edge chromium-browser.
Right-click the shortcut file and go to Properties.
Under Shortcut tab, in the Target textbox, add --enable-features=msSpeechRecognition after the msedge.exe path. Make sure to add 1 space between the path and command-line argument.
It should look like below.
Click on the OK button to close the properties window.
Launch the Edge browser via shortcut and visit any sample code example for SpeechRecognition. Here I am making a test with this example.
Output in MS Edge 88.0.705.56:
In addition, it's useful to check for errors (as shown in the above example source code, see below, https://www.google.com/intl/en/chrome/demos/speech.html): for instance audio might be disabled if not on a https website.
recognition.onerror = function(event) {
if (event.error == 'no-speech') {
start_img.src = '/intl/en/chrome/assets/common/images/content/mic.gif';
showInfo('info_no_speech');
ignore_onend = true;
}
if (event.error == 'audio-capture') {
start_img.src = '/intl/en/chrome/assets/common/images/content/mic.gif';
showInfo('info_no_microphone');
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
showInfo('info_blocked');
} else {
showInfo('info_denied');
}
ignore_onend = true;
}
};

Checking the user browser using javascript on body load [duplicate]

I need some function returning a boolean value to check if the browser is Chrome.
How do I create such functionality?
To check if browser is Google Chrome, try this:
// please note,
// that IE11 now returns undefined again for window.chrome
// and new Opera 30 outputs true for window.chrome
// but needs to check if window.opr is not undefined
// and new IE Edge outputs to true now for window.chrome
// and if not iOS Chrome check
// so use the below updated condition
var isChromium = window.chrome;
var winNav = window.navigator;
var vendorName = winNav.vendor;
var isOpera = typeof window.opr !== "undefined";
var isIEedge = winNav.userAgent.indexOf("Edg") > -1;
var isIOSChrome = winNav.userAgent.match("CriOS");
if (isIOSChrome) {
// is Google Chrome on IOS
} else if(
isChromium !== null &&
typeof isChromium !== "undefined" &&
vendorName === "Google Inc." &&
isOpera === false &&
isIEedge === false
) {
// is Google Chrome
} else {
// not Google Chrome
}
Example of use: https://codepen.io/jonathan/pen/RwQXZxJ?editors=1111
The reason this works is because if you use the Google Chrome inspector and go to the console tab. Type 'window' and press enter. Then you be able to view the DOM properties for the 'window object'. When you collapse the object you can view all the properties, including the 'chrome' property.
You can't use strictly equals true anymore to check in IE for window.chrome. IE used to return undefined, now it returns true. But guess what, IE11 now returns undefined again. IE11 also returns a empty string "" for window.navigator.vendor.
UPDATE:
Thank you to Halcyon991 for pointing out below, that the new Opera 18+ also outputs to true for window.chrome. Looks like Opera 18 is based on Chromium 31. So I added a check to make sure the window.navigator.vendor is: "Google Inc" and not is "Opera Software ASA". Also thanks to Ring and Adrien Be for the heads up about Chrome 33 not returning true anymore... window.chrome now checks if not null. But play close attention to IE11, I added the check back for undefined since IE11 now outputs undefined, like it did when first released.. then after some update builds it outputted to true .. now recent update build is outputting undefined again. Microsoft can't make up it's mind!
UPDATE 7/24/2015 - addition for Opera check
Opera 30 was just released. It no longer outputs window.opera. And also window.chrome outputs to true in the new Opera 30. So you must check if OPR is in the userAgent. I updated my condition above to account for this new change in Opera 30, since it uses same render engine as Google Chrome.
UPDATE 10/13/2015 - addition for IE check
Added check for IE Edge due to it outputting true for window.chrome .. even though IE11 outputs undefined for window.chrome. Thanks to artfulhacker for letting us know about this!
UPDATE 2/5/2016 - addition for iOS Chrome check
Added check for iOS Chrome check CriOS due to it outputting true for Chrome on iOS. Thanks to xinthose for letting us know about this!
UPDATE 4/18/2018 - change for Opera check
Edited check for Opera, checking window.opr is not undefined since now Chrome 66 has OPR in window.navigator.vendor. Thanks to Frosty Z and Daniel Wallman for reporting this!
Update: Please see Jonathan's answer for an updated way to handle this. The answer below may still work, but it could likely trigger some false positives in other browsers.
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
However, as mentioned User Agents can be spoofed so it is always best to use feature-detection (e.g. Modernizer) when handling these issues, as other answers mention.
If you want to detect Chrome's rendering engine (so not specific features in Google Chrome or Chromium), a simple option is:
var isChrome = !!window.chrome;
NOTE: this also returns true for many versions of Edge, Opera, etc that are based on Chrome (thanks #Carrm for pointing this out). Avoiding that is an ongoing battle (see window.opr below) so you should ask yourself if you're trying to detect the rendering engine (used by almost all major modern browsers in 2020) or some other Chrome (or Chromium?) -specific feature.
And you can probably skip !!
even shorter: var is_chrome = /chrome/i.test( navigator.userAgent );
console.log(JSON.stringify({
isAndroid: /Android/.test(navigator.userAgent),
isCordova: !!window.cordova,
isEdge: /Edge/.test(navigator.userAgent),
isFirefox: /Firefox/.test(navigator.userAgent),
isChrome: /Google Inc/.test(navigator.vendor),
isChromeIOS: /CriOS/.test(navigator.userAgent),
isChromiumBased: !!window.chrome && !/Edge/.test(navigator.userAgent),
isIE: /Trident/.test(navigator.userAgent),
isIOS: /(iPhone|iPad|iPod)/.test(navigator.platform),
isOpera: /OPR/.test(navigator.userAgent),
isSafari: /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent),
isTouchScreen: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
isWebComponentsSupported: 'registerElement' in document && 'import' in document.createElement('link') && 'content' in document.createElement('template')
}, null, ' '));
As of Chrome 89 (March 2021), all earlier answers are obsolete. Chrome now supports User Agent Hints. So now this should be done using:
navigator.userAgentData?.brands?.some(b => b.brand === 'Google Chrome')
Or, if you're not using Babel:
navigator.userAgentData && navigator.userAgentData.brands && navigator.userAgentData.brands.some(b => b.brand === 'Google Chrome')
This returns true for Chrome 89 and above, false for the latest Opera and Edge, and undefined for browsers that don't support userAgentData.
var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );~
This is an old answer, written more than 12 years back; as of now(i.e., August 2022)
Update(August 2022):
Nowadays, browser detection using user agent (user agent sniffing) is usually a bad idea. Feature detection should be the way to go.
Reference: Browser detection using the user agent
However, if you still wish to do so, use a third party library like
var parser = new UAParser();
var result = parser.getResult();
console.log(result.browser);// {name: "Chrome", version: "104.0.0.0", "major": "104"}
console.log(result.device); // {model: undefined, type: undefined, vendor: undefined}
console.log(result.os); // {name: "Windows", version: "10"}
console.log(result.engine); // {name: "Blink", version: "104.0.0.0"}
console.log(result.cpu); // {"architecture": "amd64"}
<script
src="https://cdnjs.cloudflare.com/ajax/libs/UAParser.js/1.0.2/ua-parser.min.js">
</script>
The above snippet use the library ua-parser-js
CDN - https://cdnjs.com/libraries/UAParser.js
npm - https://www.npmjs.com/package/ua-parser-js
P.S: Please note that UA sniffing is bad practice and use feature detection wherever possible.
You can use:
navigator.userAgent.indexOf("Chrome") != -1
It is working on v.71
If you're feeling brave, you can experiment with browser sniffing and get a version:
var ua = navigator.userAgent;
if(/chrome/i.test(ua)) {
var uaArray = ua.split(' ')
, version = uaArray[uaArray.length - 2].substr(7);
}
This detected version might be a Chrome version, or a Edge version, or something else. Browser plugins can easily change userAgent and platform and other things though, so this is not recommended.
Apologies to The Big Lebowski for using his answer within mine.
There are some optional window properties that that can be used when doing browser detection. One of them is the optional chrome property (Chromium) and the other the optional opr property (Opera).
If a browser has the optional chrome property on the Window object, it means the browser is a Chromium browser. Previously this meant Chrome in most cases, but these days many browsers are built on Chromium (including Edge and Opera) so only checking the presence of the property will not help to detect Chrome browsers specifically.
Then there are often several user-agents for different browser versions (Edg or Edge) or operation systems (EdgiOS, ChriOS and FxiOS).
I use the following logic and tested against a lot of cases (common user agents):
const GOOGLE_VENDOR_NAME = 'Google Inc.';
function isOpera(){
return Boolean(window.opr);
}
function isChromium() {
return Boolean(window.chrome);
}
function getBrowserName() {
const userAgent = window.navigator.userAgent;
const vendor = window.navigator.vendor;
switch (true) {
case /Edge|Edg|EdgiOS/.test(userAgent):
return 'Edge';
case /OPR|Opera/.test(userAgent) && isOpera():
return 'Opera';
case /CriOS/.test(userAgent):
case /Chrome/.test(userAgent) && vendor === GOOGLE_VENDOR_NAME && isChromium():
return 'Chrome';
case /Vivaldi/.test(userAgent):
return 'Vivaldi';
case /YaBrowser/.test(userAgent):
return 'Yandex';
case /Firefox|FxiOS/.test(userAgent):
return 'Firefox';
case /Safari/.test(userAgent):
return 'Safari';
case /MSIE|Trident/.test(userAgent):
return 'Internet Explorer';
default:
return 'Unknown';
}
}
function isChrome() {
const name = getBrowserName();
return name === 'Chrome';
}
You can find this simplified code in this fiddle:
The trick is to test against other browsers then Chrome (Edge, Opera) first. In all these cases in the switch the different possible identifiers for a browser are combined in one regular expression and tested against the user agent string. For Chrome and Opera additional tests for the window property are added and for Chrome we also check whether the vendor name matches the expected value.
Note: I tested against a lot of different user agents, but won't claim here that this solution is flawless. Any suggestions for improvements, or failing browser detections are welcome so I can further improve this code.
UPDATE:
Fixed bug with Chrome on iOS (user agent CriOS) detection. Chrome on iOS doesn't have the chrome: true property on the window object, so should only be tested for presence of the user agent string.
To check if browser is Google Chrome:
var isChrome = navigator.userAgent.includes("Chrome") && navigator.vendor.includes("Google Inc");
console.log(navigator.vendor);
// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36 "
console.log(navigator.userAgent);
// "Google Inc."
User could change user agent . Try testing for webkit prefixed property in style object of body element
if ("webkitAppearance" in document.body.style) {
// do stuff
}
Works for me on Chrome on Mac. Seems to be or simpler or more reliable (in case userAgent string tested) than all above.
var isChrome = false;
if (window.chrome && !window.opr){
isChrome = true;
}
console.log(isChrome);
To know the names of different desktop browsers (Firefox, IE, Opera, Edge, Chrome). Except Safari.
function getBrowserName() {
var browserName = '';
var userAgent = navigator.userAgent;
(typeof InstallTrigger !== 'undefined') && (browserName = 'Firefox');
( /* #cc_on!#*/ false || !!document.documentMode) && (browserName = 'IE');
(!!window.chrome && userAgent.match(/OPR/)) && (browserName = 'Opera');
(!!window.chrome && userAgent.match(/Edge/)) && (browserName = 'Edge');
(!!window.chrome && !userAgent.match(/(OPR|Edge)/)) && (browserName = 'Chrome');
/**
* Expected returns
* Firefox, Opera, Edge, Chrome
*/
return browserName;
}
Works in the following browser versions:
Opera - 58.0.3135.79
Firefox - 65.0.2 (64-bit)
IE - 11.413.15063 (JS Fiddle no longer supports IE just paste in Console)
Edge - 44.17763.1.0
Chrome - 72.0.3626.121 (Official Build) (64-bit)
View the gist here and the fiddle here
The original code snippet no longer worked for Chrome and I forgot where I found it. It had safari before but I no longer have access to safari so I cannot verify anymore.
Only the Firefox and IE codes were part of the original snippet.
The checking for Opera, Edge, and Chrome is straight forward. They have differences in the userAgent. OPR only exists in Opera. Edge only exists in Edge. So to check for Chrome these string shouldn't be there.
As for the Firefox and IE, I cannot explain what they do.
I'll be adding this functionality to a package i'm writing
The best solution I found, and does give either true or false in most browsers is:
var isChrome = (navigator.userAgent.indexOf("Chrome") != -1 && navigator.vendor.indexOf("Google Inc") != -1)
Using .indexOf instead of .includes makes it more browser-compatible.
Even though (or because) the whole point is to make your code browser-specific, you need the condition to work in most (or all) browsers.
now u can use navigator.userAgent.includes("Chrome")
Check this: How to detect Safari, Chrome, IE, Firefox and Opera browser?
In your case:
var isChrome = (window.chrome.webstore || window.chrome.runtime) && !!window.chrome;
var is_chrome = browseris.chrome
or check ather browsers:
browseris.firefox
browseris.ie
browseris.safari
and olso you can check the version like browseris.chrome7up and etc.
check all existing information in the 'browseris' object
all answers are wrong. "Opera" and "Chrome" are same in all cases.
(edited part)
here is the right answer
if (window.chrome && window.chrome.webstore) {
// this is Chrome
}

JavaScript and browser PDF support detection

I'm trying to get to work PDF support detection based on a browser where application is running.
First application is checking if a browser is not running on a mobile device. That part works fine - I'm getting Globals.bAllowPdfPreview = true
Then I try to execute code below
if (Globals.bAllowPdfPreview && window.navigator && window.navigator.mimeTypes)
{
Globals.bAllowPdfPreview = !!_.find(window.navigator.mimeTypes, function (oType) {
return oType && 'application/pdf' === oType.type;
});
if (!Globals.bAllowPdfPreview)
{
Globals.bAllowPdfPreview = (typeof window.navigator.mimeTypes['application/pdf'] !== 'undefined');
}
}
It works fine on Chrome but I'm not able to get it to work on FireFox or IE11 - it fails on both statements to verify.
Any tips why is not working?
It came up that Firefox is not working as Mozilla removed the application/pdf MIME type from navigator.mimeTypes object and for IE11 only application/futuresplash and application/x-shockwave-flash are available by default.

Detect if device is iOS

I'm wondering if it's possible to detect whether a browser is running on iOS, similar to how you can feature detect with Modernizr (although this is obviously device detection rather than feature detection).
Normally I would favour feature detection instead, but I need to find out whether a device is iOS because of the way they handle videos as per this question YouTube API not working with iPad / iPhone / non-Flash device
Detecting iOS
With iOS 13 iPad both User agent and platform strings are changed and differentiating between iPad and MacOS seems possible, so all answers below needs to take that into account now.
This might be the shortest alternative that also covers iOS 13:
function iOS() {
return [
'iPad Simulator',
'iPhone Simulator',
'iPod Simulator',
'iPad',
'iPhone',
'iPod'
].includes(navigator.platform)
// iPad on iOS 13 detection
|| (navigator.userAgent.includes("Mac") && "ontouchend" in document)
}
iOS will be either true or false
Worse option: User agent sniffing
User Agent sniffing is more dangerous and problems appear often.
On iPad iOS 13, the user agent is identical with that of a MacOS 13 computer, but if you ignore iPads this might work still for a while:
var iOS = !window.MSStream && /iPad|iPhone|iPod/.test(navigator.userAgent); // fails on iPad iOS 13
The !window.MSStream is to not incorrectly detect IE11, see here and here.
Note: Both navigator.userAgent and navigator.platform can be faked by the user or a browser extension.
Browser extensions to change userAgent or platform exist because websites use too heavy-handed detection and often disable some features even if the user's browser would otherwise be able to use that feature.
To de-escalate this conflict with users it's recommended to detect specifically for each case the exact features that your website needs. Then when the user gets a browser with the needed feature it will already work without additional code changes.
Detecting iOS version
The most common way of detecting the iOS version is by parsing it from the User Agent string. But there is also feature detection inference*;
We know for a fact that history API was introduced in iOS4 - matchMedia API in iOS5 - webAudio API in iOS6 - WebSpeech API in iOS7 and so on.
Note: The following code is not reliable and will break if any of these HTML5 features is deprecated in a newer iOS version. You have been warned!
function iOSversion() {
if (iOS) { // <-- Use the one here above
if (window.indexedDB) { return 'iOS 8 and up'; }
if (window.SpeechSynthesisUtterance) { return 'iOS 7'; }
if (window.webkitAudioContext) { return 'iOS 6'; }
if (window.matchMedia) { return 'iOS 5'; }
if (window.history && 'pushState' in window.history) { return 'iOS 4'; }
return 'iOS 3 or earlier';
}
return 'Not an iOS device';
}
After iOS 13 you should detect iOS devices like this, since iPad will not be detected as iOS devices by old ways (due to new "desktop" options, enabled by default):
let isIOS = /iPad|iPhone|iPod/.test(navigator.platform)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
The first condition for iOS < 13 or iPhone or iPad with disabled Desktop mode, the second condition for iPadOS 13 in the default configuration, since it position itself like Macintosh Intel, but actually is the only Macintosh with multi-touch.
Rather a hack than a real solution, but work reliably for me
P.S. As being said earlier, you probably should add IE checkup
let isIOS = (/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream
None of the previous answers here work for all major browsers on all versions of iOS, including iOS 13. Here is a solution that works for Safari, Chrome and Firefox for all iOS versions:
var isIOS = (function () {
var iosQuirkPresent = function () {
var audio = new Audio();
audio.volume = 0.5;
return audio.volume === 1; // volume cannot be changed from "1" on iOS 12 and below
};
var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
var isAppleDevice = navigator.userAgent.includes('Macintosh');
var isTouchScreen = navigator.maxTouchPoints >= 1; // true for iOS 13 (and hopefully beyond)
return isIOS || (isAppleDevice && (isTouchScreen || iosQuirkPresent()));
})();
Note that this code snippet was written with priority on readability, not conciseness or performance.
Explanation:
If the user agent contains any of "iPod|iPhone|iPad" then clearly the device is iOS. Otherwise, continue...
Any other user agent that does not contain "Macintosh" is not an Apple device and therefore cannot be iOS. Otherwise, it is an Apple device, so continue...
If maxTouchPoints has a value of 1 or greater then the Apple device has a touch screen and therefore must be iOS since there are no Macs with touch screens (kudos to kikiwora for mentioning maxTouchPoints). Note that maxTouchPoints is undefined for iOS 12 and below, so we need a different solution for that scenario...
iOS 12 and below has a quirk that does not exist in Mac OS. The quirk is that the volume property of an Audio element cannot be successfully set to any value other than 1. This is because Apple does not allow volume changes on the Audio element for iOS devices, but does for Mac OS. That quirk can be used as the final fallback method for distinguishing an iOS device from a Mac OS device.
This sets the variable _iOSDevice to true or false
_iOSDevice = !!navigator.platform.match(/iPhone|iPod|iPad/);
If you are using Modernizr, you can add a custom test for it.
It doesn't matter which detection mode you decide to use (userAgent, navigator.vendor or navigator.platform), you can always wrap it up for a easier use later.
//Add Modernizr test
Modernizr.addTest('isios', function() {
return navigator.userAgent.match(/(iPad|iPhone|iPod)/g);
});
//usage
if (Modernizr.isios) {
//this adds ios class to body
Modernizr.prefixed('ios');
} else {
//this adds notios class to body
Modernizr.prefixed('notios');
}
A simplified, easy to extend version.
var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
UPDATE: My original answer doesn't cover iPad in desktop mode (the default changes to desktop mode in upcoming iPadOSĀ 13 and higher).
That's fine for my usecases, if it's not for you, use this update:
// iPhone and iPad including iPadOS 13+ regardless of desktop mode settings
iOSiPadOS = /^iP/.test(navigator.platform) ||
/^Mac/.test(navigator.platform) && navigator.maxTouchPoints > 4;
This should be safe as long as
desktop Macs don't support touch events at all
or not more than 4 touch points (current iOS devices support 5 touch points)
It's fast because the regexp ^ first checks the starting position of the platform string and stops if there is no "iP" (faster than searching the long UA string until the end anyway)
It's safer than navigator.userAgent check as navigator.platform is much less likely faked
Detects iPhone / iPad Simulator
ORIGINAL ANSWER: Wow, a lot of longish tricky code here. Keep it simple, please!
This one is IMHO fast, save, and working well:
iOS = /^iP/.test(navigator.platform);
// or, if you prefer it verbose:
iOS = /^(iPhone|iPad|iPod)/.test(navigator.platform);
Detecting iOS (both <12, and 13+)
Community wiki, as edit queue says it is full and all other answers are currently outdated or incomplete.
const iOS_1to12 = /iPad|iPhone|iPod/.test(navigator.platform);
const iOS13_iPad = (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1));
const iOS1to12quirk = function() {
var audio = new Audio(); // temporary Audio object
audio.volume = 0.5; // has no effect on iOS <= 12
return audio.volume === 1;
};
const isIOS = !window.MSStream && (iOS_1to12 || iOS13_iPad || iOS1to12quirk());
It's probably worth answering that iPads running iOS 13 will have navigator.platform set to MacIntel, which means you'll need to find another way to detect iPadOS devices.
I wrote this a couple years ago but i believe it still works:
if(navigator.vendor != null && navigator.vendor.match(/Apple Computer, Inc./) && navigator.userAgent.match(/iPhone/i) || (navigator.userAgent.match(/iPod/i)))
{
alert("Ipod or Iphone");
}
else if (navigator.vendor != null && navigator.vendor.match(/Apple Computer, Inc./) && navigator.userAgent.match(/iPad/i))
{
alert("Ipad");
}
else if (navigator.vendor != null && navigator.vendor.match(/Apple Computer, Inc./) && navigator.userAgent.indexOf('Safari') != -1)
{
alert("Safari");
}
else if (navigator.vendor == null || navigator.vendor != null)
{
alert("Not Apple Based Browser");
}
Wherever possible when adding Modernizr tests you should add a test for a feature, rather than a device or operating system. There's nothing wrong with adding ten tests all testing for iPhone if that's what it takes. Some things just can't be feature detected.
Modernizr.addTest('inpagevideo', function ()
{
return navigator.userAgent.match(/(iPhone|iPod)/g) ? false : true;
});
For instance on the iPhone (not the iPad) video cannot be played inline on a webpage, it opens up full screen. So I created a test 'no-inpage-video'
You can then use this in css (Modernizr adds a class .no-inpagevideo to the <html> tag if the test fails)
.no-inpagevideo video.product-video
{
display: none;
}
This will hide the video on iPhone (what I'm actually doing in this case is showing an alternative image with an onclick to play the video - I just don't want the default video player and play button to show).
There is no need to test navigator.userAgent or navigator.platform:
const isIOS = typeof navigator.standalone === 'boolean';
navigator.standalone is only set on iOS Safari. See MDN, Safari HTML Reference.
If you're using React, There is great library for this kind of issues: REACT-UGENT. (Built with ua-parser-js.)
https://github.com/medipass/react-ugent
Available browsers are:
chrome, chromium, edge, firefox, ie, lynx, safari, opera
Available OS are:
android, blackberry, chromium os, debian, ios, linux, mac os, ubuntu, unix, windows
Available devices are:
console, computer, mobile, tablet, smarttv, wearable, embedded
Easy to use as:
<Ugent browser="safari" os="ios">
<div>
This text only shows on Safari on iOS.
</div>
</Ugent>
If you're not using React, basically, you can use - ua-parser-js
https://github.com/faisalman/ua-parser-js
The user-agents on iOS devices say iPhone or iPad in them. I just filter based on those keywords.
If you are still trying to check if is iOS or not, I recommend you to use this approach:
Create a folder called helper
Create a file called platform.ts or platform.js
Export the function isIOS:
export const isIOS = () => {
let platform = navigator?.userAgent || navigator?.platform || 'unknown'
return /iPhone|iPod|iPad/.test(platform)
}
The result will be true if is an iPhone or iPod or Ipad or it will be false otherwise.
You may ask, why do I need to check navigator.userAgent || navigator.platform, well the reason is simple the second option used to be the default one but now it is deprecated and some browsers will stop supporting this in the future, the first one is more reliable.
You can check here about the deprecation that I mentioned above:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform#:~:text=Deprecated%3A%20This%20feature%20is%20no,be%20kept%20for%20compatibility%20purposes.
Logging the userAgentData, userAgent and platform.
Using the function below, I received these logs:
console.log({
userAgentData: navigator?.userAgentData?.platform,
userAgent: navigator?.userAgent,
platform: navigator?.platform,
})
{
"userAgentData": "",
"userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
"platform": "MacIntel"
}
I was testing it on my Macbook and it worked on different browsers and operation systems. So, as you can see navigator?.userAgentData?.platform will not work at all.
I also didn't receive any errors related to my typescript, even though that I am using React to call this function.
Bonus, isAndroid
If you wondering how to check if is an Android platform, I suggest you don't follow the idea of doing the opposite of isIOS as:
const isAndroid = !isIOS();
The reason is quite simple, it will not work since desktops will be recognized as an Android platform.
To solve this problem you just need to do this check:
export const isAndroid = () => {
const ua = navigator.userAgent.toLowerCase() + navigator?.platform.toLowerCase();
const isAndroid = ua.indexOf("android") > -1;
return isAndroid;
}
The reason why we are checking navigator.userAgent plus navigator?.platform is to support old browsers and the new ones.
You can also use includes
const isApple = ['iPhone', 'iPad', 'iPod', 'iPad Simulator', 'iPhone Simulator', 'iPod Simulator',].includes(navigator.platform)
Because navigator.platform is deprecated and it is better to not use it anymore, I want to add an other solution.
You can filter on MacOS systems by checking the navigator.vendor.
When the outcome is Apple Computer, Inc., you know it is MacOS.
In my case the user agent was not good enought since in the Ipad the user agent was the same as in Mac OS, therefore I had to do a nasty trick:
var mql = window.matchMedia("(orientation: landscape)");
/**
* If we are in landscape but the height is bigger than width
*/
if(mql.matches && window.screen.height > window.screen.width) {
// IOS
} else {
// Mac OS
}
In order to detect the iOS version, one has to destructure the user agent with a Javascript code like this:
var res = navigator.userAgent.match(/; CPU.*OS (\d_\d)/);
if(res) {
var strVer = res[res.length-1];
strVer = strVer.replace("_", ".");
version = strVer * 1;
}
var isiOSSafari = (navigator.userAgent.match(/like Mac OS X/i)) ? true: false;

How to check if a custom protocol supported

We are using software that registers its own protocol. We can run application from browser then by link like:
customprotocol://do_this.
but is there a way to check is such custom protocol supported by user`s system? If not we would like to ask user to install software first.
E.g:
if (canHandle ('customprotocol')) {
// run software
}
else {
// ask to install
}
Edit
I know about protocolLong property but it works only in IE.
Unfortunately, there's no easy way of achieving this. There's certainly no method of pre-determining whether or not the protocol handler is installed.
Internet Explorer, as you mentioned, has the protocolLong property but I'm having trouble getting it to return anything other than "Unknown Protocol" for all custom protocol handlers -- if anyone knows how to get IE to return the correct value please let me know so I can update this section. The best solution I've found with IE is to append to the user agent string or install a browser extension along with your app that exposes a Javascript accessible property.
Firefox is by far the easiest of the major browsers, as it will allow you to try and catch a navigation attempt that fails. The error object returned contains a name property whose value is NS_ERROR_UNKNOWN_PROTOCOL:
try {
iframe.contentWindow.location.href = "randomprotocolstring://test/";
} catch(e) {
if (e.name == "NS_ERROR_UNKNOWN_PROTOCOL")
window.location = "/download/";
}
Firefox will pop up with its own alert box:
Firefox doesn't know how to open this address, because the protocol (randomprotocolstring) isn't associated with any program.
Once you close this box, the catch block will execute and you have a working fallback.
Second is Opera, which allows you to employ the laws of predictability to detect success of a custom protocol link clicked. If a custom protocol click works, the page will remain the same location. If there is no handler installed, Opera will navigate to an error page. This makes it rather easy to detect with an iframe:
iframe.contentWindow.location = "randomprotocolstring://test/";
window.setTimeout(function () {
try {
alert(ifr.contentWindow.location);
} catch (e) { window.location = "/download/"; }
}, 0);
The setTimeout here is to make sure we check the location after navigation. It's important to note that if you try and access the page, Opera throws a ReferenceException (cross-domain security error). That doesn't matter, because all we need to know is that the location changed from about:blank, so a try...catch works just fine.
Chrome officially sucks with this regard. If a custom protocol handler fails, it does absolutely zip. If the handler works... you guessed it... it does absolutely zip. No way of differentiating between the two, I'm afraid.
I haven't tested Safari but I fear it would be the same as Chrome.
You're welcome to try the test code I wrote whilst investigating this (I had a vested interest in it myself). It's Opera and Firefox cross compatible but currently does nothing in IE and Chrome.
Here's an off-the-wall answer: Install an unusual font at the time you register your custom protocol. Then use javascript to check whether that font exists, using something like this.
Sure it's a hack, but unlike the other answers it would work across browsers and operating systems.
Just to chime in with our own experience, we used FireBreath to create a simple cross-platform plugin. Once installed this plugin registers a mime type which can be detected from the browser javascript after a page refresh. Detection of the mime type indicates that the protocol handler is installed.
if(IE) { //This bastard always needs special treatment
try {
var flash = new ActiveXObject("Plugin.Name");
} catch (e) {
//not installed
}
else { //firefox,chrome,opera
navigator.plugins.refresh(true);
var mimeTypes = navigator.mimeTypes;
var mime = navigator.mimeTypes['application/x-plugin-name'];
if(mime) {
//installed
} else {
//not installed
}
}
Internet Explorer 10 on Windows 8 introduced the very useful navigator.msLaunchUri method for launching a custom protocol URL and detecting the success or failure. For example:
if (typeof (navigator.msLaunchUri) == typeof (Function)) {
navigator.msLaunchUri(witchUrl,
function () { /* Success */ },
function () { /* Failure */ showError(); });
return;
}
Windows 7 / IE 9 and below support conditional comments as suggested by #mark-kahn.
For Internet Explorer, the best solution I've found is to use Conditionl comments & Version Vector (application must write something to registry while installing protocol, see http://msdn.microsoft.com/en-us/library/ms537512.aspx#Version_Vectors). protocolLong doesn't work for custom protocol.
On mobile you can use an embedded iframe to auto switch between the custom protocol and a known one (web or app store), see https://gist.github.com/2662899
I just want to explain more previous Mark's answer (some people did not understand for example user7892745).
1) When you launch you web-page or web-application it checks for an unusual font (something like Chinese Konfuciuz font http://www.fontspace.com/apostrophic-lab/konfuciuz).
Below is the code of sample web-page with function which checks the font (called isFontAvailable):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
/**
* Checks if a font is available to be used on a web page.
*
* #param {String} fontName The name of the font to check
* #return {Boolean}
* #license MIT
* #copyright Sam Clarke 2013
* #author Sam Clarke <sam#samclarke.com>
*/
(function (document) {
var width;
var body = document.body;
var container = document.createElement('span');
container.innerHTML = Array(100).join('wi');
container.style.cssText = [
'position:absolute',
'width:auto',
'font-size:128px',
'left:-99999px'
].join(' !important;');
var getWidth = function (fontFamily) {
container.style.fontFamily = fontFamily;
body.appendChild(container);
width = container.clientWidth;
body.removeChild(container);
return width;
};
// Pre compute the widths of monospace, serif & sans-serif
// to improve performance.
var monoWidth = getWidth('monospace');
var serifWidth = getWidth('serif');
var sansWidth = getWidth('sans-serif');
window.isFontAvailable = function (font) {
return monoWidth !== getWidth(font + ',monospace') ||
sansWidth !== getWidth(font + ',sans-serif') ||
serifWidth !== getWidth(font + ',serif');
};
})(document);
function isProtocolAvailable()
{
if (isFontAvailable('Konfuciuz'))
{
return true;
}
else
{
return false;
}
}
function checkProtocolAvail()
{
if (isProtocolAvailable())
{
alert('Custom protocol is available!');
}
else
{
alert('Please run executable to install protocol!');
}
}
</script>
<h3>Check if custom protocol was installed or not</h3>
<pre>
<input type="button" value="Check if custom protocol was installed!" onclick="checkProtocolAvail()">
</body>
</html>
2) First time when user opens this page, font will not be installed so he will get a message saying "Please run executable to install custom protocol...".
3) He will run executable which will install the font. Your exe can just copy the font file (in my case it is KONFUC__.ttf) into C:\Windows directory or using a code like this (example on Delphi):
// Adding the font ..
AddFontResource(PChar('XXXFont.TTF'));
SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
4) After that, when user runs web app again, he gets "Custom protocol is available!" message because font was installed this time.
Tested on Google Chrome, Internet Explorer and Firefox - working great!
For Firefox, most of articles I googled, including Andy E 's answer here, and this gist Cross-browser implementation of navigator.msLaunchUri or https://github.com/ismailhabib/custom-protocol-detection using
iframe.contentWindow.location.href = uri
But it has stopped working since Firefox 64, e.g here https://github.com/ismailhabib/custom-protocol-detection/issues/37 also confirmed that.
So FF 64+ I found I can either using Chrome's method, blurHandler or using the post there https://github.com/ismailhabib/custom-protocol-detection/issues/37#issuecomment-617962659
try {
iframe.contentWindow.location.href = uri;
setTimeout(function () {
try {
if (iframe.contentWindow.location.protocol === "about:") {
successCb();
} else {
failCb();
}
} catch (e) {
if (e.name === "NS_ERROR_UNKNOWN_PROTOCOL" ||
e.name === "NS_ERROR_FAILURE" || e.name === "SecurityError") {
failCb();
}
}
}, 500);
} catch (e) {
if (e.name === "NS_ERROR_UNKNOWN_PROTOCOL" || e.name === "NS_ERROR_FAILURE"
|| e.name === "SecurityError") {
failCb();
}
}
For Chrome 86+ it also fails to work, check my answer for details Detect Custom Protocol handler in chrome 86
BTW, I find most of answers/articles are outdated in some cases.

Categories