Blog

Signals Blog

Saving the Last-Drawn Chemical Structure: Using HTML5 Local Storage with ChemWriter

If you draw a structure in the ChemWriter editor above and reload the page, your structure will be re-loaded as well. This article explains why this capability might be useful and how to implement it.

The Problem

Drawing a chemical structure can take a lot of valuable time and effort. There are some situations in which a chemical structure editor that remembers the last structure drawn by a user would be helpful:

HTML5 Local Storage

All modern browsers support a helpful new feature called Local Storage. In contrast to cookies, which suffer from size restrictions and other undesirable performance characteristics, HTML5 Local Storage is ideal for client-side storage of larger bits of data such as chemical structure representations. This storage persists across browser sessions.

Source Code

The demo above takes advantage of HTML5 Local Storage and the onbeforeunload event:

var hasLocalStorage = function() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch (e) {
    return false;
  }
};

var readMolfile = function() {
  return hasLocalStorage() ? localStorage['stored-molfile'] : undefined;
};

var saveMolfile = function() {
  if (hasLocalStorage()) {
    localStorage['stored-molfile'] = persistentEditor.getMolfile();
  }
};

var persistentEditor = chemwriter.loadEditor('editor', {
  licensePath: '/chemwriter.lic',
  molfile: readMolfile()
});

window.onbeforeunload = function (event) {
  saveMolfile();
};
 

Conclusions

HTML5 Local Storage makes it simple and easy to save the last-drawn structure from a ChemWriter editor. The same technique described here can be used to persist additional ChemWriter state, such as drawing preferences and other settings.