tabs.getCurrent() result is undefined?(tabs.getCurrent() 结果未定义?)
问题描述
不确定为什么当我导航到 amazon.com 或 google.com 并点击浏览器图标进行浏览器操作时,我无法使用 getCurrent() 检索有关当前选项卡的信息.关于我缺少什么的任何提示?
Not sure why I cannot retrieve info about current tab using getCurrent() when I navigate to, say, amazon.com or google.com and hit the browser icon for a browser action. Any hints on what I am missing?
清单:
{
"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 onError(error) {
console.log(`Error: ${error}`);
}
var gettingCurrent = browser.tabs.getCurrent();
gettingCurrent.then(onGot, onError);
}
browser.browserAction.onClicked.addListener(displayInfo);
这是输出:
Inside onGot() ... background.js:4:7
undefined background.js:5:7
Firefox 开发版 54(64 位)
Firefox Dev Edition 54 (64bit)
https://developer.mozilla.org/zh-CN/Add-ons/WebExtensions/API/tabs/getCurrent
推荐答案
来自 MDN tabs.getCurrent()
:
From MDN tabs.getCurrent()
:
获取 tabs.Tab 包含有关运行此脚本的选项卡的信息.
Get a tabs.Tab containing information about the tab that this script is running in.
您可以在有浏览器选项卡的上下文中调用此函数,例如 选项页面.如果您从后台脚本或弹出窗口调用它,它将返回 undefined.
You can call this function in contexts where there is a browser tab, such as an options page. If you call it from a background script or a popup, it will return undefined.
browserAction.onClicked
事件返回活动选项卡,您不需要其他 API 调用.
The browserAction.onClicked
event returns the active tab, you do not need another API call.
browser.browserAction.onClicked.addListener(function(tab) {
console.log(tab)
})
查看 标签
browserAction.onClicked
listener的code>参数.
See the tab
parameter for browserAction.onClicked
listener.
这篇关于tabs.getCurrent() 结果未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!