Mozilla 文档对此问题保持沉默。有知道的人可以回答和解释为什么或为什么不吗?如果没有,我想知道为什么不这样做的政策原因和架构决策。
编辑:这个问题仅限于不能使用附加 SDK 而是使用传统覆盖模式的扩展。
Mozilla 文档对此问题保持沉默。有知道的人可以回答和解释为什么或为什么不吗?如果没有,我想知道为什么不这样做的政策原因和架构决策。
编辑:这个问题仅限于不能使用附加 SDK 而是使用传统覆盖模式的扩展。
框架脚本不是网页,并且不提供对 jquery 期望存在的大多数全局变量的访问,例如 XHR、文档和窗口本身等。
即使您以一种看起来像窗口环境的方式操纵变量,这仍然是一个很大的问题,因为框架脚本的生命周期超出了 DOM 窗口的生命周期,即它的存在与选项卡相关联,而不是与单个页面相关联的一个选项卡。Jquery 被设计为只与页面一样长。
第三个问题是安全性,framescripts 以chrome/system 权限运行,如果您直接从 frame 脚本运行它,jquery 也会如此。Jquery 并非设计为具有安全意识,因为它通常受网站同源策略的约束。事件处理和 XHR 的一些复杂交互可能会因此打开安全漏洞。
所以不推荐在浏览器内部脚本环境中使用 jquery。
从框架脚本进行 DOM 操作的两个选项是
a) 直接从框架脚本中使用标准 DOM API。插件脚本在启用 ES6 支持的情况下自动运行(例如解构、箭头函数等),并且不必担心跨浏览器兼容性。换句话说:不需要jquery
b) 如果使用 jquery 是绝对必要的,例如因为某些 3rd-party 库依赖于它,那么可以创建一个以当前窗口为原型的沙箱,并使用下标加载器将 jquery 和自定义脚本注入其中。
创建沙盒以将其与不受信任的内容隔离并同时删除系统权限的推荐方法:
let options = {
// this is the name reported in about:memory
sandboxName: "<addon name> <purpose of sandbox>",
// ensure that jquery sees the window as global
sandboxPrototype: content,
// reduces GC overhead by having the sandbox reside in the same space as target window
sameZoneAs: content,
// don't include components object that grants access to privileged APIs
wantComponents: false,
// helper functions for interacting with untrusted content
wantExportHelpers: true,
// clean view of DOM APIs, otherwise untrusted content could override prototypes
wantXrays: true,
// addon ID, used by addon debugger and memory reporting
// sdk addons can obtain it via require("sdk/self").id, other addons define it in the install.rdf
metadata: {addonID: id}
}
// set the security principal to an extended principal covering the target window
let sandbox = Cu.Sandbox([content], options)
// structured-clone objects into the sandbox
sandbox.myData = {foo: "bar"}
loader.loadSubscript("resource://myaddon-id/libs/jquery.js", sandbox, "UTF-8")
loader.loadSubscript("resource://myaddon-id/src/mypagescript.js", sandbox, "UTF-8")
// call custom function created by mypagescript.js
sandbox.myFunc()
请注意,沙箱仅在页面的生命周期内有效,因此如果框架被导航到新窗口(content
对象),您将不得不创建一个新的沙箱
以上基本上是 SDK 的page-mod和 webextensions content-scripts使用的底层底层 API 。
请参阅我对您的 OP 的评论。您阅读的文档与内容脚本无关。它是关于框架脚本和其他提升范围的。谷歌浏览器没有这些提升的范围。他们只有内容脚本。这就是为什么我们都感到困惑。
这就是您在内容脚本中使用 jpm addon sdk 的方式。
将 jquery 库下载到您的数据文件夹中。
var tabs = require("sdk/tabs");
var mod = require("sdk/page-mod");
var self = require("sdk/self");
var pageUrl = self.data.url("page.html")
var pageMod = mod.PageMod({
include: '*',
contentScript: [self.data.url('jquery.min.js'), "console.log(jQuery);"]
})
这会将 jQuery 插入所有网站。tabs.open(pageUrl);
如果您使用 webextensions 的方式与 google chrome 完全相同:https ://developer.mozilla.org/en-US/Add-ons/WebExtensions/