How to prevent stack overflows when intercepting local storage in a Chrome Extension

拥有回忆 提交于 2019-12-25 01:10:32

问题


I'm trying to add a "tab namespace" to all local storage keys so that I can achieve a uniqueness of local storage for sites between multiple tabs.

In a simple HTML5 page, let's say a web page has the following script:

Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value) {
    console.log("intercepted set local storage " + key + " = " + value);
    this._setItem(key, value);
}

Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype.getItem = function(key) { 
    console.log("intercepted get local storage " + key);
    return this._getItem(key);
}

This gives the user a chance to intercept all gets/sets to the local storage.

Now let's say you have an extension doing the same thing:

var actualCode = `Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value) {
    console.log("intercepted set local storage " + key + " = " + value);
    this._setItem(key, value);
}

Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype.getItem = function(key) { 
    console.log("intercepted get local storage " + key);
    return this._getItem(key);
}

console.log("local storage get/set injector completed");
`;

var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.remove();

You will get a stack overflow when you have this extension enabled while loading the page with the script above:

Uncaught RangeError: Maximum call stack size exceeded
at Storage.getItem [as _getItem] (<anonymous>:48:37)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)
at Storage.getItem [as _getItem] (<anonymous>:50:17)

Is there some way to detect that someone has already done an intercepted local storage and prevent the issue?

来源:https://stackoverflow.com/questions/51003814/how-to-prevent-stack-overflows-when-intercepting-local-storage-in-a-chrome-exten

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