Is there a way to try/catch an entire page dynamically? - javascript

I have a page on which mysterious JavaScript errors keep popping up. They appear to be coming from the application we use and do not own the source for. I'm working on a real solution to this issue, but we have a demo tomorrow and I was wondering if there is a way to just suppress JS errors page wide (like wrapping ALL the javascript components in a giant try catch).

You could add a handler to the window.onerror event. In this case, all the errors that occur inside the window will be redirected to the handler of this event. (I did test this in Firefox and it worked, but I was having trouble with it in Chrome - my Chrome installation is pretty messed up, so that could be the problem, but there are Chromium bugs filed that relate to this issue: bug #7771 and bug #8939)
window.onerror = function (msg, url, line) {
alert("Error on line " + line + " in " + url + ":\n" + msg);
// return true to prevent browser from displaying error
return true;
}

Related

How to catch all javascript warnings and errors to an output div?

i'm using try, catch, for debugging, but warnings is not create exceptions. How to get all javascript warnings and errors to output div?
UPDATED:
If browser supports Afaik logging, how to get that log to string or output div?
UPDATED:
I found the way how to do that:
i can reload console.log function to my custom function an call native console.log function.
First of all, get rid of the try catch. Don't use try catch when you are debugging.
Second, you don't want to out errors to a div, use firebug or inspector for that - console.log();
Third, if you really want to do it: you could use try catch and in the catch, use something like
$('body').append($('div').html('variable for error message goes here'));
if you are using jquery
OR
document.getElementByTagName("body").appendChild( document.createTextNode("variable for error message goes here") );
if you have plain javascript
EDIT: try looking up ie debug bar , ie webDeveloper
I understand myself why someone may want something to actually happen when an error occours in the document. The answers above just say that you would use developer tools, but I needed things to actually happen, and after some searching, here's what I found...
If you wish to catch all errors that come through, you can put the following code into your file, best at the top:
window.onerror = function(errorMsg, url, lineNumber){
// any action you want goes here
// errorMsg is the error message itself.
// url should be the file presenting the error, though i have
// found that it only presents to me the address of the site.
// lineNumber is the line number the error occoured on.
// here is an example of what you could do with it:
alert("Error in " + url + " at " + lineNumber + ":\n" + errorMsg);
}
I, myself, like to output the errors to a div that contains them all, though you can do literally anything to this information that you could do with any other string passed to a function.
Here is an example of what may happen if you throw an error with a button using the code above:
Error in your.site.here at 1:
Uncaught ReferenceError: foo is not defined
For IE javascript debugging you can follow this guide:
http://msdn.microsoft.com/en-au/library/ie/gg699336(v=vs.85).aspx
Keep in mind that the developer tools window must be open prior to loading the page for the warnings and errors to appear in the console.
For webkit, (chrome, safari) developer console - here is a guide:
https://developers.google.com/chrome-developer-tools/docs/console
...Firefox also has a console

Javascript function not defined in FireFox only - indeed_clk is not defined

I'm at a loss to figure out why a JavaScript function is not defined.
It works on all browsers, and all versions of FireFox on my dev machine. But the error occurs for some users running FireFox.
The external JavaScript include file is provided by Indeed.com.
The include file that contains the function definition (indeed_clk) is
<script type="text/javascript" src="http://www.indeed.com/ads/apiresults.js"></script>
This line appears immediately after the head elememt
Further down the page, the indeed_clk function is referenced using the following pattern
<a onmousedown = "indeed_clk(this,'7832');" href="landing page..." >Click to view</a>
The error message is "indeed_clk is not defined"
A sample page that demonstrates the rendered html and Javascript code is
http://www.contractsforgeeks.com/TechJobs/All_States/All_Cities.aspx
Any suggestions as to why the function would not be defined in FF, and not work only for certain machine configurations would be appreciated.
Try changing:
indeed_clk(this,'7832')
To:
indeed_clk(this,'7832');"
I found a solution/workaround to the problem, but still don't understand why the error occurs.
It seems that the presence of an error Handler causes an error (but only in FF for some users)
An error handler was hooked up
(document).ready ( errorHandling);
function errorHandling()
{
window.onerror = function (message, url, line) {
var msg = message + "\n" + " url:" + url + "\nline:" + line;
alert(msg);
}
Disabling the error handling enabled the missing indeed_clk function to be found.

Improving our javascript error reporting

So right now we have some generic code to report errors either from our code or third party code. Our project is a JQM/Phonegap project for iOS. What is happening is we pretty much always get the same useless error... TypeError: 'undefined' is not a function... with no line number or other helpful information. Is there a way I could change the code to maybe get WHAT is undefined or WHERE it is?
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
//Handle errors not in a jquery event handler
//DebugMessage(errorMSg + " "+ url + " " + lineNumber);
var ex = new Error(errorMsg, url, lineNumber);
HandleError(ex, "window.onerror");
//HandleError sends the error object to
//a webservice to log the error.
return true;
};
Any tips on debugging javascript errors would help as well.
In recent months, browsers have extended the signature of window.onerror to provide more information.
window.onerror = function(msg, file, line, col, error) {
// backwards compat
if (!error) {
error = new Error(msg);
}
// send error to your logger
}
This should give you a lot more information. But there are still things where you need better context. You should check out some third-party tools for this like TrackJS that automatically give you this, plus extra information on how the error occurred.
Disclaimer: I am one of the original authors of TrackJS, so I know a bunch about JavaScript errors :)
Have you heard of Ripple? It is a mobile emulator for Chrome designed for testing PhoneGap applications.
That might help you find your errors before you debug on the devices.

