Local storage in chrome apps using Dart

When I try to use the Storage class in a chrome-packaged application like window.localStorage , it returns null . The code below works fine when run in Dartium or Chrome. Why does localstorage not work in package applications? And what would I write to get the following functions?

 import 'dart:json'; void save(List data) { var jsonString = stringify(data); window.localStorage['highscore'] = jsonString; } List load() { var jsonString = window.localStorage['highscore']; return parse(jsonString); } 
+6
source share
1 answer

According to the chrome documentation of the application API , you cannot use window.localStorage , but you can use chrome.storage to get an API with similar functions (and more).

You also need to request permission to store in your manifest:

 ... "permissions": [ "storage" ], 

Check out the chrome pub package , which should provide access to chrome. * API in Dart (when you import it into your pubspec. You are especially interested in the chrome.storage Dart library .

Usage example below (using the Chrome Packaged App option in the new Dart Editor application) ...:

 import 'dart:html'; import 'package:js/js.dart' as js; import 'package:chrome/chrome.dart' as chrome; void main() { print("Starting..."); query("button").onClick.listen(onClick); } onClick(e) { document.body.append(new Element.html("<p>Clicked...</p>")); // save the highscore 123 chrome.storage.local.set({'highscore':'123'}).then((storageArea) { // load the highscore chrome.storage.local.get(['highscore']).then((Map<String,String> vals) { var highscore = vals['highscore']; document.body.append(new Element.html("<p>$highscore</p>")); }); }); } 

with HTML that looks like this:

 ...snip <button>Click Me</button> <script src="storage.dart" type="application/dart"></script> <script src="packages/browser/dart.js"></script> <script src="packages/browser/interop.js"></script> <script src="packages/js/dart_interop.js"></script> ... 

and a manifest that looks like this:

 { "name": "StorageExample", "version": "1", "manifest_version": 2, "icons": {"128": "dart_icon.png"}, "permissions" : [ "storage" ], "app": { "background": { "scripts": ["background.js"] } } } 

I have not tested it in Dartium, but converting to JS and downloading as a packaged application in Chrome v28 works fine.

+7
source

Source: https://habr.com/ru/post/950313/


All Articles