19

I am trying to execute javascript on a page when I click on a button in popup.html. I tried to use such a way:

In background.js:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo){
    if(changeInfo.status == "loading") {
        insert(tabId);
    }
});
function insert(tabId) {
    chrome.tabs.get(tabId, function(tab) {
        $('button').click(function() {
            chrome.tabs.executeScript(tab.id, {file: 'js/alert.js'});
        });
    });
}

Alert.js consists only of one string: alert('works');

Alert is just an example. Real script should do some DOM manipulation with opened tab after user clicks on a button im popup.html.

Vlad Holubiev
  • 4,876
  • 7
  • 44
  • 59
  • You seem to have messed up some concepts (such popup, background-page, etc). It would help to post your manifest as well. – gkalpak Dec 24 '13 at 19:57
  • 1
    The presented `background.js` doesn't meet your requirements, and seems useless. In your content script, place alert into a function, say 'handleButtonClick'. Make sure the content script is registered in the manifest. Then in the popup.html just invoke your function: `chrome.tabs.executeScript({code: 'handleButtonClick()'});`. – Stan Dec 24 '13 at 21:03

2 Answers2

42

I wrote a demo for your need.

https://gist.github.com/greatghoul/8120275


alert.js

alert('hello ' + document.location.href);

background.js

// empty file, but needed

icon.png

icon

manifest.json

{
  "manifest_version": 2,

  "name": "Click to execute",
  "description": "Execute script after click in popup.html (chrome extension) http://stackoverflow.com/questions/20764517/execute-script-after-click-in-popup-html-chrome-extension.",
  "version": "1.0",

  "icons": {
    "48": "icon.png"
  },

  "permissions": [
    "tabs", "<all_urls>"
  ],

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  }
}

popup.html

<!DOCTYPE html>
<html>
  <body style="width: 300px">
    Open <a href="http://stackoverflow.com" target="_blank">this page</a> and then 
    <button id="clickme">click me</button>
    <script type="text/javascript" src="popup.js"></script>
  </body>
</html>

popup.js

// var app = chrome.runtime.getBackgroundPage();

function hello() {
  chrome.tabs.executeScript({
    file: 'alert.js'
  }); 
}

document.getElementById('clickme').addEventListener('click', hello);
Shayan
  • 709
  • 1
  • 15
  • 31
greatghoul
  • 1,448
  • 1
  • 17
  • 19
  • I upvoted for your efforts, but what for you added the empty background.js? – Stan Dec 25 '13 at 13:44
  • forgive me, background.js is not necessary. – greatghoul Dec 30 '13 at 02:07
  • 1
    @VladGolubev there is no such api, but you can insert html use pure javascript `document.createElement('tag_name');` or jQuery to go. it's easy. – greatghoul Jan 06 '14 at 02:33
  • 1
    While this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. It would be trivial to just copy the contents of your Gist into this answer. However, you do not state the licensing terms for the code in your gist. Thus, it is not clear that it would be permissible for me to just do that. – Makyen Jan 24 '17 at 06:40
  • 1
    Where will this script executed? On popup.html? Or the active webpage (like contentscript)? – Shayan Nov 27 '19 at 10:50
  • For manifest V3: \ 1. you need to use `chrome.scripting.executeScript({` & `files` https://stackoverflow.com/questions/66549560/executescript-is-undefined-or-not-a-function-in-a-manifestv3-extension \ 1. for the `target` you may use `chrome.tabs.query({currentWindow: true, active: true}, function(tabs){` https://stackoverflow.com/questions/7303452/how-to-get-current-tabid-from-background-page – Nor.Z May 27 '23 at 09:37
5

You can also use Messaging:

in popup.js

document.getElementById("clicked-btn").addEventListener("click", function(e) {
    chrome.runtime.sendMessage({'myPopupIsOpen': true});
});

in background.js

chrome.runtime.onMessage.addListener(function(message, sender) {
      if(!message.myPopupIsOpen) return;

      // Do your stuff
});

Not tested but should works, further informations about Messaging.

Community
  • 1
  • 1
Jean-Luc Barat
  • 1,147
  • 10
  • 18