webext-bridge icon indicating copy to clipboard operation
webext-bridge copied to clipboard

fix: Firefox cross-origin object access

Open pnd280 opened this issue 1 year ago • 1 comments

PR: Resolve Firefox cross-origin object access issue in message port handling

Issue

Firefox was throwing the following error when attempting to send message from window context:

Error: Not allowed to define cross-origin object as property on [Object] or [Array] XrayWrapper

image

Solution

The fix involves modifying how we handle the message port in the getMessagePort function. Instead of directly accessing and modifying ports[0], we now store it in a local variable port. This approach avoids the cross-origin object access issue.

Changes

In src/internal/message-port.ts:

export const getMessagePort = (
  // ... existing code ...
) => {
  // ... existing code ...
  window.addEventListener('message', function acceptMessagingPort(event) {
    const { data: { cmd, scope, context }, ports } = event
    if (cmd === 'webext-port-offer' && scope === namespace && context !== thisContext) {
      window.removeEventListener('message', acceptMessagingPort)
      const port = ports[0]
      port.onmessage = onMessage
      port.postMessage('port-accepted')
      return resolve(port)
    }
  }
  // ... existing code ...
}

Impact

This change resolves the Firefox-specific error without affecting functionality on other browsers. It ensures consistent behavior across different browser environments when handling message ports in cross-origin contexts.

Testing

  • Verified that the error no longer occurs on Firefox.
  • Ensured that the functionality remains intact on other supported browsers.

Please review and test this change to confirm it resolves the issue without introducing any regressions.

pnd280 avatar Oct 22 '24 10:10 pnd280

I'm getting the same error, only this fix didn't work. With some ChatGPT, this does work for me.

Find

win.onMessage((message) => {
  message.origin = {
    context: "window",
    tabId: null
  };
  endpointRuntime.handleMessage(message);
});

replace with

win.onMessage((message) => {
  // Clone the message object to avoid modifying the XrayWrapper.
  const clonedMessage = { ...message, origin: { context: "window", tabId: null } };
  endpointRuntime.handleMessage(clonedMessage);
});

ericfri avatar Feb 12 '25 23:02 ericfri

@jaydrogers, any traction on this (with promoting @ericfri's fix to main)? This is a hard blocker for us (and possibly many others) with being able to use webext-bridge as a cross-platform messaging framework.

EspressoBeans avatar Apr 22 '25 14:04 EspressoBeans

Referring to @danpastori for a resolution

jaydrogers avatar Apr 22 '25 15:04 jaydrogers

has anyone else found a way past this - outside of updating module code?

EspressoBeans avatar May 23 '25 15:05 EspressoBeans