我正在开发Chrome扩展程序.我没有使用manifest.json匹配所有URL的内容脚本,而是chrome.tabs.executeScript在用户单击扩展图标时通过调用来懒惰地注入内容脚本.
我正在尝试的是避免多次执行脚本.所以我在我的内容脚本中有以下代码:
if (!window.ALREADY_INJECTED_FLAG) {
window.ALREADY_INJECTED_FLAG = true
init() // <- All side effects go here
}
Run Code Online (Sandbox Code Playgroud)
问题#1,chrome.tabs.executeScript每次点击扩展图标时这是否足够安全?换句话说,这是幂等的吗?
问题#2,是否有类似的方法chrome.tabs.insertCSS?
似乎无法在backgroud脚本中检查内容脚本注入状态,因为它无法访问网页的DOM.我已经尝试了ping/pong方法来检查任何内容脚本实例是否存活.但这会带来设计ping超时的开销和复杂性.
问题#3,任何更好的后台脚本方法来检查内容脚本的注入状态,所以我可以阻止chrome.tabs.executeScript每次用户点击图标时调用?
提前致谢!
请原谅我的任何明显错误,因为我是 chrome 扩展程序的新手,但是 Chrome 消息传递 API 的这个错误已经在这里、这里和这里讨论过,常见的响应是“禁用现有的 Chrome 扩展程序,一个他们中的一个导致错误'。这是能做到的最好的吗?我们是否应该只是滚动并接受我们的扩展会与其他扩展发生冲突的事实?为侦听器回调函数返回 true 或返回 Promise 并使用sendResponse并不能解决我的问题。
目前,我只能chrome.storage.local通过禁用所有其他 chrome 扩展、删除扩展并重新加载解压缩的扩展来获取存储在(无错误)中的新值。有趣的是,该代码似乎只适用于 developer.chrome.com,它根本不适用于manifest.json.
我认为awaitandasync操作符在解决这个问题上有一定的意义,但我不确定如何正确实现它。
清单.json:
{
"manifest_version": 2,
"name": "my extension",
"version": "1.0",
"description": "its my extension",
"permissions": [
"declarativeContent",
"storage",
"activeTab"
],
"content_scripts": [
{
"matches": [
"*://developer.chrome.com/*",
"*://bbc.co.uk/*",
"*://theguardian.com/*",
"*://dailymail.co.uk/*"
],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": …Run Code Online (Sandbox Code Playgroud) 我设法构建了Ripple Emulator开源软件(https://github.com/apache/incubator-ripple).
我根据说明(Jake构建)构建了它,它创建了Chrome扩展目标,允许我通过我内置的chrome扩展测试我的网络应用程序,按照https://github.com/apache/incubator-ripple/blob /master/doc/chrome_extension.md.
我成功地将解压缩的扩展加载到chrome上,但是当我启用它时没有任何反应,虽然页面重新加载扩展不起作用,而是我得到2个错误:
未捕获的ReferenceError:未定义webkitNotifications
webkitNotifications.createHTMLNotification('/views/update.html').show();
Run Code Online (Sandbox Code Playgroud)运行tabs.executeScript时未经检查的runtime.lastError:无法访问chrome:// URL
chrome.tabs.executeScript(tabId, {
Run Code Online (Sandbox Code Playgroud)我该如何解决这个问题?
完整的background.js:
if (!window.tinyHippos) {
window.tinyHippos = {};
}
tinyHippos.Background = (function () {
var _wasJustInstalled = false,
_self;
function isLocalRequest(uri) {
return !!uri.match(/^https?:\/\/(127\.0\.0\.1|localhost)|^file:\/\//);
}
function initialize() {
// check version info for showing welcome/update views
var version = window.localStorage["ripple-version"],
xhr = new window.XMLHttpRequest(),
userAgent,
requestUri = chrome.extension.getURL("manifest.json");
_self.bindContextMenu();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
var manifest = JSON.parse(xhr.responseText),
currentVersion = …Run Code Online (Sandbox Code Playgroud)