M
M
Michael Kim2015-06-24 16:33:50
JavaScript
Michael Kim, 2015-06-24 16:33:50

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");
        }
    });
}

background.js:
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});
      });
    }
    });
  });
}

The problem is that when the content script is injected, the site becomes empty, just a white background:
ff20b0bd4ddc48bbadcee94dd35abc73.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question