[英]How do I add or remove Chrome extension, content-script, javascript files dynamically?
I'm making a chrome extension. 我正在制作镀铬扩展程序。 I want to add or remove a few content script files from a popup page, using javascript, when the extension is running. 我想在扩展程序运行时使用javascript从弹出页面添加或删除一些内容脚本文件。
In my extension, the user picks a color from popup page. 在我的扩展程序中,用户从弹出页面中选择一种颜色。 There are 5 colors. 有5种颜色。 So I have 5 javascript files -- one for each color. 所以我有5个javascript文件 - 每种颜色一个。
So, what javascript code, in the popup page, will change the running content script javascript file? 那么,弹出页面中的哪些javascript代码会改变运行内容脚本javascript文件?
First off, if you have 5 JS files, one for each of 5 colors, this smacks of "Clone And Modify Programming" -- which is a bad habit to be in. 首先,如果你有5个JS文件,每个5个颜色一个,这就是“克隆和修改编程” - 这是一个坏习惯。
The smart thing to do is to have one JS file, with "DRY" code that switches off color as a parameter. 聪明的做法是拥有一个 JS文件,其中“DRY”代码将颜色作为参数关闭。 See "Dont Repeat Yourself" (sic). 请参阅“不要重复自己” (原文如此)。
To load whole content scripts, from your extension's background, see "Programmatic injection" . 要加载整个内容脚本,请从扩展程序的背景中查看“程序化注入” 。
As for adding or removing javascript files dynamically... 至于动态添加或删除javascript文件...
You can't remove a file once it is loaded. 加载后无法删除文件。 Even if it is in a <script>
node and you delete that, the parsed functions, variables, timers, event-listeners, etc. will still be active in memory. 即使它在<script>
节点中并且您删除它,解析的函数,变量,计时器,事件监听器等仍将在内存中处于活动状态。
x=7;
例如,如果File‗1.js全局设置x=7;
, you can later load File‗2.js to set x=11;
,你可以稍后加载File‗2.js来设置x=11;
. 。 (function () {... ...} )()
). 您不能覆盖匿名对象( (function () {... ...} )()
)。
In most cases, this is all more trouble than it is worth. 在大多数情况下,这比它的价值更麻烦。 Best to design your code to where it's not necessary. 最好将代码设计到不必要的地方。
You can add JS (or other kinds of files) dynamically, see below. 您可以动态添加JS(或其他类型的文件),请参阅下文。
To add JS files dynamically... 要动态添加JS文件......
Make sure that the file(s) are listed in the web_accessible_resources
section of your manifest.json file. 确保manifest.json文件的web_accessible_resources
部分中列出了文件。 For example: 例如:
{ "manifest_version": 2, "content_scripts": [ { "exclude_globs": [ ], "include_globs": [ ], "js": [ "MyContentScript.js" ], "matches": [ "http://YOUR_SERVER.COM/YOUR_PATH/*" ] } ], "name": "Dynamically load JS, demo", "version": "1", "web_accessible_resources": [ "MyJavascript_1.js", "MyJavascript_2.js", "MyJavascript_3.js" ] }
Then, in your content script ( MyContentScript.js ), you can use chrome.extension.getURL
, like so: 然后,在您的内容脚本( MyContentScript.js )中,您可以使用chrome.extension.getURL
,如下所示:
var D = document; var scriptNode = D.createElement ('script'); scriptNode.type = "text/javascript"; scriptNode.src = chrome.extension.getURL ("MyJavascript_2.js"); var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement; targ.appendChild (scriptNode);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.