flutter webview浏览器及与js交互、打开第三方app

添加pubspec.yaml依赖

url_launcher: ^5.4.1

webview_flutter: ^0.3.18+1

--------------main.dart

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(MyApp());

const String TITLE='whq_test';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: TITLE,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: TITLE),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  String _title = TITLE;
  WebViewController _webViewController=null;

  @override
  void initState() {
    super.initState();
  }

  void _openApp(openurl) async{
    // Android
    print("open app");
    final url = 'vnd.'+openurl;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      //  Ios
      final url = openurl;
      if(await canLaunch(url)){
        await launch(url);
      }else{
      throw 'Could not launch $url';
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_title),
      ),
      body: WebView(
        initialUrl: "http://whqtest/app/test.html",
        javascriptMode: JavascriptMode.unrestricted,
        navigationDelegate: (NavigationRequest request){
          if (request.url.startsWith('js://webview')) {
            print('blocking navigation to $request}');
            _openApp(request.url.replaceAll("js://webview", "").replaceAll("?url=", ""));
            return NavigationDecision.prevent;
          }
          print('allowing navigation to $request');
          return NavigationDecision.navigate;
        },
        onWebViewCreated: (WebViewController webViewController){
          _webViewController=webViewController;
        },
        onPageFinished: (url){
          _webViewController.evaluateJavascript("document.title").then((result){
            String title = result.substring(1, result.length - 1);
            if (title.length > 0) {
              print(title);
              setState(() {
                _title = title;
              });
            }
          });
        },
      ),
    );
  }
  @override
  void dispose(){
    super.dispose();
    _webViewController=null;
  }
}

————————test.html

hello world!

<a href="https://www.baidu.com">百度</a>

<a href="js://webview?url=weixin://">微信</a>

发布了426 篇原创文章 · 获赞 33 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/whq12789/article/details/103629794