Preventing auto-creation of global variables in Javascript - javascript

I just spent some time debugging a problem that boiled down to forgetting to use the var keyword in front of a new variable identifier, so Javascript was automatically creating that variable in the global scope. Is there any way to prevent this, or change the default behavior, without using a validator like JSLint?
Running a validator in between writing and executing Javascript code seems like a poor excuse for compiling, which is the step I'd usually rely on to catch this sort of thing.
I'm guessing the answer is a "no," so I'm looking into a JSLint Eclipse plugin as I post this.

ES5 strict mode prevents automatic creation of global variables, but it's probably going to be a year before there are any shipping browsers that recognise strict mode, so JSLint is probably your best bet until then :-/

Check this handy bookmarklet created by Remy Sharp, you can use it to check whether any variables have slipped out to the global namespace.

Not that I know of -- JS developers have historically been adverse to adding "seat belts" to the core language, so they've been implemented in external tools like JSLint instead. You might consider adding JSLint to your build/test process via it's Rhino version, and make the test suite fail if JSLint reports errors.

The answer is indeed no - but you could use the Eclipse plugin as you said, which can as far as I know run when saving etc., so it won't require additional steps.
IntelliJ IDEA is also able to spot undeclared variables. IntelliJ does it real-time as you type and can also analyze your codebase jslint-style. Probably some other alternatives too.

I made a bookmarklet some time ago to inspect and detect global variables.
(source: thinkweb2.com)
It has some additional features (like filtering out Prototype.js or Google Analytics properties) too.

Install Firebug, and enable it on your site. It will complain each time you create a global without var, as well as some other situations which you might or might not want to catch.
You can also do this using the about:config option javascript.options.strict, but since that's global it'll affect all the other sites you browse too.

Related

Checking JavaScript code for typos in Notepad++

I use a combination of Notepad++, JSHint and Cordova CLI to create my hybrid Android web apps - yes, I am aware that there are more sophisticated ways of doing this but tht is not what this question is about.
One of the issues I run into every now and again is a typographic - as opposed to syntactic which is easily caught by JSHint - error which only manifests itself once I am compiled the APK and tried to run it. For instance
docment instead of document (missing u)
getElmentByID instead of getElementById (missing e, wrong capitalization on ID)
The one thing I really love about Java is that the compiler stops you dead in your tracks and demands that you fix such errors first. That is not the case with JavaScript where the best one can do is test for correct syntax.
However, I am wondering - perhaps there is a way (maybe a NPP plugin that I am unaware of) to check for such errors?
Use typescript or flowtype to catch those, and many more errors. Alternatively, find a decent syntax theme that's set up to highlight DOM methods.

How to detect global variables with the sonar javascript plugin

We're trying to detect usage of global variables in our js code by using a sonar analysis. It seems that this rule was present in old versions of the javascript plugin, but not anymore (we're using version 1.2 of the plugin).
Are we doing something wrong ? Or is there a way to use XPath to mimic this rule ?
Thanks in advance
Previous version of the Sonar Javascript plugin was based on JSLint, and JSLint has a check for global variables. However, in the newest versions of the Sonar Javascript plugin, we removed JSLint and implemented our own parser and rules. This is why you don't get violations on this now.
Currently, we haven't implemented this rule but it's in our backlog (see http://jira.codehaus.org/browse/SONARPLUGINS-1821). Feel free to vote for it to push it up to the top of the backlog!
I'm not familiar with Sonar, but you can detect globals using this nifty little bookmarklet; or you could use the source code to work the results into your testing or CI framework, etc, etc.

What's the best tool for Javascript security auditing?

Something that can at least scan a batch of .js files looking for eval statements and other questionable code. Maybe just a regex pattern would do it, but I'd like to find a more sophisticated (and regularly maintained) tool.
old topic but new tool :
ScanJS, developed by mozilla in order to check the Firefox OS security.
https://github.com/mozilla/scanjs
Have you tried Douglas Crockford's JSLint? Although it doesn't scan your code for security problems, however, it does alert you on "eval" statements. OTOH, Predrag Tomasevic has wrote a JavaScript Verifier based on JSLint that can be integrated with Visual Studio (read more on this here).
I'm not aware of any Open Source tools that conduct static analysis of JavaScript.
Grepping for eval() likely isn't going to help for anything other than very simple, very obvious mistakes. It'll be even more difficult to analyze if the script has been minified or obfuscated because you'll be hard-pressed to determine if the argument is being used safely or not.
There are plenty of security problems in JavaScript that rely on the interaction with the DOM. Grepping for eval() might work, but it'll miss other execution points like hrefs or event handlers that might be attacked, e.g. href=javascript:xss or onFoo=xss. You really need a tool that deals with JavaScript and the DOM, not just a JavaScript console.
IBM/Watchfire recently released a paper about a JavaScript analyzer they've created. The paper provides details on results rather than implementation. A commercial tool might not be the way you want to go, but the paper should help shed more light on the challenges of doing this well.
This tool from Facebook seems promising.
https://github.com/facebook/jsgrep

Javascript obfuscation and extreme situation in production solving

I have a few questions regarding JavaScript obfuscation on client side.
First question:
What is the best tool or best three tools which ones you could suggest for this operation?
Second question:
How developers should debug such code (in example with firebug) when extreme situation appears in the production if the code is obfuscated?
P.S. - I know that it's bad practice to debug in production, but we had some emergencies and experienced sometimes such situations.
Thanks for any help!
1) closure compiler with advanced optimizations
2) First double their pay, then show them jsbeautifier.org
If you are looking for obfuscation I would say JScrambler. They also have a comparison table on the site that lists other well known javascript obfuscators.
For debugging you could use something like SpiderMonkey or Rhino. Firebug is very good to retrive the decoded source code when encoding is applied.
I think IE8 javascript debugger (under the developer tools) actually re-indent/re-format your code so its readable again.
Not sure if this feature has been added to Firebug, haven't used it lately, but I really wanted this feature a while ago.
Our SD ECMAScript Obfuscator retains a map of how it obfuscated your code. If you do client-side, obfuscated-code debugging, that map will tell which symbol in the original source is it actually referencing.
If you want to debug "nicely formatted" obfuscated code, you can get that from the ECMAScript Obfuscator, by first obfuscating (getting code with all layout lost), and then running back through the obfuscator to prettyprint it (it has this option).
A third option is to generate the obfuscated code in "debugging" mode. The obfsucated result is identifcal to what the production obfuscation is, except that each scrambled variable is named "XXX". This makes understanding the code being debugged just as easy as the original, while validating that the obfuscation renaming is correct. After you've done your debugging, you simply re-obfuscate in production mode.

