3

I am load website with Flutter webview. But I want replace HTML element when it load. For example:

<span class="name">Replace text</span>

How to do?

FlutterFirebase
  • 2,163
  • 6
  • 28
  • 60

1 Answers1

6

So, it depends what library you are using to load your webview.

I have had some good success using webview_flutter_plus (https://pub.dev/packages/webview_flutter_plus).

With this, you just need to wait for your html to load and inject some javascript to modify whatever html you want.

Like this:

Widget build(BuildContext context) {
    return WebViewPlus(
        initialUrl: myUrl,
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewPlusController webViewController) {
            _webViewController = webViewController;
        },
        onPageFinished: (String url) {
            _webViewController.evaluateJavascript('document.querySelector(".name").innerHTML = "new text";');
        }
   }
}
Didier Prophete
  • 1,834
  • 1
  • 12
  • 11
  • dear @Didier Prophete I using this way but it seems evaluating jave script takes too long what I could done about that – kikicoder Apr 10 '21 at 22:48
  • Yeah. The truth is that binging up a webview inside a native app in flutter does take some time (like half a second). After that I think the js evaluation is fine but that initial time is a giant pain. Not sure there is much we can do there until flutter itself improves the webview perf (and there as well, I am not sure flutter can do anything. It might just be that a webview is an expensive class to instanciate...) – Didier Prophete Apr 11 '21 at 23:13
  • Dear is there a way I could manage to not showing the webview until it evaluate, I mean the evaluation happens on onpagefinished callback and that it self need some time to be fired – kikicoder Apr 12 '21 at 16:33
  • yes @kikicoder, that's exactly what I do in my own code. I basically hide the webview (I put it in a stack, below a splash page) until onPageFinished is invoked... – Didier Prophete Apr 14 '21 at 01:01