Chrome extension - run script contents only when a button is clicked

I had a good look, but I cannot find and answer this question (well, nevertheless, it works for me anyway).

I made a Chrome extension that should run code that in my script content only when the icon is clicked, but it always starts as soon as the page loads. Is there any way to prevent this? None of the possible lines that I can enter for run_at is really suitable for this.

Here is sample code in both scenarios:

Script Content:

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

background.js:

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

It will record β€œworker” as soon as the page loads, and for each button, click after that. Is there any way to stop it as soon as the page loads?

Thanks in advance for all contributions.

+4
source share
1 answer

The browserAction.onClicked code on your background page does exactly what you want. If you want to stop content.js from starting as the contents of the script when the page loads, just do not include it as the contents of the script in your manifest.

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

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

Just delete these lines and the script will stop working when the page loads, while your listener code will continue to work.

+7
source

All Articles