Skip to content

Using MessagePorts (+ Transferables) over ContextBridge #27024

Closed
@willium

Description

@willium

Transferables aren't listed in the relevant documentation, but given their type, it seems like the preferred case would be that they are indeed "transferred" over the contexts. Is that possible?

In any case, is there a good path forward for using MessagePorts alongside contextBridge? How about passing transferables over MessagePorts without incurring the intermediary copy across the bridge?

Here is my best guess about how that might work (though, again, transferables don't seem to work as expected).

import { contextBridge } from "electron"

contextBridge.exposeInMainWorld("electron", {
  foo: (bar) => bar,
  connect: (port, connection) => {
		if (!validPorts.includes(port)) {
			throw new Error(`Invalid Channel "${port}"`)
		}

		const callback = ({ ports }, _) => {
                        // really don't know how this API could be expanded to support juggling multiple ports in one "connection"
			if (ports.length !== 0) throw new Error("Connection requires (1) port")

			ports.forEach((messagePort) => {

				const post = (outgoing, transferables) => {
					messagePort.postMessage(outgoing, transferables)
				}

				const disconnect = () => {
					ipcRenderer.removeListener(port, callback)
				}

				messagePort.onmessage = ({ data }) => {
					connection(data, post, disconnect)
				}
				messagePort.onmessageerror = ({ data }) => {
					connection(data, post, disconnect)
				}

				messagePort.start()
			})
		}

		ipcRenderer.on(port, callback)
	},
})

Preflight Checklist

  • I have read the Contributing Guidelines for this project.
  • I agree to follow the Code of Conduct that this project adheres to.
  • I have searched the issue tracker for an issue that matches the one I want to file, without success.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions