tldr
tldr

Reputation: 12112

Chrome Extension: chrome.tabs.executeScript not working

I'm writing a chrome extension, and want to execute a content script from my background script. The background script executes, but the content doesn't. Here are the relevant chunks of code:

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 inspect element, the console has background logged on it, but not content. The regular console also has nothing logged on it. What am I doing wrong?

Upvotes: 4

Views: 12656

Answers (4)

Jitender Raghav
Jitender Raghav

Reputation: 31

It must be as mentioned below:

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

});

Note: can execute in background script, Don't forgot to allow necessary permissions in manifest.json

Upvotes: 0

Charles Clayton
Charles Clayton

Reputation: 17966

In your background.js wrap your chrome.tabs.executeScript in this:

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

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

});

Upvotes: 4

tldr
tldr

Reputation: 12112

I can't get programmatic injection to work, so I have just specified it in the content_scripts field in manifest.json (https://developer.chrome.com/extensions/content_scripts#registration)

Upvotes: 1

Alex Filatov
Alex Filatov

Reputation: 2321

you should add permision "activeTab". more information https://developer.chrome.com/extensions/content_scripts#pi

Upvotes: 0

Related Questions