Search code examples
javascriptgoogle-chromegoogle-chrome-extensionmessage-passing

Communication between contentscript, background and popup scripts


On sending side : i.e from contentscript.

contentscript.js:

<script> 
    //some DOM code to obtain values to store in 'marks' array.


    //here I'm sending marks array to background.js.
    // 1) Am I sending it right?
    chrome.runtime.sendMessage(marks);

</script>

On receiving end : i.e in background script.*

background.js:

chrome.runtime.onMessage.addListener(function(MessageSender sender, function     
    sendResponse){
     /* 2) what should be here */ });

3) here , how can I collect(store) the array variable passed from contentscript.

4) Now,from background.js can I directly call any function in popup.js(script file
linked to popup.html).

Can anyone please answer the above 4 questions?
Thanks in advance!

Inspecting my popup,gave me following error :

enter image description here


Solution

  • in manifest.json

    add storage permission

    "permissions": ["storage"]
    

    in contentscript.js

    save your data in the local storage Google Chrome : Chrome Storage API

    var data = ''; //set your data here
        chrome.storage.local.set({
             'myVariable': data
            });
    

    use sendMessage to call the background page : Chrome messaging API

     chrome.runtime.sendMessage({
         greeting: "myAction"
     });
    

    in background.js

    get the message from contentscript.js

    chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {
        if (request.greeting == "myAction") {
            collectData();
        }
     });
    

    define the collectData() function

    function collectData() {
      chrome.storage.local.get('myVariable', function (items) {
        console.log(items); //your data is on items.myVariable 
      });
    }
    

    to call popup.js function from background.js use the messaging API