w3c / webextensions

Charter and administrivia for the WebExtensions Community Group (WECG)
Other
579 stars 50 forks source link

Proposal for `runtime.onConnectNative` Event #457

Open xeenon opened 9 months ago

xeenon commented 9 months ago

Currently, web extensions are required to initiate communication with native apps via runtime.connectNative. This approach has limitations. For example, Safari always allows native apps to send messages to an extension, and will hold these messages in a queue until the extension calls runtime.connectNative. To address this issue, I propose the addition of a runtime.onConnectNative event.

For example:

browser.runtime.onConnectNative.addListener((port) => {
  port.onMessage.addListener((message) => {
    // Handle incoming messages
  });

  port.onDisconnect.addListener(() => {
    // Handle disconnect
  });
});

The port.name property would serve as an identifier for the native app, matching the name parameter used in runtime.connectNative(name). In Safari's specific scenario with a containing app delivery mechanism, the name parameter is optional for outgoing connections from the extension. Nonetheless, incoming connections from native apps should always include an app identifier in the port.name property.

To control which native apps can connect, a new app_ids field could be added to the externally_connectable section of the manifest. This field could also potentially support wildcard entries, like the existing ids field for external extension connections. Despite this, the browser would reserve the right to allow or deny app connections at its discretion.

For instance:

{
  "externally_connectable": {
    "matches": ["https://*.example.com"],
    "ids": ["extension-one", "extension-two"],
    "app_ids": ["com.example.nativeAppOne", "com.example.nativeAppTwo"]
  }
}

On the native app side, error-handling mechanisms will be crucial for cases where the extension is either not loaded or restricted from connecting due to manifest or browser constraints; however, this falls outside the scope of this group but is worth mentioning for a complete developer narrative.

tophf commented 9 months ago

FWIW, this is implemented in Chrome dev channel, disabled by default, enabled via --enable-features=OnConnectNative command line, see https://crbug.com/967262 for more implementation details.

rdcronin commented 3 months ago

Discussed this at the WECG Meet-Up.

We agreed the general shape of this looks fine. We don't have immediate plans on the Chrome side to expand this past dev channel, but in case we do decide to expand this on a later date, please take a look at the Chrome version and let's discuss if there are any changes that would need to be made from the Chrome signature.

Rob--W commented 1 month ago

It's worth noting that Chrome's implementation has several requirements before a "connection" can be established between the native messaging app and the browser: