When I try to use the Storage class in a chrome packaged app like this window.localStorage
it returns null
. The code below works fine when launching in Dartium or Chrome though. Why does localstorage not work in Package apps? And what would I write to get the following functionality?
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);
}
According to the chrome packaged app API documentation, you can't use window.localStorage
but you can use chrome.storage
to get an API with similar features (and more).
You also need to request the storage permission in your manifest:
...
"permissions": [
"storage"
],
Take a look at the chrome
pub package which should provide access to chrome.* APIs in Dart (when you import it in your pubspec. You're particularly interested in the chrome.storage
Dart library.
Example of use below (by using the Chrome Packaged App option in the Dart Editor New 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 havn't tested it in Dartium, but converting to JS and loading as a packaged app into Chrome v28 works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With