Jquery - how to load everything except the images?

I'm currently working on a WordPress addition which loads full post content (normally it shows exceprts) when asked to. I did my code like this:
$(".readMore").click(function() {
var url = $(this).attr("href");
$(this).parent("p").parent("div").children("div.text").slideUp("slow", function () {
$(this).load(url + " .text", function(){
$(this).slideDown("slow");
});
});
$(this).parent("p").fadeOut();
return false; });
And it works. But I don't want images to be loaded. I tried .text:not(img), but it didn't worked. How can I do this?
The trick, of course, is preventing the images from being downloaded unnecessarily by the user's browser; not displaying them is easy.
I only have two browsers were it's easy and convenient to tell what's downloading: Chrome and Firefox+Firebug. In my tests, Martin's solution using *:not(img) results in the images being downloaded (although not displayed) in both Chrome and Firefox+Firebug. (I emphasize "Firefox+Firebug" because Firebug can change the behavior of Firefox on occasion, and so it may well be changing its behavior here, although I don't think it is; more on that below.)
It took some tweaking, but this seems to do the trick (more on testing below):
$.ajax({
url: url,
success: function(data) {
var div = $("<div>").html(data);
if (stripImages) {
// Find the images, remove them, and explicitly
// clear the `src` property from each of them
div.find("img").remove().each(function() {
this.src = "";
});
}
$(targetSelector).append(div.children());
},
error: function(jxhr, status, err) {
display("ajax error, status = " + status + ", err = " + err);
}
});
Live example The "Include big image" checkbox includes a large file from NASA's Astronomy Picture of the Day (APOD).
The key there was setting the src of the img elements to "". On Chrome, just removing the elements was enough to prevent Chrome starting the download of the images, but on Firefox+Firebug it not only started downloading them, but continued even when the download took considerable time. Clearing the src causes Firefox to abort the download (I can see this in the Firebug Net console).
So what about IE? Or Firefox without Firebug? I only did unscientific testing of those, but it's promising: If I run my live example of Martin's solution on either IE or Firefox without Firebug in a VM, I see the VM's network interface working hard, suggesting that it's downloading that big APOD picture. In contrast, if I run my solution above in that same environment (with caches cleared, etc., etc.), I don't see the VM network interface doing that work, suggesting that the download is either not being started or is being aborted early on.
.text *:not(img) will select every descendant from .text that is not an image, so in theory it should work.

Firebug not showing Javascript errors for Rails applications

I have a Rails application, and when I have Javascript errors they are not showing in the Firebug console. I have 'Show javascript errors' and 'Show javascript warnings' selected.
When I insert javascript errors in a basic html file, the errors show as expected.
In the javascript of the Rails app, it only shows errors in rare cases.
For example i can insert nonsense like:
dfghaefb;
and no error is shown in Firebug. But if i insert a space in there Firebug does show the error:
dfgh aefb;
Any ideas? This is driving me nuts.
UPDATE:
Pumbaa80 was right, it's syntax vs runtime.
So I set up onerror:
onerror=errorHandler;
var error="";
function errorHandler(errMessage,url,line){
error="There is an error at this page.\n";
error+="Error: " + errMessage+ "\n";
error+="URL: " + url + "\n";
error+="Line: " + line + "\n\n";
error+="Click OK to continue viewing this page,\n";
alert(error);
return true;
}
And I have a method with an error:
function initForm() {
asdfs;
}
And it works when I call it outside of a method:
initForm();
but not in this case:
document.observe('dom:loaded', function() {
initForm();
});
Why is that?
dfghaefb;
produces a run-time error. Those errors may be suppressed by putting an onerror handler on the window or by trapping them in a try/catch in some way. In that case, Firebug won't show anything.
In contrast,
dfgh aefb;
is a syntax error, which is shown in the error console, regardless of try/catch and onerror.
Did you let the page load completely? I have a rails app running in front of me right now with firebug on and i entered dfghaefb; and yes it does throw an error!
ReferenceError: dfghaefb is not defined { message="dfghaefb is not defined", more...}
Running Firefox 3.6.3, Firebug 1.5.3 and MacOSX 10.5.6 :)
This may appear to be obvious, but be sure you wrap your inline JS using
<script type="text/javascript"> code </script>
Otherwise FireBug won't look at it at all.
I had the same, it wasn't showing anything and it was driving me crazy for ages, even if i had "Show javascript errors" in the console tab selected, it seems that it started working after I did "Enable all panels".
These kinds of problems cannot be answered without a test case.

Categories

Resources