I have some tricky AJAX code on a form, and sometimes it will fail (don't ask why, I can't get around it). When this happens, I need to trap the error, reset a hidden field indicator, and submit the form naturally so that the user does not have an unpleasant experience. I planned on using window.onerror to do this, but it is never firing! I am using IE8 and all I have to worry about is the IE browser. Is there some gotcha to getting this event to work? Here's my code...
window.onerror = function() {
alert("Error!");
document.getElementById("hidAjax").value = "0";
document.forms[0].submit();
}
"A common problem that bites many developers occurs when their onerror handler is not called because they have script debugging enabled for Internet Explorer. This will be the case by default if you have installed the Microsoft Script Debugger or Microsoft Visual Studio 6.0® (specifically Visual InterDev 6.0™)—onerror handling is how these products launch their debugger. You can disable script debugging for a given instance of Internet Explorer on the Advanced tab of the Internet Options dialog box (note that checking the Disable script debugging setting will apply only to that instance of Internet Explorer):"
http://msdn.microsoft.com/en-us/library/ms976144.aspx
try/catch also introduces an additional error object that only has the scope of the catch. In applications where performance matters, this is not a good idea.
Any reason not to just put a try/catch around the tricky code?
Related
I'm using window.onerror to catch and log client-side errors. I've read about the various caveats to this approach, but I haven't been able to track down any info on this particular case.
For some reason IE9 does not seem to catch stack overflow exceptions. The below example catches both errors when run in Chrome and Firefox as well as if I use devtools in IE9 and set browser mode to IE8 or IE7. However, when run in IE9 mode, it only catches the 'test' is undefined exception, but ignore the stack overflow exception.
I have put together a simple example, to demonstrate this:
window.onerror = errorHandler;
function errorHandler (msg) {
alert(msg);
}
setTimeout(function () {
test.test = "test";
}, 1000);
setTimeout(function stackoverflow() {
stackoverflow();
}, 2000);
Here is a working example as well: http://jsfiddle.net/Mzvbk/1/
Can anyone shed some light on why this is?
Update August 29, 2012
I posted this question on the Internet Explorer Developer Center as well, but so far it hasn't given me much.
At this point, the best guess (as suggested by #RyanKinal in his comment) is that since the call stack size is exceeded, there is no room to put the call to the error handler on the stack.
I still like to believe that error handling is handled separately from the normal stack, as it seem to be in other browser (even older versions of IE), but if that isn't the case, it would be nice to see a reference, bug-report or statement of some kind, indicating that this actually is the case with IE9.
Update September 5, 2012
As described by Ren and Vega in their comments, Firefox 15 sometimes (seemingly random) seem to swallow that exception as well.
Have you tried disabling script debugging on the browser?
A common problem that bites many developers occurs when their onerror
handler is not called because they have script debugging enabled for
Internet Explorer. This will be the case by default if you have
installed the Microsoft Script Debugger or Microsoft Visual Studio
6.0® (specifically Visual InterDev 6.0™)—onerror handling is how these products launch their debugger.
Source (includes details on how to disable it).
Additional information following up on the comments:
Then I wonder is it related to this:
Internet Explorer 9 is compiled with the new C++ compiler provided
with Visual Studio 2010. This compiler includes a feature known as
Enhanced GS aka Stack Buffer Overrun Detection, which helps prevent
stack buffer overruns by detecting stack corruption and avoiding
execution if such corruption is encountered.
(Source)
Sounds like it could be that it is stopping before the overflow as a protection mechanism?
Our product inserts a script into client's websites, kind of like a live chat box.
Often, clients' websites have buggy javascript that also stops our code (the browser stops execution when errors are encountered). Is there any way to make our code still execute even though there are errors in the console about things like undefined methods or variables?
Thanks for your help.
The short answer is that you really can't.
"Solution" #1: You could insist that YOUR 3rd party code run before anyone else's. In most cases, this isn't possible or even desirable.
"Solution" #2: You could insist that the 1st party engineers wrap all 3rd party code in try/catch blocks. But, this solution really doesn't buy you any guarantee, because very frequently 3rd party libraries attach additional <script> tags to the page - these would not fall under the "jurisdiction" of the try/catch scope enclosing the code which created this/these tag(s).
"Solution" #3: You could build YOUR app entirely within the scope of an <iframe>, thereby avoiding the issue entirely. Unfortunately, even if you're very smart, you'll quickly run into cross domain violations, 3rd party cookie restrictions, and the like. It's very probable that this will not work for you.
"Solution" #4: You could explain the issue to your client, and have them demand that the other 3rd party code run cleanly. I say this is a "solution" because, frankly, it's not a "solution" to your question if your question is how to avoid doing exactly this.
Unfortunately, option #4 is your best bet. It may help if you observe other 3rd party libraries "breaking" in the same fashion: you can tell your client "hey, it's not just me - X, Y, and Z are all also 'broken' because of <name of other 3rd party library>." It may cause them to put the heat on the offending code, which makes the web a happier place for all involved.
As others have said, continuing after an error might not be the best thing to do but you can try this:
function ignoreerror()
{
return true
}
window.onerror=ignoreerror();
More details here
The onerror event fires whenever an JavaScript error occurs (depending
on your browser configuration, you may see an error dialog pop up).
The onerror event is attached to the window object, a rather unusual
place to take refuge in, but for good reason. It is attached this way
so it can monitor all JavaScript errors on a page, even those in the
section of the page.
Opera has a page with more details
Browsers supporting window.onerror
Chrome 13+
Firefox 6.0+
Internet Explorer 5.5+
Opera 11.60+
Safari 5.1+
You can't from your code - they need to use try/catch for questionable pieces of script.
You could have them insert an iframe into their page instead of you trying to inject code using a script tag like so: http://jsfiddle.net/EzMGD/ Notice how the script throws an error yet we can still see the content in the iframe. The iframe should help from using each others variables if applicable.
<script>
MeaningOfLife();
</script>
<iframe src="http://bing.com"></iframe>
Or inject the code so it's the very first or very last script.
Well, to me that work fine:
element = document.querySelector('.that-pretty-element');
if (element != null) {
element.onclick = function () {
alert(" I'm working beibi ;) ");
}
}
querySelector() returns false, so, we can verify with if's
I ran into this problem today in IE6 (but is reproducible on all recent version of IE).
I noticed quite a few people run into this problem and I haven't seen a very practical way to fix this.
There seems to be some other solution floating about regarding the order of script tags and meta tags in the head of the HTML document. I haven't confirm this but here's a link anyway:
What causes the error "Can't execute code from a freed script"
I also know the solution to this problem so I'm posting it below
First of all you need to locate the source of the message.
IE is known for it's abysmal error reporting but luckily IE9 seems somewhat capable. If this bug occurs in IE6, IE7 or IE8 it will also occur in IE9, so use IE9 to debug (for your sanity)
Open the webdeveloper console in IE9 (press F12) and run through the steps to produce this error.
IE9 should now give you a file and line indication on the console, yay!
What typically goes wrong is a callback that is executed after some delay, either by setTimeout or because of an Ajax request. If the window, document or frame the callback is defined in got unloaded then you will get this message when it tries to execute your callback function.
Seemingly other browsers ignore this problem, which is fine I guess. To make IE do the same just wrap the callback in a try-catch block (I don't know what the callback would evaluate to, I don't think it evaluates to undefined). If you want have more precise error handling or if you actually want to take action when this occurs you can probably do so and please make a post here because I'm curious as to what kind of use case would actually require this.
If you have page that uses several Frames, this error might be caused by objects initialized in one frame being used in some other frame after the initial frame was removed from the page.
When that happens, then depending on situation, you might want to:
Review your code looking for potential memory leaks
If those object represent some data you do actually want passed between frames, then consider using their stringified form instead.
The solution - be sure to place all META statements BEFORE any script statements.
Since upgrading to Firefox 4.0, I've noticed that I'm occasionally getting an error in the console stating:
attempt to run compile-and-go script on a cleared scope
The only information I can find about this on the net currently is on the mozilla groups forum, where it is suggested that it's something to do with session restoring. In my case, though I haven't been able to reliably reproduce the error, it happens at any time, not just after a restore.
What's the deal? How do I stop the error?
For me (Firefox 11, Firebug 1.9.1) it happens sometimes after I refresh the page (either F5 or CTRL+F5) while debugger is paused on a breakpoint.
The solution seems to be to continue the execution of the script, and refresh the page only when Firebug is not paused.
In my case, it was document.write method causing the problem on Firefox 4, 5, 6 on Windows. Linux versions are unaffected. What I had to do is to overwrite document.write method.
I aware that document.write shouldn't be used these days, but deployJava.js, a standard Java Applet deployment script written by Sun/Oracle, is using it. Google is using it in Google AdSense ads. document.write is everywhere.
<script>
var documentWriteOutput = '';
var got = document.write;
document.write = function(arg) { documentWriteOutput += arg; }
</script>
<script src="badScriptThatIsUsingDocumentWrite.js"></script>
<script>
runBadScriptThatIsUsingDocumentWrite();
document.write = got;
// Do whatever you want with the documentWriteOutput
// e.g. $('#somewhere').html(documentWriteOutput);
</script>
I hope this helps. However, I saw lots of "solutions" on the Internet that didn't work for me. It may mean that "Attempt to run compile-and-go script on a cleared scope" is a Firefox JavaScript engine problem/bug.
I've noticed that this error can happen if you write to the document with document.write after the document has completed loading (e.g. in a function called from JQuery's $(document).ready() method). When this happens, it seems that Firefox discards the old document and writes a new one. I don't know if this is new behavior or not. It seems that when you try to operate on the old document, e.g. with JQuery selectors, you get this error. For me, fixing the script in question to not call document.write after the document had loaded fixed the error.
I have noticed that if I disable the cache, I no longer get this error in the console.
The error doesn't occur if Firebug (in my case 1.8) is disabled.
Check your code for duplicated meta cache-control and remove one of them:
<meta http-equiv="cache-control" content="no-cache" />
i had this problem too but I did a clean re-installation of FireFox.
after that the error was gone.
I got this error when I tried adding events on elements appended from a same domain iframe. Added clone() and errors stopped.
It has nothing to do with firebug. The reason it "goes away" when firebug is disabled is that you are no longer seeing the exception. The cause of this is having an handler attached to an event that is now null but not properly cleaned up. You need to make sure that handler is properly disposed of, otherwise the event still fires the reference to the handler.
It is: menu Firebug -> Console -> Show Chrome Errors
switch off, end of story ;)
When a javascript error occures in IE (or in other browsers) you get a popup saying that javascript error has occurred - usually this comes with a line number and some hint.
Sometimes it comes with line 0 and with no way of knowing what the problem is.
Javscript can come from HTML itself, from a js file or from JSP (and more).
Microsoft has a script debugger that helps a lot in finding where js errors are, however sometimes when a js error occurs the script debugger cannot find the code portion and thus its difficult of finding where is the root cause of the problem.
My question is whether anyone knows any way of making script debugger find the code any way (mostly happen with js code that is in JSP file), or at least include in the IE popup the method or js file where the error has occurred. (it only display the line number, and many times its line 0...).
Thanks,
Tal.
The error object which is created when an error is thrown by JavaScript is very unreliable when it comes to the source line, especially within IE. Browsers like Firefox and Safari are better at line numbers, but they are generally pointless due to minification of the files.
What is obviously of more use is getting the call stack, but due to the anonymous nature of JavaScript functions (well, that they can be anonymous) a call stack can often be hard to work out.
If you're doing a try/ catch you can do arguments.callee which will return you the method which called the current method which failed.
Here's a good example of doing a complete stack in JavaScript - http://eriwen.com/javascript/js-stack-trace/
Also developer tools included with Internet Explorer 8 is something good to trace and debug your javascript code
There is a version of Firebug called Firebug Lite that will work with Internet Explorer. It's performance is going to be based on how complex your pages are; however, for relatively lightweight pages, it should provide some insight.
I recommend this tool rather than simply using Firebug and Firefox because not all errors that occur in Internet Explorer will occur in Firefox, and so performing any debugging in that browser may not yield any results.
Firebug on Firefox is usually considered one of the best debugging tools.
On Firefox, go to
http://getfirebug.com
to get it.
This will print you a stack trace:
function Stack()
{
try
{
throw Error()
}
catch(ex)
{
return ex.stack
}
};
print( Stack() );
If all else fails (and when dealing with IE it sometimes does) you can always walk through your code with alerts. It's crude and tedious, but sometimes it's all you can do:
Simply:
var count = 0;
then sprinkle some:
alert(count++);
at strategic lines along your code and note where it stops alerting.
Lather rinse repeat until you have your line.
If using Firefox you can press Ctrl + Shift + J to bring up the JavaScript error console that is built into Firefox, which will tell you exactly what went wrong.