Answer the question
In order to leave comments, you need to log in
How to correctly send messages from background.js to content_script in a Chrome extension?
All good!
I'm writing extensions for Chrome and ran into a problem that I don't understand when sending a message with background to content_script . I receive data in background via Websocket and send it to content_script .
Here is my code:
background:
ws.onmessage = function (event) {
console.log('MESSAGE: ' + event.data);
let msg = event.data;
console.log('got msg form device -> ', msg);
chrome.tabs.query({active: true}, function (tabs) {
console.log('tab > ', tabs[0].url, tabs[0].id);
let convertedData = String(tabs[0].url).includes("siteA.com") ? dataFormater('siteA', msg) : dataFormater('siteB', msg);
chrome.tabs.sendMessage(tabs[0].id, {
action: msg == 'removed' ? msg : 'showDepositModal',
data: convertedData
}, function (response) {
console.log(response);
});
})
};
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if(window.location.href.includes("siteA.com") || window.location.href.includes("siteB.com")){
if (request.action == 'showDepositModal') {
console.log("content script got masg ", request.data);
showModal(request.data);
} else {
hideModal();
}
}
}
);
Answer the question
In order to leave comments, you need to log in
Add the permission to the manifest.json file "permissions" : [ "activeTab" ]
.
and
"background" : { "scripts" : [ "eventPage.js" ], "persistent" : true }
"persistent" : true
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question