5

I have a Chrome extension which requires a sandbox so that I can use a custom content security policy and also requires a Service Worker so I have a script running that is persistent. I would like the Service Worker to open a new (sandbox) window, and then be able to communicate with this sandbox by using postMessage.

I have tried three methods to create this window but none of them quite work for me:

  • I tried chrome.windows.create which is able to create the window, but I don't have accese to postMessage (or at least I don't know how to access postMessage this way).
  • I tried window.open which returns a WindowProxy object which I can call postMessage on. However this only works where the window context is available and this is not the case in Service Worker.
  • I tried clients.openWindow however I ended up with an error "Not allowed to open a window".

Is there anyway to create a (sandboxed) window which allows me to use postMessage from a Service Worker in a chrome extension?

Bentley Carr
  • 672
  • 1
  • 8
  • 24
  • chrome.windows.create + navigator.serviceWorker.controller.postMessage in the new page + self.onmessage inside the service worker. See also [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm Sep 23 '21 at 06:50
  • @wOxxOm Thanks for your suggestion, however when trying to do `navigator.serviceWorker.controller.postMessage` in the sandboxed page I get `Uncaught DOMException: Failed to read the 'serviceWorker' property from 'Navigator': Service worker is disabled because the context is sandboxed and lacks the 'allow-same-origin' flag.` According to [these docs](https://developer.chrome.com/docs/extensions/mv3/manifest/sandbox/), `allow-same-origin` is not allowed in a sandbox's content security policy. Do you have any suggestions? – Bentley Carr Sep 23 '21 at 14:41
  • 1
    Put the sandboxed page inside an iframe. The container page (non-sandboxed) will use iframe.contentWindow.postMessage and window.onmessage for the response. – wOxxOm Sep 23 '21 at 15:51
  • 1
    Did that work? If so, could someone post a proof of concept ? – Klapaucius Klapaucius Oct 22 '21 at 07:22

0 Answers0