I want to write a chrome extension which can get the URL of active tab. I want it to always display the current website the person is viewing on his active tab of the current active window. I use the following code in my background script:
chrome.tabs.onActivated.addListener( function(activeInfo){
chrome.tabs.get(activeInfo.tabId, function(tab){
y = tab.url;
console.log("you are here: "+y);
});
});
This code displays current urls fine whenever I change the active tab in browser. But If I change the active tab url manually by clicking or typing, it fails to register the new url and will only do so if we switch between tabs and come back to this tab. I want to detect both the cases. How should I change my code?
Below is a script which takes care of both the cases:
chrome.tabs.onActivated.addListener( function(activeInfo){
chrome.tabs.get(activeInfo.tabId, function(tab){
y = tab.url;
console.log("you are here: "+y);
});
});
chrome.tabs.onUpdated.addListener((tabId, change, tab) => {
if (tab.active && change.url) {
console.log("you are here: "+change.url);
}
});
you should use the chrome.tabs.onUpdated.addListener
api
const getActiveUrl = (tabid, changeInfo, tab) => {
const url = changeInfo.url;
// url is likely to be empty, and filter chrome:// and about:// URLs
if (!url || ['chrome://', 'about://'].some(p => url.startsWith(p))) return;
// filtering is not an active tab
if (!tab.active) return;
// the url address you need
console.log(url);
}
chrome.tabs.onUpdated.addListener(getActiveUrl);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.