问题
I want to set some key&value pairs in local storage of my WebView in my flutter app. I am using the library called flutter_webview_plugin.
I am aware of this question.
Eventually i want to set a token, in order to reach a authentication-required URL directly, which is stored as 'jwt_token' in Chrome's local storage.
The library i use provides a withLocalStorage
property, and a evalJavascript
method:
flutterWebviewPlugin
.launch("SOME_URL",
withLocalStorage: true, withJavascript: true,)
.whenComplete(() {
flutterWebviewPlugin.evalJavascript("window.localStorage.setItem('key', 'key')");
flutterWebviewPlugin.evalJavascript("alert(window.localStorage.getItem('key'))");
flutterWebviewPlugin.evalJavascript("alert('test alert')");
After running the code above the "test alert" pops in my webview browser, which indicates that evalJavascript
method is working correctly, but the prior alert with the localStorage.getItem
method does not pop. I have tried with and without window object, all '' "" combinations and the result is the same. I cannot set information in my local storage with this JS method. Can you help me please ?
回答1:
You can use my plugin flutter_inappwebview, which is a Flutter plugin that allows you to add inline WebViews or open an in-app browser window and has a lot of events, methods, and options to control WebViews.
localStorage
feature is enabled by default!
Here is a quick example that sets and retrieve a localStorage
value when the page stops loading:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewController _webViewController;
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('InAppWebView Example'),
),
body: Container(
child: Column(children: <Widget>[
Expanded(
child: InAppWebView(
initialUrl: "https://github.com/flutter",
initialHeaders: {},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
),
),
onWebViewCreated: (InAppWebViewController controller) {
_webViewController = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {
},
onLoadStop: (InAppWebViewController controller, String url) async {
await controller.evaluateJavascript(source: "window.localStorage.setItem('key', 'localStorage value!')");
await controller.evaluateJavascript(source: "alert(window.localStorage.getItem('key'))");
},
))
])),
),
);
}
}
Screenshot:
来源:https://stackoverflow.com/questions/60335677/local-storage-property-does-not-work-in-flutter-webview-plug-in