Flutter webivew how to set local storage
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");
});
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, 2022Comments
-
Tran Triet over 1 year
My Flutter application flow works like this:
- User logins
- If login successfully, server returns a token
- Set token to local storage in webview
- 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:
- Create new
FlutterWebviewPlugin
instance - Set local storage on the newly-created instance by calling method
evalJavascript
-
call
launch
on the instance, setwithJavascript
,withLocalStorage
totrue
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 over 4 yearsCan you help me with this.