[英]Can I sandbox 3rd party JavaScript to protect the global namespace?
At work I have to deal with a lot of (sometimes awful) JavaScript that vendors expect us to drop into our websites. 在工作中,我必须处理很多(有时很糟糕)JavaScript,供应商希望我们将它们放到我们的网站中。 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? 有哪些解决方案可以在仍然使用任意第三方JavaScript的情况下保持全局范围整洁?
Edit: @kirilloid's comment tells me I haven't been clear about how this code is delivered. 编辑:@kirilloid的评论告诉我,我不清楚该代码的交付方式。 I'm not usually given code to put into our website. 通常我不会得到要放入我们网站的代码 。 Most of the time, I'm just given a URL and asked to create a script
tag that points to it. 大多数时候,我只是得到一个URL,并被要求创建一个指向它的script
标签。
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. 如果您以无法修改的<script>
标记的形式显示代码,则可以立即停止尝试。
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). 这将停止使用var
声明的任何变量在全局范围内发布(但是隐式全局变量仍然会出现问题)。
(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. 您可以使用“ use strict”来防止它们使用隐式全局变量,但是,如果代码看上去如此糟糕,这将无济于事。
An additional change (and prehaps the best) you could make could be to wrap your own code in a closure, and keep local copies of the important window properties ( undefined
) etc in there; 您可能要做的另一项更改(可能是最好的更改)是将自己的代码包装在一个闭包中,并在其中保留重要窗口属性( undefined
)等的本地副本; this way you prevent other scripts affecting yours (this is what libraries such as jQuery do). 这样,您可以防止其他脚本影响您的脚本(这就是jQuery之类的库)。
(function (jQuery, $, undefined) {
alert(undefined == 4); // false!
}(jQuery, $));
undefined = 4;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.