Skip to main content

Chrome extensions are powerful tools that allow developers to enhance the browsing experience by adding custom functionalities to websites. One common use case is the injection of scripts into web pages, and the executeScript API in Chrome extensions makes this process seamless.

Overview

In this example, we’ll create a Chrome extension named “Coded Brainy executeScript Extension” to demonstrate the usage of executeScript. The extension will inject a script to rotate the Google logo on the active tab when a button is clicked in the extension popup.

Overview

In this example, we’ll create a Chrome extension named “Coded Brainy executeScript Extension” to demonstrate the usage of executeScript. The extension will inject a script to rotate the Google logo on the active tab when a button is clicked in the extension popup.

Manifest File (manifest.json)

The manifest file defines the extension’s properties, including the name, version, description, and permissions. It also specifies the background service worker and the action popup.

In this manifest, we’ve set up a service worker (worker.js) as the background script and specified the necessary permissions for scripting and accessing the active tab.

Background Script (worker.js)

The background script listens for messages from the popup and executes the execute-script type, injecting a content script into the active tab.

This script defines an event listener for messages and, upon receiving a message of type execute-script, retrieves the active tab and injects a content script using executeScript.

Popup Script (popup.js)

The popup consists of a button triggering the execution of the content script.

This script sends a message to the background script when the button is clicked, triggering the execution of the content script.

Conclusion

The example extension showcases the usage of executeScript to dynamically modify a web page. While this specific demonstration rotates the Google logo, the executeScript API provides a powerful mechanism for injecting custom scripts and styles, opening up endless possibilities for enhancing the user experience in Chrome extensions.

Feel free to customize and expand upon this example to suit your specific needs. Remember to adhere to Chrome’s extension development guidelines and seek appropriate permissions when modifying website content.

Creating Chrome extensions with executeScript empowers developers to build feature-rich and interactive browser extensions. As you explore and experiment, you’ll discover numerous ways to leverage this API for creating unique and valuable extensions.

The source code for this project is available on Github.

Close Menu

Welcome to Coded Brainy

Coded Brainy Provides you with technical blogs

Coded Brainy