0

I'm fairly new to JavaScript and am creating an extension that saves user data to display on a specific page (Google Classroom, to be specific). I have tried using localStorage but this saves it to a specific page's local storage. I need a user to be able to save and access data from anywhere in Chrome, and I need it to be available in new sessions as well.

In summary, I need three functions. One to save user data to chrome.storage, one to grab a value from chrome.storage given a key, and one that lists all keys in chrome.storage.

manifest.json

{
  "manifest_version": 2,
  "name": "AssignMe for Classroom",
  "short_name": "AssignMe",
  "description": "Create your own assignments on Google Classroom.",
  "version": "1.0",

  "browser_action": {
   "default_icon": "src/icon128.png",
   "default_popup": "popup.html"
  },

  "icons": {
   "16": "src/icon16.png",
   "19": "src/icon19.png",
   "48": "src/icon48.png",
   "128": "src/icon128.png"
  },

  "content_scripts": [{
   "matches": ["https://classroom.google.com/*/not-turned-in/all"],
   "js": ["displayBackground.js"],
   "run_at": "document_end"
  }],

  "permissions": [
   "activeTab",
   "storage",
   "tabs",
   "<all_urls>"
  ]
}

popup.html

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <form name="newAssignment" onsubmit="return display()">
      <fieldset>
        <legend><strong>New Assignment</strong></legend>
        <strong>Title</strong>
        <input type="text" id="title" spellcheck="false" name="title">
        <br /><br />
        <strong>Date</strong>
        <input type="date" id="date" spellcheck="false" name="date">
        <br />
        <p id="demo">0</p>
        <button type="button" id="do-count">Create Assignment</button>
        <script src="content.js"></script>
      </fieldset>
    </form>
  </body>
</html>

content.js

var title = document.getElementById("title").value;
var date = document.getElementById("date").value;

// Function that saves user data to chrome.storage
// Function that grabs user data from chrome.storage by key
// Function that grabs all keys from chrome.storage

2 Answers2

2

Try this.

curAssignment = 0;
// save data (you can use .local or .sync)
function saveData() {
  chrome.storage.local.set({
    Data: {
      ["Assignment" + curAssignment]: {
        Title: title,
        Date: date
      }
    }
  }, function() {console.log("Data Saved");});
  curAssignment = curAssignment + 1;
}

["Assignment" + curAssignment] gives the new item a unique id based on how many items have been saved.


// load data
loadedAssignment = 0;
function loadData() {
  chrome.storage.local.get(["Data"], function(results) {
    while (loadedAssignment < results.Data.length) {
      loadedTitle = results.Data[loadedAssignment].Title;
      loadedDate = results.Date[loadedAssignment].Date;

      // your code that handles the loaded data

      loadedAssignment = loadedAssignment + 1;
    }
    curAssignment = results.Data.length;
  });
}

The loadData function loops through the "Data" item in chrome.storage.local and gets the Title and Date for the stored Item.

According to StackOverflow you can use

// get all items
function getAllItems() {
  chrome.storage.local.get(null, function(items) {
    var allKeys = Object.keys(items);
  });
}

To get all items that are in storage.

0

A more fancy way to do it (Set and Get), and it handles errors as well:

const getStorageData = key =>
  new Promise((resolve, reject) =>
    chrome.storage.sync.get(key, result =>
      chrome.runtime.lastError
        ? reject(Error(chrome.runtime.lastError.message))
        : resolve(result)
    )
  )

const { data } = await getStorageData('data')


const setStorageData = data =>
  new Promise((resolve, reject) =>
    chrome.storage.sync.set(data, () =>
      chrome.runtime.lastError
        ? reject(Error(chrome.runtime.lastError.message))
        : resolve()
    )
  )

await setStorageData({ data: [someData] })
bde-maze
  • 299
  • 3
  • 3