0

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?

  • Remove onclick attribute and use a listener in the js file. Rework the code to correctly reflect the extension architecture: the background page is a separate hidden page that's not connected to the popup so the popup can't use background.js directly (if it does, you misunderstand the architecture). Start using devtools debugger: the popup has is own devtools which you can invoke by right-clicking the popup, the background page has its own devtools too accessible from chrome://extensions page. Using devtools properly should help you resolve such simple issues in a matter of seconds/minutes. – wOxxOm Jun 16 '18 at 04:20

1 Answers1

0

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
}
jakobinn
  • 1,832
  • 1
  • 20
  • 20
  • I tried this, it didn't work. Still the same story, nothing happens once I press the button. – Jan Procházka Jun 15 '18 at 20:50
  • Did you create a new javascript file, add after the

    element and before the

    element in your popup.html and then put the event listener inside that file?

    – jakobinn Jun 16 '18 at 18:27