I'm trying to register a service worker from an iframe that is created dynamically like this:
var iframe = document.createElement('iframe');
var html = '
<head><script src="/script.js"></script></head>
<body>Iframe</body>
';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();
script.js
contains the code that registers a service worker (texbook example from google's documentation).
This throws an error saying "Failed to register a ServiceWorker: The document is in an invalid state."
I tried having the service worker registration code in the 'load' event handler of the iframe and adding a timeout to account for the service worker registration code potentially being called at a bad time without any success.
In the source code of Chromium I found the following code which is where I think the error is coming from:
if (!m_provider) {
resolver->reject(DOMException::create(InvalidStateError, "Failed to register a ServiceWorker: The document is in an invalid state."));
return promise;
}
What does "The document is in an invalid state" mean in this context?
What is m_provider
and why is it that it's not available?
This looks to be caused by a bug in Chromium: https://bugs.chromium.org/p/chromium/issues/detail?id=1102209
Ideally, the dynamically-created frame would inherit the services workers registered on the parent, eliminating the need to write in the iframe's contentWindow at all.