1

Could anybody suggest how can I test if a particular line of JavaScript code is supported by Browser or not. If not how can I handle it? As I am learning JavaScript it would be a great help to know.

5
  • have a look at modernizr.com Commented Nov 13, 2014 at 1:22
  • Check the window object for existence of the API you want Commented Nov 13, 2014 at 1:23
  • 5
    Please post the specific code you're asking about. The techniques vary depending upon what it is. Commented Nov 13, 2014 at 1:24
  • 2
    There's a site I ran across a few weeks ago where you paste in JS and it detects potential browse compatibility issues, but I'm too lazy to track it down right now. I tried it and it seemed to be moderately useful. Commented Nov 13, 2014 at 1:36
  • 2
    More context information is needed. Do you want to take any arbitrary line of JS code and find out whether it can be executed in the browser? I.g. i++ or new Map()? Or do you want to conditionally execute code in your own module? Commented Nov 13, 2014 at 1:39

2 Answers 2

3

This would seem to be the perfect time to use try/catch:

    try {
        // your JavaScript here
        document.executeSomeUnknownFunction();
    }
    catch (error) {
        console.log("There was an error: " + error);
    }

console.log("...but nothing broke");

Or, alternatively, assuming it's a method of an Object you're testing for (for example querySelectorAll()):

if ('querySelectorAll' in document) {
  console.log("We support  'document.querySelectorAll()'");
 }

References:

Sign up to request clarification or add additional context in comments.

6 Comments

Might be that something does not work, but there is no exception.
True, but it depends what 'that' might be; and given the limited information in the question it's hard to account for possibilities I can't anticipate.
That's right. This question can most likely not be answered in a general way. Like @jfriend00 said in the comments: The techniques vary depending upon what it is.
BTW: console.log might also not supported ;-)
@Thilo: that would be entertainingly ironic... :D
|
2

You can either: 1) Assume that the code works, and handle the cases where it doesn't:

try{
   // ...
}catch(e){
   // an error occurred
}

Or 2) check if the function it relies on exists, and then use it:

if(window.yourfunction){
   // The function is present in the global scope
}else{
   // Not available, try alternatives?
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.