NativeBridge is a plugin based on webview_flutter that realizes JS intermodulation capability between App and H5.
Language: English | 简体中文
- Support the H5 to call the JSBridge method on the App, and can directly get the return value.
- Support App call H5 JSBridge method, and can directly get the return value.
- It is simple to use and extend the NativeBridgeController class after integration to support the JavaScript calling ability of App.
Add dependencies in pubspec.yaml:
dependencies:native_bridge: ^latest_version- extend
NativeBridgeController
classAppBridgeControllerextendsNativeBridgeController {
AppBridgeController(WebViewController controller) :super(controller);
/// Define the JSChannel name@overrideget name =>"nativeBridge";
@overrideMap<String, Function?> get callMethodMap =><String, Function?>{
// Version number"getVersionCode": (data) async {
returnawaitAppUtil.getVersion();
},
...
};
}- Init AppBridgeController.
// Init WebViewController
_controller =WebViewController()
..enableZoom(true)
..loadFlutterAsset('assets/test/index.html');
// Init AppBridgeController
_appBridgeController =AppBridgeController(_controller);- Add the
receiveMessagemethod to H5.
functionreceiveMessage(jsonStr){if(jsonStr!=undefined&&jsonStr!=""){letdata=JSON.parse(JSON.stringify(jsonStr));window.jsBridgeHelper.receiveMessage(data);}}- Define method names and Function calls in the App's callMethodMap, for example, to get the App version number:
// 版本号"getVersionCode": (data) async {
returnawaitAppUtil.getVersion();
}- Call the corresponding method in H5:
asyncfunctiongetVersionName(){// 获取 App 的值letappVersionName=awaitwindow.jsBridgeHelper.sendMessage("getVersionName",null);}There are two ways for the App to get the value of H5:
AppBridgeController's
sendMessagemethod.// is home pagebool? isHome =await _appBridgeController.sendMessage(Message(api:'isHome'));
Call AppBridgeController
runJavaScriptReturningResultmethod.// get UserAgentvar userAgent =await _appBridgeController.runJavaScriptReturningResult('getUserAgent()');
The difference is the first sends a message to H5 the WebViewController's runJavaScript and waits for H5 to reply to the message. The last user WebViewController runJavaScriptReturningResult method directly to obtain the return value.
The first is more applicable and supports a variety of business scenarios, the last is more suitable for obtaining Window-related properties.
Series 1:NativeBridge:基于webivew_flutter的JSBridge插件
Series 2:NativeBridge:实现原理解析
Series 3:App实现JSBridge的最佳方案
Series 4:NativeBridge:我在Pub上发布的第一个插件