Panos Papadopoulos
Panos Papadopoulos

Reputation: 59

Trigger a JavaScript function on a WebView in Flutter

I have a webpage that I load on a WebViw in flutter and that webpage has a javascript function that I want to run with a parameter from flutter.

I wrote this uderneath, and it looks like it is running the alert function fine, but when I try to run the function that is defined on the webpage javascript it says it is undefined. Why could this be? Also, do you see any other mistakes on my code that I may be missing, despite it working?

class WebViewPageState extends State<WebViewPage> {
  final String url;
  final String title;

  WebViewPageState(this.url, this.title);

  final Completer<WebViewController> _controller = Completer<WebViewController>();
  late WebViewController _mycontroller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(this.title),
        ),
        body: Column(children: [
          Expanded(
              child: WebView(
                  initialUrl: this.url,
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webviewcontroller) {
                    _controller.complete(_mycontroller = webviewcontroller);
                  },
                  onPageFinished: (url){
                    print("Ok we loaded page");
                    setState(() {
                      _mycontroller.runJavascriptReturningResult('alert("Hello, World!")');
                    });
                  },
              ))
        ]));
  }
}

Upvotes: 1

Views: 3450

Answers (1)

Esteban Aquino
Esteban Aquino

Reputation: 1

runJavascriptReturningResult is trying to get a return value from your javascript and since it's an alert it can't find it. try using _mycontroller.runJavascript('alert("Hello, World!")');

Upvotes: 0

Related Questions