Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Storage in chrome apps using Dart

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);
}
like image 351
Simon Bengtsson Avatar asked Jul 25 '13 23:07

Simon Bengtsson


1 Answers

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.

like image 200
Chris Buckett Avatar answered Oct 06 '22 18:10

Chris Buckett