Skip to content

Commit

Permalink
feat: add support for JavaScript channels
Browse files Browse the repository at this point in the history
  • Loading branch information
Frank3K committed Apr 6, 2023
1 parent 03e19a9 commit 5b5b6e3
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:collection';
import 'dart:convert';
import 'dart:html' as html;

Expand Down Expand Up @@ -57,6 +58,10 @@ class WebWebViewController extends PlatformWebViewController {
WebWebViewControllerCreationParams get _webWebViewParams =>
params as WebWebViewControllerCreationParams;

/// Mapping between channel names and message event handlers.
HashMap<String, Null Function(html.Event)> javascriptChannels =
HashMap<String, Null Function(html.Event)>();

@override
Future<void> loadHtmlString(String html, {String? baseUrl}) async {
// ignore: unsafe_html
Expand Down Expand Up @@ -106,6 +111,31 @@ class WebWebViewController extends PlatformWebViewController {
encoding: encoding,
).toString();
}

@override
Future<void> addJavaScriptChannel(
JavaScriptChannelParams javaScriptChannelParams,
) async {
final Null Function(html.Event) handler = (html.Event event) {
if (event is html.MessageEvent) {
javaScriptChannelParams.onMessageReceived(
JavaScriptMessage(message: event.data.toString()));
}
};

javascriptChannels[javaScriptChannelParams.name] = handler;
html.window.addEventListener('message', handler);
}

@override
Future<void> removeJavaScriptChannel(String javaScriptChannelName) async {
final Null Function(html.Event)? handler =
javascriptChannels[javaScriptChannelName];

if (handler != null) {
html.window.removeEventListener('message', handler);
}
}
}

/// An implementation of [PlatformWebViewWidget] using Flutter the for Web API.
Expand Down

0 comments on commit 5b5b6e3

Please sign in to comment.