2

I am creating a chrome extension that activates via a shortcut. Basically, a div is created on the page you are on that has a few questions. The answers are each with a checkbox.

A user can then choose an answer or a few, and will need to go to another page/tab and he/she can choose more options or less.

The issue is that once you activate this extension in the other tab, all the checkboxes that a user clicked on from the other tab are not passed to the new tab (though they are saved on that tab). Thus, my goal is to figure out how to cache that info locally so a user can go to different tabs and continue using those checkboxes and they will be saved across tabs.

I have been reading about Chrome.Storage (https://developer.chrome.com/extensions/storage.html) but could not figure out how the syntax will be like.

Was wondering if someone can point me to a better example or get me started here.

Cheers and thanks a lot, -Y

Yura F Kleban
  • 71
  • 1
  • 6

1 Answers1

2

If you want to save data to the user's Google account for cross-computer goodness, use chrome.storage.sync.

But if you only need to save the data locally, use chrome.storage.local.

Save data:

var answersToSet = {};
answersToSet.answerA = 'foo';
answersToSet.answerB = 'bar';
chrome.storage.sync.set(answersToSet, function(){
    if (chrome.runtime.lastError) {
        alert('Error setting answers:\n\n'+chrome.runtime.lastError);
    } else {
        alert('Answers saved.');
    }
});

Retrieve data:

var answersToGet = [];
answersToGet.push('answerA');
answersToGet.push('answerB');
chrome.storage.sync.get(answersToGet, function(answers){
    console.log(answers.answerA);
    console.log(answers.answerB);
});

Alternatively, you could just use localStorage, though this is not asynchronous:

localStorage.answerA = 'foo';
localStorage.answerB = 'bar';
console.log(localStorage.answerA);
console.log(localStorage.answerB);
Chris McFarland
  • 6,059
  • 5
  • 43
  • 63
  • 1
    just wondering: how would it know once a checkbox is clicked on and save it ? (sorry if it's a noob question, just trying to understand it as I got it to work for a text area but not for checkboxes) – Yura F Kleban Jul 29 '13 at 21:18
  • I don't know about normal JavaScript, but if you're using jQuery you can listen for the `change` event. Example: http://stackoverflow.com/a/9180144/206410 Official documentation: http://api.jquery.com/change/ – Chris McFarland Jul 30 '13 at 04:31