前端与Flutter的跨界对话:探索JavascriptChannel的潜力掌握Flutter与JavaScript的双
前言
在 Flutter
中,JavascriptChannel
是一种用于与 JavaScript
代码进行通信的机制。
它允许你从 Dart
代码调用 JavaScript
函数,或者从 JavaScript
调用 Dart
代码。
以下是如何使用 JavascriptChannel
的基本步骤:
创建
创建 JavaScriptChannel
:
首先,你需要创建一个 JavascriptChannel
实例,并注册它到你的 WebView
中。
注册
late Set<JavascriptChannel> jsbridge;
initState(){
jsbridge = Set<JavascriptChannel>();
}
webView中调用
WebView(
initialUrl:yourUrl,
onWebViewCreated: (WebViewController controller) {
webController = controller;
},
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: jsbridge,
),
前端注册
window.flutter_inappwebview = {};
window.flutter_inappwebview.callHandler = (name, data = null) => {
console.log('***********flutter_inappwebview************',name);
if (data === null) data = {};
data = {
data: data,
key: name + Date.now().toString()
}
console.log('window[name]::',window[name]);
window[name].postMessage(JSON.stringify(data).toString());
return new Promise((resolve, reject) => {
let getMessage = (e) => {
console.log("getMessage:", e.data);
const res = e.data
// 拿到消息后解析resolve数据
if (res.type == "flutterCallingMessage" && res.key == data.key) {
window.removeEventListener("message", getMessage, true);
resolve(res.data);
}
// 50s 超时抛出错误
setTimeout(() => {
window.removeEventListener("message", getMessage, true);
reject("timeout");
}, 500000);
};
window.addEventListener("message", getMessage, true);
});
};
flutter调用前端代码
void callJavaScriptFunction() {
// 调用JavaScript中的函数
jsbridge.invokeJavascript('functionName', args: ['arg1', 'arg2']);
}
效果如下:
前端调用flutter代码
export const loaction = () => {
window.flutter_inappwebview.callHandler('loaction').then((e) => {
console.log(e);
})
}
效果如下:
总结
请注意,实际使用时,你需要根据你的具体需求调整 JavaScript
函数的名称和参数。
同时,确保 JavaScript
代码在 WebView
加载的页面中被正确执行。
– 欢迎点赞、关注、转发、收藏【我码玄黄】,各大平台同名。
转载自:https://juejin.cn/post/7404777637380685834