javascript - 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.
解决方案
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);
});
});
推荐阅读
- scala - Spark 2.2 Scala 中的 TRUNCATE 命令删除 SAP HANA 表而不是截断
- java - 在 Azure Functions 中重用 MongoDB 连接
- machine-learning - 情绪分析:使用数据集(IMDB 评论)训练神经网络并使用它来预测完全不同的数据集(政治文章)
- regex - 用正则表达式重命名,bash
- excel - Excel VBA:行中的最大日期,包括空白单元格
- javascript - JSZip 在解压缩时更改文件的内容 (pdf)
- python - 如何将本地模块导入 azure databricks 笔记本?
- kubernetes - K8S Ingress 是否提供任何后端目标路径以及端口?
- mysql - 如何根据评分获得前 3 名用户
- c - 如何为 Tizen 本机服务应用程序请求隐私权限