How can I reliably detect the browser without using window.navigator? - javascript

I know there are a thousand questions on Stack Overflow about detecting the browser with JavaScript. My question is how can you detect the browser without window.navigator (which includes navigator.userAgent)?
First, to clarify, I don't need to know the rendering engine, this isn't for adaptive layout, and don't panic: I'm already doing feature detection. If why I'm asking about detecting the browser is important, please comment and I'll be happy to splice in the explanation, but it will probably make the question egregiously long.
Next, let me describe why my question is not a duplicate of:
Browser detection in Javascript? because of 19 answers, 12 of them use navigator.userAgent specifically (including jQuery.browser which used userAgent, and is now gone anyway), 4 use navigator.appName (which gives "Netscape" in Chrome...), 1 side-steps the question by recommending feature detection, which is different from browser detection (I am already using feature detection, but to know the extent to which I can use them, I need browser detection), and 2 aren't really answers or are IE-specific. (Although this non-answer is actually very explanatory about why my question here is relevant: I'm trying to avoid hitting pain points on certain browsers that would crash the tab!) Since my question is asking for an answer (even a hack?) without using window.navigator, it is not a duplicate of that question.
Check if the user is using IE because of 11 answers, 10 use navigator.userAgent and 1 of them uses an IE trick to detect IE only, which is not sufficient to answer my question (though it may be potentially be a small part of a helpful solution posted here)?
In Javascript, how do I determine if my current browser is Firefox on a computer vs everything else? because of 11 answers, 8 use navigator.userAgent, 2 recommend feature detection (again, not my question), and 1 isn't even an answer, really.
How to detect chrome and safari browser (webkit) because of 8 answers, 6 of them use navigator.userAgent, and 2 are webkit-specific. Unfortunately, WebKit is not necessarily tied to just Safari, and I need to know the browser, not the rendering engine.
Hopefully that is crystal clear.
I know there are other ways to do this, but I don't know the ins-and-outs of each browser well enough. Are there objects or variables that are consistently or reliably exposed to JavaScript in certain browsers, maybe? I know that some experimental APIs are vendor-prefixed, but that doesn't seem like a good idea for use in a commercial product, although I'm willing to stoop that low if needed. Any other possibilities?

A thought:
IE uses ActiveX (still does up to IE11, legacy), You can fairly easy deduce the fact that the user is using IE from looking at activeX availability, however if the security settings are on, you need to fall back on, guess what, other feature detection.
Chrome and Firefox both support the use of extensions, maybe detecting these extensions will help
Chrome has the window['chrome']['webstore'] object available in the global scope.
You can sort through the window object with Object.keys and look for vendor specific names like 'moz' or 'ms' or 'o'.
If you combine moz, ms and chrome-object you can sniff out the three largest browsers.
On a side note, feature detection is still the best option, not for the OP, but for the "I'm-just-getting-into-programming-and-I-like-to-know-how-I-sniff-out-a-browser-programmers" out there.

First off, just to be clear no inbound HTTP request is guaranteed to be accurate in saying who they are. In fact this is how some hackers operate by faking out the User-Agent field of the HTTP header. Most browser providers; however, do a good job of identifying who they are by saying so in the User-agent field of the inbound HTTP request header. The only problem working at the Javascript layer is that it is one layer too high for seeing the headers. However there are tricks and here's one of them :
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
I found this after thinking about the problem a bit and knowing the Network side pretty well... You can read more about this here: Accessing the web page's HTTP Headers in JavaScript, in fact this question could be considered a duplicate of that answer, however, not everyone knows the HTTP layer. The code above is pretending to be a legitimate inbound request, and opens the document.location using a "Get", but it sends nothing. Without knowing the browser internals I am guessing that it is the DOM itself that is returning the already known header information. Just parse the User-Agent portion of he response and you are all set.

Related

Is there a foolproof way to check browser in JS or Node.JS?

