Sha*_*hay 6 google-chrome google-chrome-extension
我正在编写一个 chrome 扩展程序,在一些网站中 chrome.tabs.onUpdated.addListener() 被调用了两次。
它主要发生在我点击链接而不是我自己输入 URL 时。
从我在网上找到的内容以及在 StackOverflow 上提出的许多问题来看,chrome 上存在一个错误,但几年前已修复。
有些人声称如果页面中有多个 iframe 就会发生这种情况,但就我而言,我的页面中没有 iframe。
这是我的代码:
var storage = chrome.storage.local;
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.status == 'complete' && tab.url != undefined) {
storage.get('URLs', function(URLs){
for (var item in URLs)
{
if (tab.url == item)
{
return;
}
else
{
//alert ("tab load complete");
storage.set({URLs: [tab.url]});
chrome.tabs.executeScript(tab.id, {
"file": "flashblocker.js"
}, function () { // Execute your code
console.log("Script Executed .. "); // Notification on Completion
});
}
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能让它只运行一次?
谢谢。
使用变量并在侦听器内部添加检查以在执行警报之前检查此变量的值。你可以这样做:
var tabUpdated = false;
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.status == 'complete' && tab.url != undefined) {
if (!tabUpdated) {
alert("tab load complete");
tabUpdated = true;
}
}
});
Run Code Online (Sandbox Code Playgroud)
但是如果内容脚本实际上加载了两次,这将失败,因为 tabUpdated 变量将再次初始化为 false。在这种情况下,您可以使用 chrome 的 Storage API 并存储已调用侦听器的 URL。只需为此添加一个检查,如果 URL 在存储中,则不会调用警报,否则它将调用。然后,您可以在浏览器启动或关闭时清除存储。
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.status == 'complete' && tab.url != undefined) {
chrome.local.storage.get('URLs', function(URL's) {
// Iterate through this list here and match with tab.url, if the match is found, just return.
if (url is there in list) {return;}
else {
alert("tab load complete");
chrome.local.set({URLs: [tab.url]});
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
这只是您如何实现它的一个示例。根据您的需要调整它。
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
4480 次 |
| 最近记录: |