Firefox add-on tools for checking JavaScript syntax?

Not sure if there is any Firefox add-on tool for checking JavaScript syntax, var declaration, or even pre-compiling available?
I find out is very difficult to debug JavaScript in a web html page. I have to add some script there. When the scripts get very big or long, it stops working. Basically, there must be some bugs. It is very frustrating even the load event stop working. I do need some good tools to find out the bugs.
I have tried FireBug. It is good but not enough. Maybe I don't know all its features. Anyway, I need any good suggestions.
This page may help you a bit as it also contains a screencast.
Debugging Javascript in Firefox with Firebug
It's not strictly an Add-On (although you can obviously run it in a Firefox web page), but I've found JSLint to be helpful in exposing expression anomalies that might or might not be strictly invalid syntax (although it will catch all those, too.)
My suggestion is to check you javascript with JSLint. JSLint will show you common problems in javascript code and helps you to create strict and compatible code.
YSlow includes JSLint as Tool.
As an alternative to FireBug check this debugger: Venkman JavaScript Debugger, has been out there for a while, and it's not bad at all...
I have always been a firebug fan and it sure is one of the best debuggers out there. Any JS issue Press F12, Enable the console for catching the errors and then you can find the exact line causing the error. Add a breakpoint and you can see the exact values of variables too. Very intuitive UI..just get used to using it and it will save a lot of your time.
I HIGHLY recommend Rainbow. It's still in Beta and only works in FF3, but it offers syntax highlighting. That will get you half-way there when it comes to syntax.
I constantly use firebug with a js file that has some 15000 lines. I've had no problems with it (sometimes I have to wait a few seconds for it to scroll to the breakpoint but even then it works fine).
Unfortunately JSLint does'nt work for us. We use some third party code that while beeing "valid" has unnecessary ";" according to jsLint. The code is in the beginning of our js file and jslint stops analyzing at 3% because it thinks there are too many errors (all of them unnecessary ";".)
You're missing the point on 2 counts:
First, being presented with a gazillion unnecessary error messages will make it impossible to find the problem in the first place.
Secondly, the errors are unnecessary. I used to use JSLint religiously, but now it's become too much of a code Nazi and I can't use it.
I'm aware that many of the things it checks for can be disabled, but I just don't have enough time to research what I'd have to do.
The issue is the usability of the default configuration. I, like the original poster, am just looking for a way to find true JavaScript syntax errors very quickly, including on HTML pages. I'm sure that Firebug can do it, but as in the case with JSLint, I don't have the spare time to find out how.
I do, however, use Firebug for debugging, though the version I'm using (1.10.3) has a bad habit of displaying errors, but reporting an incorrect file and line number.
Hi Gene: you could change one variable option.maxerr inside your jslint.js file into the number you want.
The default value is 50, you could change it to 500 or 1000 to suite your taste.
I use both the following for code validation.
JSHint # http://jshint.com
JSLint FF Plugin. Get at https://addons.mozilla.org/en-us/firefox/addon/jslinter/
Alternatively, jshint and jslint plugins are available for text editors like Notepad ++, sublime etc.

Categories

Resources