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:
- Structure-searchable database A user frequently searches for related structures - a family of steroids for example. Always starting the editor with the structure s/he last drew means that the next query structure can be entered by editing the last one, not drawing from scratch.
- Lab notebooks and registration systems A user repeatedly enters structures bearing the same core. Displaying the last structure drawn at startup lets the user edit, rather than draw from scratch. This promotes efficiency and consistency. If a completely new molecule needed to be drawn, the editor's 'clear' button would start the canvas from scratch.
- Back button protection The developer wants to ensure that in the event the browser window should be accidentally closed or navigated from, the user will be able to pick up where they left off with their structure drawing.
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.