how to get html content form flutterWebViewPlugin ( webview ) in flutter
Asked Answered
G

4

12

My question is pretty simple. how can I get the html data form the loaded page in webview. The data is in JSON format. for a reason I cannot use a post request for any get request here so I need to get the data with webview only. how to achive this ?

flutterWebViewPlugin.onUrlChanged.listen((String url) {
      if (url.contains('/recon?')) {
        print('printing url : $url');
        // need to get data ( html content ) on this url
        flutterWebViewPlugin.close();
        Navigator.of(context).pop(url);
      }
    });
});


WebviewScaffold(
                userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0",
                url: myurl,               
              )

Goldschmidt answered 5/4, 2020 at 14:51 Comment(1)
any update here. I am still searching for a solution for this.Goldschmidt
G
-1

Well the answer for me was to get the token from a url and not from html content as I am not able to extract it properly and get errors

[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: FormatException: Unexpected character (at character 1)
<html><head></head><body><pre style="word-wrap: break-word; white-space: pr...
^

so what worked for me for the start is the below solution:

WebView(
          userAgent: "random",
          initialUrl: mainUrl,
          onWebViewCreated: (controller) {
            _controller = controller;
            print(_controller.currentUrl());
          },
          javascriptMode: JavascriptMode.unrestricted,
          gestureNavigationEnabled: true,
          onPageFinished: (_) {
            _controller.currentUrl().then(
              (url) {
                if (url.contains("recon?")) {
                  var token = url.split('recon?')[1];
                  _prefs.setString('token', token);
                }
                if (url.contains("dashboard")) {
                  _controller.clearCache();
                  _controller.loadUrl(mainUrl);
                }
              },
            );
          },
        ),

here we are taking the url, spliting it based on keyword and then storing the other half which is the token and continuing. I was able to do this in both ways that is with flutter_webview_plugin as well as flutter_inappwebview its the same procedure but URL thing only worked for me. extracting context didn't so they are not marked as an answer but an up vote for helping me out understanding the possibility.

Goldschmidt answered 13/9, 2020 at 6:35 Comment(3)
here what is _controller? Please suggest Thanks.Besprinkle
I got it, what was _controller mean. WebViewController? _controller;Besprinkle
WebView( initialUrl: "${widget.networkURL}", javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (controller) { _controller = controller; // print(_controller!.currentUrl()); }, onPageFinished: (_) { _controller!.currentUrl().then((url) { if (url.toString().contains('transactionstatus')) { String encUtIdData = url.toString().split('transactionstatus/')[1]; Navigator.push( context, MaterialPageRoute( builder: (context) => UsersTransactionDetailScreen( encUtId: encUtIdData, ), ), ); } }); }, )Besprinkle
E
22

You can do this with official webview library:

WebView(
  initialUrl: model.luxtrustUrl,
  onWebViewCreated: (controller) {
    _controller = controller;
  },
  javascriptMode: JavascriptMode.unrestricted,
  gestureNavigationEnabled: true,
  onPageFinished: (_) {
    readJS();
    model.hideProgress();
  },
)

void readJS() async{
    String html = await _controller.evaluateJavascript("window.document.getElementsByTagName('html')[0].outerHTML;");    
    print(html);
}
Eurypterid answered 4/8, 2020 at 10:21 Comment(6)
This is new to me so will try this solution too and comment on the same :)Goldschmidt
how to get the data from below out put ? <html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{"did":null,"token_type":"Bearer","access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiGoldschmidt
how to get current page url?Besprinkle
I tried this on a page that contains a video tag, and it gives me the video tag with empty 'src' property, any help?Odum
It must be approved answerJard
yes, it is the right answer. It works on meSteger
C
13

You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.

To get HTML data, you can simply use var html = await controller.evaluateJavascript(source: "window.document.getElementsByTagName('html')[0].outerHTML;"); inside the onLoadStop event.

Here is an example using your userAgent:

import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

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

class _MyAppState extends State<MyApp> {
  InAppWebViewController webView;
  String myurl = "https://github.com/flutter";

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                  child: InAppWebView(
                    initialUrl: myurl,
                    initialHeaders: {},
                    initialOptions: InAppWebViewGroupOptions(
                      crossPlatform: InAppWebViewOptions(
                        debuggingEnabled: true,
                        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0"
                      ),
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      webView = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) async {
                      if (url.contains('/recon?')) {
                        // if JavaScript is enabled, you can use
                        var html = await controller.evaluateJavascript(
                            source: "window.document.getElementsByTagName('html')[0].outerHTML;");

                        log(html);
                      }
                    },
                  ))
            ])),
      ),
    );
  }
}

