5

i am sending message from background to content script. My background.js

chrome.runtime.onMessage.addListener(
 function(request, sender, sendResponse) {
  switch(request.type){
    case "login-check":
     checkLogin();
    break;
  }
});

function checkLogin() {
 // var test = localStorage.getItem("test");
 // alert(test);
 chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ 
  chrome.tabs.sendMessage(tabs[0].id, {type: "login"}, function(response) {
   console.log(response.farewell);
   //alert(response.farewell);
  }); 
 });
}

My content-script.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.type == "login")
      sendResponse({farewell: "goodbye"});
  });

it is showing me an error "Error in event handler for (unknown): TypeError: Cannot read property 'farewell' of undefined ". i have tried all the ways almost but it didn't work please help. thanks in advance

hu7sy
  • 983
  • 1
  • 13
  • 47
  • I guess your active window is devtools of the background page while you debug it. Anyway try to use chrome.tabs.query in your popup and pass the tab id along with login-check. – wOxxOm Jul 15 '16 at 06:58
  • Where does 'login-check' come from? The same content script? – Haibara Ai Jul 15 '16 at 07:45
  • This may answer your question: https://stackoverflow.com/questions/23895377/sending-message-from-a-background-script-to-a-content-script-then-to-a-injected/23895822 – Xan Jul 15 '16 at 08:29

0 Answers0