JavaScript and browser PDF support detection - javascript

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.

Related

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
}

Download files (movies) with Internet Explorer

A page contains a player where you can view videos from a given list. Videos which are currently running in the player should be downloadable to disk. So there is a button download beside the player which starts a pure javascript function downloadClip(). This is the code :
function downloadClip() {
if (media.currentSrc="") return;
var url =media.currentSrc;
var file = url.substring(url.lastIndexOf('/')+1);
// Mac -> works with Safari 8.0.6, FireFox 37.0.2, Chrome 41.0.2272.64
// WIN -> works with FireFox 38.0.5, Chrome 43.0.2357.130m
if (!window.ActiveXObject) {
var hyperlink = document.createElement('a');
hyperlink.href = 'loadmovie.php?file='+file;
hyperlink.download = file;
var mouseEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
hyperlink.dispatchEvent(mouseEvent);
}
// for IE
else
if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(media.currentSrc, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, url || media.currentSrc)
_window.close();
}
}
I got this script here from SA but I must say I do not know if this is the best (simple) way to download files. Anyway it works fine for browser noted above.
My problem is IE. As I found out ActiveXObject is hidden from the DOM starting with IE11 , as written here. But I only have access to IE11 on a provided laptop and I cant test earlier vesions. So I am asking if anyone can give me hints / support to the question how to download files to disk with :
a) IE11 (no ActiveXObject support anymore
b) IE10 and before.
Please note: I use only pure js
Any link to official docs and code samples are welcome.

What is the best way to detect websocket support using 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.

How can I check if the browser support HTML5 file upload (FormData object)?

How can I check if the browser support HTML5 file upload (FormData object)?
var fd = new FormData();
Following the answer from this post, but the code does not return correct answer about the browser,
window.onload = function()
{
if (!!window.FileReader)
{
alert('supported');
}
else
{
alert('not supported');
}
}
Firefox - supported
Chrome - supported
Opera - supported
Safari - not supported
IE9 - not supported
But the correct browser support should be,
Firefox - supported
Chrome - supported
Opera - not supported
Safari - supported
IE9 - not supported
I have tested the html 5 file upload on Opera and it is not working for sure.
I am sure that safari supports html 5 file upload.
Try if( window.FormData === undefined ) or if( window.FormData !== undefined ).
From
http://blog.new-bamboo.co.uk/2010/7/30/html5-powered-ajax-file-uploads
function supportAjaxUploadProgressEvents() {
var xhr = new XMLHttpRequest();
return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
};
As FormData, the ability to send() one, and the upload property (and its onprogress event) are all part of XMLHttpRequest level 2, you can test for .upload to see if you've got a level 2. I don't have a Mac handy, but the function (sadly, but correctly) returns false for Opera 11.50 (and true for Firefox 4).
function supportFormData() {
return !! window.FormData;
}
Source: https://www.new-bamboo.co.uk/blog/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata/
This is the one-liner I use to check if the browser supports FormData and upload progress, in jQuery:
var xhr2 = !! ( window.FormData && ("upload" in ($.ajaxSettings.xhr()) );
You could may be use the workaround provided by this library.
https://github.com/francois2metz/html5-formdata
On Safari 5.1.7 , Firefox <6, Opera < 12.14 form data is suported but it is buggy.
Safari will return file size 0
Opera does not support append method of form data
firefox <6 does not work correctly
You need to check if the browser supports the HTML5 file API. I do that by checking if the FileReader function is set, if it’s not set it means that the browser won’t support the file API.
// Check if window.fileReader exists to make sure the browser supports file uploads
if (typeof(window.FileReader) == 'undefined')
{
alert'Browser does not support HTML5 file uploads!');
}

Browser Detection via JS for Safari 5

How can I check if the user's current browser is Safari 5?
Update
We have a check on our site that displays a "Browser not supported" message if the user is using an older browser. Currently our error is showing up for the latest Safari and it shouldn't be.
If you indeed want to do this, you can check the User Agent along the same lines Ext uses to do it.
A snippet from Ext.js:
ua = navigator.userAgent.toLowerCase(),
check = function(r){
return r.test(ua);
},
DOC = document,
isStrict = DOC.compatMode == "CSS1Compat",
isOpera = check(/opera/),
isChrome = check(/\bchrome\b/),
isWebKit = check(/webkit/),
isSafari = !isChrome && check(/safari/),
isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
isSafari3 = isSafari && check(/version\/3/),
isSafari4 = isSafari && check(/version\/4/),
I'm guessing for Safari 5 you could write a similar test where version would be 5, though I did not check what Safari 5's User Agent string looks like myself.
See:
jsBrowsersDetect
Or
Browser detect
But that is not a good practice, it is always best, however, to avoid browser specific code entirely where possible. The JQuery $.support property (if you want) is available for detection of support for particular features rather than relying on browser name and version.

Categories