Attention: If you develop cross-browser extensions (I hope you do!), I recommend that you use chrome.tabs.query()
. Please see Jean-Marc Amon's answer for more information. This answer still works in both Firefox and Chrome, but query()
is more commonly used, has more options, and works in background pages and popup views.
Additional: Be aware that you cannot use the Tabs API from content scripts. As per the documentation page - "The Tabs API can be used by the service worker and extension pages, but not content scripts". If you have a need to use the Tabs API using content scripts then I would suggest looking at the Messaging API.
From the chrome.tabs
API, you can use getCurrent()
, query()
, or update()
.
Right now, I prefer update()
as this allows you to update the current tab without needing to do much else.
If updating the url from a content script is required then you should look to use query
instead. Jean-Marc Amon's answer provides a wonderful example of how to get the active tab in this case (don't forget to upvote him!).
update()
let myNewUrl = `https://www.mipanga.com/Content/Submit?url=${encodeURIComponent(tab.url)}&title=${encodeURIComponent(tab.title)}`;
chrome.tabs.update(undefined, { url: myNewUrl });
Here, we have set the first argument of update to undefined. This is the tab id that you're wanting to update. If it's undefined then Chrome will update the current tab in the current window.
Please see Domino's answer for more information on update
and also note that undefined
is not needed. Again, please don't forget to upvote their answer as well if you find it useful.
getCurrent()
getCurrent
also cannot be called from a non-tab context (eg a background page or popup view).
Once you have the current tab, simply pass update()
.
chrome.tabs.getCurrent(function (tab) {
//Your code below...
let myNewUrl = `https://www.mipanga.com/Content/Submit?url=${encodeURIComponent(tab.url)}&title=${encodeURIComponent(tab.title)}`;
//Update the url here.
chrome.tabs.update(tab.id, { url: myNewUrl });
});
NB: In order to use this this functionality, you must ensure that you have the tabs
permission enabled in your manifest.json
file:
"permissions": [
"tabs"
],
Messaging API
As per the documentation page - The Tabs API can be used by the service worker and extension pages, but not content scripts.
See the answer by TimS which alludes to this. Please upvote them!
Example of interacting with the Tabs API using a service worker via the Messaging API: https://github.com/Omicron18/nitter-extension