admin管理员组

文章数量:1317915

I am using evaluateJavascript with js code document.getElementsByTagName ('main') [0] .style.display = 'none' but it fails _webController.evaluateJavascript ("document.getElementsByTagName ('main') [0] .style.display = 'none'", );

I have already tried everything in order to perform my own JS on the webview page, JS is not performed in any way. What could be the problem ?? Why is it not working?

Code:

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/',
                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')),
          ],
        ),
      ),
    );  
  }
}

Please help me solve this problem!!

I am using evaluateJavascript with js code document.getElementsByTagName ('main') [0] .style.display = 'none' but it fails _webController.evaluateJavascript ("document.getElementsByTagName ('main') [0] .style.display = 'none'", );

I have already tried everything in order to perform my own JS on the webview page, JS is not performed in any way. What could be the problem ?? Why is it not working?

Code:

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./',
                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')),
          ],
        ),
      ),
    );  
  }
}

Please help me solve this problem!!

Share Improve this question asked Oct 13, 2021 at 13:37 Artem NikolaevichArtem Nikolaevich 251 gold badge1 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5
_webViewController.evaluateJavascript('JS code');

This code is deprecated, Use this instead:

_webViewController.runJavascriptReturningResult('JS code');

There are 2 things wrong with your code:

  1. The _webController.evaluateJavascript should be in the onPageFinished, not on the onPageStarted, that callback is invoked when the page starts loading, so if you execute Javascript in that moment you get an error since the page hasn't loaded yet.

  2. You are in a statless widget and you are reassigning the controller variable, this is not good. You should have a StatefulWidget and call setState when assigning the controller to the variable.

So to solve the issue move the callback on onPageFinished and change your widget to a Stateful Widget

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

本文标签: javascriptEvaluateJavascript does not work in Webview flutter Why isn39t the JS fulfilledStack Overflow