Search code examples
javascriptcontenteditableautosave

Is there a way to autosave contenteditable content to a sqlite-database with addEventListener?


I'm building a neat texteditor in Electron and want to autosave everything that has been typed in <div id="editor" contenteditable="true">. How can this be done?

At the moment, the saving-stuff works with the click of a button, which is reasonably simple:

document.getElementById("saveChanges").onclick = function() { }

I tried to change the above line to this:

document.addEventListener('keydown', function(e) {
    for (var i = 0; i < editor.length; i++)

This doesn't work, but I've also no clue as to why not. It doesn't give any errors, but also doesn't do anything.

What am I doing wrong?

// This is the code that doesn't work

document.addEventListener('keydown', function(e) {
    for (var i = 0; i < editor.length; i++)
    {
        let content = document.getElementById("editor").innerHTML;

        console.log(content);

        const sqlite3 = require('sqlite3').verbose();

        let db = new sqlite3.Database('./appdata/resources/protodatabase.evv');

        let sql = 'UPDATE Subchapters SET subtext=? WHERE subid=1';

        db.run(sql, content, function (err) {
            console.log();
            if (err) {
            return console.error(err.message);
        }});

    db.close();
    };
    });

Solution

  • I actually figured it out myself:

    var editable = document.getElementById('editor');
    editable.addEventListener('keydown', function(e) {
        // execute code when spacebar or enter is pressed
        var toets = e.keyCode;
        if (toets == 32 || toets == 13)
    

    This works pretty well. But the code is very, very disk-intensive. Need to figure out how to put the database in memory, do all the changes there and save it periodically to the database on the disk...