不知道为什么当我导航到例如amazon.com或google.com并点击浏览器图标进行浏览器操作时,我无法使用getCurrent()检索有关当前选项卡的信息.我缺少什么提示?
表现:
{
"name": "testGetCurrentTab",
"version": "1.0",
"description": "",
"manifest_version": 2,
"icons": {
"48": "icons/icon-48.png"
},
"permissions": [
"tabs",
"<all_urls>"
],
"browser_action": {
"default_icon": "icon/icon-32.png"
},
"background": {
"scripts": ["background.js"]
}
}
背景:
function displayInfo() {
function onGot(tabInfo) {
console.log('Inside onGot() ...');
console.log(tabInfo);
}
function one rror(error) {
console.log(`Error: ${error}`);
}
var gettingCurrent = browser.tabs.getCurrent();
gettingCurrent.then(onGot, one rror);
}
browser.browserAction.onClicked.addListener(displayInfo);
这是输出:
Inside onGot() ... background.js:4:7
undefined background.js:5:7
Firefox开发版54(64位)
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/getCurrent
解决方法:
来自MDN tabs.getCurrent()
:
Get a 07001 containing information about the tab that this script is running in.
You can call this function in contexts where there is a browser tab, such as an 07002. If you call it from a background script or a popup, it will return undefined.
browserAction.onClicked事件返回活动选项卡,您不需要其他API调用.
browser.browserAction.onClicked.addListener(function(tab) {
console.log(tab)
})