Kev*_*ang 7 javascript include google-chrome-extension
我想在更新选项卡时执行内容脚本功能.问题是,有时候标签更新是ajax(没有页面重新加载),同时仍然会更改页面的URL.因此,注入的旧内容脚本仍然存在于页面上.结果是在同一页面上注入并运行了多个内容脚本实例.
所以,我正在寻找一种注入内容脚本的机制,只有在之前没有注入相同的内容脚本时.有任何想法吗?
Uza*_*ooq 13
您可以尝试向内容脚本发送消息(消息传递).如果内容脚本成功返回响应,则表示内容脚本已经存在,否则返回空响应,您可以检查空响应并注入内容脚本.
背景:
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");
}
});
});
Run Code Online (Sandbox Code Playgroud)
ContentScript:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({message: "hi"});
});
Run Code Online (Sandbox Code Playgroud)
实施包含保护非常简单:
(function() {
if (window.hasRun) return;
window.hasRun = true;
// Rest of code
})();
Run Code Online (Sandbox Code Playgroud)
如果要以编程方式注入内容脚本,请考虑使用其中一个webNavigation事件(例如onCommitted)而不是chrome.tabs.onUpdated.与tabs事件不同,webNavigation事件也会触发帧内导航,并提供一种预先声明URL过滤器的方法.
| 归档时间: |
|
| 查看次数: |
5440 次 |
| 最近记录: |