Just set the myurl variable to your url.

Through window.document.getElementsByTagName('html')[0].outerHTML; you will get all the HTML string. Instead, if you need only the body text, you can change it with window.document.body.innerText;.

Charin answered 3/6, 2020 at 8:41 Comment(4)
I will try this now as was tired search a solution. will update the results once done with the other task. thank you.Goldschmidt
I Love your plugin.Bagdad
#69238680Odum
I only add userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:61.0) Gecko/20100101 Firefox/61.0', and that's alone fixed the issue!Terzas
T
0

The lastest version is WebViewWidget. The command runJavaScriptReturningResult is equivalent to evaluateJavascript.

  late final WebViewController controller;

  WebViewWidget(
    controller: controller,
    gestureRecognizers: gestureRecognizers,
  ),

  void checkPenguinPicture() async {
    String textPenguin = '<use xlink:href="#penguin"></use>';
    var textHTML = await controller.runJavaScriptReturningResult("window.document.getElementsByTagName('html')[0].outerHTML;").toString();
    bool isPenguinError = textHTML.contains(textPenguin);
    if (isPenguinError) {

    }
  }
Thenar answered 20/8 at 11:37 Comment(0)
G
-1

Well the answer for me was to get the token from a url and not from html content as I am not able to extract it properly and get errors

[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: FormatException: Unexpected character (at character 1)
<html><head></head><body><pre style="word-wrap: break-word; white-space: pr...
^

so what worked for me for the start is the below solution:

WebView(
          userAgent: "random",
          initialUrl: mainUrl,
          onWebViewCreated: (controller) {
            _controller = controller;
            print(_controller.currentUrl());
          },
          javascriptMode: JavascriptMode.unrestricted,
          gestureNavigationEnabled: true,
          onPageFinished: (_) {
            _controller.currentUrl().then(
              (url) {
                if (url.contains("recon?")) {
                  var token = url.split('recon?')[1];
                  _prefs.setString('token', token);
                }
                if (url.contains("dashboard")) {
                  _controller.clearCache();
                  _controller.loadUrl(mainUrl);
                }
              },
            );
          },
        ),

here we are taking the url, spliting it based on keyword and then storing the other half which is the token and continuing. I was able to do this in both ways that is with flutter_webview_plugin as well as flutter_inappwebview its the same procedure but URL thing only worked for me. extracting context didn't so they are not marked as an answer but an up vote for helping me out understanding the possibility.

Goldschmidt answered 13/9, 2020 at 6:35 Comment(3)
here what is _controller? Please suggest Thanks.Besprinkle
I got it, what was _controller mean. WebViewController? _controller;Besprinkle
WebView( initialUrl: "${widget.networkURL}", javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (controller) { _controller = controller; // print(_controller!.currentUrl()); }, onPageFinished: (_) { _controller!.currentUrl().then((url) { if (url.toString().contains('transactionstatus')) { String encUtIdData = url.toString().split('transactionstatus/')[1]; Navigator.push( context, MaterialPageRoute( builder: (context) => UsersTransactionDetailScreen( encUtId: encUtIdData, ), ), ); } }); }, )Besprinkle

© 2022 - 2024 — McMap. All rights reserved.