1

Im trying to communicate background with content script, but my way doesnt work. And I want to know why it doesnt work and how to solve this problem(other solutions dont work. idk why).

Manifest.json:

{
    "manifest_version": 2,
    "name": "X",
    "version": "2.0",
    "browser_action": {
        "default_title": "title"
    },
    "permissions": [
        "activeTab",
        "tabs"
    ],
    "content_scripts": [
        {
            "matches": ["https://*/*"],
            "js": ["content_scripts/jquery.min.js", "content_scripts/script.js"],
            "run_at": "document_idle"
        }
    ],
    "background": {
        "scripts": ["background/background.js"]
    },
    "icons": {
        "16": "icon.png",
        "32": "icon.png",
        "48": "icon.png",
        "64": "icon.png",
        "128": "icon.png"
    }
}

Background.js:

chrome.tabs.query({active: true}, function (tabs) {
    tabs.forEach((cur, i)=>{    
        chrome.tabs.sendMessage(tabs[i].id, {"delBody": true})
    })
})

ContentScript:

chrome.runtime.onMessage.addListener(function(obj, sender) {
    if(obj.delBody)
        document.body.remove()
})
  • The background script runs when your extension is loaded on browser startup/update, when your content script haven't yet been injected. Other possibilities: 1) the active tab wasn't `https` - for example it's a new tab or chrome://extensions or a devtools window, 2) you didn't reload the extension on chrome://extensions page, 3) you didn't reload the web page after reloading/installing/enabling the extension. Anyway, this is a *debugging question* so simply use devtools to set breakpoints in the content script (web page tab) and in the [background script](https://stackoverflow.com/a/10258029). – wOxxOm Dec 22 '18 at 14:55

1 Answers1

0

Thanks you very much wOxxOm. Problem was in

The background script runs when your extension is loaded on browser startup/update, when your content script haven't yet been injected

So I solve it like this:

content:

chrome.runtime.sendMessage({"getInfo": true})
chrome.runtime.onMessage.addListener(function(obj, sender) {  
    if(obj.delBody)
        document.body.remove()
})

background:

chrome.runtime.onMessage.addListener(function(obj, sender) {  
    if(request.getInfo) {
        chrome.tabs.query({active: true}, function (tabs) {
            tabs.forEach((cur, i)=>{    
                chrome.tabs.sendMessage(tabs[i].id, {"delBody": true})
            })
        })
    }
})