基本上,我有一个gmail铬扩展,它将特定版本的jQuery注入主页面(这很好),然后向其添加一些jQuery插件,该扩展稍后将根据需要使用这些插件。
问题是,由于所有jQuery版本(据我所知)都使用$来调用函数(和插件),如果另一个扩展进入并在我的顶部加载它的jQuery版本,那么我就失去了已安装的插件。有时,我甚至看到另一个扩展使用的版本太老了,以至于我使用的一些“标准”jQuery函数不在其中,而且它们也是未定义的。
有什么简单的方法可以把我的版本从任何其他的扩展中分离出来吗?我无法知道我的用户可能安装了哪些扩展,所以我不能这样解释所有的事情。这几天有大量的gmail铬扩展,“玩得好”似乎是一个很大的问题,随着时间的推移变得越来越成问题。
有什么想法如何“保护”我的jQuery版本和插件?
发布于 2015-09-13 20:51:25
正如亚伯拉罕在我最初问题中的评论中所指出的,正确的做法是将扩展名javascript文件放在内容脚本中,这样它们就处于一个“孤立的世界”,不能被其他扩展或页面本身修改。您甚至可以使用这一方法显式地包含几个JS文件(在我的例子中,jquery和single以及几个jquery插件),而不必将它们全部定义在一个文件中,并且仍然将它们与页面本身隔离开来。
只需注意您在清单文件中定义它们的顺序,因为这正是chrome将加载它们的顺序(因为有些可能是其他文件的依赖项)。
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.
要参考Google文档,请参阅:scripts
发布于 2015-09-11 09:10:16
可以将jQuery对象保存在特定变量中,并在插件中引用此变量:
// load jQuery and any plugins here
<script src="BryanPjQuery.js"></script>
<script src="plugins.js"></script>
<script>
var BryanPjQuery = jQuery.noConflict();
(function( $ ) {
$(function() {
// add all code here. $ refers to BryanPjQuery
// so within this function $ = jQuery, outside this function
// other versions of $ can be used
});
})(BryanPjQuery);
</script>
有关更多细节,请参见https://api.jquery.com/jquery.noconflict/或(有更多示例) https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
https://stackoverflow.com/questions/32528591
复制相似问题