Sending message from background script to content script on app install
What I thought I wanted was to send a message from the background script to the content script once the app is installed.
It took me almost an hour to realise that my requirement itself was wrong.
The actual requirement was to create a modal on the UI using chrome extension as soon as the page was loaded.
So all I had to do was listen to the page load event instead of app install event using background script and then pass the message to the content script.
The sample listener for this is:
chrome.webNavigation.onCompleted
But webNavigation API is not accessible by default, hence you have to add this in the permission section in the manifest.json
“permissions”:[…,”webNavigation”]
But, as you already know, chrome native APIs are not accessible to the content script, hence you have to write this in the background script and pass a message to the content script.
chrome.webNavigation.onCompleted.addListener(
function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// Send a message to the content script in the active tab
chrome.tabs.sendMessage(tabs[0].id, { message: "myMessage" });
});
},
{ url: [{ schemes: ["http", "https"] }] }
);
Above is a sample background.js code for the same.
And in content script you do the following:
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.message === "myMessage") {
console.log("recieved message");
}
});
I hope this helps you.
If not, best of luck accessing conent script during installation.
I hope you found this article useful. I would love to hear your thoughts. 😇
Thanks for reading. 😊
Cheers! 😃
If you find this article useful, you can show your appreciation by clicking on the clap button. As the saying goes, ‘When we give cheerfully and accept gratefully, everyone is blessed’.