0

I am making a chrome extension, and trying to send a message from the chrome extension page to the content.js. I know that in order to that I need to send the message to the bakcground.js and forward it to the content.js by sending it to either a specific tabs. I hvae done that many times and have not had any issues, but this time it just doesn't work.

main.js file (from the extension page):

chrome.runtime.sendMessage({
    name: "stop"
})

background.js:

chrome.tabs.query({}, tabs => {
    for (let i = 0; i < tabs.length; i++) {
        if (tabs[i].status == "complete") {
            chrome.tabs.sendMessage(tabs[i].id, { msg: "Hello" })
        }
    }
})

content.js:

function recieve(msg) {
    console.log(msg)
}

chrome.runtime.onMessage.addListener(recieve)

manifest.json:

{
    "manifest_version": 2,
    "name": "app",
    "description": "app description",
    "version": "3.0.0",
    "icons": {
        "19": "./images/icon_19.png",
        "128": "./images/icon_128.png",
        "150": "./images/icon_150.png"
    },
    "browser_action": {
        "default_title": "title"
    },
    "permissions": [
        "tabs",
        "alarms",
        "notifications"
    ],
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "jquery-3.4.1.min.js",
                "content.js"
            ]
        }
    ],
    "background": {
        "scripts": [
            "background.js"
        ]
    }
}
Hef
  • 606
  • 6
  • 16
  • 2
    The code is fine so apparently the content script wasn't running at the time you were sending a message. It usually happens if you reloaded or updated the extension but didn't reload the tabs, see [Chrome extension content script re-injection after upgrade or install](https://stackoverflow.com/a/11598753) – wOxxOm Feb 27 '21 at 14:09
  • Thanks for the answer. I have now solved the problem. – Hef Feb 27 '21 at 15:00

0 Answers0