dart 在Flutter Webview中运行一些JavaScript

fbcarpbf  于 11个月前  发布在  Flutter
关注(0)|答案(7)|浏览(204)

如何在flutter_webview_plugin中运行JavaScript?我尝试了这个:

onPressed: () {
   flutterWebviewPlugin.evalJavascript('<script language="JavaScript" type="text/javascript">alert("Hello World")</script>');
},

字符串
但什么也没发生。
我以为flutterWebviewPlugin.evalJavascript可以在Webview中运行JavaScript。我做错了什么吗?

s71maibg

s71maibg1#

flutterWebviewPlugin.evalJavascript('<script language="JavaScript" type="text/javascript">alert("Hello World")</script>')

字符串
需要JavaScript,而不是HTML

<script language="JavaScript" type="text/javascript">alert("Hello World")</script>


是HTML。
尝试

flutterWebviewPlugin.evalJavascript('alert("Hello World")')

bvjxkvbb

bvjxkvbb2#

你可以试试我的插件flutter_inappwebview,这是一个Flutter插件,允许你添加内联WebViews或打开应用内浏览器窗口,并有很多事件,方法和选项来控制WebViews。
要运行一些js,您可以使用:用途:

  • Future<dynamic> evaluateJavascript({@required String source}):在WebView中计算JavaScript代码并返回计算结果。
  • Future<void> injectJavascriptFileFromUrl({@required String urlFile}):从定义的URL将外部JavaScript文件插入WebView。
  • Future<void> injectJavascriptFileFromAsset({@required String assetFilePath}):将一个JavaScript文件从flutter assets目录插入到WebView中(更多关于如何从assets文件夹加载文件的信息,请参见此处)。

完整示例:

import 'dart:async';

import 'package:flutter/material.dart';

import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: InAppWebViewPage()
    );
  }
}

class InAppWebViewPage extends StatefulWidget {
  @override
  _InAppWebViewPageState createState() => new _InAppWebViewPageState();
}

class _InAppWebViewPageState extends State<InAppWebViewPage> {
  InAppWebViewController webView;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text("InAppWebView")
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                child: Container(
                  child: InAppWebView(
                    initialUrl: "https://www.example.org/",
                    initialHeaders: {},
                    initialOptions: InAppWebViewWidgetOptions(
                      inAppWebViewOptions: InAppWebViewOptions(
                        debuggingEnabled: true,
                      ),
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) async {
                      int result1 = await controller.evaluateJavascript(source: "10 + 20;");
                      print(result1); // 30

                      String result2 = await controller.evaluateJavascript(source: """
                        var firstname = "Foo";
                        var lastname = "Bar";
                        firstname + " " + lastname;
                      """);
                      print(result2); // Foo Bar

                      // inject javascript file from an url
                      await controller.injectJavascriptFileFromUrl(urlFile: "https://code.jquery.com/jquery-3.3.1.min.js");
                      // wait for jquery to be loaded
                      await Future.delayed(Duration(milliseconds: 1000));
                      String result3 = await controller.evaluateJavascript(source: "\$('body').html();");
                      print(result3); // prints the body html

                      // inject javascript file from assets folder
                      await controller.injectJavascriptFileFromAsset(assetFilePath: "assets/myJavascriptFile.js");
                    },
                  ),
                ),
              ),
            ]))
    );
  }
}

字符串

egmofgnx

egmofgnx3#

这就是Webview小部件的外观

WebView(
    initialUrl: 'http://<domain>',
    javascriptMode: JavascriptMode.unrestricted,
    onWebViewCreated: (WebViewController webViewController) {
      webViewController.evaluateJavascript(
          'alert('hello from flutter)');
    }

字符串
在代码中的任何地方使用webViewController

3phpmpom

3phpmpom4#

好吧,没有发生任何事情,因为flutter webview不支持JavaScript alert功能。尝试编写一个javascript函数,更改HTML元素的innerText的值,然后使用.evalJavascript调用该函数以查看结果。

o2rvlv0m

o2rvlv0m5#

我使用webview_flutteronPressed函数的最佳方法。使用“runJavascript”或"evaluateJavascript“或”runJavascript Returning Result“:

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter/services.dart';

dynamic ctrl; // Created here to keep working with Hot Reload

void main() {
  runApp(
    MaterialApp(
      home: WebViewExample(),
    ),
  );
}

class WebViewExample extends StatefulWidget {
  @override
  WebViewExampleState createState() => WebViewExampleState();
}

class WebViewExampleState extends State<WebViewExample> {
  @override
  void initState() {

    super.initState();

    // Enable virtual display.
    if (Platform.isAndroid) WebView.platform = AndroidWebView();

  }

  @override
  Widget build(BuildContext context) {

    void runJS(command) async {
      ctrl.runJavascript(command);

      // If you get any result
      // dynamic r = await ctrl.runJavascriptReturningResult(command);
      // print(r);
    }

    return Scaffold(
      appBar: AppBar(
          title: Container(
        child: ElevatedButton(
          onPressed: () => {
            runJS('alert("Hello: Button Clicked! "+new Date())')
          },
          child: const Text('Click on the button'),
        ),
      )),
      body: WebView(
        initialUrl:
            'https://www.google.com',

        debuggingEnabled: true,

        onWebViewCreated: (WebViewController webViewController) {
         
          ctrl = webViewController;
         
          ctrl.runJavascript('alert("Hello: created!")');
          // ctrl.evaluateJavascript('alert("Hello: created!")');
          // ctrl.runJavascriptReturningResult('alert("Hello: created!")');
        },

        onPageStarted: (String url) async {
          // ctrl.runJavascript('alert("Hello: started!")');
          // ctrl.evaluateJavascript('alert("Hello: started!")');
          // ctrl.runJavascriptReturningResult('alert("Hello: started!")');
        },

        onPageFinished: (String url) async {
          // ctrl.runJavascript('alert("Hello: finished!")');
          // ctrl.evaluateJavascript('alert("Hello: finished!")');
          // ctrl.runJavascriptReturningResult('alert("Hello: finished!")');
        },
      ),
    );
  }
}

字符串

6psbrbz9

6psbrbz96#

我已经调试了flutter_webview_plugin的iOS部分。

iOS部分

发现它与iOS原生部件iOS WKWebView not showing javascript alert() dialog有关。
实现代码的好例子是gist
我已经为此创建了一个fix

临时解决方案

您可以使用

flutter_webview_plugin:
    git:
      ref: "dev/fix_alert_not_work_in_webview"
      url: "https://github.com/jerryzhoujw/flutter_webview_plugin"
      source: git

字符串
这是在合并PR之前pubspec.yaml中的临时值。

gcxthw6b

gcxthw6b7#

我通过将我的自定义JavaScript函数注册到全局窗口对象来实现这一点。

window.onMessageSending = (running)=> {
      console.log("state is running")
    }

字符串
然后我以这种方式调用flutter_webview小部件:

_controller = WebViewController()
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..setNavigationDelegate(NavigationDelegate(
    onPageStarted: (String url) {},
    onPageFinished: (String url) {
    },
  ));

 _controller.runJavaScript("onMessageSending(true)");

相关问题