1

有没有办法拦截对 localStorage 的调用?或者可能存在一些处理程序?

如果我在 localStorage.getItem() 之类的代码脚本中有某个地方,我需要知道存储将获取一些项目,并且我想防止这种情况发生,并做一些我需要的事情。

我想为移动 Web 开发人员编写一个框架。我希望他们以通常的方式使用本地存储调用。我的框架将拦截此调用,并将数据不放入 W3C 存储,而是放入本机设备存储。那可能吗?谢谢。

4

3 回答 3

2

您可以使用原型。尝试这样的事情:

 Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function (key, value)
        {
            alert("works");
        }

    localStorage.setItem("A", "A");

如果您需要进一步说明,请随时询问。

于 2013-12-21T10:08:41.047 回答
0

You can replace the entire localStorage variable with your own although you may not be able to replicate every part of the API...

var localStorage = (function () {
    return {
        setItem: function (key, value) {
            alert(key);
        }
    };
}());

localStorage.setItem('a', 'b');

You will need to implement the same interface so your code invisibly slots in, but this example with setItem shows you how to do it all.

You can still call the old localStorage if you pop it into a variable to keep hold of it.

I haven't implemented whatever condition you're going to test to decide whether to store it elsewhere.

Or course, you can slightly change this to make it a library rather than an interceptor by giving it a different name... This allows you to implement a fixed API for people to follow.

var storageLibrary = (function () {
    return {
        setItem: function (key, value) {
            alert(key);
            if (true) {
                localStorage.setItem(key, value);
            } else {
                // Save it somewhere else   
            }
        }
    };
}());

storageLibrary.setItem('a', 'b');
于 2013-12-20T14:51:43.233 回答
0

您可以使用在 window- 上触发的 storage 事件跟踪对 localStorage 和 sessionStorage 的更改-

该事件在来自同一来源的所有打开的选项卡或页面上触发。

function storageHandler(e){
    var info={
        key:e.key, oldV:e.oldValue, newV:e.newValue, url:e.url || e.uri
    };
    //do something with info
}
window.addEventListener('storage', storageHandler, false);

特殊存储事件属性:

key- the named key that was added, removed, or modified
oldValue- the previous value(now overwritten), or null if a new item was added
newValue-the new value, or null if an item was removed
url or uri-     the page which called a method that triggered this change

您可能需要测试以下 IE #9(attachEvent 和全局事件处理)和 localStorage 支持。

于 2013-12-20T15:33:44.863 回答