首页 > 解决方案 > My "background.js" code to get the selected chrome tabs url is not working properly in my chrome extension

问题描述

I have looked up many threads and i learned how to get the current url of a focused chrome tab. But the thing is when i refresh my extension it only outputs "chrome://extensions/" and when i click on other tabs it doesnt do anything. Here is my code:

chrome.tabs.query({'active': true, 'lastFocusedWindow': true, 'currentWindow': true}, function (tabs) {
var url = tabs[0].url;
console.log(url);
});

And my permissions are like this

"permissions": [
    "tabs",
    "activeTab"
]

Thanks in advance.

标签: javascripthtmlgoogle-chromegoogle-chrome-extension

解决方案


I assume you are executing the query function only once in your background.js. Try listening to the onActivated event so you get information when the user switches tabs. Here is an example:

chrome.tabs.onActivated.addListener((activeInfo) => {
    chrome.tabs.query({'active': true, 'lastFocusedWindow': true, 'currentWindow': true}, function (tabs) {
        var url = tabs[0].url;
        console.log(url);
    });
});

Edit: You don't even need to use query at this point. Since you have access to the tab id you can use the get method.

chrome.tabs.onActivated.addListener((activeInfo) => {
    chrome.tabs.get(activeInfo.tabId, function (tab) {
        console.log(tab.url);
    });
});

推荐阅读