2

My web application needs access to UDP sockets, something that the web does not support, presumably for security reasons. I have decided to create a chrome extension that users are required to install to use my web application, of course doing this at their own risk.

The idea is for my extension to expose custom UDP socket APIs by adding a global variable such as myExtension.udpSockets to webpages. The webpage can check that window.myExtension exists first (the extension is installed) before attempting to access my UDP socket API.

When a webpage accesses my UDP socket API, I will create a popup to ensure that the user would like to give this webpage access to UDP sockets and state the security implications.

I currently have my code in a content script, e.g.

function createUDPSocket() {
  // use chrome API
  console.log("Creating a UDP socket!");
}

I know I can inject JavaScript into the webpage by modifying the DOM.

document.createElement("script");
// etc.

But how can I expose my API to this webpage? They are in separate JS contexts, so this wouldn't work. Is there some way of communicating between them?


Edt: It seems I'm looking for something similar to exportFunction in Firefox extensions.

David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • I think you would have to inject the script, and then communicate with your extension via the postMessage API. So, you'll be essentially wrapping postMessage on each end. – Brad Jan 14 '20 at 17:49
  • @Brad Thanks I'll search that and see if it works – David Callanan Jan 14 '20 at 17:49

1 Answers1

1

There's no exportFunction/cloneInto in Chrome so you'll have to use a DOM script element and messaging.

If you expose the API only to one or several URLs you can use the secure extension API messaging via externally_connectable directly to the background script (it can't connect to the content script). Otherwise, for DOM messaging I suggest using CustomEvent with a unique or even better a random event id, definitely not postMessage, so that no other code can eavesdrop on your channel (assuming you use a random event id which can be passed to the script element when created using textContent, see method 2).

In any method of messaging your data must be JSON-compatible (number, string, boolean, null, and objects/arrays consisting of these types). Attempting to send an incompatible object such as a function or DOM element or a Map or a typed array may cause your entire message to be null.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136