Reputation: 1181
I know there are many similar questions on SO, but I cannot seem to get it working.
I am trying to get the URL of the current tab from my Chrome extension. Hoewever, the alert(tab.url) returns "Undefined". I have added the "tabs" to my permissions in the manifest.json. Any ideas?
<html>
<head>
<script>
chrome.tabs.getSelected(null, function(tab) {
tab = tab.id;
tabUrl = tab.url;
alert(tab.url);
});
</script>
</head>
Upvotes: 90
Views: 118717
Reputation: 199
In manifest.json:
"permissions": [
"tabs"
]
In JavaScript:
chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function(tabs) {
// and use that tab to fill in out title and url
var tab = tabs[0];
console.log(tab.url);
alert(tab.url);
});
Upvotes: 19
Reputation: 5756
Just an FYI for people from Google:
The method OP uses is deprecated. To get the tab the user is viewing and only in the window they are viewing use this:
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// since only one tab should be active and in the current window at once
// the return variable should only have one entry
var activeTab = tabs[0];
var activeTabId = activeTab.id; // or do whatever you need
});
Upvotes: 168
Reputation: 59
The newest versions indicates it must be like this
async function getCurrentTab() {
let queryOptions = { active: true, lastFocusedWindow: true };
let [tab] = await chrome.tabs.query(queryOptions);
return tab;
}
And you must add to your manifest.json this
"permissions: [
"tabs"
]
Upvotes: 4
Reputation: 5363
For me, I was missing the "tabs" permission as per Kartik Kkartin answer
Rest of the code in my background script
chrome?.tabs?.onUpdated?.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status == 'complete') {
console.log('tabId', tabId, 'changeInfo', changeInfo, 'tab', tab)
}
})
That will log the tab information, including the url in the tab.url
when loading a tab
Upvotes: 0
Reputation: 39
Remember to add this to your manifest.json file
"permissions": [
"tabs"
]
Upvotes: 3
Reputation: 1086
Just if someone using Web Extension Polyfill like me, for cross browser support.
// using async function
const [currentTab] = await browser.tabs.query({
active: true,
currentWindow: true,
});
console.log({ id: currentTab.id, url: currentTab.url });
Upvotes: 0
Reputation: 314
With a little help of ES6, you can easily write nicer code :)
chrome.tabs.query({
active: true,
currentWindow: true
}, ([currentTab]) => {
console.log(currentTab.id);
});
Upvotes: 6
Reputation: 889
This is what worked for me:
chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function(tabs) {
// and use that tab to fill in out title and url
var tab = tabs[0];
console.log(tab.url);
alert(tab.url);
});
Upvotes: 9
Reputation: 111265
The problem is in this line:
tab = tab.id;
It should be something like:
var tabId = tab.id;
Upvotes: 34