WARNING:
This post is intended solely to educate and is not to by any means encourage that anyone use this method to globally evaluate JavaScript code. Most JavaScripters avoid eval(), especially globalEval() (like what is provided in libraries such as jQuery), as if it were the plague. Its use can be substantiated in some cases but it is of the utmost importance to consider the risks involved with the two functions.
SCRIPTER’S DISCRETION IS ADVISED. 😆

Since many modern browsers now offer the ability to use Data URIs for more than just images, we could actually use them to essentially run a string of JS code on a page in the global namespace. How so? Here is the code for a simple globalEval() function that can be used in modern browsers such as Chrome and FireFox:

Conceivable Uses

As the jQuery docs mention, one good reason that this type of function exists is to provide a way to execute external scripts in the global namespace. It is important to reiterate that you must use this type of function sparingly, analyzing the reasons why you are using it in the first place.

Another conceivable use would be if you are developing a browser extension that really needs to execute a JavaScript snippet on certain pages. At this point though, if you decide that you want to publish your extension through Google or whichever other channel, that authority may deny your request in the interest to safeguard users from malicious intent. On the other hand, if you are simply creating something like a Chrome extension for private use, I believe you should be able to use this type of approach to execute additional code within pages visited by the user.

Final Words

Much more could be said of the uses of globalEval() and reasons not to use globalEval(), but I like to keep my posts short. If you do find yourself thinking you want to use globalEval(), be sure to calculate the risks (such as possibly running malicious code if it is coming from an external source). Also, this implementation, although very simple, will not work in older browsers such as IE7 (and hasn’t been tested in IE8 or IE9). If you really need a version that has been tested for almost all browsers, I suggest using jQuery’s implementation or perhaps this one. Be careful! 😎

Categories: BlogJavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *