5

I quite like using bookmarks with small scripts in them.

For example, I have edited the note editing script from this post on Reddit to automatically save and load the last note via localstorage.

...

window.addEventListener("load", function () {
    div.innerHTML = localStorage.getItem("note");
}, false);
document.body.addEventListener("keyup", debounce(function () {
     localStorage.setItem("note", div.innerHTML);
}, 760));
...

It runs fine if I open my html document as an actual html document stored on my hard drive. But when I run it using the URL bar pasting in the (minified) version of my code with data: text/html, ..., I get a NS_ERROR_NOT_AVAILABLE: error. This makes sense, since localstorage is domain-bound.

Is there a way to make localstorage work with bookmarks?

The full note code is available here, note that this code will work if you save it locally on your hard-drive. So you can bookmark this and use it if you want to.

Azeirah
  • 6,176
  • 6
  • 25
  • 44

1 Answers1

4

As you describe in the question, localstorage belongs to a web origin. In your browser, bookmarked data: URIs have "null" origin. This means that the browser treats the data: page as being served from a unique origin each time it loads. Even if such an origin could have localStorage, there would be no way to return to the origin to access the data there.

A bookmarklet runs a script in the origin of the current page. This is a problem that has made certain things, like your task, very difficult. In another example, password managers that provide a bookmarklet need to be careful--they're running code in the current page's security sandbox. It's easy for a minor flaw in their code to expose sensitive keys to the currently open page.

If you're determined to have the bookmark point to a data: URI, the current answer is no.

Addendum: There are other ways to have an origin other than by getting a domain. Extensions in Google Chrome have their own origin, and they can run entirely from your local computer.

guest
  • 6,450
  • 30
  • 44
  • And you just answered a question of mine, whether I can use dropbox-js in a bookmark let without forcing the user to confirm every time. Dropbox-js uses localStorage as well... – awendt May 22 '14 at 20:19
  • I had always thought the bookmarklet executed in the context of the currently open page, and had access to any local storage values on that page. I have made bookmarklets that appear to work on that assumption. – Ruskin Sep 09 '14 at 14:16
  • "that the bookmarklet executed in the context of the currently open page" Right you are. I've updated the answer to use "bookmark" instead of "bookmarklet" in some places. – guest Sep 09 '14 at 19:41