9 Understanding Chrome Extensions Tabs

The chrome.tabs API is used for interacting with your browser tabs. You can do all sort of this with this API from creating new tabs, rearranging them, redirecting to a new URL, and even communicate to the content scripts running on those tabs. In this article we are going to look at several functions the chrome.tabs API provides.

However, if you want more info on all the methods, functions and events you can use in the chrome.tabs reference Google Chrome’s documentation: https://developer.chrome.com/docs/extensions/reference/api/tabs

Getting started — In the manifest.json

The chrome.tabs are one of many API that you need to declare it in the permissions section in your manifest.json file to used it.


{
...
"permissions": [
"tabs"
]
...

}

Now we are all set!

Note: chrome.tabs API are one of the many APIs that only work in the background script(service work) or popup(extension pages).

The activeTab Permission

The activeTab permission gives an extension temporary access to the currently active tab when the user clicks the extension’s action icon. It helps to get temporary access as opposed to using <all_urls> in the host_permissions

{
...
"permissions": [
"activeTab"
]
...

}

Active Tab Permission Documentation can be found here: https://developer.chrome.com/docs/extensions/develop/concepts/activeTab

Sample Project

Let’s get our feet wet with using the API. We are going to make a chrome extension that when the popup icon is clicked it will open 3 social media tabs Facebook, Instagram, YouTube. It will also send a message to the content script of the active tab to show an alert that social media pages were just opened. However we also want the chrome extension to redirect to Google went every a user tries to go on LinkedIn. Our target audience are a bunch of LinkedIn addicts.

You can get the source code for the sample project herehttps://github.com/BuildChromeExtensions/socialmediamanager

We are only going to need three files from this project content.js background.js and manifest.json

Manifest.json

{
"name": "Social Media Manager",
"manifest_version": 3,
"version": "1.0.0.0",
"action": {
"default_title": "Open social media tabs"
},
"background": {
"service_worker": "background.js"
},
"permissions": [ "tabs" ],
"content_scripts": [
{
"matches": [ "<all_urls>" ],
"js": [ "content.js" ]
}
]
}

Content Script (content.js)

chrome.runtime.onMessage.addListener((request, sender, senderResponse) => {
alert(request.message);
})

// Bonus tip: here is another way of just redirecting when unwanted page is loaded
// if(window.location.href.includes("linkedin.com")) window.location.href = 'https://google.com/';

Background Script (background.js)

chrome.action.onClicked.addListener(async (currentTab) => {

// You can put all sort of query options here
// https://developer.chrome.com/docs/extensions/reference/api/tabs#method-query
// you can use chrome.tabs.query with async/await of with callback.
const tabs = await chrome.tabs.query({}) // get all the tabs

let isFacebookAvailable = false;
let isInstagramAvailable = false;
let isYouTubeAvailable = false;

//check if the facebook, instagram and youtube are available in the tabs
for (const tab of tabs) {
if (!tab.url) {
// skip if url not available
continue;
}

if (tab.url.includes('facebook.com')) {
isFacebookAvailable = true;
}
else if (tab.url.includes('instagram.com')) {
isInstagramAvailable = true;
}
else if (tab.url.includes('youtube.com')) {
isYouTubeAvailable = true;
}
}

// open tabs that are not available
if (!isFacebookAvailable) {
chrome.tabs.create({ url: "https://facebook.com", active: false });
}
if (!isInstagramAvailable) {
chrome.tabs.create({ url: "https://instagram.com", active: false });
}
if (!isYouTubeAvailable) {
chrome.tabs.create({ url: "https://youtube.com", active: false });
}

// Get active tab
// you can use chrome.tabs.query with async/await of with callback.
chrome.tabs.query({ active: true }, (tabs) => {
const tab = tabs[0];
// would could have also used the currentTab variable
// from the chrome.action.onClick.addListener
// const tab = currentTab

// send a message to the content script of the active tab
chrome.tabs.sendMessage(tab.id, { message: `Social Media Pages opened successfully` });
})


})

// Redirect any linkedin links to google.com
chrome.tabs.onCreated.addListener((tab) => {
// https://developer.chrome.com/docs/extensions/reference/api/tabs#event-onUpdated
if (tab.url && tab.url.includes("linkedin.com")) {
chrome.tabs.update(tab.id, { url: "https://google.com" })
}
})

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// https://developer.chrome.com/docs/extensions/reference/api/tabs#event-onUpdated
if (tab.url && tab.url.includes("linkedin.com")) {
chrome.tabs.update(tabId, { url: "https://google.com" })
}
})
Extension Screenshot

Note: chrome.tabs.sendMessage is the function you use to send messages from extension pages or background script to content scripts. But content scripts use chrome.runtime.sendMessage

Leave a Reply

Your email address will not be published. Required fields are marked *

More Articles & Posts