Closed
Description
I am trying to migrate from html package, and figured out that it is impossible to call postMessage() for iframe with content from another domain.
myIFrame.contentWindow?.postMessage('aaa'.toJS, '*'.toJS);
The same code with html package works without any security exceptions.
I'm getting the following error when accessing myIFrame.contentWindow:
SecurityError: Failed to read a named property from 'Window': Blocked a frame with origin "http://localhost:51005" from accessing a cross-origin frame.
There is a quite ugly workaround for this issue.
Add to index.html:
<script>
window.jsMyx = {
postMessage(iframeElt, msg) {
if (iframeElt) {
iframeElt.contentWindow.postMessage(msg, '*');
}
}
};
</script>
Then in Dart:
import 'dart:js_interop';
import 'package:web/web.dart' as web;
extension type JsMyx._(JSObject _) implements JSObject {
external void postMessage(web.HTMLIFrameElement iframe, JSAny? msg);
}
@JS()
external JsMyx get jsMyx;
And the following call works without any errors again:
void _sendMessage(Map<String, String> msg) {
if (kIsWeb) {
HTMLIFrameElement? fr = getMyIframe();
if (fr != null) {
jsMyx.postMessage(fr, msg.jsify());
}
}
}