Chrome Extension how to send data from content script to popup.html
Employ chrome.runtime.sendMessage in your content script to send data, and leverage chrome.runtime.onMessage in the popup script to receive it.
Content Script:
Popup Script:
A closer look at asynchronous message passing
Understanding the asynchronous nature of message passing is essential to building a robust extension. Prepare for callbacks to handle responses when the message has been delivered.
Handling Responses:
Strategies for smooth messaging
Local storage - your data warehouse
localStorage is an efficient way to create a semi-persistent bridge between the content script and the popup. It is invaluable for maintaining data between popup window lifecycles.
Messaging with a secret handshake
Incorporate a "type" field in your messages to distinguish between different kinds of messages, like a secret handshake.
Content Script:
Popup Script:
Active tab - your target for messages
Aim your messages at the right tab. Use chrome.tabs.query to accurately target message sending from the popup to the content script.
Watch out! Here’s what could go wrong
Sequencing scripts - The order of knights
In your extension's manifest.json, the order of scripts affects their execution. Ensure content scripts start the dance before popups scripts to prevent one stepping on the other's toes.
Local storage - A rocky boat
In modern browsers, with localStorage access from the content script, you might feel empowered. However, avoid this rocky boat due to isolated worlds of content scripts and consider proper message passing routines for safe sailing.
Asynchronous messaging – the time traveler
Messaging APIs are asynchronous, time is a trippy concept in the async world. Code your scripts to handle this time-travel by properly waiting for message responses with callbacks or promises.
Was this article helpful?