Tutorials

Using Content Scripts in Chrome Extensions: A Complete Guide

Learn how to use content scripts in Chrome extensions to interact with web pages. Includes setup, messaging, best practices, and API call advice.

Mellowtel Team

Mellowtel Team

🧠 Using Content Scripts in Chrome Extensions: A Complete Guide

Content scripts are a powerful feature of Chrome extensions that allow you to interact directly with web pages. This guide walks you through creating and implementing content scripts effectively.


❓ What are Content Scripts?

Content scripts are JavaScript files that run in the context of a webpage. They can:

  • Read and modify page content
  • Listen to user actions
  • Communicate with other parts of your extension

πŸ“Œ Note: If you're new to Chrome extension development, check out our beginner's guide.


πŸͺœ Creating and Implementing Content Scripts

1. Create the Content Script File

Create a file named content.js in your extension directory.


2. Write Your Content Script

console.log('Content script loaded');

// Change background color
document.body.style.backgroundColor = 'lightblue';

// Listen for messages
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'getPageTitle') {
    sendResponse({title: document.title});
  }
});

3. Register in manifest.json

Add the following to your manifest:

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "description": "An extension with a content script",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

4. Communicate with Content Scripts

Send messages from a background or popup script:

chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
  chrome.tabs.sendMessage(tabs[0].id, {action: "getPageTitle"}, (response) => {
    console.log('Page title:', response.title);
  });
});

βœ… Best Practices for Content Scripts

  • Keep it lightweight: Don't block page rendering
  • Use event listeners: Avoid constant loops
  • Modify pages safely: Don’t break site functionality
  • Persist state: Use chrome.storage to save data

🌐 Making API Calls from Content Scripts

While you can make API calls directly from content scripts, it's safer and more efficient to delegate that to a background script.

πŸ‘‰ Check out our API Call Guide to learn more.


🧾 Conclusion

Content scripts allow your Chrome extension to deeply interact with web pages. You now know how to:

  • Create and inject a content script
  • Modify web pages safely
  • Communicate across your extension

Keep practicing and refining your architecture as you build more complex extensions.

Happy scripting! πŸš€

On this page