Using localstorage in bookmarks

爷,独闯天下 提交于 2019-12-23 19:42:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23816081/using-localstorage-in-bookmarks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!