Flutter webivew how to set local storage

6,179

In the step #2 the code evaluates in an empty about:blank page. Hence, saved property is assigned to about:blank address and not SOMEURL address. Try evaluating #2 only after the Future returned by .launch(...) completes.

e.g.

flutterWebviewPlugin.launch("https://SOMEURL",
  withLocalStorage: true,
  withJavascript: true
).whenComplete(() {
  final res = flutterWebviewPlugin.evalJavascript("(function() { try { window.localStorage.setItem('token', 'SOMETOKEN'); } catch (err) { return err; } })();");
  // Wrapped `setItem` into a func that would return some helpful info in case it throws.
  print("Eval result: $res");
});   
Share:
6,179
Tran Triet
Author by

Tran Triet

Currently a disciple of Computer and Science at Ho Chi Minh University of Technology. Have a passion with human language and some programming languages (but still prefer human languages :D) Been into Unity and Android development for more than 2 years and still learning. Hobbies: Language, language and more about language, Unity and Android. Playing/Listening to music

Updated on December 05, 2022

Comments

  • Tran Triet
    Tran Triet over 1 year

    My Flutter application flow works like this:

    1. User logins
    2. If login successfully, server returns a token
    3. Set token to local storage in webview
    4. 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 tried:

    1. Create new FlutterWebviewPlugin instance
    2. Set local storage on the newly-created instance by calling method evalJavascript
    3. call launch on the instance, set withJavascript, withLocalStorage to true and launched it to a URL;

      //1
      final flutterWebviewPlugin = new FlutterWebviewPlugin();
      //2
      flutterWebviewPlugin.evalJavascript("window.localStorage.setItem('token','SOMETOKEN')");
      //3
      flutterWebviewPlugin.launch(
          "https://SOMEURL",
          withLocalStorage: true,
          withJavascript: true);   
      

    If I correctly set the local storage, the Webview would show account page; otherwise a login page (which was what happened)

    I also note that the evalJavascript invocation doesn't seem to work. Also, changing order of step 2 and step 3 doesn't change anything.

    Note that I'm aware of this question. The answer provided doesn't show how to set the local storage either, and it doesn't show the Webview fullscreen so it won't solve my problem.

  • Sunisha Guptan
    Sunisha Guptan over 4 years
    Can you help me with this.