FlutterFirebase
FlutterFirebase

Reputation: 2343

How to manipulate HTML in Flutter webview?

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?

Upvotes: 3

Views: 3666

Answers (2)

Alex777
Alex777

Reputation: 1

try this code in the init state :

 @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (String url) async {
            // Wait for the page and execute JavaScript to manipulate the DOM
            await controller.runJavaScript(
              """
              (function() {
                // Ensure DOM is loaded
                document.addEventListener('DOMContentLoaded', function() {
                  // Find the element
                  var element = document.querySelector('.name');
                  if (element) {
                    // Replace the content
                    element.textContent = 'Updated text';
                  }
                });
              })();
              """
            );
          },
        ),
      )
      ..loadRequest(Uri.parse('https://www.website.com'));
  }

Upvotes: 0

Didier Prophete
Didier Prophete

Reputation: 2031

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";');
        }
   }
}

Upvotes: 6

Related Questions