最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chrome Extension - Run content script only when button is clicked - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Apr 5, 2013 at 13:21 Dr PighouseDr Pighouse 1531 gold badge1 silver badge4 bronze badges 1
  • chrome.tabs.executeScript doesn't let my main browser page, if i remove this it works – Rakesh Chand Commented Aug 6, 2018 at 14:36
Add a comment  | 

1 Answer 1

Reset to default 18

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.

发布评论

评论列表(0)

  1. 暂无评论