2

I'm having trouble with a simple task. In Xcode 13, you can create a Safari Extension App (Safari Web Extension for iOS 15).

From looking around, the Shared Extension has various js resources: background.js, content.js, and popup.js.

Popup.js is the presented modal when you launch your Safari web extension. In popup.html, you can add elements to the popup DOM (such as text, button, etc). In my popup, I have a button which I have wired up in popup.js. When I press this button, I want to notify content.js of this event. How do I do this?

My current code adds an event listener to the button containing browser.runtime.sendMessage({ type: "start" }); in popup.js.

Xcode's template includes the following in content.js:

browser.runtime.sendMessage({ greeting: "hello" }).then((response) => {
    console.log("Received response: ", response);
});

browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log("Received request: ", request);
});

As far as I can tell, the JS is running in popup.js, but I am not seeing anything in console.log for content.js. Sidenote: console.log is really hard to use for iPhone Safari app.

I've found this documentation, but it only discusses passing message from macOS app to JS. I'm trying to pass message from iOS popup to content.js.

xta
  • 729
  • 2
  • 8
  • 29

1 Answers1

0

See if this works

const isChrome = !window["browser"] && !!chrome;
const browser = isChrome ? chrome : window["browser"];

function sendMessageToContent(message) {
    browser.tabs.query({ active: true }).then(function (currentTabs) {
        if (currentTabs[0].id >= 0) {
            browser.tabs.sendMessage(currentTabs[0].id, message);
        }
    });
}
Nima.sa
  • 13
  • 1
  • 2
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Aug 09 '22 at 08:41