I have a website where I want to ban all users not using a chrome and derivatives, firefox and derivatives, safari, or a new version of opera (IE and other old browsers may compromise security). Is there an absolutely foolproof way (so that even a hacker couldn't spoof their browser) to do this in JavaScript on the client or server side?
No, it can't be done reliably. You could use some complex JavaScript timing runs and compare the time to execute for the bank of tests against the known timings for each browser and version. Obviously this would have to be tested on a ratio basis to rule out differences in hardware performance. This would not, however, be foolproof and would require "fingerprinting" performance for every single browser version and make that you will accept and would need to be constantly updated as each new browser version was released. This is not a foolproof method and is generally considered a very bad idea. It can also result in false positives which will cause people with compliant browsers to be denied access based on variability in your JavaScript fingerprinting tests.
Hardening your server is a much better way to go and using simple browser identifiers like navigator name will provide the results you need. The trouble with trying to design a foolproof method is that, even if you get it to work, a cagey hacker can still get you. Hardening the Server is the only real way to secure your site.
This is a terrible security method
You should not be banking on the fact that a user is visiting your site from a particular browser. You should instead choose to either allow functionality to those compliant browsers and disable it to others via signatures (the part the browser sends which helps identify the particular browser type).
Most importantly, you should never leave a vulnerability in your application! If you know it's a vulnerability in different browser types, fix the problem - don't try to hide it. People will always find a way around a hidden problem. Easy fix? Make it so there is no problem to hide!

Best way to display warning message to "untested" browsers?

I have an app that I have fully tested in Safari 5, IE 9, FF6, and Chrome 14. I'm not looking to block or exclude any browsers from the experience. But I want to warn/inform users that there may be a better experience in another browser, and if they choose to continue, there may be features not working or broken.
I have looked at jQuery browser detection, but it seems to be a bit quirky. I know the best solution would be to warn based on feature detection, but we are currently in beta and I am not completely sure what features make or break. Such as web workers, its known that web workers not working breaks our app, but it works in IE lower versions. But then there is an issue with Opera that web workers is available, but not functioning correctly.
Ultimately I am looking for an easy way to say Browser X Version y and up don't show warning, and those and under show warning.
What is the best way to approach this?
Browser detection is indeed "a bit quirky", in pretty much any scenario. The jQuery route is probably as good as you're going to get, but as you say it's not great.
A better solution is generally to do feature detection, especially in cases like the one you describe where your site relies on specific features.
The best feature detection library is Modernizr. This will give you an bunch of Javascript flags which are set to true or false according to whether the browser supports a given feature. It detects support for a whole bunch of stuff, including Web Workers.
Check out this: http://www.w3schools.com/js/js_browser.asp
-Easy way of detecting the user's browser with javascript. From there I'd just use a switch statement or something to display the messages for browsers that aren't tested yet. If you want the exact browser version you'll have to parse it from the "navigator.userAgent" field.
If the goal is full validation, you need to be even more specific about versions. Keep in mind that some browser upgrades are not 100% backwards compatible with previous versions. (Look at how IE8 mode in IE9 is not the same as native IE8 rendering, for instance.) You're going to have to retest with every new browser version, and sooner or later there's going to be a "Fully tested with browser version X, not tested with version X+1 that was released yesterday" problem. Feature detection, graceful degradation, and a warning non-intrusively displayed to the user if their experience is being significantly downgraded is a better way to go.
To directly answer your question, if you must implement what you are asking for just parse the user agent. This could be useful specifically watching out for a browser you know doesn't work right and warning, or as a bandaid for a badly written intranet app that is very picky about the exact browser version it will run on. For a newly developed app where you have control over the requirements, I would not recommend warning on browser version since there are better ways to do it.

What are the chronological steps in building a cross browser compatible site? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 12 years ago.
Improve this question
I am working on my first project that requires me to worry about cross browser compatibility. Since this is my first time doing so, I dont know how to go about completing the project. I am specifically worried about IE. Should I complete my project in a more graceful browser then hack it to work in IE, or should I simultaneously build my program up in both environments?
Design your site to work in standards complaint browsers first. I always start with Firefox, even when developing on my company Intranet (where everyone uses IE). Doing so will let you focus on getting your markup and CSS correct. This is what is most important.
The important thing to note is that you'll want to "future proof" your site, and concentrating on a standards compliant browser will help you do that.
Then, once you're confident your site is looking correct (validators are your friend!), try it out in the versions of IE you want to support. In order to get your layout to look OK in IE, I strongly suggest using different stylesheets for each version of IE, using conditional comments.
Also, you should note that many others have been in the same scenario as yourself, and there is quite a bit of help available. One popular method of forcing IE to behave is the ie-7.js project.
Lastly, be mindful of the top IE bugs, such as:
IE6 Box Model Bug
IE6 transparent PNG images (I have used this fix in the past)
A few tips:
Code to Standards — Start by ensuring that what you've just developed works in Firefox and Chrome, and then verify it in IE. I'll usually then check it out in Safari. It's always better to make sure your markup/code works in a more standards compliant browser first.
Validate Early, Validate Often — You don't want your design to look perfect in one browser, find out that it's broken in another, discover that to fix the broken layout you needed to correct some invalid HTML/CSS, only to find that now the first browser looks wrong.
Progressive enhancement — will be your friend. Start basic, with simple HTML and simple CSS, and no JavaScript whatsoever. Repeat tips #1 and #2, then move on to more complex styles and layout. Contiue this iterative process until you are happy with the design in all browsers. Only then should you consider JavaScript to polish the site.
Check each browser often — Don't develop the entire website in a single, compliant browser like Firefox, and then decide to "see what's broken" in IE. If you've got a complex, dynamic website, there could be MANY problems in Internet Explorer. Trying to decipher each one when they are compounding on each other is a nightmare.
Reset Stylesheet — As #Eir mentioned in the comments, find a good reset stylesheet. Although, they have fallen out of favor for some people, I find putting every browser on the same footing from the start helps tremendously.
Use a Framework — I find CSS Frameworks to be excessive, but some people swear by them, so to each his own. On the other hand, as soon as you have made it to the JavaScript phase of development, I highly recommended using jQuery or MooTools. They are very focused on circumventing cross-browser inconsistencies.
Let JSLint hurt your feelings — Even when using a JavaScript framework, there are certain standards of coding to which JSLint will help you conform. Some of the options are a bit overly strict, but I promise that if you clean your scripts through this tool often enough during development, you will almost never encounter those strange times when everything seems to work in all browsers except IE.
And some great tools! Everything in the above list you should consider mandatory practice. The following can spice it up for you in a pinch, but is optional:
CSS Browser Selector — it is rare that you will need this, but if all else fails, it's way cooler than using a separate stylesheet just for one browser (I despise conditional comments). It basically adds classes to your <html> tag, so you can do things like the following in your main stylesheet: .ie7 #header {/*stylese here for IE7 only*/}. It supports a lot of browsers on many operating systems. And it's fast.
Browsershots — Nothing beats the real thing, but if you can't install a suite of browsers, this and other tools like it can help.
IE6 CSS Fixer — I outright refuse to debug my designs in IE6. I coerced my company (via many chagrin-filled meetings with IT and management) to drop support for it (thank god). It's just counter-productive to waste so much time forcing this pile-of-ahem... Anyway, if you aren't like me and need to support IE6, this tool can help.
Also you should focus on resetting css like this
OOoooo, good question:
here's my take:
Decide which browsers you are supporting. I suggest IE 7 + 8, FF, Chrome and Safari as in order of importance. (only support IE6 if you absolutely have to!). It helps if you know your userbase here.
Use a css reset. Different browsers have different default styles. a css reset gives you a consistent base.
Keep your markup as simple as possible. Follow Standards (and see progressive enhancement on Stephen's answer).
Test every step of the way on your target browsers. That way you can correct problems right away. http://crossbrowsertesting.com/ is the best resource for this, but there are free ones for screenshots as well.
Avoid Hacks as much as possible. Most cross-browser issues these days can be solved without resorting to hacks.
Ask questions here when you get stuck. If this is your first project dealing with browsers, you will get bewildered by inconsistencies. We all face these issues, and are glad to help.
Be ok with the fact that webpages are not going to look exactly the same in all browsers. (once again, see progressive enhancement).
Good luck coding!
I develop for Firefox first, and then work out the IE buggery. Rarely do I "hack" it, rather find something that works in both, or at worst use IE conditional comments. Just one coder's preference. Always a good idea to test with Safari, too.
Two big advantages of Firefox are: the Error Console, and the Firebug plugin.
there is alot of greate tools that makes life alot easier for you there is for example a
css framework called blueprint you could use, it has already everything set for every specific browser so that you get the same outcome in all browsers. And using jquery as your javascript framework does add an extra insurance that you'll have it working in most browser.
but remeber there is no such thing as 100% cross browser compatibility for all the browsers and all the versions in world.
In theory would be best to develop for all browsers at once, always testing for every browser...
Realistically, that rarely happens... I typically develop/test with firefox. when I introduce complex javascript or css, I check in ie... this tool is incredibly handy for checking all versions at once... google ie tester.
By checking all browsers at regular intervals, and when you make complex changes, you ensure that major features are compatable :)
Also, ensuring that all of your code is valid is not only good practice, but helps identify cross browser issues.. google w3schools validator :)
Using javascript libraries such as jquery also aid in cross browser compatability, and some even come with css libraries as well. These libraries are purpose built for quick, reliable features that are typically cross browser guaranteed.
Finally, before launching, use launchlist to check that all works: http://lite.launchlist.net/
Hope all that makes sense and helps with your first project :)

