Persistent molecule in JME

How to keep molecule in the JME editor after page is reloaded

Several users asked for a "persistent molecule" in the JME Molecular Editor. That means that when they visit another page and then come back, the JME should remember the molecule recently edited.
It is relatively easy to implement this feature. It requires just to add several lines of JavaScript code to the page with the JME applet, as shown below.

Add the following two JavaScript functions into the page HEAD section.

<script>

function saveCookie() {
  var jme = document.JME.jmeFile();
  document.cookie = "jme="+jme+";expires=Thu, 31 Dec 2020 00:00:00 GMT; path=/";
}

function readCookie() {
  var editor = document.JME;
  if (editor.smiles().length > 0) return; // editing already started
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf("jme=") == 0) {
      var jme = c.substring(4,c.length);
      //alert("jme="+jme);
      editor.readMolecule(jme);
      return;
    }
  }
}

</script>  

And additionally add the following event handlers into the page BODY tag.

<body onLoad='readCookie()' onUnload='saveCookie()'>

Whenever the HTML page with the editor is abandoned, the actual molecule is stored into a so called "cookie" (a small piece of persistent information) and when the page is revisited (even after several weeks), the molecule is automatically restored.