0

I am creating a chrome extension. In that I am getting problem in sending message from background.js to popup.js. I am successfull in sending some static data from background.js to popup.js. But, when I try to send data dynamically (i.e. the data sent to background.js by content-script.js) from background.js to popup.js, it is giving undefined as I print it on popup.html.

This is my popup.js:

 var value;
  window.onload = function(){   
    chrome.runtime.sendMessage({getVal: "Hi"}, function(response){
    value = response.responseSeltext;
    alert(value);
    });
    document.getElementById('save').onclick = test;
}

This is my background.js:

    var seltext;
        chrome.runtime.onMessage.addListener(
        function(request, sender, sendResponse) {

        if (request.ezynotes != ""){
          seltext = request.ezynotes;
          alert("In extension "+seltext);

          //document.getElementById("notes").innerHTML += request.ezynotes;
         }
        if (request.getVal != ""){
          sendResponse({responseSeltext:seltext});

          //seltext = request.ezynotes;
          alert("In extension "+seltext);

          //document.getElementById("notes").innerHTML += request.ezynotes;
         }

  });
3
  • Can you please not use alert() for debugging? It steals focus from your popup and might make it close. Also, it is known to cause problems due to blocking execution.
    – Xan
    Feb 18, 2015 at 11:38
  • I tried by removing all alerts, but still it is giving undefined on popup.html.
    – RSY
    Feb 18, 2015 at 15:48
  • How are you testing that it is undefined? Also, please try to debug by right-clicking on the extension button and selecting "Inspect popup", if you haven't already.
    – Xan
    Feb 18, 2015 at 15:55

1 Answer 1

-2

I m assuming u r listening for message in background from content.js and trying to send it to popup.js. Right??In that case u have to send message from background and add a listening event in popup.js which is not present in your code.

2
  • Thanks. I am listening for message in background from content.js and trying to send it to popup.js. It is correct. I think listening to message in popup.js is one way and other way is what I have written - i.e. the response which will come from background.js. I have verified by just sending static data ("Hi") from background.js to popup.js, but I am unable to get this dynamic data.
    – RSY
    Feb 18, 2015 at 15:45
  • @RSY In background.js seltext is not defined thats the reason u r getting undefined. In javascript global variables default value is undefined.
    – Casey
    Feb 19, 2015 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.