javascript - 如何用数据: URL?保存数据到浏览器

标签 javascript html browser

我创建了一个小书签,它尝试使用具有以下 data: url 的 localStorage 进行读写:

data:text/html;base64,PGRvY3R5cGUgaHRtbD4KPGh0bWw+Cjxib2R5Pgo8c2NyaXB0Pgpsb2NhbFN0b3JhZ2Uuc2V0SXRlbSgnY29udGVudCcsICdoZWxsbyB3b3JsZCcpOwpkb2N1bWVudC53cml0ZShsb2NhbFN0b3JhZ2UuZ2V0SXRlbSgnY29udGVudCcpKTsKPC9zY3JpcHQ+CjwvYm9keT4KPC9odG1sPg==

这在浏览器中转换为以下代码:

<doctype html>
<html>
<body>
<script>
localStorage.setItem('content', 'hello world');
document.write(localStorage.getItem('content'));
</script>
</body>
</html>

这段代码尝试将字符串hello world写入浏览器的localStorage,读取字符串,最后写入页面。

但是,这会导致以下错误:

Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Storage is disabled inside 'data:' URLs.

由于这种方法行不通,我想到了一个问题:如何使用 data: URL 将数据保存到浏览器?除了 localStorage 之外,还有其他 API 可以用来将数据保存在 data: URL 中吗?

编辑:

Cookie 不起作用。尝试访问 cookie 会出现以下错误:

Uncaught DOMException: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs.

编辑 2:

File system API也不起作用。因错误对象而失败:

file error

最佳答案

@charlietfl Creating a simple "notepad" where I could persist textual content in the browser even when offline or when the browser is restarted.

处理记事本用例,以下是一个简单的解决方案,它可以离线工作,当浏览器重新启动时,在多个设备上持续存在(如果您的历史记录在不同的浏览器之间共享)并且您可以说它带来了额外的好处内置的版本控制......

您可用的一种“存储”机制是实际 url,因此使用它似乎是一个可能的选择。只要您对 url 在这种情况下发生变化感到满意,那么您就可以在以下内容之上进行构建。

<!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>

希望对您有所帮助!

关于javascript - 如何用数据: URL?保存数据到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37379254/

相关文章:

javascript - 下拉菜单仅在移动设备上闪烁并消失

html - 如何在 Opera 中将 TextBox 多行转换为大写?

javascript - 如何在多选主列表中设置路由模式?

javascript - 将 Angular 从 1.2 更新到 1.3 破坏了我的指令

javascript - 交替点击时的 setTimeout 和clearTimeout

javascript - 内存:Java vs C++ vs JS

javascript - webassembly 可以成为执行 drm 的一种方式吗?

javascript - 视口(viewport) JQuery - 如果元素在视口(viewport)中,则将文档准备好

javascript - HTML 表单在提交时触发 php 和 javascript

javascript - XML 解析节点值在 IE 中不起作用