当选项卡更新时,我希望执行内容脚本函数。问题在于,有时选项卡更新是ajax(无需重新加载页面),但仍更改页面的URL。因此,旧的内容脚本注入仍存在于页面上。结果是多个实例的内容脚本被注入并在同一页面上运行。
因此,我正在寻找一种机制,只有在之前没有注入相同的内容脚本时才注入内容脚本。有什么想法吗?
因此,我正在寻找一种机制,只有在之前没有注入相同的内容脚本时才注入内容脚本。有什么想法吗?
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
if (response) {
console.log("Already there");
}
else {
console.log("Not there, inject contentscript");
}
});
});
内容脚本:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({message: "hi"});
});
实现包含保护非常容易:
(function() {
// Comparing to a literal value to prevent matching a DOM element with id="hasRun"
// https://dev59.com/-3A75IYBdhLWcg3wK1wp/do-dom-tree-elements-with-ids-become-global
if (window.hasRun === true) return;
window.hasRun = true;
// Rest of code
})();
webNavigation
事件之一(例如onCommitted),而不是chrome.tabs.onUpdated
。与tabs
事件不同,webNavigation事件也会触发框架内导航,并提供了一种预先声明URL过滤器的方法。window.hasRun
是什么?这段代码应该从哪里运行? - c00000fdhasRun
是一个任意选择的全局变量名称,应该包装内容脚本,以便只执行一次。 - Rob W