This question already has answers here:
Javascript ES6 cross-browser detection
(10 answers)
Closed 7 years ago.
I have a big chunk of JS libraries that I should rewrite since it's really old and outdated. So, I decided to come up with a solution where I would just use most of ES2015 features like rest parameters.
The thing is, I am sure all the clients would not have their browser up-to-date and I am confused whether I will face any issue regarding their browser is compatible with my new JS libs.
So, I was wondering if I could detect whether the client browsers are compatible with ES2015. And if not, I would just include my old JS library.
I am looking for a solution like Conditional comments, but I am getting nowhere to solution.
Any help in HTML, JS or PHP is appreciated. Please kindly suggest your advice.
I was wondering if I could detect whether the client browsers are
compatible with ES2015. And if not, I would just include my old JS
library.
You cannot do that, simply because AFAIK there's no browser that fully supports ES2015. Also, you don't really want to maintain two different versions of your code, because it's painful and it could get messy really quick.
The approach nowadays is to use a transpiler, which is sort of a compiler that compiles your ES2015 code to ES5 (the JavaScript that every browser knows). It is still kind of messy, but at least you get to write only one version of your code, and it's ES2015.
I think Babel (formerly 6to5) is the most popular transpiler. You can check out their website for getting started.
As to answer your actual question,
How to detect if browser is compatible with ES2015
You can do that in many ways. I'm not sure what could be the most reliable one, but for example you could simply try on your browser's console:
'Promise' in window
If this statement returns true, then the current browser supports promises, which is a new feature of ES2015, so you could assume that it supports most of the features of ES2015.
This is not enough for most cases though; you may want to be 100% sure that what you're using is not going to throw a SyntaxError in any old browser.
A solution could be to manually check for each feature you want to use. For example, if you need the Fetch API, you could create a function that tells you if the current browser supports it:
function isFetchAPISupported() {
return 'fetch' in window;
}
You can do this for any new API you need. However, if you need something syntactically different, I think your only bet is eval() (as Katana314 suggested). For example, in order to check support for rest parameters you could do:
function isRestSupported() {
try {
eval('function foo(bar, ...rest) { return 1; };');
} catch (error) {
return false;
}
return true;
}
This works great in Firefox, because the rest parameters are supported.
It works as well on Safari, returning false because rest parameters are not supported there yet.
Related
I have the following code that basically gets some JSON data, looks for the keys with "servergenre", and saves the results in an array.
This is a follow up of this question.
let result = [];
Object.keys(data).forEach( key => {
if(/servergenre/.test(key)){
result.push(data[key])
}
});
Even though the code is working correctly, in some editors it raises syntactic errors:
"key": unsolvable variable or type key
"=>": expression expected
"if( / server...": formal parameter name expected
")){": , expected
"});": statement expected
Here is an image to show you where the errors are:
As I said the code is working fine, I just need it to be fixed or another approach to get rid of the errors.
Furthermore, many compressors and minifiers do not support this bit of code. So I can’t minify it.
Thanks in advance.
ES2015, formerly known as ES6, is a more recent version of JavaScript, which introduces features such as the => syntax for functions you are using.
Not all features of ES2015 are fully supported in all browsers, so many people who use it pass it through a compiler (“transpiler”) first to convert it to ES5, which is supported by all browsers. Babel is one such transpiler. But if you are only targeting newer browsers, that would explain why the => syntax is working for you.
You just need to change your editor settings to understand that syntax. Exactly how you do that depends on what text editor you are using. It could be that your editor's built-in JavaScript mode doesn't know how to read ES2015 syntax, and you need to either upgrade your editor or install a third-party plugin that provides an updated error-checker. Or it could be that your editor supports both ES5 and ES2015, and it thinks you are trying to write your project only in ES5. In this case you just need to go to the settings and tell your editor that you mean for this project to use ES2015 (or ES2016, which is currently the most recent version).
Fat arrows are ES6 syntax. If that causes trouble, just write good old ES5 :
let result = [];
Object.keys(data).forEach( function(key) {
if(/servergenre/.test(key)){
result.push(data[key])
}
});
I know that feature detection works for sniffing objects and methods (things like JSON, querySelector,...) but what about new syntax? like default function parameters?
The problem is that they cause a syntax error that cannot be caught.
Any insight on this? apart from browser and version sniffing which is mostly unreliable.
And if there is no way, does this mean we can not use new features! what are they for then (maybe for use after 10 years !)
Try to create a function within a try-catch block.
var code = '"forgotten close quote';
var valid = true;
try {
new Function(code);
}catch(exc) {
valid = false;
}
Here, trying to put "forgotten close quote into a function will fail due to a syntax error, which is then caught and will set valid to false.
As icktoofay demonstrates, there are ways to check for syntactical features without causing a syntax error, but even if you do that, what would you do with that information? You would need to have multiple versions of your code depending on the supported syntax features and need to do dynamic loading of your scripts for no real purpose.
To address your last question, you don't necessarily have to wait to use the new features. You can use a JavaScript-next to JavaScript-of-today compiler like traceur-compiler, or Typescript, which includes future JavaScript features and compiles into browser-friendly JavaScript.
There is no reliable way to check general support for syntax errors.
However there is plenty that can be used in NodeJS, today.
Also, there's nothing preventing you from using a transpiler, like Traceur, to write fancy JS and have it come out ES5-compatible on the other side.
I want to build a library in JavaScript/JScript/ECMAScript...whatever you want to call it, which will target modern standards (HTML5, CSS3, ESv5) with that in mind, any browser that supports the standard! Now I know there are already plenty of useful libraries out there, i.e. jQuery and MooTools. Of course they're great and I already use those where necessary, but I should not be forced to jump on the same bandwagon as every other developer just because it's popular!
So for the sake of the following questions, let us not concern ourselves with 3rd party libraries such as jQuery and MooTools. Lets get down to nitty-gritty JavaScript/JScript/ECMAScript.
Firstly, I asked a question prior to this (What's the difference between JavaScript, JScript & ECMAScript?), as I did not know what the difference was.
Thankfully I concluded the following:
ECMAScript is the language specification. JavaScript and JScript are dialects of ECMAScript.
JavaScript is Mozilla's implementation of ECMAScript.
JScript is Microsoft's implementation of ECMAScript.
OK, that was a nice simple answer wasn't it? But here's some questions which stem from that:
is "JavaScript" supported in non-mozilla browsers, and to what extent?
is "JScript" supported in non-microsoft browsers, and to what extent?
Based on those two questions, I did a little digging and ran a simple test on IE9, FF14 and GC19.
Here is the test code:
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 Template</title>
<script language="JavaScript1.3">
jsver = "1.3";
</script>
<script language="JavaScript1.4">
jsver = "1.4";
</script>
<script language="JavaScript1.5">
jsver = "1.5";
</script>
<script language="JavaScript1.6">
jsver = "1.6";
</script>
<script language="JavaScript1.7">
jsver = "1.7";
</script>
<script language="JavaScript1.8">
jsver = "1.8";
</script>
<script type="text/javascript">
document.write("<B>Your browser supports JavaScript version " + jsver + ".</B>")
</script>
</head>
<body>
</body>
</html>
The results were: IE9 = JSv1.3, FF14 = JSv1.8, GC19 = JSv1.7
OK, then I ran this test, which tests for ECMAScript version 5 support:
http://kangax.github.com/es5-compat-table/#showold
Again using the same browsers (IE9, FF14, GC19), ESv5 seems to be fairly well supported!
Now comes the tricky bit! I come from a Microsoft background, and write software using languages like C#, ASP.NET etc, so naturally, my IDE of choice is Visual Studio (currently 2010). When I look through the JavaScript intellisense I see things like ActiveXObject, Array, Object, etc.
Should I trust VS2010's intellisense?
Where can I find a reference of ESv5 supported objects and features?
How do I detect if a browser supports a particular object or feature?
Is there anything better than VS2010 out there that will help me write compliant ESv5 code?
Is it safe to override implementations of existing objects like Object, Number, Boolean etc, or should I just extend the existing implementation?
Finally, concerning myself with jQuery. Let's say I can't be bothered to write the core compliancy & functionality myself, can I just write my library to sit on top of jQuery...or is this just a copout?
1) Nope. Certainly it won’t restrict to just valid ECMAScript.
2) http://kangax.github.com/es5-compat-table/ is always useful.
3) You can just check to see if it’s defined. E.g.
typeof(Array.isArray) === 'function'; // true in newer browsers, false in IE8
4) Your best bet is to read the spec! Using "use strict"; in your code will also catch some classes of errors and it good practise. More explanation on strict mode at http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
5) Certainly I wouldn’t replace the original objects. If you’re going to extend properties I’d first double-check that a compliant implementation doesn’t already exist. E.g. PrototypeJS added (before browsers implemented it) a document.getElementsByClassName. When browsers started implementing it natively they found out that sites using Prototype were still using the slow JS-based version. The fix was just to wrap Prototype’s definition in a if (document.getElementsByClassName == undefined) { }
2) I find the Overview you provided pretty good. What else do you want?
3) A good library to even out the differences between the browser is ES5-shim. It autodetects the features and provides shims for the browsers who lack support.
4) Always use "use strict"; and a have good editor of your choice which has some kind of code-highlighting and perhaps code-completion. I use the browser consoles or firefox scratchpad (silly name for a good tool) for quick hacking sessions and put it all together in notepad++ (= the IDE of your choice).
5) Augmenting the native javascript objects has been debated a lot and has pros and cons. Prototype and MooTools go this way. jQuery takes the other way and provides a separate object for that. I personally prefer to leave the native (and especially host) objects alone and have your own namespace with the functions you need.
I'm trying to understand an intermittent script error that I am seeing in a JavaScript intensive thin-client application running under Internet Explorer 6 and Windows XP. The root cause of the problem is that the following function call returns a null value (however it does succeed without an error):
var doc = targetWindow.document.open("text/html","_replace");
Where targetWindow is a window object.
Neither targetWindow nor targetWindow.document is null and so I'm struggling to understand why this call would return null. My interpretation of the documentation is that this method shouldn't ever return null.
This code has been unchanged and working perfectly for many years - until I understand why this is happening I'm not sure either how I might handle this, or what might have changed to cause this to start happening.
What might cause this function call to return null?
According to the documentation you should be passing "replace", not "_replace". Try this instead:
var doc = targetWindow.document.open("text/html", "replace");
Since you say your code has worked for years, then it is likely that something has changed and the above suggestion may not be the issue. However, it is still worth a try.
Have you changed any js files / libraries you are using in your application lately? Also, are you using any browser plugins within the page? It is possible that a newer version of either of these could be somehow affecting your call to "document.open".
document.open() does not have any parameters by W3C standard. Check out this link: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-72161170
I recommend you to use W3C documentation instead of Microsoft's one because with W3C you are sure it works on all modern browsers, while Microsoft is well known for adding extensions that, of course, works only in their own products. It's called EEE (Embrace, extend and extinguish).
Simply use document.open() without arguments. There are ways to manipulate user history, but that's called bad programming practice. History is user's private data and web application should not try to manipulate it.
I am interested if which would be the best place to detect the client's user-agent, client-side (javascript) or server-side? I brought up the question due to the fact that some IE8 users are getting a message saying they're using IE6.
The short and correct answer is : do not use anything that relies on UserAgent sniffing.
To reliable be able to adjust code paths you should test for the specific 'thing' that the codepath is adjusted for, primarily features. This is called Feature Detection.
So if feature X is supported we do this, if not we do that.
Deducing if a feature is supported based on which UserAgent is present will rapidly fail, especially when new browsers come to the marked.
Take the following example, which can actually be found in several major libraries (!)
if (isIE8) {
// use new feature provided by IE8
} else if (isIE7) {
// use not so new feature provided by IE7 (and IE8)
} else {
// use fallback for all others (which also works in IE7 and IE8)
}
What do you think happens when IE9 comes along?
The correct pattern in this case would be
if ("addEventListener" in foo) {
// use DOM level 2 addEventListener to attach events
foo.addEventListener(...
} else if ("attachEvent" in foo) {
// use IE's proprietary attachEvent method
foo.attachEvent(...
} else {
// fall back to DOM 0
foo["on" + eventName] = ....
}
The User-agent available on both sides should be the same, unless there's funny stuff going on, which normally isn't.
If you want to show a message to IE6 users, I suggest you use conditional comments. They're an IE-specific feature and work very well for detecting IE versions.
The information found through client or server-side detection is basically the same.
Keep in mind it is extremely easy to spoof what browser you're in. There is no fail-safe way to detect all browser types accurately.
i don't know how you're checking for the user agent, but i'd do this way:
<%=
case request.env['HTTP_USER_AGENT']
when /Safari/
"it's a Mac!"
when /iPhone/
"it's a iPhone"
else
"i don't know :("
end
%>
checking directly in the user request seems to be the most consistent way to verify the user browser. And the request.env is avaliable in your controller and views, so you could pass this to rjs if needed.
For those who need to get the actual user-agent using JavaScript, you can use navigator.userAgent