Execute script after click in popup.html (chrome extension)

17,901

Solution 1

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);

Solution 2

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.

Share:
17,901
Vlad Holubiev
Author by

Vlad Holubiev

💻 AWS, Cloud, Serverless, Microservices, node.js, Docker, Elasticsearch, MongoDB, APIs, IaaC, CI, DevOps, TDD, Terraform, Jest 🌐 Website: vladholubiev.com 💬 Twitter: twitter.com/vladholubiev ✏️ Blog: medium.com/@vladholubiev 💼 LinkedIn: linkedin.com/in/vlad-holubiev

Updated on June 05, 2022

Comments

  • Vlad Holubiev
    Vlad Holubiev 6 months

    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.

  • Stan
    Stan almost 9 years
    I upvoted for your efforts, but what for you added the empty background.js?
  • greatghoul
    greatghoul almost 9 years
    forgive me, background.js is not necessary.
  • greatghoul
    greatghoul almost 9 years
    @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.
  • Makyen
    Makyen almost 6 years
    While this may theoretically answer the question, it would be preferable 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.
  • Shayan
    Shayan about 3 years
    Where will this script executed? On popup.html? Or the active webpage (like contentscript)?
  • cercatrova
    cercatrova about 2 years
    This is a better way to do it rather than running raw scripts like in @greatghoul's answer
  • EGS
    EGS almost 2 years
    Theoractly It may be better, but it doesn't work.