Chrome extension: chrome.tabs.executeScript not working

I am writing a chrome extension and want to execute a content script from my background script. The background script is executed, but the content is not working. Here are the relevant code snippets:

manifest.json

:

"background": {
    "scripts": ["js/app/background.js"],
    "persistent": true
},

"permissions": [
    "identity",
    "tabs",
    "activeTab",
    "*://*/*"
]

      

background.js

:

console.log('background')
chrome.tabs.executeScript(null, {file: "content.js"})

      

content.js

:

console.log('content')

      

When I check the item, the console has background

but not content

. Nothing is recorded on the regular console either. What am I doing wrong?

+3


source to share


4 answers


In background.js

wrap chrome.tabs.executeScript

in this:



chrome.tabs.onUpdated.addListener(function(tab) {

    chrome.tabs.executeScript({
        file: '/scripts/runsOnPageLoad.js'
    }); 

});

      

+2


source


I can't get programmatic injection to work, so I just specified it in a field content_scripts

in manifest.json ( https://developer.chrome.com/extensions/content_scripts#registration )



+1


source


you must add the "activeTab" permission. More information https://developer.chrome.com/extensions/content_scripts#pi

0


source


This should be as follows:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
chrome.tabs.executeScript({
        code:"alert('Any Javascript code comes here !');"
    });

      

});

Note: can run in background script, don't forget to allow required permissions in manifest.json

0


source







All Articles