Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension - Run content script only when button is clicked

I've had a good look, but I can't seem to find and answer to this question (well, one that works for me anyway).

I've made a Chrome extension that should run the code that's in my content script on click of the icon only, but it always runs as soon as the page loads. Is there a way to prevent this from happening? None of the possible strings I can enter for run_at really cater for this.

Here is example code in both scripts:

Content Script:

function runIt() {
    console.log('working');
}
runIt();

background.js:

chrome.browserAction.onClicked.addListener(function(activeTab) {
    chrome.tabs.executeScript(null, {file: "content.js"});
});

It will log 'working' as soon as the page loads, and for each button click after that. Is there a way to stop it running as soon as the page loads?

Thanks in advance for all contributions.

like image 500
Dr Pighouse Avatar asked Apr 05 '13 13:04

Dr Pighouse


Video Answer


1 Answers

The browserAction.onClicked code in your background page does exactly what you want. If you want to stop content.js from running as content script on page load, simply don't include it as a content script in your manifest.

Specifically, in your manifest.json file, you have some lines that look something like this:

"content_scripts": [
  {
    "matches": ["*://*/*"],
    "js": ["content.js"]
  }
],

Simply remove those lines, and the script will stop running on page load, while your click listener code will continue working.

like image 124
apsillers Avatar answered Oct 17 '22 04:10

apsillers