0

My Flutter application flow works like this:

User logins 1-If login successfully, server returns a token 2-Set token to local storage in webview 3-Open Webview fullscreen to a specific URL I am using this Webview plugin. The sample code shows that it supports local storage (it has a withLocalStorage option) but does not show how to use it.

I am aware of this question1 question2

f I correctly set the local storage, the Webview would show account page; otherwise a login page ( That's Not What Happened) Instade am getting this error

I/chromium(13409): [INFO:CONSOLE(1)] "Uncaught SyntaxError: Invalid or unexpected token", source: (1)

My code:

    void webwiew(token) {
    flutterWebViewPlugin
        .launch(
      "URLExpml",
      withLocalStorage: true,
      withJavascript: true,
    )
        .whenComplete(() {
  final res = flutterWebViewPlugin.evalJavascript("(function() { try { window.localStorage.setItem('token', $token); } catch (err) { return err; } })();");

  print("Eval result webview : ${res.toString()}");
}); 
  }

1 Answers1

0

From https://github.com/fluttercommunity/flutter_webview_plugin/pull/51#issuecomment-399468804
You can wait until the first page loading is completed and then accessing LocalStorage with evalJavascript
To achieve this you can use onStateChanged.listen and check state.type == WebViewState.finishLoad

StreamSubscription<WebViewStateChanged> _onStateChanged;
_onStateChanged = flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged state) {
  if (mounted) {
    if (state.type == WebViewState.finishLoad) {
      flutterWebviewPlugin.evalJavascript(
          "window.localStorage.setItem('LOCAL_STORAGE','SOMETOKEN');" +
              "document.getElementById('showLocalStorageBtn').click();"
      );
    }
  }
});
chunhunghan
  • 51,087
  • 5
  • 102
  • 120