Sending a variable value from background.js to popup

Viewed 20

I try to send the input value from contentscript.js to popup.js for displaying it in popup.html. I give the following shot, but nothing is working.

I created five files for building the extension as describ below:

  • manifest.js

    {
        "name": "bla bla",
        "version": "1.0.0",
        "manifest_version": 3,
        "description": "bla bla",
        
        "background": {
          "service_worker": "background.js"
        },
    
        "content_scripts": [
          {
            "matches": ["<all_urls>"],
              "js": ["contentscript.js"]
          }
        ],
        "permissions": [
                        "activeTab",
                        "background"
                        ],
        "action":
         {
          "default_icon": "extension-logo.png",
          "default_popup": "popup.html"
         }
      }

  • contentscript.js

         let inputtext = document.getElementById("search_form_input");
         inputtext.addEventListener('input', ()=>{
         console.log(inputtext.value);
         text_input = inputtext.value
    
            let message = {
                text: text_input
            };
    
            chrome.runtime.sendMessage(message.text);
    });

  • background.js

    chrome.runtime.onMessage.addListener(receiver);
    
    window.word = "";
    function receiver(request, sender, sendResponse){
        console.log(request);
        window.word = request.text;
    }
  • popup.js

        p_id = document.getElementById('p-id');
        let bgpage = chrome.extension.getBackgroundPage();
        let word = bgpage.word;
        console.log(p_id.innerHTML);
        
        p_id.innerHTML = word;


  • popup.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Paragraph</title>
        <script src="libraries/p5.js" type="text/javascript"></script>
        <script src="popup.js" type="text/javascript"></script>
        <!-- <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script> -->
    
    </head>
    <body>
        <h1>Paragraph Replacer</h1>
    
        <p id="p-id"> hhhh
            
            <!-- <input type="text" name="par" id="userinput"> -->
        </p>    
    </body>
    </html>

When I reload the extension, “window is undefined” error popups. Any helpful tips will greatly be appreciated. Thanks.

0 Answers
Related