Safari web extension: Communicate between injected JS and background.js

29 Views Asked by At

I need to convert a Chrome extension (Manifest 3) to a Safari web extension. I've already tried the converter and it doesn't create a working extension.

What is Safari's equivalent method of communicating between the background script and the injected javascript? (I can't find an actual API description for Safari web extensions anywhere.)

(Please don't link to answers related to the old legacy extensions. This is the new kind.)

The following works in the Chrome extension:

background.js

// injects content.js when user clicks extension icon

// listen for and respond to msg from content.js:

chrome.runtime.onConnect.addListener(function(port){
    //  listen for port msg from content.js
    port.onMessage.addListener(async function(msg) {
        if (msg.msgtype == "msg1"){
            var dict = msg.dict;
            // do stuff here
            // then return message to content.js to display to user:
            var resp = "We did that thing!"
            port.postMessage({msgtype:"response",response:resp});
        }
    });
});

Injected content.js

// set up communication port
var port = chrome.runtime.connect();
 
// listen for response from background.js
port.onMessage.addListener(function(message,sender){
    if(message.msgtype === "response"){
        alert(message.response);
    } 
});
  
// Send msg to background page
var dict = {};
port.postMessage({msgtype:"msg1",dict:dict});

Manifest.json permissions

"permissions": ["activeTab","contextMenus","cookies","scripting"],
"host_permissions": [],
0

There are 0 best solutions below