欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Flutter webview与网页通讯交互实现

时间:2022-06-23 11:39:07|栏目:Android代码|点击:

前言

在app开发中我们有JSBridge来实现app和网页端通讯,现参考JSBridge实现了Flutter webview和网页端通讯。

预览

flutter

import 'package:ds_bridge/ds_bridge.dart';
class JsBridgeUtil {
  // 向H5调用接口
  static executeMethod(flutterWebViewPlugin, String jsonStr) async{
    DsBridge dsBridge = DsBridge(flutterWebViewPlugin);
    Result result = dsBridge.dispatch(jsonStr);
    if(result.method == 'share'){
      result.callBack('收到网页端share事件,内容为${result.data}并返回此文本给网页');
    }
    if(result.method == 'share1'){
      result.callBack('收到网页端share1事件');
    }
  }
}

网页

import 'dsbridge_flutter'
dsBridge.call('share', { name: 'woyehaizaixiang' }, function (res) {
  alert(res)
})

具体实现

flutter中使用ds_bridge

此包是flutter_webview_pluginwebview与网页交互的工具包,需要先添加flutter_webview_plugin组件,具体flutter_webview_plugin组件使用请前往官网查看 ,在添加flutter_webview_plugin组件后,添加ds_bridge组件

1.配置依赖包

dependencies:
    ds_bridge: ^0.0.1

2.在webview页面添加JavascriptChannel

webview.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:yundk_app/routes/application.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import '../../utils/JsBridgeUtil.dart';

class WebviewPage extends StatefulWidget {
  final String url;
  final VoidCallback backCallback;

  WebviewPage({
    Key key,
    @required this.url,
    this.backCallback,
  }) : super(key: key);

  @override
  _WebviewPageState createState() => _WebviewPageState();
}

class _WebviewPageState extends State<WebviewPage> {
  String _title = '';
  final flutterWebViewPlugin = FlutterWebviewPlugin();
  final Set<JavascriptChannel> jsChannels = [
    JavascriptChannel(
        name: 'DsBridgeApp',
        onMessageReceived: (JavascriptMessage msg) {
          String jsonStr = msg.message;
          JsBridgeUtil.executeMethod(FlutterWebviewPlugin(), jsonStr);
        }),
  ].toSet();

  StreamSubscription<String> _onUrlChanged;

  @override
  void initState() {
    super.initState();
    flutterWebViewPlugin.close();

    // 监听 url changed
    _onUrlChanged =
    flutterWebViewPlugin.onUrlChanged.listen((String url) async {

    });

    // 监听页面onload
    flutterWebViewPlugin.onStateChanged.listen((viewState) async {
      if (viewState.type == WebViewState.finishLoad) {
        flutterWebViewPlugin.evalJavascript('document.title').then((result) => {
          setState(() {
            _title = result;
          })
        });
      }
    });

  }

  @override
  void dispose() {
    _onUrlChanged.cancel();
    flutterWebViewPlugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WebviewScaffold(
        appBar: new AppBar(
          leading: IconButton(
            hoverColor: Colors.transparent,
            highlightColor: Colors.transparent,
            icon: Icon(const IconData(0xe61b, fontFamily: 'IconFont'), color: Color(0xff333333), size: 18),
            onPressed: (){
              flutterWebViewPlugin.close();
              Application.router.pop(context);
            },
          ),
          title: new Text(
            _title,
            style: TextStyle(color: Color(0xff333333), fontSize: 17),
          ),
          actions: [
            new IconButton(
              icon: new Icon(
                Icons.refresh_outlined,
                color: Color(0xff333333),
                size: 20
              ),
              onPressed: () {
                flutterWebViewPlugin.reload();
              }
            ),
          ],
          centerTitle: true,
          elevation: 0,
        ),
        url: widget.url,
        javascriptChannels: jsChannels,
        mediaPlaybackRequiresUserGesture: false,
        withZoom: true,
        withLocalStorage: true,
        hidden: true,
      )
    );
  }
}

3.在JsBridgeUtil类中

utils/JsBridgeUtil.dart

import 'package:ds_bridge/ds_bridge.dart';
class JsBridgeUtil {
  // 向H5调用接口
  static executeMethod(flutterWebViewPlugin, String jsonStr) async{
    DsBridge dsBridge = DsBridge(flutterWebViewPlugin);
    Result result = dsBridge.dispatch(jsonStr);
    if(result.method == 'share'){
      result.callBack('收到网页端share事件,内容为${result.data}并返回此文本给网页');
    }
    if(result.method == 'share1'){
      result.callBack('收到网页端share1事件');
    }
  }
}

网页端使用dsbridge_flutter

此插件为网页端插件,配合flutter端ds_bridge一起使用

1.安装

npm install dsbridge_flutter

2.使用

import 'dsbridge_flutter'
dsBridge.call(<String> method, <Object> data, <Function> callback)

3.例子

import 'dsbridge_flutter'
dsBridge.call('share', { name: 'woyehaizaixiang' }, function (res) {
  alert(res)
})

总结

本文参考JSBridge实现了Flutter webview和网页端交互。具体用到的插件有Flutter端flutter_webview_pluginds_bridge、网页端有dsbridge_flutter

上一篇:Android基于Flutter编写文件下载管理器

栏    目:Android代码

下一篇:Android仿微信布局的实现示例

本文标题:Flutter webview与网页通讯交互实现

本文地址:http://www.codeinn.net/misctech/205681.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有