Flutter 与 JS|HTML 通信

in Flutter with 0 comment

这里先做定义

Flutter 端 为 app 端

js 端 为 客户端

app 端 调用 客户端代码

使用 runJavascript("js函数"); 进行执行
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class CustomWebview extends StatefulWidget {
const CustomWebview({Key? key}) : super(key: key);

@override
State<CustomWebview> createState() => _CustomWebviewState();
}

class _CustomWebviewState extends State<CustomWebview> {
late WebViewController _controller;

runJsFunc() {
    _controller.runJavascript("alert('我是app触发的')");
}

@override
Widget build(BuildContext context) {
    return WebView(
        onPageStarted: (url) {
            print("onPageStarted($url) ----------------------");
        },
        onPageFinished: (url) {
            print("onPageFinished($url) ----------------------");
            print('Web加载完成:${DateTime.now()}');
        },
        // 禁止缩放(ios 端会自动缩放)
        zoomEnabled: false,
        // 运行js 执行
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webcontroller) {
            _controller = webcontroller;
        },
        initialUrl: "https://www.baidu.com",
        navigationDelegate: (NavigationRequest request) async {
            // 自定义路由拦截
            // return NavigationDecision.prevent; // 禁止跳转
            return NavigationDecision.navigate;
        },
        );
    }
}

客户端 调用 App 端代码

需要在 APP 端定义好 通道
// 路由跳转
JavascriptChannel appRedirect(BuildContext context) {
    return JavascriptChannel(
        name: 'AppRedirect',
        onMessageReceived: (JavascriptMessage message) {
            final pathName = message.message;
            // 我要跳转路由
            Navigator.of(context).pushNamed(pathName);
        },
        );
    }
}


// Webview 定义渠道
WebView(
    ...
    javascriptChannels: <JavascriptChannel>{
        appRedirect(context),
    },
)

// 客户端执行 方法
try {
    AppRedirect.postMessage("login")
}catch (e) {}
Comments are closed.