另一个答案是不正确的。第一部分(关于onSuspend
事件)实际上是不正确的。about 部分setUninstallURL
是相关的,但不能回答问题,因为它不允许您将选项卡恢复到其原始状态(正如您在问题中所问的那样)。
在这个答案中,我将首先澄清关于 的误解runtime.onSuspend
,然后解释如何在禁用扩展时为内容脚本运行代码。
关于runtime.onSuspend
和事件chrome.runtime.onSuspend
与chrome.runtime.onSuspendCanceled
禁用/卸载的扩展无关。这些事件是为事件页面定义的,这些页面基本上是在一段时间不活动后暂停(卸载)的背景页面。当事件页面由于暂停而即将卸载时,runtime.onSuspend
被调用。如果在此事件期间调用了扩展 API(例如发送扩展消息),则暂停将被取消并触发onSuspendCanceled
事件。
当由于浏览器关闭或卸载而卸载扩展程序时,无法延长扩展程序的生命周期。因此,您不能依赖这些事件来运行异步任务(例如从后台页面清理选项卡)。
此外,这些事件在内容脚本中不可用(仅限扩展页面,例如背景页面),因此这些事件不能用于同步清理内容脚本逻辑。
从上面可以明显看出,这与禁用runtime.onSuspend
时清理的目标无关。不在 Chrome 中,更不用说 Firefox(Firefox 不支持事件页面,这些事件将毫无意义)。
在扩展禁用/卸载时在选项卡/内容脚本中运行代码
Chrome 扩展中的一个常见模式是使用port.onDisconnect
事件来检测后台页面已卸载,并使用该事件来推断扩展可能已卸载(结合此方法的选项 1以获得更高的准确性)。Chrome 的内容脚本在扩展程序被禁用后会保留下来,因此可用于运行异步清理代码。
这在 Firefox 中是不可能的,因为在禁用 Firefox 扩展时,内容脚本的执行上下文会在port.onDisconnect
事件有机会触发之前被破坏(至少在bugzil.la/1223425修复之前)。
尽管有这些限制,但在禁用加载项时仍然可以为内容脚本运行清理逻辑。此方法基于这样一个事实,即在 Firefox 中,插入的样式表tabs.insertCSS
在禁用附加组件时会被删除。
我将讨论利用这一特性的两种方法。第一种方法允许执行任意代码。第二种方法不提供任意代码的执行,但如果您只想隐藏一些扩展插入的 DOM 元素,则更简单且足够。
方法一:禁用扩展时在页面中运行代码
观察样式更改的方法之一是声明CSS 过渡并使用过渡事件来检测 CSS 属性更改。为此,您需要以仅影响 HTML 元素的方式构建样式表。因此,您需要生成一个唯一的选择器(类名、ID、...)并将其用于您的 HTML 元素和样式表。
这是您必须放入后台脚本的代码:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message !== 'getStyleCanary') return;
// Generate a random class name, insert a style sheet and send
// the class back to the caller if successful.
var CANARY_CLASS = '_' + crypto.getRandomValues(new Uint32Array(2)).join('');
var code = '.' + CANARY_CLASS + ' { opacity: 0 !important; }';
chrome.tabs.insertCSS(sender.tab.id, {
code,
frameId: sender.frameId,
runAt: 'document_start',
}, function() {
if (chrome.runtime.lastError) {
// Failed to inject. Frame unloaded?
sendResponse();
} else {
sendResponse(CANARY_CLASS);
}
});
return true; // We will asynchronously call sendResponse.
});
在内容脚本中:
chrome.runtime.sendMessage('getStyleCanary', function(CANARY_CLASS) {
if (!CANARY_CLASS) {
// Background was unable to insert a style sheet.
// NOTE: Consider retry sending the message in case
// the background page was not ready yet.
return;
}
var s = document.createElement('script');
s.src = chrome.runtime.getURL('canaryscript.js');
s.onload = s.remove;
s.dataset.canaryClass = CANARY_CLASS;
// This function will become available to the page and be used
// by canaryscript.js. NOTE: exportFunction is Firefox-only.
exportFunction(function() {}, s, {defineAs: 'checkCanary'});
(document.body || document.documentElement).appendChild(s);
});
我使用上面的脚本标记,因为它是在页面中运行脚本而不会被页面的内容安全策略阻止的唯一方法。确保添加canaryscript.js
到web_accessible_resources
manifest.json,否则脚本将不会加载。
如果运行清理代码并不重要(例如,因为您还使用我稍后解释的方法 2),那么您最好使用内联脚本而不是外部脚本(即使用s.textContent = '<content of canaryscript.js>'
代替s.src = ...
)。这是因为使用.src
扩展资源会给 Firefox 带来指纹识别漏洞(错误 1372288)。
这是的内容canaryscript.js
:
(function() {
// Thes two properties are set in the content script.
var checkCanary = document.currentScript.checkCanary;
var CANARY_CLASS = document.currentScript.dataset.canaryClass;
var canary = document.createElement('span');
canary.className = CANARY_CLASS;
// The inserted style sheet has opacity:0. Upon removal a transition occurs.
canary.style.opacity = '1';
canary.style.transitionProperty = 'opacity';
// Wait a short while to make sure that the content script destruction
// finishes before the style sheet is removed.
canary.style.transitionDelay = '100ms';
canary.style.transitionDuration = '1ms';
canary.addEventListener('transitionstart', function() {
// To avoid inadvertently running clean-up logic when the event
// is triggered by other means, check whether the content script
// was really destroyed.
try {
// checkCanary will throw if the content script was destroyed.
checkCanary();
// If we got here, the content script is still valid.
return;
} catch (e) {
}
canary.remove();
// TODO: Put the rest of your clean up code here.
});
(document.body || document.documentElement).appendChild(canary);
})();
注意:CSS 转换事件仅在选项卡处于活动状态时才会触发。如果选项卡处于非活动状态,则在显示选项卡之前不会触发转换事件。
注意:exportFunction
是一种仅限 Firefox 的扩展方法,用于在不同的执行上下文中定义函数(在上面的示例中,函数是在页面上下文中定义的,可用于在该页面中运行的脚本)。
所有其他 API 在其他浏览器中也可用(Chrome/Opera/Edge),但代码不能用于检测禁用的扩展,因为tabs.insertCSS
在卸载时不会删除样式表(我只用 Chrome 测试过;它可能在 Edge 中工作) .
方法二:卸载后视觉恢复
方法 1 允许您运行任意代码,例如删除您在页面中插入的所有元素。作为从 DOM 中删除元素的替代方法,您还可以选择通过 CSS 隐藏元素。
下面我将展示如何修改方法 1 以隐藏元素而不运行其他代码(例如canaryscript.js
)。
当您的内容脚本创建要插入 DOM 的元素时,您可以使用内联样式将其隐藏:
var someUI = document.createElement('div');
someUI.style.display = 'none'; // <-- Hidden
// CANARY_CLASS is the random class (prefix) from the background page.
someUI.classList.add(CANARY_CLASS + 'block');
// ... other custom logic, and add to document.
在使用 添加的样式表中tabs.insertCSS
,然后使用标志定义所需的display
值,!important
以便覆盖内联样式:
// Put this snippet after "var code = '.' + CANARY_CLASS, above.
code += '.' + CANARY_CLASS + 'block {display: block !important;}';
上面的例子是故意通用的。如果您有多个具有不同 CSSdisplay
值的 UI 元素(例如block
, inline
, ...),那么您可以添加多个这样的行来重用我提供的框架。
为了显示方法 2 相对于方法 1 的简单性:您可以使用相同的后台脚本(经过上述修改),并在内容脚本中使用以下内容:
// Example: Some UI in the content script that you want to clean up.
var someUI = document.createElement('div');
someUI.textContent = 'Example: This is a test';
document.body.appendChild(someUI);
// Clean-up is optional and a best-effort attempt.
chrome.runtime.sendMessage('getStyleCanary', function(CANARY_CLASS) {
if (!CANARY_CLASS) {
// Background was unable to insert a style sheet.
// Do not add clean-up classes.
return;
}
someUI.classList.add(CANARY_CLASS + 'block');
someUI.style.display = 'none';
});
如果您的扩展有多个元素,请考虑将 的值缓存CANARY_CLASS
在一个局部变量中,以便您在每个执行上下文中只插入一个新样式表。