Search code examples
javascriptgoogle-chrome-extension

The output not shown in message passing


I am working on a google chrome extension project where content.js script sends message to popup.js. Also trying to get some text from content.js to be turned into the same thing but on popup.js. Here is all my code.

This is my manifest file. manifest.json

{
    "name": "hoko's ext",
    "description": "my ext",
    "version": "1.0",
    "manifest_version": 3,
    "action": {
        "default_popup": "popup.html" 
      },
      "content_scripts": [
        {
          "matches": ["https://*/*", "http://*/*"],
          "js": ["content-script.js"]
        }
      ],
      "background":  {
        "service_worker": "background.js"
      },
      "permissions": [
        "tabs",
        "activeTab"
      ]
  
}

This is the popup you get when you click on the icon in the toolbar. popup.html

<html>
    <head>
        <title>Title</title>
        
    </head>
    <body>
        <h1>I am the popup</h1>


<p id="extensionpopupcontent"></p>
<script type="text/javascript" src="popup.js"></script>
    </body>
</html>

This is my content script called content-script.js

function injectScript(file_path, tag) {
    var node = document.getElementsByTagName(tag)[0];
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', file_path);
    node.appendChild(script);
}

injectScript(chrome.runtime.getURL('inject.js'), 'body');


chrome.runtime.sendMessage(document.getElementsByTagName('title')[0].innerText);

In background.js, I am receiving the message from content-script.js.

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
  function onMessage(request, sender, sendResponse) {
    console.log(sender.tab ?
    "from a content script:" + sender.tab.url :
    "from the extension");
    if (request.greeting == "hello") {
       sendResponse({farewell: "goodbye"});
    }
}
})

In popup.js, it is receiving from background.js to output the code from content-script.js.

window.addEventListener('DOMContentLoaded', () => {
let bg = chrome.extension.getBackgroundPage();


    chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
            document.getElementById('extensionpopupcontent').innerHTML = response;
         });
    

});

});

I believe I need to inject this script that is inject.js.

function click() {
    return document.getElementsByTagName('title')[0].innerText;
}

click();

Solution

    1. remove background and content_scripts in manifest.json
    2. remove tabs from permissions in manifest.json
    3. remove background.js, content-script.js, and inject.js
    4. rewrite popup.js as follows:
    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
      document.getElementById('extensionpopupcontent').textContent = tabs[0]?.title;
    });