Javascript 在浏览器中处理“内存不足异常”时出错?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25903625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error handling "Out of Memory Exception" in browser?
提问by user547794
I am debugging a javascript/html5 web app that uses a lot of memory. Occasionally I get an error message in the console window saying
我正在调试一个使用大量内存的 javascript/html5 Web 应用程序。有时我会在控制台窗口中收到一条错误消息说
"uncaught exception: out of memory".
Is there a way for me to gracefully handle this error inside the app?
有没有办法让我在应用程序内优雅地处理这个错误?
Ultimately I need to re-write parts of this to prevent this from happening in the first place.
最终,我需要重写其中的一部分,以防止这种情况发生。
回答by Sergiu Gordienco
You should calclulate size of your localStorage, window.localStorage is full
您应该计算 localStorage 的大小,window.localStorage 已满
as a solution is to try to add something
作为解决方案是尝试添加一些东西
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
var storageIsFull = function () {
var size = localStorageSpace(); // old size
// try to add data
var er;
try {
window.localStorage.setItem("test-size", "1");
} catch(er) {}
// check if data added
var isFull = (size === localStorageSpace());
window.localStorage.removeItem("test-size");
return isFull;
}
回答by safian syed
I also got the same error message recently when working on a project having lots of JS and sending Json, but the solution which I found was to update input type="submit" attribute to input type="button". I know there are limitations of using input type="button"..> and the solution looks weird, but if your application has ajax with JS,Json data, you can give it a try. Thanks.
最近在处理具有大量 JS 并发送 Json 的项目时,我也收到了相同的错误消息,但我发现的解决方案是将 input type="submit" 属性更新为 input type="button"。我知道使用 input type="button"..> 有一些限制,而且解决方案看起来很奇怪,但是如果您的应用程序有带有 JS,Json 数据的 ajax,您可以尝试一下。谢谢。
回答by Shasha
Faced the same problem in Firefox then later I came to know I was trying to reload a HTML page even before setting up some data into local-storage inside if loop. So you need to take care of that one and also check somewhere ID is repeating or not.
在 Firefox 中遇到了同样的问题,后来我知道我试图重新加载 HTML 页面,甚至在将一些数据设置到 if 循环内的本地存储之前。所以你需要照顾那个,并检查某个地方的 ID 是否重复。
But same thing was working great in Chrome. Maybe Chrome is more Intelligent.
但同样的事情在 Chrome 中运行良好。也许 Chrome 更智能。

