Because StorageEvent does not work here, I want to implement an event handler by localStorage
.
Assume we have a web page as follows. Any change to the input field will trigger an event, we save the new value to localStorage. JSBin
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="Ctrl">
<input type="text" ng-model="text"></input>
<div id="console"></div>
<script>
var app = angular.module('app', []);
app.controller('Ctrl', ["$scope", function ($scope) {
$scope.$watch('text', function (newValue, oldValue) {
var x = "nV: " + newValue;
localStorage.setItem("messages", localStorage.getItem("messages") + " " + x)
debug(localStorage.getItem("messages"))
}, false)
}])
function debug(msg) {
document.getElementById("console").innerHTML += msg + "<br/>";
}
</script>
</body>
</html>
And we have another web page that listens. It scans localStorage by setInterval
. It is actually a pipe: several messages can be stored in localStorage, and we should treat them all and then empty localStorage
. JSBin
<html>
<body>
<div id="console"></div>
<script>
var listen = setInterval(function () {
var m = localStorage.getItem("messages");
if ((m !== "") && (m !== undefined)) {
localStorage.setItem("messages", "")
treatMessages(m);
}
}, 100)
function treatMessages(messages) {
debug(messages)
}
function debug(msg) {
document.getElementById("console").innerHTML += msg + "<br/>";
}
</script>
</body>
</html>
But what is important, is that we should make sure that no message is missed by the receiver. Unfortunately, it is not the case for the moment, For example, I typed quickly 123456789
in the input field, then 12345
was missing on the side of the receiver. It is probably because the sender generated 12345
just after the receiver read the localStorage and before the receiver emptied the localStorage.
So does anyone know how to fix this? Should we have a semaphore for localStorage or is there any other workaround?
Edit 1: I tried to add a semaphore by lock
and waitfor
: the sender and the receiver, but it still can miss messages. For example, 123456
is missing in the example below. It is not surprising, I think it is because when lock
is free
, we entered simultaneously the callback of the 2 waitfor, then it messed up.
Edit 2: I have done another shot which is supposed to work better, but I don't know why the two pages cannot align their localStorage value: the sender and the receiver