#我尝试了什么
# 有问题吗?
当我在 Webview 中单击 btn 向 Flutter App 发送消息时 发生错误 v-on 处理程序中出现错误:“TypeError: 无法读取 null 的属性(读取 'postMessage')”
# Web 代码(VScode 中的 vue.js)
1.main.js
import Vue from 'vue'
import App from './App.vue'
import message from './message';
Vue.config.productionTip = false
Vue.use(message);
window.sendMessage = message;
new Vue({
render: h => h(App)
}).$mount('#app')
const sendMessage = (message) => {
if (userAgent.indexOf('android') !== -1) {
return WebViewBridge.postMessage(message);;
} else if (userAgent.indexOf('iphone') !== -1 || userAgent.indexOf('ipad') !== -1) {
return window.webkit.messageHandlers.webViewMessageHandler.postMessage(message);
} else {
return window.opener.postMessage(message);
}
}
export default {sendMessage}
<template>
<div class="main">
<div class="btn" @click="toast()">communicate!</div>
</div>
</template>
<script>
import message from "../src/message.js"
export default {
name: 'App',
methods:{
toast(){
console.log("message to Flutter App!")
message.sendMessage("hello")
}
},
};
</script>
<style>
.main{
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: antiquewhite;
}
.btn{
background-color: black;
color: #fff;
padding: 10px 20px;
border-radius: 10px;
}
</style>
# Flutter 代码(在 Android Studio 中)
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(
MaterialApp(
title: 'Navigator',
initialRoute: '/my',
routes: {
"/my": (context) => MyApp(),
},
),
);
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: EmptyAppBar(),
body: WebView(
//userAgent: "random", //Add this to resolve issue
initialUrl: "http://myipaddress:8080/",
javascriptMode: JavascriptMode.unrestricted,
//A named channel for receiving messaged from JavaScript code running inside a web view
javascriptChannels: <JavascriptChannel>{
_webToApp(context),
}
)
);
}
}
// Webview Native commuication
JavascriptChannel _webToApp(BuildContext context) {
return JavascriptChannel(
name: 'WebViewBridge',
// A callback that's invoked when a message is received through the channel.
onMessageReceived: (JavascriptMessage message) {
print('javascript run');
});
}
原样 WebViewBridge.postMessage(消息);
未来 // eslint-禁用-下一行 window.WebViewBridge.postMessage(消息);