Chrome扩展:从弹出窗口获取未定义的活动url



当Chrome扩展插件的弹出窗口打开时,我正在尝试获取选项卡url。我研究了其他答案,得出了这个:

export const getTab = () => {
return new Promise((res) => {
chrome.tabs.query({ currentWindow: true, active: true }, (tabs) => {
console.log('tabs:', tabs);
res(tabs[0]);
});
});
};

对的承诺

{
"active": true,
"audible": false,
"autoDiscardable": true,
"discarded": false,
"groupId": -1,
"height": 624,
"highlighted": true,
"id": 2297,
"incognito": false,
"index": 1,
"mutedInfo": {
"muted": false
},
"openerTabId": 128,
"pinned": false,
"selected": true,
"status": "complete",
"width": 160,
"windowId": 1
}

选项卡的url为undefined

我已经尝试将"tabs""activeTab"添加到清单v3的permissions数组中,但url仍然未定义。帮助

编辑:

manifest.json

{
"manifest_version": 3,
"name": "Test",
"version": "1.0.0",
"action": {
"default_title": "Test",
"default_popup": "popup.html"
},
"permissions": ["tabs"],
"background": {
"service_worker": "src/background.js",
"type": "module"
},
"content_scripts": [
{
"js": ["src/contentScript.js"],
"matches": ["<all_urls>"],
"run_at": "document_start",
"all_frames": true
}
],
}

如何等待chrome.tabs.query返回tab id

如果你把Lakshya Thakur发布的id改为url,这个问题的答案就是解决你的问题。

这确实解决了我的问题,当时我正试图将当前选项卡的url转换为chrome扩展。

function getTabID() {
return new Promise((resolve, reject) => {
try {
chrome.tabs.query({
active: true,
}, function (tabs) {
resolve(tabs[0].id);
})
} catch (e) {
reject(e);
}
})
}
//function where you need it
async function something() {
let responseTabID = await getTabID();
}

最新更新