TextDecoder TextEncoder feature detection in javascript - javascript

I am trying to use TextDecoder TextEncoder API's on my website. How can I check if it is available.
https://caniuse.com/#feat=textencoder says IE and Edge still doesn't support it.
What is the best way to make sure these libraries exist on browser. Is there any drop in libraries that would pollyfill? And if it does not exist can I conditionally load a pollyfill. I do not want to load pollyfills if it is not necessary for that browser.

You could just use typeof to check whether or not they are defined:
typeof(TextEncoder)!='undefined'

Pay attention to use the property of window instead of the variable. Otherwise the browser can give you an error: 'TextDecoder' is not defined
if(window.TextDecoder === undefined){
// load some pollyfill
}

Related

Cross browser navigation of DOM elements in Javascript

A teammate of mine wrote some code about a short time ago which navigated about the DOM elements in out HTML page to pre-fill some fields in a modal based on the already existing data in an object (the modal allowed a user to edit that data). The items are generated generically from a database table.
function showModal(editImage) {
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0];
var nameAndTitle = editImage.srcElement.parentElement.innerHTML;
var parent = editImage.srcElement.parentElement.parentElement;
etc....
The problem is, they only tested that it worked in Chrome. The code never worked in firefox, it seems. When I try to open one of the modals in firefox, I get the console output "TypeError: editImage.srcElement is undefined"
My question is, is there a more "correct" way to access this data that will work for any browser, or do I need to check what browser I am in and access that information in a different way depending on the browser being used?
Your immediate answer is: change srcElement to target. The Mozilla Developer Network is a very good (one of many) resource to check for standards compliance. A visit to their site for srcElement indicates that it is non-standard and makes the suggestion on the correct way (target).
Unfortunately, even APIs that are standard don't always work in all browsers. Usually, parts of a standard are implemented piecemail. Checking with authoritative sources is vital to know what is supported where.
Other resources:
The World Wide Web Consortium (W3C) for HTML, CSS, XML and many others
The European Computer Manufacturer's Association (ECMA) for JavaScript
CanIUse.com Good for quick compatibility compliance checking
As for your explicit question:
"My question is, is there a more "correct" way to access this data that will work for any browser, or do I need to check what browser I am in and access that information in a different way depending on the browser being used?"
Use standards and check for support (via the resources I've provided above) to have the best chance at cross-browser code.
DO NOT write code that checks the browser type and version to see if your code will run (browser detection) because:
There are too many browsers and too many versions - this sucks!
Browsers can and will lie to you about what they are!
Use "feature detection" when in doubt. Feature detection is code that evaluates whether a feature exists and uses it if it does. If it doesn't a fallback is provided. Here's a very common one for IE8 (and lower) browsers that did not yet support the W3C standard for event handling:
// Here we are attempting to obtain the value of the
// addEventListener property of the window object.
// IE 8 doesn't implement this property so "undefined"
// will be returned. But, because we are attempting to
// use the value as the condition of an if/then construct
// "undefined" will be converted to a boolean. "undefined"
// is a "falsey" value, so it will convert to false.
// This means that if the else portion of our construct
// is reached, we have a browser that doesn't support
// addEventListener
if(window.addEventListener){
// W3C standards are supported - do things the standard way
obj.addEventListener("click", someFunction, capture);
} else {
// Must be IE 8 or less - do things the IE way
obj.attachEvent("onclick", someFunction);
}
This is but one way to use feature detection, but it typically hinges on converting a value to a boolean. See more on it here.
That function showModal is probably an event listener, so the argument editImage is actually an Event object.
As such, the actual property that reports the source of the event - and the only one supported by Firefox - is target, while srcElement is a legacy property that was created by Microsoft and Webkit/Blink based browsers kept supporting it for compatibility. But not Firefox.
In short: use target or, if you need to support older version of Internet Explorer, try with (editImage.target || editImage.srcElement).
srcElement is from IE. The standard property is target.
You should do this:
var target = editImage.srcElement || editImage.target;

how can i use require(""); in javascript

i want to use a plugin in Firefox that it is in this. in this plugin tutorial use require function, and it is: require("sdk/preferences/service");
but i get error that require is not defined. so i search and download requireJS. but when attach this i get error module name sdk/preference/service has not been loaded yet from context. use require([]).
so i use require(["sdk/preferences/service"],function(pref){}); but in function i can't use pref and get error script error sdk/preferences/service
so how can i use require function?
or a HTML example that use require function and it works correctly?
The code you found was for use in a Firefox extension. You’re not writing a Firefox extension, you’re using a web page, so you can’t use that code. There’s no drop-in replacement; you’ll have to find something else.

Css property support detection

Is there a generic way in javascript to check if the css property is supported by current browser or not?
I am currently using "document.compatMode" to check if it is quirks or not. But there must be a way to check specific to a property.
You can do this, ex:
typeof document.body.style.borderRadius
In supported browsers, it should return 'string'. In non supported, it will be 'undefined'
There is a new DOM API CSS.supports for that purpose. FF, Opera (as supportsCSS) and Chrome Canary already implement this method.
For cross-browser compatibility you can use my CSS.supports polyfill
Example:
CSS.supports("display", "table");//IE<8 return false
But, you still need to specify browser prefix for prefixing css properties. For example:
CSS.supports("-webkit-filter", "blur(10px)");
I suggest to using Modernizr for feature-detection.
No.
There's not.

In what situation would document.open() return null?

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.

Which is a better way to detect a client's user-agent?

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

Categories

Resources