¿Puedo aislar JavaScript de terceros para proteger el espacio de nombres global?

At work I have to deal with a lot of (sometimes awful) JavaScript that vendors expect us to drop into our websites. Some of them add arbitrary, un-namespaced, names to the global scope. I've been toying with different ideas about sandboxing these programs so they don't have direct access to the global scope, but I haven't been able to think of anything that might actually work. (I thought of evalling the fetched code, but I'm convinced that's a bad idea.)

What solutions are there to keep the global scope clean while still using arbitrary 3rd party JavaScript?

Edit: @kirilloid's comment tells me I haven't been clear about how this code is delivered. I'm not usually given código to put into our website. Most of the time, I'm just given a URL and asked to create a script etiqueta que lo señala.

preguntado el 09 de marzo de 12 a las 14:03

Insert code dropped at you into function call and expose only functions, your need. adecuadamentegood.com/2010/3/JavaScript-Module-Pattern-In-Depth -

@kirilloid Sorry about the confusion. I could use the module pattern if I had code to use the module pattern on. I would've done that with my eval idea above, but most of the time I'm just given a URL pointing to the third-party script hosted elsewhere. I've updated my question to reflect this. -

1 Respuestas

Your options are pretty limited. If the code is presented to you in the form of a <script> tag you can't modify, you can stop trying now.

If you can modify the script, you can wrap the code in a closure; this will stop any variables they declare with var being published in the global scope (but you'll still get problems with implicit globals).

(function () {

    var aGlobalVariableThatUsedToCauseACollision = 4; // no longer collides!

    anotherGlobalVariableThatUsedToCauseACollision = 4; // Mmmmm.


Probably an infeasible option; you could use "use strict" which prevents them using implicit globals, but if the code is as awful as it seems, this won't help you.

An additional change (and prehaps the best) you could make could be to wrap your es dueño code in a closure, and keep local copies of the important window properties (undefined) etc in there; this way you prevent other scripts affecting yours (this is what libraries such as jQuery do).

(function (jQuery, $, undefined) {
    alert(undefined == 4); // false!
}(jQuery, $));

undefined = 4;

respondido 09 mar '12, 14:03

Agreed, if their code is so awful they are probably relying on a reference to a global namespace object and sandboxing this or changing its namespace could break it. Best option is to protect yourself from the bad. - jjnford

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.