- Published on
Sending & Listening to Messages within Chrome Extension
- Authors
- Name
- Ashik Nesin
- @AshikNesin
Chrome extension has different environment to perform different actions. Most common one are content script and background.
Communicating between content script and background / event page involves little bit more work.
Let’s have a quick look at those environments
Content Script
Its just a JavaScript files that run in the in the web pages, much more like the JavaScript that we include/write in our webpage.
It can be used to perform any changes in DOM, displaying toast message, perform AJAX operations, etc
Here’s quick demo of all the things we can do using content script.
However we can’t use all chrome APIs (primarily for security reasons) ?
Because of that to create things like context menu we’ve to use background environment.
Background / Event page
Its where we perform extension specific actions like creating content menu
We can access all the chrome APIs ?
Communicate within Chrome Extension
Here’s are some common scenarios for one-time requests. For long-living connections please refer docs and make appropriate changes :)
We can only send JSON-serializable message
Sending messages from Content Script
// Sending messages from Content Script
const msg = 'Hello from content Script ⚡';
chrome.runtime.sendMessage({ message: msg }, function (response) {
console.log(response);
});
Listening to messages in Context Script
// Listening to messages in Context Script
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request);
// Callback
sendResponse({ message: 'Content script has received that message ⚡' });
});
Sending messages from background / event page
We’ve to make sure that the tab has been loaded.
// Sending messages from background / event page
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.query({ active: true }, function (tabs) {
const msg = 'Hello from background ?';
chrome.tabs.sendMessage(tabs[0].id, { message: msg });
});
}
});
Listening to messages in background / event page
// Listening to messages page
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request);
// Callback for that request
sendResponse({ message: 'Background has received that message ?' });
});
Example
I’ve put tougher all those code and created a sample chrome extension for your reference.