Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

android webview - Flutter webivew how to set local storage

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...