I'm a noob to Flutter Web. I have a package that I'm trying to create support for in Flutter Web, but it uses a webview for some functions. Webviews aren't supported in Flutter Web so I'm using a IFrameElement
and ui.platformViewRegistry.registerViewFactory()
to act like a webview. I'm passing an HTML String to be loaded rather than a file.
I need to be able to run JS functions and get data from JS. I've tried a lot of different things with events and event listeners, also context.callMethod()
and none of it has worked so far. Is there a simple way to accomplish this?
For reference, I am using the Summernote library and I can run something like \$('#summernote').summernote('reset');
to reset the Summernote editor. Sometimes I need to get data from JS so I am running var str = \$('#summernote').summernote('code'); console.log(str);
which gives me the HTML code in the editor.
Thanks in advance!
Code for reference:
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:html_editor_enhanced/html_editor.dart';
import 'package:html_editor_enhanced/utils/pick_image.dart';
import 'package:path/path.dart' as p;
import 'package:flutter/material.dart';
import 'dart:html' as html;
import 'dart:js' as js;
import 'dart:ui' as ui;
bool callbacksInitialized = false;
js.JsObject jsDocument;
class HtmlEditorWidgetWeb extends StatelessWidget {
HtmlEditorWidgetWeb({
Key key,
this.value,
this.height,
this.useBottomSheet,
this.imageWidth,
this.showBottomToolbar,
this.hint,
this.callbacks,
this.toolbar,
this.darkMode
}) : super(key: key);
final String value;
final double height;
final bool useBottomSheet;
final double imageWidth;
final bool showBottomToolbar;
final String hint;
final UniqueKey webViewKey = UniqueKey();
final Callbacks callbacks;
final List<Toolbar> toolbar;
final bool darkMode;
final String createdViewId = 'html_editor_web';
@override
Widget build(BuildContext context) {
String summernoteToolbar = "[\n";
for (Toolbar t in toolbar) {
summernoteToolbar = summernoteToolbar +
"['${t.getGroupName()}', ${t.getButtons()}],\n";
}
summernoteToolbar = summernoteToolbar + "],";
String darkCSS = "";
if ((Theme.of(context).brightness == Brightness.dark || darkMode == true) && darkMode != false) {
darkCSS = "<link href=\"packages/html_editor_enhanced/assets/summernote-lite-dark.css\" rel=\"stylesheet\">";
}
String htmlString = """
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="description" content="Flutter Summernote HTML Editor">
<meta name="author" content="xrb21">
<title>Summernote Text Editor HTML</title>
<script src="main.dart.js" type="application/javascript"></script>
<script src="app.js" defer></script>
<script src=".4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<link href="/[email protected]/dist/summernote-lite.min.css" rel="stylesheet">
<script src="/[email protected]/dist/summernote-lite.min.js"></script>
$darkCSS
<script>
function test() {
console.log("Listening");
}
</script>
</head>
<body>
<div id="summernote-2"></div>
<script type="text/javascript">
\$('#summernote-2').summernote({
placeholder: "$hint",
tabsize: 2,
height: ${height - 125},
maxHeight: ${height - 125},
toolbar: $summernoteToolbar
disableGrammar: false,
spellCheck: false
});
document.addEventListener("setFS", function(){
console.log('fired');
\$('#summernote-2').summernote("fullscreen.toggle");
});
</script>
<style>
body {
display: block;
margin: 0px;
}
.note-editor.note-airframe, .note-editor.note-frame {
border: 0px solid #a9a9a9;
}
.note-frame {
border-radius: 0px;
}
</style>
</body>
</html>
""";
html.window.onMessage.forEach((element) {
print('Event Received in callback: ${element.data}');
});
// todo use postmessage and concatenation to accomplish callbacks
final html.IFrameElement iframe = html.IFrameElement()
..width = MediaQuery.of(context).size.width.toString() //'800'
..height = MediaQuery.of(context).size.height.toString() //'400'
..srcdoc = htmlString
..style.border = 'none'
..onLoad.listen((event) async {
html.document.on['setFS'].listen((html.Event event) {
print("HEY! I'M LISTENING!");
});
html.document.dispatchEvent(html.Event("setFS"));
});
ui.platformViewRegistry.registerViewFactory(
createdViewId, (int viewId) => iframe);
return Column(
children: <Widget>[
Expanded(
child: Directionality(
textDirection: TextDirection.ltr,
child: HtmlElementView(
viewType: createdViewId,
)
)
),
],
);
}
}
I'm a noob to Flutter Web. I have a package that I'm trying to create support for in Flutter Web, but it uses a webview for some functions. Webviews aren't supported in Flutter Web so I'm using a IFrameElement
and ui.platformViewRegistry.registerViewFactory()
to act like a webview. I'm passing an HTML String to be loaded rather than a file.
I need to be able to run JS functions and get data from JS. I've tried a lot of different things with events and event listeners, also context.callMethod()
and none of it has worked so far. Is there a simple way to accomplish this?
For reference, I am using the Summernote library and I can run something like \$('#summernote').summernote('reset');
to reset the Summernote editor. Sometimes I need to get data from JS so I am running var str = \$('#summernote').summernote('code'); console.log(str);
which gives me the HTML code in the editor.
Thanks in advance!
Code for reference:
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:html_editor_enhanced/html_editor.dart';
import 'package:html_editor_enhanced/utils/pick_image.dart';
import 'package:path/path.dart' as p;
import 'package:flutter/material.dart';
import 'dart:html' as html;
import 'dart:js' as js;
import 'dart:ui' as ui;
bool callbacksInitialized = false;
js.JsObject jsDocument;
class HtmlEditorWidgetWeb extends StatelessWidget {
HtmlEditorWidgetWeb({
Key key,
this.value,
this.height,
this.useBottomSheet,
this.imageWidth,
this.showBottomToolbar,
this.hint,
this.callbacks,
this.toolbar,
this.darkMode
}) : super(key: key);
final String value;
final double height;
final bool useBottomSheet;
final double imageWidth;
final bool showBottomToolbar;
final String hint;
final UniqueKey webViewKey = UniqueKey();
final Callbacks callbacks;
final List<Toolbar> toolbar;
final bool darkMode;
final String createdViewId = 'html_editor_web';
@override
Widget build(BuildContext context) {
String summernoteToolbar = "[\n";
for (Toolbar t in toolbar) {
summernoteToolbar = summernoteToolbar +
"['${t.getGroupName()}', ${t.getButtons()}],\n";
}
summernoteToolbar = summernoteToolbar + "],";
String darkCSS = "";
if ((Theme.of(context).brightness == Brightness.dark || darkMode == true) && darkMode != false) {
darkCSS = "<link href=\"packages/html_editor_enhanced/assets/summernote-lite-dark.css\" rel=\"stylesheet\">";
}
String htmlString = """
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="description" content="Flutter Summernote HTML Editor">
<meta name="author" content="xrb21">
<title>Summernote Text Editor HTML</title>
<script src="main.dart.js" type="application/javascript"></script>
<script src="app.js" defer></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/summernote-lite.min.js"></script>
$darkCSS
<script>
function test() {
console.log("Listening");
}
</script>
</head>
<body>
<div id="summernote-2"></div>
<script type="text/javascript">
\$('#summernote-2').summernote({
placeholder: "$hint",
tabsize: 2,
height: ${height - 125},
maxHeight: ${height - 125},
toolbar: $summernoteToolbar
disableGrammar: false,
spellCheck: false
});
document.addEventListener("setFS", function(){
console.log('fired');
\$('#summernote-2').summernote("fullscreen.toggle");
});
</script>
<style>
body {
display: block;
margin: 0px;
}
.note-editor.note-airframe, .note-editor.note-frame {
border: 0px solid #a9a9a9;
}
.note-frame {
border-radius: 0px;
}
</style>
</body>
</html>
""";
html.window.onMessage.forEach((element) {
print('Event Received in callback: ${element.data}');
});
// todo use postmessage and concatenation to accomplish callbacks
final html.IFrameElement iframe = html.IFrameElement()
..width = MediaQuery.of(context).size.width.toString() //'800'
..height = MediaQuery.of(context).size.height.toString() //'400'
..srcdoc = htmlString
..style.border = 'none'
..onLoad.listen((event) async {
html.document.on['setFS'].listen((html.Event event) {
print("HEY! I'M LISTENING!");
});
html.document.dispatchEvent(html.Event("setFS"));
});
ui.platformViewRegistry.registerViewFactory(
createdViewId, (int viewId) => iframe);
return Column(
children: <Widget>[
Expanded(
child: Directionality(
textDirection: TextDirection.ltr,
child: HtmlElementView(
viewType: createdViewId,
)
)
),
],
);
}
}
Share
Improve this question
edited Feb 22, 2021 at 16:54
Tanay Neotia
asked Feb 22, 2021 at 16:43
Tanay NeotiaTanay Neotia
5154 silver badges18 bronze badges
2
|
1 Answer
Reset to default 19A little bit hacky, but here's the solution I use:
Dart -> JS
In dart:
html.window.postMessage(//data to send here, "*");
and in the IframeElement HTML <script>
:
window.parent.addEventListener('message', handleMessage, false);
function handleMessage(e) {
var data = e.data;
}
I personally use JSON when sending data to make it easier to send/receive/parse. So in Dart that is a Map<String, dynamic>
, sent like this:
final data = Map<String, dynamic>{
//your data here
}
final jsonEncoder = JsonEncoder();
final json = jsonEncoder.convert(data);
html.window.postMessage(json, "*");
and in JS:
window.parent.addEventListener('message', handleMessage, false);
function handleMessage(e) {
var data = JSON.parse(e.data);
}
A suggestion would be to create a unique key/string that you can pass in between JS and Dart so you make sure you are intercepting the correct postMessage
every time.
JS -> Dart
In the IframeElement
HTML <script>
:
window.parent.postMessage(//data to send, "*");
and in Dart:
html.window.onMessage.listen((event) {
var data = event.data;
});
Again, I use JSON to communicate because I think it makes things easier. Use JSON.stringify()
in JS and json.decode()
in Dart.
<iframe>
but dart'sIFrameElement
. I have in my widget:HtmlElementView( viewType: createdViewId, )
I registerui.platformViewRegistry.registerViewFactory( createdViewId, (int viewId) => iframe);
let me update the question with my code – Tanay Neotia Commented Feb 22, 2021 at 16:50