Search code examples
javascriptfileurlsavebookmarklet

how to save <html contenteditable> content as text file


i saw the content editable url trick from https://coderwall.com/p/lhsrcq

    data:text/html, <html contenteditable>

it lets you use the browser as a txt file but content is lost when you save the html page.

i've made a string that can be used as a bookmarklet that lets you save what you were typing by creating an iframe with src like

    data: Content-type: application/octet-stream

plus the contents of the contenteditable element in the browser url

you can see my code at http://pastebin.com/4z8tttuA then copy it into your browser url

my problems are

  1. all of the spaces get turned into ' ' and the carriage returns disappear. this is when my content editable element is a div. i tried it with a textarea it also doesn't work

  2. name the file something other than 'download' (which later becomes download(1), download(2)...)


Solution

  • I cleaned up and fixed what you had, here: http://pastebin.com/sJXVvRUB

    I think it does what you want. You still have to restyle the link to look like a button, if you want. I've also only tested in Chrome, so it may need other small modifications.

    As for your problems and how I fixed them:

    1. I'm not sure I completely understand the "spaces" part of the problem, unless you meant that all consecutive whitespace gets (incorrectly) saved as a single space. That's how HTML renders it, actually. I fixed that by replacing your note = note.replace("&nbsp;", ""); with note = note.replace('&nbsp;', ' ');. You were replacing non-breaking spaces with nothing. For line breaks, I just escaped the note before saving: escape(note). I also tweaked the calls to replace() to be a bit simpler and more targeted (at least on Chrome).
    2. For controlling the filename, I replaced the form+button with a link so I could use the "download" attribute, documented here: https://developer.mozilla.org/en-US/docs/HTML/Element/a#attr-download (also mostly only supported by Chrome at the moment).

    Hope this helps!