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?
source to share
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 )
source to share
you must add the "activeTab" permission. More information https://developer.chrome.com/extensions/content_scripts#pi
source to share
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
source to share