Chewie The Chorkie
Chewie The Chorkie

Reputation: 5244

How do you call a JS function in a Safari extension popover?

I'm making a Safari extension that mostly uses javascript. The popover displays html I put inside including a button with an id, but it does not trigger a function inside my content.js, which manipulates the site I'm using it on.

I can't find any information about this. Even the example project Apple has does not show an example of this.

What I want to achieve is being able to toggle the extension on and off for a specific tab, but I eventually want it to interact with my script that is manipulating the page.

popup.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="popup.css">
</head>
<body>
<h2>Extension Title</h2>
<button id="onOffToggleButton">ON</button>
<div id="color-container">
</div>
</body>
</html>

content.js

document.getElementById("onOffToggleButton").addEventListener("click", function() {
    console.log("hi") // does not occur
});

Upvotes: 3

Views: 765

Answers (2)

Chewie The Chorkie
Chewie The Chorkie

Reputation: 5244

I found out you need a lot more going on. First you need a script inside the popup. Here's popup.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="popup.css">
<script type="module" src="popup.js"></script>
</head>
<body>
<h2>Extension Title</h2>
<button id="onOffToggleButton">ON</button>
<div id="color-container">
</div>
<script src="popup.js"></script>
</body>
</html>

This is popup.js. I have a function to get the current browser tab, which is returned when you click the button in popup.html. It sends the command "test" to content.js.

function getActiveTab() {
    return browser.tabs.query({active: true, currentWindow: true});
}

document.getElementById("onOffToggleButton").addEventListener("click", function() {
    getActiveTab().then((tabs) => {
        browser.tabs.sendMessage(tabs[0].id, {
            command: "test",
        });
    });
});

content.js receives the message, and writes the message to the console:

browser.runtime.onMessage.addListener((message) => {
    if (message.command === "test") {
        console.log("hi")
    }
});

Upvotes: 5

wesleybreukers
wesleybreukers

Reputation: 1

Try using the built in alert function

alert("what you want")

Upvotes: 0

Related Questions