I have created a bookmarklet that tries to read and write with localStorage
with the following data:
url:
data:text/html;base64,PGRvY3R5cGUgaHRtbD4KPGh0bWw+Cjxib2R5Pgo8c2NyaXB0Pgpsb2NhbFN0b3JhZ2Uuc2V0SXRlbSgnY29udGVudCcsICdoZWxsbyB3b3JsZCcpOwpkb2N1bWVudC53cml0ZShsb2NhbFN0b3JhZ2UuZ2V0SXRlbSgnY29udGVudCcpKTsKPC9zY3JpcHQ+CjwvYm9keT4KPC9odG1sPg==
This translates to following code in the browser:
<doctype html> <html> <body> <script> localStorage.setItem('content', 'hello world'); document.write(localStorage.getItem('content')); </script> </body> </html>
This code tries to write the string hello world
to the browser’s localStorage, read the string and finally write it to the page.
However, this results in the following error:
Uncaught SecurityError: Failed to read the ‘localStorage’ property from ‘Window’: Storage is disabled inside ‘data:’ URLs.
As this approach doesn’t work, it brings me to the question: How to save data to the browser with data:
URL? Is there some other API than localStorage
that I could use to save data in data:
URLs?
EDIT:
Cookies do not work. Trying to access cookies gives the following error:
Uncaught DOMException: Failed to read the ‘cookie’ property from ‘Document’: Cookies are disabled inside ‘data:’ URLs.
EDIT 2:
File system API does not work either. Fails with the error object:
Answer
@charlietfl Creating a simple “notepad” where I could persist textual content in the browser even when offline or when the browser is restarted.
Working off the notepad use case, the following is a simple solution which works offline, when the browser restarts, persists across multiple devices (if you have your history shared across your different browsers) and you could argue comes with the added bonus of versioning built in…
One ‘storage’ mechanism you have available is the actual url so using it seems like a possible choice. As long as your happy for the url to change in this situation then you could build on top of the following.
<!doctype html> <html> <body> <div id="editable" contenteditable="true"> My notepad! </div> <script> document.getElementById('editable').addEventListener('blur', function (event) { window.location = 'data:text/html;base64,' + btoa(document.documentElement.outerHTML); }); </script> </body> </html>
Hope this help!