简体   繁体   English

我的“background.js”代码用于获取选定的 chrome 标签 url 在我的 chrome 扩展中无法正常工作

[英]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.我查了很多线程,我学会了如何获取当前 url 的焦点 chrome 标签。 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.但问题是,当我刷新我的扩展程序时,它只输出“chrome://extensions/”,当我点击其他选项卡时,它什么也不做。 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.提前致谢。

I assume you are executing the query function only once in your background.js.我假设您在 background.js 中只执行一次查询 function。 Try listening to the onActivated event so you get information when the user switches tabs.尝试监听 onActivated 事件,以便在用户切换选项卡时获取信息。 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.由于您可以访问选项卡 ID,因此您可以使用 get 方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM