EvaluateJavascript 在 Webview flutter 中不起作用。为什么JS没有完成?

EvaluateJavascript does not work in Webview flutter. Why isn't the JS fulfilled?

我正在使用 evaluateJavascript 和 js 代码 document.getElementsByTagName ('main') [0] .style.display = 'none' 但它失败了 _webController.evaluateJavascript ("document.getElementsByTagName ('main') [0] .style.display = 'none'", );

为了在webview页面上执行自己的JS,我已经尝试了所有方法,无论如何都不执行JS。 可能是什么问题呢 ??为什么它不起作用?

代码:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
        home: AnimatedSplashScreen(
          splash: Image.asset(
            'assets/animation.gif',
          ),
          nextScreen: YellowBird(),
          // nextScreen: MainScreen(),
          splashTransition: SplashTransition.slideTransition,
        ),
      );
    }
}

class MainScreen extends StatelessWidget {
  late WebViewController _webController;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Column(
          children: [
            Expanded(
              child: WebView(
                
                javascriptMode: JavascriptMode.unrestricted,
                initialUrl: 'http://212.80.206.193/test.project-270.com/',
                debuggingEnabled: true,
                onWebViewCreated: (controller) {
                  _webController = controller;
                  _webController.clearCache();
                },
               
                onPageStarted: (url) {
                  _webController.evaluateJavascript("document.getElementsByTagName('main')[0].style.display ='none'",);
                },
                navigationDelegate: (NavigationRequest request) {
                  print(request.url);
                  if (request.url.contains("geo:")) {
                    launch(request.url);
                    return NavigationDecision.prevent;
                  } else {
                  return NavigationDecision.navigate;
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class YellowBird extends StatefulWidget {
  @override
  MainLocation createState() => MainLocation();
}

class MainLocation extends State<StatefulWidget> {
  Location location = new Location();
  late bool _isSeviceEnabled;
  late PermissionStatus _permissionGranted;
  late LocationData _locationData;
  bool _isListenLocation = false, _isGetLocation = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(onPressed: () async{
              _isSeviceEnabled = await location.serviceEnabled();
              if(!_isSeviceEnabled){
                _isSeviceEnabled = await location.requestService();
                if (_isSeviceEnabled) return;
              }

              _permissionGranted = await location.hasPermission();
              if(_permissionGranted == PermissionStatus.denied){
                _permissionGranted = await location.requestPermission();
                if (_permissionGranted != PermissionStatus.granted) return;
              }
              _locationData = await location.getLocation();
              setState(() {
                  _isGetLocation = true;
              });
            }, child: Text('Get Location')),
            _isGetLocation ? Text('Location: ${_locationData.latitude} ${_locationData.longitude}') : Container(),
            ElevatedButton(onPressed: () async{Navigator.of(context).push(MaterialPageRoute(builder: (context) => MainScreen()));}, child: Text('Proceed')),
          ],
        ),
      ),
    );  
  }
}

请帮我解决这个问题!!

您的代码有两处错误:

  1. _webController.evaluateJavascript应该在onPageFinished,而不是在onPageStarted,那个回调是在什么时候调用的页面开始加载,因此如果您在那一刻执行 Javascript,您会收到错误消息,因为页面尚未加载。

  2. 你在一个无状态的小部件中,你正在重新分配控制器变量,这是不好的。在将控制器分配给变量时,您应该有一个 StatefulWidget 并调用 setState

因此,要解决此问题,请移动 onPageFinished 上的回调并将您的小部件更改为 有状态小部件

WebView(
        initialUrl: 'exampleUrl',
        onWebViewCreated: (WebViewController webViewController) {
          setState(() {
            _controller = webViewController;
          });
        },
        onPageFinished: (String url) async {
          await _controller?.evaluateJavascript('your js code');
        },
);
_webViewController.evaluateJavascript('JS code');

此代码已弃用,请改用此代码:

_webViewController.runJavascriptReturningResult('JS code');