flutter開(kāi)發(fā)實(shí)戰(zhàn)-inappwebview實(shí)現(xiàn)flutter與Javascript方法調(diào)用
在使用inappwebview時(shí)候,需要flutter端與JS進(jìn)行交互,調(diào)用相應(yīng)的方法,在inappwebview中的JavaScript Handlers。
一、JavaScript Handlers
要添加JavaScript Handlers,可以使用InAppWebViewController.addJavaScriptHandler方法,在該方法中定義handlerName和JavaScript端調(diào)用它時(shí)要調(diào)用的回調(diào)?;卣{(diào)可以返回要在JavaScript端發(fā)送的數(shù)據(jù)。如果您需要在加載網(wǎng)頁(yè)后立即管理JavaScript處理程序,則應(yīng)在創(chuàng)建InAppWebView時(shí)調(diào)用InAppWebViewController.addJavaScriptHandler。
以下是如何注冊(cè)JavaScript處理程序的示例:
onWebViewCreated: (controller) {
// register a JavaScript handler with name "myHandlerName"
controller.addJavaScriptHandler(handlerName: 'myHandlerName', callback: (args) {
// print arguments coming from the JavaScript side!
print(args);
// return data to the JavaScript side!
return {
'bar': 'bar_value', 'baz': 'baz_value'
};
});
},
在JavaScript端,要執(zhí)行回調(diào)處理程序并將數(shù)據(jù)發(fā)送到Flutter,您需要使用window.Flutter_inappwebview.callHandler(handlerName,…args)方法,其中handlerName是一個(gè)字符串,表示您正在調(diào)用的處理程序名稱(chēng),args是可以發(fā)送到Fluter方面的可選參數(shù)。
注意:
如果相更換一個(gè)名字,我們可以更換一個(gè)名字來(lái)嵌套window.flutter_inappwebview
window.myCustomObj = { callHandler: window.flutter_inappwebview.callHandler } and, then, you can use window.myCustomObj.callHandler
此外,可以通過(guò)這種方式包裝整個(gè)特定的處理代碼:
const myHandlerName = (…args) => window.flutter_inappwebview.callHandler(‘myHandlerName’, …args);
然后調(diào)用myHandlerName();
在Javascript端,如果需要調(diào)用callHandler,需要監(jiān)聽(tīng)flatterInAppWebViewPlatformReady??梢允褂迷趂latterInAppWebViewPlatformReady事件被分派時(shí)設(shè)置的全局標(biāo)志變量,并在調(diào)用window.flutter_inappwebview.callHandler方法之前使用它。
示例代碼如下
// execute inside the "flutterInAppWebViewPlatformReady" event listener
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
const args = [1, true, ['bar', 5], {foo: 'baz'}];
window.flutter_inappwebview.callHandler('myHandlerName', ...args);
});
// or using a global flag variable
var isFlutterInAppWebViewReady = false;
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
isFlutterInAppWebViewReady = true;
});
// then, somewhere in your code
if (isFlutterInAppWebViewReady) {
const args = [1, true, ['bar', 5], {foo: 'baz'}];
window.flutter_inappwebview.callHandler('myHandlerName', ...args);
}
在flutter端,F(xiàn)lutter在執(zhí)行注入方法時(shí)候,調(diào)用evaluateJavascript來(lái)執(zhí)行callHandler,這個(gè)flutterInAppWebViewPlatformReady無(wú)需監(jiān)聽(tīng),因?yàn)檫@個(gè)flutterInAppWebViewPlatformReady已經(jīng)Ready了。
可以在onLoadStop中調(diào)用代碼
onLoadStop: (controller, url) async {
await controller.evaluateJavascript(source: """
const args = [1, true, ['bar', 5], {foo: 'baz'}];
window.flutter_inappwebview.callHandler('myHandlerName', ...args);
""");
},
window.flutter_inappwebview.callHandler返回一個(gè)JavaScript Promise,該P(yáng)romise可用于獲取回調(diào)返回的json結(jié)果。在這種情況下,只需返回您想要發(fā)送的數(shù)據(jù),它將使用dart:convert庫(kù)中的jsonEncode自動(dòng)進(jìn)行json編碼。
一個(gè)簡(jiǎn)單的示例代碼
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isAndroid) {
await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
}
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
android: AndroidInAppWebViewOptions(
useHybridComposition: true,
),);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("JavaScript Handlers")),
body: SafeArea(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialData: InAppWebViewInitialData(
data: """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<body>
<h1>JavaScript Handlers</h1>
<script>
window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
window.flutter_inappwebview.callHandler('handlerFoo')
.then(function(result) {
// print to the console the data coming
// from the Flutter side.
console.log(JSON.stringify(result));
window.flutter_inappwebview
.callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result);
});
});
</script>
</body>
</html>
"""
),
initialOptions: options,
onWebViewCreated: (controller) {
controller.addJavaScriptHandler(handlerName: 'handlerFoo', callback: (args) {
// return data to the JavaScript side!
return {
'bar': 'bar_value', 'baz': 'baz_value'
};
});
controller.addJavaScriptHandler(handlerName: 'handlerFooWithArgs', callback: (args) {
print(args);
// it will print: [1, true, [bar, 5], {foo: baz}, {bar: bar_value, baz: baz_value}]
});
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
// it will print: {message: {"bar":"bar_value","baz":"baz_value"}, messageLevel: 1}
},
),
),
]))),
);
}
}
二、監(jiān)聽(tīng)自定義CustomEvent
可以設(shè)置一個(gè)消息事件偵聽(tīng)器(與postMessage一起使用)或一個(gè)自定義事件偵聽(tīng)器。
// message event listener
window.addEventListener("message", (event) => {
console.log(event.data);
}, false);
// or custom event listener
window.addEventListener("myCustomEvent", (event) => {
console.log(event.detail);
}, false);
然后使用window.dispatch
// using postMessage method
window.postMessage({foo: 1, bar: false});
// or dispatching a custom event
const event = new CustomEvent("myCustomEvent", {
detail: {foo: 1, bar: false}
});
window.dispatchEvent(event);
因此,可以在運(yùn)行時(shí)使用InAppWebViewController.eevaluatteJavascript方法或在web應(yīng)用程序內(nèi)部設(shè)置這些事件偵聽(tīng)器,并使用相同的方法調(diào)度這些事件。
例如:
onLoadStop: (controller, url) async {
await controller.evaluateJavascript(source: """
window.addEventListener("myCustomEvent", (event) => {
console.log(JSON.stringify(event.detail));
}, false);
""");
await Future.delayed(Duration(seconds: 5));
controller.evaluateJavascript(source: """
const event = new CustomEvent("myCustomEvent", {
detail: {foo: 1, bar: false}
});
window.dispatchEvent(event);
""");
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
// it will print: {message: {"foo":1,"bar":false}, messageLevel: 1}
},
三、小結(jié)
flutter開(kāi)發(fā)實(shí)戰(zhàn)-inappwebview實(shí)現(xiàn)flutter與Javascript方法調(diào)用。描述可能不是特別準(zhǔn)確,請(qǐng)見(jiàn)諒。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-773625.html
學(xué)習(xí)記錄,每天不停進(jìn)步。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-773625.html
到了這里,關(guān)于flutter開(kāi)發(fā)實(shí)戰(zhàn)-inappwebview實(shí)現(xiàn)flutter與Javascript方法調(diào)用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!