简体   繁体   English

在Flutter Webview中运行一些Javascript文件,例如index.js

[英]Run some Javascript file like index.js in Flutter Webview

how I can run Javascript file in the flutter_webview_plugin. 如何在flutter_webview_plugin中运行Javascript文件。 I try it with this. 我尝试这个。

flutterWebViewPlugin.evalJavascript("require('./index.js');");

But nothing happens. 但是什么也没发生。

when I try to run flutter code it's shows nothing 当我尝试运行Flutter代码时,什么也没显示

my index.Js file contains a simple alert statement 我的index.Js文件包含一个简单的警报语句

alert('hello world');

First, You used "require" function. 首先,您使用了“要求”功能。 this function is not implemented in javascript itself. javascript本身未实现此功能。 it's a part of NodeJs . 它是NodeJ的一部分 so that function will not work. 因此该功能将无法使用。

In order to load a js file into flutter, you should consider it as a text file and load it properly. 为了将js文件加载到Flutter中,您应该将其视为文本文件并正确加载。 So, you need to add the file to assets folder, add into pubspec file, then load it. 因此,您需要将文件添加到资产文件夹,添加到pubspec文件,然后加载它。 read the full answer here 在这里阅读完整答案

Second, you used evalJavascript. 其次,您使用了evalJavascript。 this function can be used in many different situations. 此功能可以在许多不同的情况下使用。 but it will work only if you have a view panel. 但是只有在有查看面板的情况下,它才有效。

Check below example: 检查以下示例:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

main() async {
  String jsCode = await rootBundle.loadString('assets/javascript.js');

  runApp(new MaterialApp(
    home: LunchWebView(jsCode),
  ));
}

class LunchWebView extends StatelessWidget {
  final String text;
  LunchWebView(this.text);

  @override
  Widget build(BuildContext context) {
    final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
    flutterWebviewPlugin.launch('https://www.google.com');
    flutterWebviewPlugin.evalJavascript(text);
    return Container();
  }
}

NOTE: : I didn't handle reloading and other exceptions. 注意::我没有处理重新加载和其他异常。 you should check if there is any webview object open and then call Lunch method. 您应该检查是否打开了任何Webview对象,然后调用Lunch方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM