Why aren't my localStorage inputs persistent across pages on my personal computer?

守給你的承諾、 提交于 2021-02-10 10:56:08

问题


I'm trying out the HTML5 localStorage method for saving data. As I understand it, localStorage should be persistent between pages within the same domain. Please correct me if I'm wrong.

However, for some reason, it appears my localStorage values aren't persisting between pages in the same directory on my computer. Is it not considered the same domain in this case? I'm a little lost.

Here's the code for the two documents in question:

Document 1 (assuming jQuery has been included elsewhere in the document)

<script type="text/javascript">
$(document).ready(function() {
    $("form#settings").submit(function(event) {
        event.preventDefault();
        localStorage["display"] = $("input[name='display']:checked").val();;
        localStorage["message"] = $("#disp_message").val();
    });
});
</script>
<form id="settings">
    <h1>Display</h1>
    <input type="radio" name="display" id="message" value="message" />
    <label for="message">Replace with message:</label>&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="text" id="disp_message" size="60" value="Test content." /><br />
    <input type="radio" name="display" id="hide" value="hide" />
    <label for="hide">Hide entries</label>
    <br />
    <br />
    <input type="submit" />
</form>

Document 2

<html><body>
    <script>
    document.write(localStorage["message"]);
    document.write("<br />");
    document.write(localStorage["message"]);
    </script>
</body></html>

Just to clarify the code a touch, the idea is basically to later use this for a Google Chrome extension to hide certain content based on certain criteria. Document 1 would serve as the basis for the Options page, and Document 2 would be the basis for the actual extension script. But that's irrelevant for my question.

As a final clarification, I have tried all three ways of storing and accessing the localStorage variable, i.e.: localStorage["key"] = "value"; localStorage.key = "value"; localStorage.setItem("key", "value");

Any ideas at all?


回答1:


If you're testing in Chrome, everything under file://, even folders in the same directory are considered separate domains, so the same origin policy is kicking in, and the localStorage is unique to each.

I don't have a test environment setup at the moment, but launching with the command line flag:
--allow-file-access-from-files should be what you're after.



来源:https://stackoverflow.com/questions/4394468/why-arent-my-localstorage-inputs-persistent-across-pages-on-my-personal-compute

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