Athium Athium - 27 days ago 5
jQuery Question

How would one set the initial value of an editable div?

So I've got a notepad extension for Google chrome that syncs and displays stored notes from a user. Currently my problem is as follows.

When the extension is run for the first time after download the word 'undefined' is displayed in the editable div (id = edit_notepad). I want it to just be blank instead of displaying anything. Obviously I know its undefined because the user hasnt been able to add any text yet.

Picture of what's displayed on initial run.

Here are my chrome.storage get and set functions (which do work)

document.body.onload = function() {
chrome.storage.sync.get("edit_notepad", function(items) {
if (!chrome.runtime.error) {
console.log(items);
document.getElementById("edit_notepad").innerHTML = items.edit_notepad;
}
});
}

document.getElementById("edit_notepad").onkeyup = function() {
var d = document.getElementById("edit_notepad").innerHTML;
chrome.storage.sync.set({ "edit_notepad" : d }, function() {
if (chrome.runtime.error) {
console.log("Runtime error.");
}
});
}


I presume I'm going to need some sort of if statement but after hours of playing around, I'm lost as to what exactly it'd contain. The issue I've kept running into is that whatever I set the initial value of 'edit_notepad' to, it always reverts back to it even when a user has written some notes! e.g. "This is a notes test" would revert back to "undefined" when the notepad is closed and reopened.

Thanks in advance!

Answer

Well, an easy way to do this would be to specify a default value in your chrome.storage.sync.get(). Doing so would apply the default value when the key does not exist in the storage. However, given that you are replacing any contents which might already exist, the better solution would be not to set the contents when you have no value, or an invalid value, stored. The only valid value will be a string. This will prevent you from overwriting any default value supplied by the webpage when you have no value stored. Thus, an if statement something like the following should work (alternately, you could test for !== 'undefined':

document.body.onload = function() {
  chrome.storage.sync.get("edit_notepad", function(items) {
    if (!chrome.runtime.error) {
      console.log(items);
      if(typeof items.edit_notepad === 'string') {
          document.getElementById("edit_notepad").innerHTML = items.edit_notepad;
      }
    }
  });
}

Note: Storing the contents of the editable <div> on every key will result in many users running into both the MAX_WRITE_OPERATIONS_PER_MINUTE and MAX_WRITE_OPERATIONS_PER_HOUR quotas. You will need to have some other criteria for writing to storage.sync. Perhaps you could temporarily store the value in storage.local and only to storage.sync every couple of minutes.