Logo

dev-resources.site

for different kinds of informations.

Tab Roulette - my first extension

Published at
12/2/2024
Categories
extensions
javascript
Author
ivan_862363c9a8b0
Categories
2 categories in total
extensions
open
javascript
open
Author
17 person written this
ivan_862363c9a8b0
open
Tab Roulette - my first extension

My current goal is to create a simple Chrome extension that utilizes the background capabilities of the extension framework.

To recap, the background script operates as a service worker, primarily designed to handle tasks that do not require direct user interaction.

One of its key roles is to act as a communication hub or event handler, serving as the only persistent and reliable component in the browser extension architecture. Unlike content scripts, popups, or options pages, which are ephemeral, the background service worker ensures continuity by automatically restarting when terminated to handle incoming events.

I plan to leverage this capability of the background script as the central controller for my extension.

The use case

This first Chrome extension will be quite straightforward. It will listen for clicks on the extension's action icon and respond by triggering a roulette-like behavior. The roulette will sequentially activate the tabs currently open in the user's browser for a short period until one tab is randomly left selected.

As you can see, this extension doesn't serve a practical purpose but is intended purely as a learning exercise.

The manifest

{
  "name": "TabRoulette",
  "version": "0.0.1",
  "manifest_version": 3,
  "icons": {
    "16": "images/icon16.png",
    "32": "images/icon32.png",
    "48": "images/icon32.png",
    "128": "images/icon128.png"
  },
  "action": {
    "default_title": "Click to start",
    "default_icon": {
      "16": "images/icon16.png",
      "24": "images/icon24.png",
      "32": "images/icon32.png"
    }
  },
  "background": {
    "service_worker": "background.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

In addition to the icons specified in the manifest for use in the Chrome Web Store and extension management interface, the most significant addition is the action attribute. This attribute configures the behavior of the extension when the toolbar icon is clicked. In our case, it instructs the service worker to initiate a tab roulette upon user interaction.

To take into account
My code uses ES imports, but as shown earlier, the service_worker was not explicitly declared as a module. How did it still work?

"background": {
  "service_worker": "service-worker.js",
  "type": "module"
}
Enter fullscreen mode Exit fullscreen mode

These imports are handled and resolved by Vite during the bundling process.

Background

As mentioned earlier, the background script will listen for clicks on the action icon and initiate a tab roulette in response.

chrome.action.onClicked.addListener(async () => {
 ...
})
Enter fullscreen mode Exit fullscreen mode

Key aspects of the listener logic to highlight: First, I need to gather all the tabs currently open in the active window. This is essential because my code requires references to these tabs to cycle through them sequentially.

const currentWindow = await chrome.windows.getCurrent();
const windowTabs = await chrome.tabs.query({
  windowId: currentWindow.id,
});
Enter fullscreen mode Exit fullscreen mode

I initially got confused when using chrome.tabs.query without specifying a windowId, as it returned all the tabs across all open browser windows, whereas I only wanted the tabs from the active window. This led to unexpected results due to the larger number of tabs in the list.

Once I understood this behavior, activating the tabs sequentially became straightforward. It simply involves updating the tab properties to set each one as active in sequence until a random tab is ultimately selected.

chrome.tabs.update(nextTab.id!, { active: true });
Enter fullscreen mode Exit fullscreen mode

Another goal I wanted to achieve was to adjust the pace at which the tabs are activated—starting quickly and slowing down toward the end. To accomplish this, the native setInterval function I used in the initial test was insufficient. Instead, I implemented a small utility that allowed me to create an adjustable interval, providing a way to dynamically modify its timing as needed.

function startInterval(callback: () => void, interval: number) {
  let intervalId = setInterval(callback, interval);
  return {
    stop: () => clearInterval(intervalId),
    changeInterval: (newInterval: number) => {
      clearInterval(intervalId);
      intervalId = setInterval(callback, newInterval);
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

And that’s it—a simple extension with a playful use case, serving as an excuse to delve deeper into the world of browser extensions. I'm also sharing the source code with you if you're curious about the details.

Oh, and I also used this project to explore the publishing process, which I found to be quite straightforward. Now, I'm just waiting for the review and final publication.

https://github.com/ivaneffable/tabRoulette

extensions Article's
30 articles in total
Favicon
Demystifying AIContents in Microsoft.Extensions.AI
Favicon
I made a chrome extension that fixes YouTube recommendations
Favicon
Visual Studio Code Extension for Developers
Favicon
Writting a GH extension with AI
Favicon
🌟 A Fresh Start with TaskMingle in 2025! 🌟
Favicon
.NET Development Essentials on macOS with VS Code
Favicon
Meet Tab-R: My New Browser Extension
Favicon
Introducing the Syncfusion® Document Viewer Extension for Visual Studio Code
Favicon
Introducing Inline Cryptography Toolkit: Simplify Encryption, Decryption, and Hashing in VS Code 🚀
Favicon
Nice Extension lifts webpage restrictions, allowing you to freely browse webpage content
Favicon
Introducing LightUp: AI-Powered Annotations for the Web
Favicon
Extract metadata of paper and export it to Notion DB
Favicon
2024 Update: Top 10 Alternatives to Postman
Favicon
WatchWithMe: A Better Alternative of Teleparty (aka Netflix Party)
Favicon
🔅 Adjust Page Brightness: Take Control of Your Screen's Luminosity
Favicon
Code Against the Clock : Automating Attendance Management
Favicon
Using Thunder Client for VS Code? Stop! Here is the Ideal Extension for Your API Testing Needs.
Favicon
A small deep dive on MutationObservers
Favicon
Tab Roulette - my first extension
Favicon
FREE: Password Generator âš¡ PRO (extension/add-on) + [source code]
Favicon
Continuous contributions
Favicon
Discover the Ultimate Collection of VSCode Extensions with DevXtensions
Favicon
Learning by Doing: working on ImprovedTube
Favicon
I Built a Chrome Extension to Bring Back the Google Maps Tab
Favicon
I wrote a vscode extension to copy filename and directory
Favicon
Chrome Extension Development - Develop minimal app with TypeScript, React, Tailwind CSS and Webpack
Favicon
Working on a browser extension
Favicon
Syncfusion Visual Studio Extensions Are Now Compatible With .NET 9.0
Favicon
Top vscode extension
Favicon
Claude.ai Voice Input & Text-to-Speech (OSS, Chrome Extension)

Featured ones: