I'm using flutter for web. I want to process custom event in my flutter javascript code. I open popup window from flutter:
import 'dart:js' as js;
js.context.callMethod('open', ['http://localhost:8083/popup-page.html?params', 'loginWindow', 'width=600,height=600,left=600,top=200']);
popup-page.html is part of my flutter web application. During its lifecycle popup-page.html is reloaded several times so I can't just assign my callback function to some specific dom.window object. So in popup-page.html I have the following javascript to call back my flutter code when needed:
opener.parent.dispatchEvent(new CustomEvent('myCallback', {detail: callbackDetailsObj}));
Now I want to get and process callbackDetailsObj in my flutter app.
My initial idea was to use window.addEventListener('myCallback', callback) or window.on['myCallback'].listen(callback) from dart:html package. In this and this examples people are just using CustomEvent as callback function arg and casting event.detail to custom dart class. But for me that doesn't work. First - in my callback I get instance of JavaScriptObject for event arg. That JavaScriptObject can't be cast to either CustomEvent or event Event (despite the fact EventListener arg is typedef EventListener(Event event)). So I was not able to cast or convert JavaScriptObject to anything useful (including JsObject from dart:js package) and also was not able to get any fields of that object - e.g. type, target, details.
So in order to create working solution I used context.callMethod + allowInterop:
import 'dart:js' as js;
void addListener() {
var callbackPopupJs = js.allowInterop(callbackPopup);
js.JsObject options = js.JsObject.jsify({'once': true});
js.context.callMethod('addEventListener', ['myCallback', callbackPopupJs, options]);
}
void callbackPopup(js.JsObject ev) {
developer.log('Browser Callback');
developer.log('Event type: ${ev['type']}, runtime: ${ev.runtimeType}, target: ${ev['target']}');
developer.log('Detail : ${ev['detail']}');
}
And now I'm able to get CustomEvent.detail. But I'm not if this method is optimal and it's not possible to use window.addEventListener() and CustomEvent to process window callbacks.