Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - localStorage event listener does not fire in Chrome for local file

I need to be notified when localStorage is changed. This code works fine in Firefox 24, but doesn't work in Chrome 29 (or 30) or in IE 10. It also works on a live server, but not when I am testing using a local file (file:///).

Here is the code:

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#submit').click(function() {
                console.log('Clicked');
                if($('#username').val() != "")
                    localStorage.setItem('someItem', 'someValue');
            });
            $(window).bind('storage', function(e) {
                alert('change');
            });


        });
    </script>
</head>
<body>
<input type="text" id="username" name="username" value="" />
<a href="#" id="submit">Click me</a>
<p id="result"></p>
</body>
</html>

What is the problem with this in Chrome? I'm opening two tabs as required.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It will only fire the event in the "other" tabs/windows but not in the one changing the data (this is a bit unclear in your question so please correct me if I misunderstood).

When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a local storage area, if the methods did something, then in every Document object whose Window object's localStorage attribute's Storage object is associated with the same storage area, other than x, a storage event must be fired, as described below.

Source W3C

Update to complete the answer based on comments:

There will be restrictions in some browsers if the page is running from the file protocol (file:///) due to security reasons.

In Chrome you can override this by supplying the argument --allow-file-access-from-files:

chrome.exe --allow-file-access-from-files

I'm not sure if you can do something similar with other browsers. I would recommend testing with a local server (e.g. such as Mongoose) in order to not run into any surprises in a live scenario.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...