How to determine in which browser your extension background script is executing? - javascript

I'm talking about Chrome extensions, Firefox WebExtensions, Edge extensions...
In a background script, not a content script, is there a clear way to know which browser I am using? I need to do different operations for different browsers.
Yes, navigator.userAgent can be useful, but it's not very clear.
Is there any extension API that can be used to do this? Something like, chrome.extension.browserType. (Of course, this one doesn't really exist..)

There is no specific API to detect which browser is currently being used. One of the benefits of the major browsers moving to support a common extension framework is being able to have a single codebase which supports multiple browsers. While the set of functionality which is available from all applicable browsers is growing, there will always be some differences. These differences are not just in what is supported, but in some cased are in the specifics of the effects for a particular API, or how the API must be used.1,2 Thus, for some things, it is necessary to be able to determine which browser the code is currently running.
There is some good code available from the top-voted answer to "How to detect Safari, Chrome, IE, Firefox and Opera browser?". However, it needs some modification to work in an extension environment.
Based on the code in that answer, the following will detect:
Chrome
Edge
Firefox
Opera
the Blink engine
// Opera 8.0+ (tested on Opera 42.0)
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera
|| navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+ (tested on Firefox 45 - 53)
var isFirefox = typeof InstallTrigger !== 'undefined';
// Internet Explorer 6-11
// Untested on IE (of course). Here because it shows some logic for isEdge.
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+ (tested on Edge 38.14393.0.0)
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+ (tested on Chrome 55.0.2883.87)
// This does not work in an extension:
//var isChrome = !!window.chrome && !!window.chrome.webstore;
// The other browsers are trying to be more like Chrome, so picking
// capabilities which are in Chrome, but not in others is a moving
// target. Just default to Chrome if none of the others is detected.
var isChrome = !isOpera && !isFirefox && !isIE && !isEdge;
// Blink engine detection (tested on Chrome 55.0.2883.87 and Opera 42.0)
var isBlink = (isChrome || isOpera) && !!window.CSS;
/* The above code is based on code from: https://stackoverflow.com/a/9851769/3773011 */
//Verification:
var log = console.log;
if(isEdge) log = alert; //Edge console.log() does not work, but alert() does.
log('isChrome: ' + isChrome);
log('isEdge: ' + isEdge);
log('isFirefox: ' + isFirefox);
log('isIE: ' + isIE);
log('isOpera: ' + isOpera);
log('isBlink: ' + isBlink);
Different implementations of an API which interfaces with something as complex and diverse as the different browsers will always end up with, at least, subtle differences between implementations. Currently, many of the differences are not that subtle.
Mozilla has explicitly stated that they intend to implement functionality for WebExtensions which is not currently available in other browsers by extending the chrome.*/browser.* APIs. One way that this is being done is that there is a mechanism called WebExtensions Experiments which is intended for non-Mozilla developers to implement additional functionality for WebExtensions. The intent is that such functionality, if approved, will be migrated into stock Firefox builds.

Here's another technique. The browser.identity.getRedirectUrl function will return a URL post-fixed with:
.extensions.allizom.org/ when running from Firefox
.chromiumapp.org/ when running from Chrome/Chromium
It's simple enough to call this upon startup and store it in the runtime state of your background script. Edge and Opera also support this function.
Now usually Web Extension API calls start with chrome when running in Chrome, but by this point cross-browser extension writers should be used to the Web Extension Polyfill JS, and you'll need to use this too if you want the call to browser.identity.getRedirectUrl to work on any browser.

It's best choice, but for now only work at Firefox.
browser.runtime.getBrowserInfo()

Related

Error.stackTraceLimit cross-browser

What browsers support Error.stackTraceLimit, from which versions? Are there any alternative APIs to limit stacktrace length?
Afaik. it is supported from IE10, and by current V8: Node, Chrome, but I don't know more about it. I guess it is non standard like other parts of the Error APIs. I did not find anything about alternative methods to set the trace length in different browsers than these. So I need more info about this feature, but I did not find much using google...
It is hard to find relevant information in this topic, at least google did not help me, so I had to write a simple test.
function testStackTraceLimitSupport(){
Error.stackTraceLimit = 2;
function firstFunction(){
secondFunction();
}
function secondFunction(){
thirdFunction();
}
function thirdFunction(){
fourthFunction();
}
function fourthFunction(){
throw new Error("xxxx");
}
try {
firstFunction();
} catch (error){
return !/firstFunction/.test(error.stack)
&& !/secondFunction/.test(error.stack)
&& /thirdFunction/.test(error.stack)
&& /fourthFunction/.test(error.stack);
}
}
console.log("Error.stackTraceLimit support: ", testStackTraceLimitSupport());
As far as I know there are no alternative ways to set the trace length limit from javascript code. All you can do to slice the stack if you want it to be shorter.
I tested the feature on the following environments.
Node - Tested on 4.2.1, it was supported. I did not find version data, probably it is in the Chromium docs.
Chrome - Tested on 52.0.2743.116 m, it was supported. I did not find version data, probably it is in the Chromium docs.
Firefox - Tested on 48.0.2 it was not supported.
Internet Explorer - Tested on 11.0.9600.18426, it was supported. It is supported by IE10+ and Edge as well https://msdn.microsoft.com/en-us/library/s4esdbwz(v=vs.94).aspx .
Opera - Tested on 39.0.2256.71, it was supported. I did not find any Opera documentation for javascript developers.
PhantomJS - Tested on 2.1.1 it was not supported.

Check browser for U2F capability

Is there a way to check whether a browser supports U2F or not?
I know that right now, Chrome is the only browser that officially does U2F, but there are addons for Firefox and there may also be customized browsers which may have gotten U2F.
I don't want to ditch such browsers like Google does, because the addon users wouldn't be able to use it.
I saw that GitHub seems to have a way to see it (because it distinguished between Firefox with and without addon), but I have no idea how to do that.
Use library caniuse-support, which uses information from the service caniuse.com (https://caniuse.com/#feat=u2f) and uses library bowser (browser detector):
const {
getSupport,
currentBrowser,
} = CaniuseSupport;
const test1 = getSupport("u2f"); // current browser
console.log(
"Get feature support of U2F current browser (" +
currentBrowser.id +
" " +
currentBrowser.version +
"):",
test1.level
);
CodePen sandbox
It's 2019 now and there actually have been some interesting improvements to the entire U2F stuff.
The U2F browser API has essentially been replaced by WebAuthn, and while sure that is throwing out some older browsers, there isnt really any relevant older browser that actually supports the U2F API which is still in a lot of use as chrome auto-updates anyway and chromium and its forks are basically the only browsers that natively supported U2F out of the box.
and with the new webauthn, you have functions you can actually check for, based on what I library I use has in an example document:
if (!navigator.credentials || !navigator.credentials.create) {
//try navigator.credentials.get for login instead of create
//tell the user
}

How can I detect iOS6 device using feature detection

Is there any generic way to detect iOS6 device using feature detection.
I think the best way is always to parse the user agent string but you can detect the Safari version introduced with iOS 6 using a previously unsupported feature (see this article for a more complete list, I'll provide just one example).
Basically you have to mimic the same technique used by modernizr, with this piece of code you'll check if the <input> type file is supported, if it is then you're running on Safari with iOS 6 or greater. Of course just using features you can't be sure that the user isn't using another browser (that's why I prefer the user agent string if you have to detect the OS version). For a comparison see this post here on SO.
function isNewVersion() {
var elem = document.createElement("input");
elem.setAttribute("type", "file");
return elem.type !== "text";
}
You could check the FileReader API, but of course this'll match many modern desktop browsers, too (I'm not sure if that's going to cause you some problems, but I doubt it):
var iOS6 = false;
if(window.FileReader)
{
iOS6 = true;
}

browser identification

I want to identify if the broswer is IE then goto if block, other browser to else block in Java script.
I have one code here,
var browserName=navigator.appName;
if(browserName == "Microsoft Internet Explorer"){
IE code
}
else{
Other code
}
but i want to know is there any other way of implementing it?
Rather than do browser sniffing, you should do feature detection. Later versions of IE may support standards compliant stuff that in older versions you needed to work around or use MS-specific stuff.
Microsoft themselves have written up about the best way to do this and provide examples of both bad code (via sniffing) and good code (via detection). Make sure you go down the "good code" route.
I just started using this script to identify browser, version, and OS:
http://www.quirksmode.org/js/detect.html
If you are needing to use different code based on browser support for certain objects or methods, it's usually better to use object or method detection instead of browser detection. I use the browser detection for collecting statistics on my users, not for enabling or disabling features.
Quirksmode has a short article about why you don't use browser detection this way: http://www.quirksmode.org/js/support.html It's also linked from the browser detection script.
I found that This task is quite difficult as browsers all have similar names and different userAgent strings, so this is my Conditional statement to identify browsers.
I used this to identify the browser for different style sheets.
function styc()
{
var str = navigator.userAgent;
var res = navigator.userAgent.match(/Trident/);
var res2 = navigator.userAgent.match(/Firefox/);
if(res=="Trident"||res2=="Firefox")
{
//alert(navigator.userAgent);//for testing
document.getElementById('IE_fix').setAttribute("href", "IE_fix.css");
}
else
{
//alert("no");//for testing
document.getElementById('IE_fix').setAttribute("href", "mt_default.css");
}
}
Find a unique word in the userAgent string match it and check if the condition is true or not true depending on what you are doing.
The unique word I found for IE is Trident, and also identifies IE versions according to MicroSoft(not positive on this).

Safe feature-based way for detecting Google Chrome with Javascript?

As the title states, I'd be interested to find a safe feature-based (that is, without using navigator.appName or navigator.appVersion) way to detect Google Chrome.
By feature-based I mean, for example:
if(window.ActiveXObject) {
// internet explorer!
}
Edit: As it's been pointed out, the question doesn't make much sense (obviously if you want to implement a feature, you test for it, if you want to detect for a specific browser, you check the user agent), sorry, it's 5am ;) Let me me phrase it like this: Are there any javascript objects and/or features that are unique to Chrome...
isChrome = function() {
return Boolean(window.chrome);
}
This answer is very outdated, but it was very relevant back then in the stone age.
I think feature detect is more usefull than navigator.userAgent parsing, as I googled Opera ambiguosity here. Nobody can know if IE16 will parse the /MSIE 16.0;/ regexp - but we can be quite sure, there will be the document.all support. In real life, the features are usually synonyms for the browsers, like: "No XMLHttpRequest? It is the f....d IE6!"
No nonIE browser supports document.all, but some browsers like Maxthon can scramble the userAgent. (Of course script can define document.all in Firefox for some reason, but it is easilly controllable.) Therefore I suggest this solution.
Edit Here I found complete resources.
Edit 2 I have tested that document.all is also supported by Opera!
var is = {
ff: window.globalStorage,
ie: document.all && !window.opera,
ie6: !window.XMLHttpRequest,
ie7: document.all && window.XMLHttpRequest && !XDomainRequest && !window.opera,
ie8: document.documentMode==8,
opera: Boolean(window.opera),
chrome: Boolean(window.chrome),
safari: window.getComputedStyle && !window.globalStorage && !window.opera
}
Using is simple:
if(is.ie6) { ... }
Not exactly an answer to the question... but if you are trying to detect a specific browser brand, the point of feature-checking is kind of lost. I highly doubt any other browsers are using the Chrome userAgent string, so if your question is 'is this browser Chrome', you should just look at that. (By the way, window.ActiveXObject does not guarantee IE, there are plug-ins for other browsers that provide this object. Which kind of illustrates the point I was trying to make.)
For all the standards nazis... sometimes you might want to use bleeding "standard technologies" which aren't just yet standard but they will be... Such as css3 features.
Which is the reason why I found this page.
For some reason, Safari runs a combo of border-radius with box-shadow just fine, but chrome doesn't render the combination correctly. So it would be nice to find a way to detect chrome even though it is webkit to disable the combination.
I've ran into hundreds of reasons to detect a specific browser/version which usually ends up in scrapping an idea for a cool feature because what I want to do is not supported by the big evil...
But sometimes, some features are just too cool to not use them, even if they aren't standardized yet.
So, if you accept Marijn's point and are interested in testing the user agent string via javascript:
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
(Credit to: http://davidwalsh.name/detecting-google-chrome-javascript )
Here's a really nice analysis/breakdown of the chromes user agent string: http://www.simonwhatley.co.uk/whats-in-google-chromes-user-agent-string
I often use behavior/capability detection. Directly check whether the browser supports functionality before working around it, instead of working around it based on what might be the browser's name (user-agent).
A problem with browser-specific workarounds, is you don't know if the bug has been fixed or if the feature is supported now. When you do capability detection, you know the browser does or doesn't support it directly, and you're not just being browser-ist.
http://diveintohtml5.ep.io/everything.html
You shouldn't be detecting Chrome specifically. If anything, you should be detecting WebKit, since as far as page rendering is concerned, Chrome should behave exactly like other WebKit browsers (Safari, Epiphany).
If you need not only to detect WebKit, but also find out exactly what version is being used, see this link: http://trac.webkit.org/wiki/DetectingWebKit
But again, as other people said above, you shouldn't detect browsers, you should detect features. See this ADC article for more on this: http://developer.apple.com/internet/webcontent/objectdetection.html
One reason you might need to know the browser is Chrome is because it 'is' so damn standards compliant. I have already run into problems with old JavaScript code which I thought was standards compliant (by FF or Opera standards - which are pretty good), but Chrome was even more picky. It forced me to rewriting some code, but at times it might be easier to use the if(isChrome) { blah...blah ) trick to get it running. Chrome seems to work very well (I'm for standard compliance), but sometimes you just need to know what the user is running in grave detail.
Also, Chrome is very fast. Problem is, some JavaScript code unintentionally depends on the slowness of other browsers to work properly, ie: page loading, iframe loading, placement of stylesheet links and javascript links in page head, etc. These can cause new problems with when functions are really available to interact with page elements. So for now, you really might need to know...
I use this code to make bookmarks for each browser (or display a message for webkit)
if (window.sidebar) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
} else if( window.external ) { // IE Favorite
if(window.ActiveXObject) {
//ie
window.external.AddFavorite( url, title);
} else {
//chrome
alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok');
}
} else if(window.opera && window.print) {
// Opera
return true; }
else { //safri
alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok'); }
There might be false positives since opera also has window.chrome object. As a nice solution I use;
var isOpera = !!window.opera || !!window.opr;// Opera 8.0+
var isChrome = !!window.chrome && !isOpera;
This solution almost always works.
However one thing I discovered is that, isChrome returns false in iPad Chrome version 52.0 as window.chrome returns false.
isIE: !!(!window.addEventListener && window.ActiveXObject),
isIE6: typeof document.createElement('DIV').style.maxHeight == "undefined",
isIE7: !!(!window.addEventListener && window.XMLHttpRequest && !document.querySelectorAll),
isIE8: !!(!window.addEventListener && document.querySelectorAll && document.documentMode == 8),
isGecko: navigator.product == 'Gecko',
isOpera: !!window.opera,
isChrome: !!window.chrome,
isWebkit: !!(!window.opera && !navigator.taintEnable && document.evaluate && navigator.product != 'Gecko'),

Categories

Resources