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

后端 未结 2 766
春和景丽
春和景丽 2020-12-29 11:47

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:

<
相关标签:
2条回答
  • 2020-12-29 12:21

    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

    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);
    
    0 讨论(0)
  • 2020-12-29 12:28

    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.

    0 讨论(0)
提交回复
热议问题