Categories
JavaScript Answers

How to send data from content script to popup.html in a Chrome Extension with JavaScript?

Spread the love

To send data from a content script to a popup HTML page in a Chrome Extension, you can use the messaging API provided by Chrome’s extension system.

To do this, we add the following:

  1. Content Script: Send a message from the content script using chrome.runtime.sendMessage().

  2. Background Script: Receive the message from the content script and relay it to the popup script.

  3. Popup Script: Receive the message sent by the content script.

Here’s an example of how you can achieve this:

Content Script (content.js):

// Send a message to the background script
chrome.runtime.sendMessage({data: "Hello from content script!"});

Background Script (background.js):

// Listen for messages from content scripts
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Relay the message to the popup script
    chrome.runtime.sendMessage(message);
});

Popup Script (popup.js):

// Listen for messages from the background script
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    // Display the message in the popup HTML
    document.getElementById("message").innerText = message.data;
});

Popup HTML (popup.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Popup</title>
</head>
<body>
    <div id="message"></div>

    <script src="popup.js"></script>
</body>
</html>

In this example, the content script sends a message to the background script using chrome.runtime.sendMessage().

The background script listens for messages from content scripts using chrome.runtime.onMessage.addListener(), and then relays the message to the popup script using chrome.runtime.sendMessage().

The popup script listens for messages from the background script using chrome.runtime.onMessage.addListener(), and then updates the popup HTML with the received message.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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