2

I am sending a message from the contentscript to popup and trying to show the received message when the extension is clicked.

enter image description here

I can see that the message is being received only when I Inspect popup
enter image description here

contentscript.js

    console.log("content script");      

    chrome.runtime.sendMessage("hello",function(response)
    {
        console.log("sending message");        
    });

popup.js

console.log("popup script");   

function onReq(request, sender, sendResponse)
{
  ph=request;
    console.log("msg: "+request);
  document.getElementById("para").innerHTML = "msg: "+request;
}

chrome.runtime.onMessage.addListener(onReq);

popup.html

<!doctype html>
<html>
  <head>
    <title>Example</title>

  </head>
  <body>
    <div id="status"></div>
    <p id="para">shows received message here</p>
  </body>
   <script src="popup.js"></script>
</html>

I want to receive the message and show the message when clicked without having to open the console. How can I achieve this.

Vinay Potluri
  • 545
  • 1
  • 9
  • 23

1 Answers1

9

The popup window is created/destroyed each time you open/close the popup. So sending messages to it while closed will not work. A simple solution would be to store the latest message in chrome.storage, and read the value from the popup.

levi
  • 23,693
  • 18
  • 59
  • 73
  • 1
    Everytime I open a new tab and run the extension, the previous value is still shown. How can i create different instances of the storage such that each tab has its own storage space. – Vinay Potluri Jun 08 '15 at 03:32
  • 1
    @Vinay The storage is shared across the entire extension. So you will need to store the messages in an object, where each message is indexed by the tab ID. The `chrome.tabs` API may be of help. – levi Jun 08 '15 at 17:04
  • 1
    see here - http://stackoverflow.com/questions/6202953/obtaining-this-tab-id-from-content-script-in-chrome-extension – levi Jun 08 '15 at 17:07