fluttercommunity / flutter_webview_plugin

Community WebView Plugin - Allows Flutter to communicate with a native WebView.
https://pub.dev/packages/flutter_webview_plugin
Other
1.48k stars 929 forks source link

How to eval javascript code without loading a web page ? #840

Closed agtokty closed 3 years ago

agtokty commented 3 years ago

Hi, I need to evaulate simple javascript codes than get the return result from it. But it seems like that I couldn't do it without page loading.

Use flutterWebviewPlugin.evalJavaScript(String code). This function must be run after the page has finished loading (i.e. listen to onStateChanged for events where state is finishLoad).

But its ok, I can wait the page load finish using a dummy web site, but this should be in background. not fill my entire screen with that web site content. Is there any way to run javascript code in background ?

agtokty commented 3 years ago

OK, I found the solution when inspecting source code. I set the hidden to true

...
  final flutterWebViewPlugin = FlutterWebviewPlugin();

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

    flutterWebViewPlugin.close();
    flutterWebViewPlugin.launch('someurl', hidden: true);

...
# after flutterWebViewPlugin loads
String result = await flutterWebViewPlugin.evalJavascript('function fun(data){ return data;} fun(123) '); # returns 123
...
  }