Chrome extension messaging between popup.html and content.js

大憨熊 提交于 2019-12-13 06:18:07

问题


So I have this script that runs on a website and gathers some data based on certain parameters, which works perfectly fine by itself, but I want to be able to have a browserAction popup with a single button in it, which on click will trigger the aforementioned script.

I believe my problem is that I can't get the message to be sent via a press of the button, I don't know how to implement this, and no browserAction tutorial I've read tried to, either.

Here's my code: popup.html

<html>
<body style="width: 200px; height: 150px;">
    <script src="background.js"></script>
    <div id="button" style="position:absolute; left: 75px;">
        <button id="mb" onclick="click()">Initialise</button>
    </div>
</body>
</html>

background.js

function click() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        var activeTab = tabs[0];
        chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
    });
}

content.js

$(document).ready(function(){
    init();
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
        if(request.message === "clicked_browser_action"){
            popup();
        }
    })
});

I know the rest of my code works, because I've tested it by adding

browserAction.onClick.addListener(function(tab){ ... });

in the place of

function click() { ... }

and everything worked exactly as I wanted it to.

How would I go about implementing the button correctly?


回答1:


You need to add an on click event listener using Javascript in the popup, in contrast to defining the event inline in the html.

document.getElementById("mb").addEventListener("click", function(e){
//event will trigger here
}


来源:https://stackoverflow.com/questions/50881251/chrome-extension-messaging-between-popup-html-and-content-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!