在书签中使用localstorage [英] Using localstorage in bookmarks

查看:144
本文介绍了在书签中使用localstorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢使用带有小脚本的书签。

I quite like using bookmarks with small scripts in them.

例如,我编辑了这篇文章通过localstorage自动保存并加载最后一个音符。

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));
...

如果我将html文档作为实际的html文档打开,它运行正常存储在我的硬盘上。但是,当我使用URL条粘贴我的代码的(缩小版)版本时使用 data:text / html,... ,我得到 NS_ERROR_NOT_AVAILABLE:错误。这是有道理的,因为localstorage是域绑定的。

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.

有没有办法让localstorage能够使用书签?

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.

推荐答案

正如你在问题中描述的那样,localstorage属于一个web起源。在您的浏览器中,书签数据:URI具有null原点。这意味着浏览器将data:page视为每次加载时从唯一来源提供服务。即使这样的原点可能有localStorage,也无法返回原点来访问那里的数据。

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.

一个bookmarklet在原点运行一个脚本当前页面。这是一个让某些事情变得非常困难的问题。在另一个示例中,提供bookmarklet的密码管理器需要小心 - 它们在当前页面的安全沙箱中运行代码。他们的代码中的一个小缺陷很容易将敏感键暴露给当前打开的页面。

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.

如果您确定让书签指向数据:URI,目前的答案是否定的。

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

附录:除了获得域名之外,还有其他方法可以拥有其他来源。 Google Chrome中的扩展程序有自己的来源,它们可以完全从您的本地计算机运行。

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.

这篇关于在书签中使用localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