sendMessage from popup to content.js not working in chrome extension

前端 未结 2 1880
鱼传尺愫
鱼传尺愫 2021-02-08 01:18

I\'m trying to make a popup interface for a chrome extension. I can\'t seem to send a message from the popup.html/popup.js to the content.js script. Here\'s what I have so far.

2条回答
  •  时光取名叫无心
    2021-02-08 01:46

    I modified your popup.js and used DOMContentLoaded as Chrome extension suggested like:

    popup.js:

     function popup() {
        chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        var activeTab = tabs[0];
        chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
       });
    }
    
    document.addEventListener("DOMContentLoaded", function() {
      document.getElementById("button1").addEventListener("click", popup);
    });
    

    content.js:

    chrome.runtime.onMessage.addListener(
          function(request, sender, sendResponse) {
            if( request.message === "start" ) {
             start();
                 }
          }
        );
    
        function start(){
            alert("started");
        }
    

    popup.html:

    
    
    
    
    
    
    
    

    I've tested on my end it works.

提交回复
热议问题