Browser Version or Bug Detection

I've recently seen some information about avoiding coding to specific browsers an instead using feature/bug detection. It seems that John Resig, the creator of jQuery is a big fan of feature/bug detection (he has an excellent talk that includes a discussion of this on YUI Theater). I'm curious if people are finding that this approach makes sense in practice? What if the bug no longer exists in the current version of the browser (It's an IE6 problem but not 7 or 8)?
Object detection's greatest strength is that you only use the objects and features that are available to you by the client's browser. In other words given the following code:
if (document.getFoo) {
// always put getFoo in here
} else {
// browsers who don't support getFoo go here
}
allows you to cleanly separate out the browsers without naming names. The reason this is cool is because as long as a browser supports getFoo you don't have to worry which one it is. This means that you may actually support browsers you have never heard of. If you target user agent strings find the browser then you only can support the browsers you know.
Also if a browser that previously did not support getFoo gets with the program and releases a new version that does, you don't have to change your code at all to allow the new browser to take advantage of the better code.
What if the bug no longer exists in the current version of the browser (It's an IE6 problem but not 7 or 8)?
That's the whole point of feature/bug detection. If the browser updates its features or fixes a bug, then the feature/bug detecting code is already up to date. If you're doing browser sniffing on the other hand, you have to change your code every time the capabilities of a browser changes.
Version and User Agent parsing remind me of stereotyping or racial profiling. Object detection is the way to go in my opinion. The book jQuery in Action does a good job of pointing out the fine details of why.
Well, if it is a problem in IE 6, but not IE 7 or IE 8 then the feature/bug detection mechanism will mark it as not a problem and use the appropriate functions.
It makes sense in practice, browser sniffing causes many issues, what if you don't update your signatures in time for some new browser that is released? You are now locking out potential customers, and visitors because you believe that their browser is unable to support something that indeed it can.
So yes, it makes sense, and your second question is moot because of the fact that it does the detection in the first place, if it is no longer a bug everything will work as expected without the work around that is in place if the bug was there!

Design order: Firefox, IE, or both?

When coding new javascript heavy websites, which order or web browser do you code for?
I can see these possible orders, but I am not sure which I like best:
Code for one first and get it working well, then start testing with other and fix errors as I go.
This will allow for the most rapid development (with Firefox at least) but I've learned from experience that debugging IE with so much going on at once can be a pain!
Code for both at the same time. In other words, for each new feature, ensure it works with both browsers before moving on.
This seems like it will actually take more time, so maybe do several features in Firefox then move to IE to patch them up.
What do you all do?
Edit 1: To respond to a couple of answers here.:
#JQuery usage: For some reason I was not expecting this kind of a response, however, now that this seems to be the overwhelming accepted answer, I guess I should tell everyone a few more things about the specifics of my app. This is actually the DynWeb that I started another question for, and as I'm developing, a lot of the important code seems to require that I use document.whatever() instead of any JQuery or Prototype functions that I could find. Specifically, when dynamically importing changing CSS, I have to use some similar to:
var cssid = document.all ? 'rules' : 'cssRules'; //found this to take care of IE and Firefox
document.styleSheets[sheetIndex][cssid][cssRule].style[element] = value;
And I expect that I will have to continue to use this kind of raw coding currently unsupported by either JQuery or Prototype in the future. So while I would normally accept JQuery as an answer, I cannot as it is not a solution for this particular webapp.
#Wedge and bigmattyh: As the webapp is supposed to build other webapps, part of the criteria is that anything it builds look and work functionally the same in whatever browsers I support (right now I'm thinking Firefox and IE7/8 atm, maybe more later on). So as this is a more interesting (and much more complicated) problem; are there any sites, references, or insights you may have for specific trouble areas (css entities, specific javascript pitfalls and differences, etc.) and how to avoid them? I'm almost certain that I am going to have to have some sort of isIE variable and simply perform different actions based on that, but I would like to avoid it as much as possible.
Thanks for your input so far! I will keep this open for the rest of the day to see what others may have to say, and will accept an answer sometime tonight.
This is sort of a trick question. In my opinion you need to work in this order:
1: Conform to Standards
This gets you closest to working in every browser without having to test against every browser. Additionally, you gain the huge benefit that your site should work with any new browser that comes along (Chrome is a good example) so long as it's well made and standards compliant. It also makes it easier to tweak your site to work in specific browsers because the way that the popular browsers deviate from standards compliance is well known.
2: Support the Most Used Browsers (For Your Site)
Note carefully the distinction between the breakdown of browser usage on the internet vs. browser usage on your site. On the internet as a whole IE is the most popular browser with Firefox a close second and Safari, Opera, and Chrome taking up most of the remainder. However, the demographics of your site's visitors can turn these numbers upside down. On sites that cater to a more technically savvy crowd it's common for firefox to be the dominant browser with IE in the distinct minority.
3: Support Other Browsers as Needed
You need to be very explicit about the fact that browser compatibility is an operating cost for your site, and you need to decide where you draw the line. Depending on your site's purpose and business model it may be fine to support only the most popular browsers, or even a subset of them. On the other hand, it may be a vital business concern to support everything under the Sun, including IE5. It's ok to make a conscious decision to not fully support every browser if you think the cost/benefit ratio is too high to justify it. Indeed, many of the most popular sites on the internet do not work well in older and niche browsers. Though you should strive to make your site still functional in the least popular browsers, even if there are serious appearance or usability problems.
FireFox first then IE. If it works in FireFox, it is more likely to work in the other non-IE browsers, IE sometimes requires special magic.
Use jQuery and do them all at once.
Code for Firefox first, but test with IE as you go. This lets you fix any quirks as they arise. It's important to test with Firefox first because it's more standards-compliant. You should learn how to write HTML/JS the right way. Fix things as you go to get a better idea of how IE renders things differently.
You may not need to test with IE for every feature you add, but test often enough so that issues don't pile on top of each other. Repeat with other browsers/browser versions to get the overall picture of your site's compatibility.
I always test on both FireFox and IE7. And then fix and botch for IE6 and other browsers.
If it works on FireFox it will almost certainly work on Opera, Safari, Chrome, etc with only a few minor tweaks
Same thing goes for IE7 and IE6, If it works on 7 it won't take too much to get a reasonable rendering on IE6
I normally use Firefox as my main development browser because of its superior debugging tools and I code very incrementally, write a few lines and test several times an hour. But at least every hour or two I make sure that what I am doing will work on IE7 as well.
As soon as I get into an area where IE7 causes problems I start to rethink the way I'm doing it, In my experience fixes tend to multiply and get out of control very rapidly. It's often better to accept defeat and move on with a simpler design.
I've been bitten too often in the past by developing something that works perfectly on FireFox only to find that it needs a complete rethink to get it working in IE7 as well - and vice versa. It can take days to sort out and can be very disheartening.
are there any sites, references, or insights you may have for specific trouble areas (css entities, specific javascript pitfalls and differences, etc.) and how to avoid them?
A good resource for this is quirksmode. The author (Peter-Paul Koch, or PPK) has lots of compatibility tables for CSS and JavaScript support. He also has articles dealing with specific issues and how to write cross-browser code.
They don't deal with JavaScript, but Position is Everything is a valuable resource for CSS issues (mostly IE6).
Like others have mentioned, I just use jQuery to avoid these issues. If there's something it doesn't support, it's pretty easy to write custom plugins.
I do IE first, and then add Firefox.
My experience is that once it works in IE, it continues to work in IE, and the question why something not work in Firefox is usually easy to answer.
If you have to code for IE6, the most frustrating part is coding the CSS and HTML. jQuery and other libraries make it easier to code the behavior -- but you generally can't get around the fact that IE6 has so many weird rendering issues that you'll be frequently banging your head on the keys trying to make it do what Firefox, Safari and Opera do right the first time.
So Javascript isn't the hardest part. Dealing with HTML and CSS is. In my experience, if you're working with any reasonably interesting design, you're better off coding for IE first and then testing on Firefox. You probably won't have to make many adjustments if you do IE first, but you definitely will have to spend some time refitting your code to make IE do what you wanted it to, if you only code in Firefox. It's like repeating yourself. It's a pain. So it's better to get it done first so you don't end up wasting too much time.
I code for both, and write (or use) abstraction layers where there are differences between the browsers. IMHO, it's much easier in the long run to be continuously testing in a cross-platform setting. This keeps me from doing something that's tuned to one browser that simply won't work well in the other: I find out very early in the development cycle what the compatibility issues will be.
When I'm making a small change, I might first do it for one browser, but before I consider that feature or change to be complete, it must work at least in firefox and IE.
To minimize your issues now, and downstream, work with the worst to the best, in size of their existence.
Edit: If you can do the below keeping in mind of "how could this degrade gracefully down to ie6 via modified jQuery elements, etc... it might be a bit clearer.."
So, today based on Market Share, it is:
1) IE 6
2) IE 7
3) Firefox
4) Safari..etc.
Coincidentally enough, the major issues with browsers occur in that order too.
This means the majority of the issues your users will face will be in that order, and in those proportions.
On our team I have banned initial-development testing in Firefox. It has to survive the weakest link, not the strongest. Inhumane, I know, but we have cut down going back and fixing bugs related to browsers by 80%, because 80% of browser bugs are IE. Yeah, there's a ton of debugging tools in Firefox that can be used ONCE we find a problem in IE.
On the flip side we put in extra-features that are Firefox only to reward the firefox users. A simple browser type check and it takes care of the rest.
If you have look at Web Browsers market share, you will find that IE and Firefox are on the top and so close to each other so,
You should put both of them in your consideration either using cross-browser Javascritp like JQuery or go on your way by testing both of them.
I think its best to design for Firefox but like others have mentioned the JavaScript isn't the hardest part, its the CSS that is the hard part. Personally I used to code for both FF and IE at once, but I find that it takes longer because your likely to make major changes during a development cycle so don't even bother coding for both at once, it could be wasted effort.
Another thing to consider when choosing which browser to start development under is if you are more familiar with W3C standards or the IE "standard" imposed by its majority user base. Its kind of a funny thing about web standards, many if not most web developers are not happy with IE's standards support, but at the same time any code IE supports is the real standard of the web.

Categories