0

I am trying to communicate some data from my website to my extension's content script that should send it to the background script to store it in my extension's localStorage. What I have done so far is the following : In my webpage , the script is communicating with my extension's content script, one the Content script receives some message it logs in the console 'message received'

My Webpage :

     <script>
     var go = function() {
    var event = document.createEvent('Event');
    event.initEvent('appid');
    document.dispatchEvent(event);
      }
     </script>
  <a href="javascript:go();">Click me</a>   

What I want to achieve is simple to make the webpage send an ID to the CS that passes it to the background script ( since to my knowledge the CS can not handle storing data in localstorage ). Can any one suggest the necessary modification ?

  • What does your event listener in the content script look like? IIRC, content scripts can access localstorage as well as chrome extension's storage api. – Teepeemm Aug 16 '15 at 18:25

1 Answers1

0

in your content script you need to send to background by

var request={aaa:'bbb'};//object
chrome.runtime.sendMessage(request);

and in background page, you need

chrome.runtime.onMessage.addListener(function(request, sender)
{
 console.log(request);
 if(request.aaa)
 {
    console.log(request.aaa)//log:bbb
    //do sonething...
 }
}

check doc for further infos: https://developer.chrome.com/extensions/messaging

jojomango
  • 156
  • 1
  • 1
  • 9
  • Thanks this helped me pass the message from the CS to the background script. But how can I define the data in the webpage. That is to say, suppose I want to pass an ID from the webpage to the Content script, Where should I put it in the webpage and how will the content script get it ? – El Marichal Aug 16 '15 at 21:14
  • That depends how you contain the 'ID' in webpage, you can trigger a function in CS to search DOM of webpage, then get the value I guess. – jojomango Aug 16 '15 at 21:33