我正在创建一个 Chrome 扩展,并试图让一个函数在用户每次更改标签页时触发。我一直在查看 webRequest API 和 chrome.tabs 中的监听器,但不知道该用什么,不该用什么。
我唯一需要的信息是它的 url。
最佳答案
Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set.
— Google Documentation
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.get(activeInfo.tabId, function (tab) {
mySuperCallback(tab.url);
});
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, updatedTab) {
chrome.tabs.query({'active': true}, function (activeTabs) {
var activeTab = activeTabs[0];
if (activeTab == updatedTab) {
mySuperCallback(activeTab.url);
}
});
});
function mySuperCallback(newUrl) {
// ...
}
它绝对适用于后台页面(正如 Locercus 在 a comment 中确认的那样),但请考虑使用 event pages (自 Chrome 22 起稳定)。
关于javascript - 添加一个在用户更改选项卡时触发的监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18162644/