Reputation: 8485
I am trying to code a simple firefox extension that displays the title of the current tab the user is viewing when the extension's button is pressed.
Here is my manifest.json file:
{
"manifest_version": 2,
"name": "Perspective",
"version": "1.0",
"description": "Displays current tab title when clicked",
"permissions": [
"tabs"
],
"icons": {
"48": "icons/border-48.png"
},
"browser_action": {
"browser_style": true,
"default_popup": "popup/choose_page.html",
"default_icon": {
"16": "icons/news-icon-16.png",
"32": "icons/news-icon-32.png"
}
}
}
And, here is my choose_page.js file
//Fetch the title of the active tab
console.log("-----------Button Clicked------------");
var activeTab = browser.tabs.query({active: true, currentWindow: true});
console.log("---------Printing type of variable \"activeTab\"");
if (typeof activeTab == "undefined")
console.log("The object is undefined")
else
console.log("The type of activeTab is:" + typeof activeTab)
console.log("The title of activeTab is:")
console.log(activeTab.title);
Whenever I click my extension's button, I get the following output in the console:
-----------Button Clicked------------
---------Printing type of variable "activeTab"
The type of activeTab is:object
The title of activeTab is:
undefined
Why is the title of "activeTab" undefined, and how do I actually get the title of the current tab the user is viewing?
Here is the link to all of the files in the extension: https://drive.google.com/file/d/1L7vho9iSL9nX2LKBmCveJvODmKQBlqX9/view?usp=sharing
Upvotes: 5
Views: 2136
Reputation: 371168
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/query
This is an asynchronous function that returns a Promise.
You have to wait for the promise's resolution first. Try something like this instead:
browser.tabs.query({active: true, currentWindow: true})
.then(tabs => {
for (const tab of tabs) {
console.log(tab.title);
}
});
Your activeTab
variable is not the active tab, but a promise that you need to wait for the resolution for. Also, when the promise resolves, it gives you an array of tabs, not a single tab.
Upvotes: 6