1

I am using a javascript lib and it seems to be failing because of my other libs on this big site. Is there a way I can sandbox it somehow? perhaps putting it in an iframe then assigning a var in my javascript class as

var myvar = iframe.theJSlib;

I'm just writing an idea. I don't know how to sandbox nor if it could be done. How do I sandbox a javascript lib and access it in my main page?

BruteCode
  • 1,143
  • 7
  • 16
  • 22

4 Answers4

1

This is why we practice keeping vars out of the global scope. Try to either enclose everything in the lib in its own function, like so:

(function(){
  // the library code
}());

Keep in mind this will only fix explicitly declared variables like var foo = 'bar'; but will NOT fix implicitly declared variables like foo = 'bar', which will still be assigned to the global object, most likely window.

You can also try to change all your code to use a single namespace like so:

var myApp = {};

myApp.foo = { /* maybe my validator code */ };
myApp.bar = { /* maybe my utilities code */ };
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • To avoid implicit globals, you can use the `"use strict";` directive. It won't prevent overwriting existing globals though. – Felix Kling Jan 24 '13 at 17:02
0

Putting it in an Iframe would certainly stop it from working properly. All you can do is wrap the offending code in a function so everything runs within the scope of that function.

See: Javascript Namespacing

And: JavaScript Namespace

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • This won't necessarily work because it will still affect the window object unless you run them in compatibility mode – PitaJ Jan 24 '13 at 16:50
  • Yes, a lot of this depends on the behaviour of the script as well. Scripts deliberately polluting the global space are also likely to break things. – Diodeus - James MacFarlane Jan 24 '13 at 16:55
0

You can't just sandbox one lib at a time. You have to sandbox them all by running them in compatibility mode in their own namespaces:

(function(myLib){
    // do stuff with this lib here
})(theLongLibname)
PitaJ
  • 12,969
  • 6
  • 36
  • 55
  • This somehow didnt fix it. I don't exactly know whats going on. I suspect it may be using global names and not caring – BruteCode Jan 24 '13 at 19:32
0

put it in an anonymous function:

(function(){
    // >Your code goes here<
})();
Erick Ribeiro
  • 756
  • 2
  • 8
  • 14