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" } }
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" }
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 () => { ... })
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, });
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.
{ "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" } }
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.
"background": { "service_worker": "service-worker.js", "type": "module" }
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
The above is the detailed content of Tab Roulette - my first extension. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
