Answer the question
In order to leave comments, you need to log in
How to send message from content script to background?
I am writing a chrome extension, I want to send a message from the content script to background.js. Here is the code:
content script:
function sendMsg(){
var port = chrome.runtime.connect({name: "main_port"});
port.postMessage({request: "status"});
port.onMessage.addListener(function(r) {
if (r.status == "on"){
port.postMessage({request2: "token"});
console.log(r.token);
}else if (r.status == "off"){
console.log("off");
}
});
}
window.onload = listenPort();
function listenPort(){
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "main_port");
port.onMessage.addListener(function(msg) {
if (msg.request == "status"){
chrome.storage.local.get("status", function(r){
port.postMessage({status: r.status});
});
}
if (msg.request2 == "token"){
chrome.storage.local.get("token", function(r){
port.postMessage({status: r.token});
});
}
});
});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question