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
"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.
You should calclulate size of your localStorage,
window.localStorage is full
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;
}
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.
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.
But same thing was working great in Chrome. Maybe Chrome is more Intelligent.
Related
Running in IE is a legacy app built with frames that makes alot of references cross-frame like parent.header.blah.blah and parent.sidebar.so.and.so. Worked fine in old IE compatibility mode. Works in chrome and edge (chromium).
But in regular IE without compatibility mode on, it's throwing a permission denied error on line 43. Thing is, it throws the error in the console NO MATTER WHAT IS ON LINE 43!!! I added superfluous lines of code to push other code down, took out code to move other code up. Doesn't matter, the console ALWAYS says it's on line 43.
I put breakpoints in and noticed the error doesn't actually add to the console until AFTER the javascript has finished running. The page is very large with ALOT of javascript, and it's dificult to comment a section out without breaking the page to experiment with what might be causing the permission denied.
Permission Denied is supposed to indicate a same-origin violation as I understand it, but all frames and files are coming through the same servlet on the same URL with only parameters changing. I printed out the document.domain of every frame, they all are identical.
So..I'm not even sure what to do at this point to narrow it down. How can I figure out what is really the offending piece of code...or even section?
UPDATE - So it seems that the error is actually coming from a function in another frame being called from this frame (nowhere near line 43 by the way). That function is managing the options in a select list. The actual error comes here:
for (var k=0; k < assetListz.options.length; k++) {
if (assetListz.options[k].value == currentAsset) { //permission denied!
inList = true;
assetListz.options[k].selected = true;
break;
}
}
assetListz didn't have a 'z' on it until I just did that to make sure I wasn't accidentally getting scope to some OTHER assetList. I can test the length of the assetList, but as soon as I check the value on that second line, kaboom. Ideas?
Update 2 -
I changed the code to get the assetlist in each reference. No storing it. Blows up in the same place.
for (var k=0; k < document.getElementById('assetList').options.length; k++) {
if (document.getElementById('assetList').options[k].value == currentAsset) {
inList = true;
document.getElementById('assetList').options[k].selected = true;
break;
}
}
Okay, I got this fixed. I'm not sure exactly WHY this fix works, though I can guess. It seems that by rewriting the method so that it avoids use of the options array on the select object, everything works fine. I reference it just once to get the length...which it allows. but if i try to get a specific option by assetList.options[i].anything, then I get permission denied.
I still think this is a bug in IE11's same-origin code, but lucky for me, it seems like MS didn't re-use code so the same bug didn't 'protect' all means of accessing the select options. Just via the array property. Or maybe something else is goin on. I just know this worked for me.
//By changing the value attribute, we change the current selection.
assetList.value = currentAsset.toUpperCase();
if(assetList.selectedIndex == -1) {
//this means the current asset wasn't in the list.
if(assetList.options.length >= 1000) {
//not allowed to add more than 1000. And if so, set the selectedIndex back
alert("The Active Asset List contains the maximum of 1000 entries. \n" +
"The current Asset ID '" + currentAsset + "' was not added to the Active Asset List.");
assetList.selectedIndex = currentSelectedIndex;
return;
} else {
var option = document.createElement("OPTION");
option.value = currentAsset;
option.text = currentAsset;
assetList.add(option, 0);
assetList.selectedIndex = 0;
}
}
I'm trying to set a HTML input to read-only using ExecuteScriptAsync. I can make it work, but it's not an ideal scenario, so I'm wondering if anyone knows why it doesn't work the way I would expect it to.
I'm using Cef3, version 63.
I tried to see if it's a timing issue and doesn't appear to be.
I tried invalidating the view of the browser but that doesn't seem to help.
The code I currently have, which works:
public void SetReadOnly()
{
var script = #"
(function(){
var labelTags = document.getElementsByTagName('label');
var searchingText = 'Notification Initiator';
var found;
for (var i=0; i<labelTags.length; i++)
{
if(labelTags[i].textContent == searchingText)
{
found = labelTags[i]
break;
}
}
if(found)
{
found.innerHTML='Notification Initiator (Automatic)';
var input;
input = found.nextElementSibling;
if(input)
{
input.setAttribute('readonly', 'readonly');
}
}})()
";
_viewer.Browser.ExecuteScriptAsync(script);
_viewer.Browser.ExecuteScriptAsync(script);
}
now, if I remove
found.innerHTML='Notification Initiator (Automatic)';
the input is no longer shown as read-only. The HTML source of the loaded webpage does show it as read-only, but it seems like the frame doesn't get re-rendered once that property is set.
Another issue is that I'm executing the script twice. If I run it only once I don't get the desired result. I'm thinking this could be a problem with V8 Context that is required for the script to run. Apparently running the script will create the context, so that could be the reason why running it twice works.
I have been trying to figure this out for hours, haven't found anything that would explain this weird behaviour. Does anyone have a clue?
Thanks!
I spent way too much time trying to understand the problem here. I am working with a HID Barcode Scanner, and am able to get the device information. But I am unable to get a hold of the HidDevice object even with the right device id. It always return null. Here is what I have:
var selector = Windows.Devices.HumanInterfaceDevice.HidDevice.getDeviceSelector(parseInt('0x1', 16), parseInt('0x6', 16));
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(selector, null).then(
function (deviceInfoCollection) {
if (deviceInfoCollection.length > 0) {
for (var i = 0; i < deviceInfoCollection.length; i++) {
var id = deviceInfoCollection.getAt(i).id;
return Windows.Devices.HumanInterfaceDevice.HidDevice.fromIdAsync(id, Windows.Storage.FileAccessMode.readWrite);
}
}
else {
throw "No Devices Discovered.";
}
})
.done(function (device) {
if (device != null)
successCallback(device.name);
});
I added these device capabilities in my manifest file:
<DeviceCapability Name="humaninterfacedevice">
<Device Id="any">
<Function Type="usage:0001 *"/>
</Device>
</DeviceCapability>
I'm going through the same issue now. The only thing I see in your code that strikes me as odd is the following manifest tag:
<Device Id="any">
Usually, the "any" value works. But I've had issues arise where the vendor and product id are required; I'm not quite sure why, but I think it's based off the type of device/usageid. I would try hardcoding the vendor and product id's to see if it makes a difference.
Another thought: I'm guessing by the usage tag that your scanner is configured as a keyboard. You can check to see if your scanner can be configured as a non-keyboard HID device, which helped me personally. I see other people on the internet having issues where an HidDevice is returned as null because another program is using that device; in your case, the OS might already be using the keyboard and locking it out somehow.
Best of luck!
I'm building a mobile web app that will rely on caching.
If my cache uses to much memory I'm seeing this message in mobile Safari...
"A problem occurred with this webpage so it was reloaded".
Without intervention the page will reload and do the same thing over again a few times until it gives up.
Are there events I can capture, heap information I can monitor or settings that I can change to build a caching system that is more resilient than forcing page reloads?
Chrome has window.performace.memory but I can't seem to find anything related to solving my issue in mobile Safari. Try/catch statements and onBeforeUnload events don't prevent the page loads or provide an opportunity to clear/reduce the cache.
Does this help ?
Error handling "Out of Memory Exception" in browser?
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;
}
I have configured PHP to send me mails whenever there is an error. I would like to do the same with Javascript.
Also given the fact that this will be client side it is open to abuse.
What are good ways to get notified by mail when JS breaks in a web application?
Update:
Just to give some perspective, i usually load several js files including libraries (most of the time jQuery).
You can listen to the global onError event.
Note that you need to make sure it doesn't loop infinitely when it raises an error.
<script type="text/javascript">
var handlingError = false;
window.onerror = function() {
if(handlingError) return;
handlingError = true;
// process error
handlingError = false;
};
</script>
The code below relies on the global onError event, it does not require any external library and will work in any browser.
You should load it before any other script and make sure you have a server-side jserrorlogger.php script that picks up the error.
The code includes a very simple self-limiting mechanism: it will stop sending errors to the server after the 10th error. This comes in handy if your code gets stuck in a loop generating zillions of errors.
To avoid abuse you should include a similar self-limiting mechanism in your PHP code, for example by:
saving and updating a session variable with the error count and stop sending emails after X errors per session (while still writing them all down in your logs)
saving and updating a global variable with the errors-per-minute and stop sending emails when the threshold is exceeded
allowing only requests coming from authenticated users (applies only if your
application requires authentication)
you name it :)
Note that to better trace javascript errors you should wrap your relevant code in try/catch blocks and possibly use the printstacktrace function found here:
https://github.com/eriwen/javascript-stacktrace
<script type="text/javascript">
var globalOnError = (function() {
var logErrorCount = 0;
return function(err, url, line) {
logErrorCount++;
if (logErrorCount < 10) {
var msg = "";
if (typeof(err) === "object") {
if (err.message) {
// Extract data from webkit ErrorEvent object
url = err.filename;
line = err.lineno;
err = err.message;
} else {
// Handle strange cases where err is an object but not an ErrorEvent
buf = "";
for (var name in err) {
if (err.hasOwnProperty(name)) {
buf += name + "=" + err[name] + "&";
}
}
err = "(url encoded object): " + buf;
}
}
msg = "Unhandled exception ["+err+"] at line ["+line+"] url ["+url+"]";
var sc = document.createElement('script'); sc.type = 'text/javascript';
sc.src = 'jserrorlogger.php?msg='+encodeURIComponent(msg.substring(0, Math.min(800, msg.length)));
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sc, s);
}
return false;
}
})();
window.onerror = globalOnError;
</script>
You would wrap your entire program in a try/catch and send caught exceptions over AJAX to the server where an email could be generated. Short of that (and I wouldn't do that) the answer is "not really."
JA Auide has the basic idea. You could also go somewhat in between, ie.:
Write an AJAX "errorNotify" function that sends error details to the server so that they can be emailed to you.
Wrap certain parts of your code (the chunks you expect might someday have issues) with a try/catch which invokes errorNotify in the catch block.
If you were truly concerned about having 0 errors whatsoever, you'd then be stuff with try/catching your whole app, but I think just try/catching the key blocks will give you 80% of the value for 20% of the effort.
Just a note from a person that logs JavaScript errors.
The info that comes from window.onerror is very generic. Makes debugging hard and you have no idea what caused it.
User's plugins can also cause the issue. A very common one in certain Firebug versions was toString().
You want to make sure that you do not flood your server with calls, limit the amount of errors that can be sent page per page load.
Make sure to log page url with the error call, grab any other information you can too to make your life easier to debug.