Javascript global error handling (not work on ie 9) - javascript

I would like to catch every error in javascript and log server side.
core.js (on first line)
// Global error javascript log
window.onerror = function(msg, url, line)
{
try
{
// Send error to server via AJAX Request
var x = new (this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
x.open('POST', '/jserrorlog.php', 1);
x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
x.send('Msg='+msg+'&Url='+url+'&Line='+line);
x.onreadystatechange = function(){
if(x.readyState > 3 && x.status == 200)
window.console && console.log(x.responseText);
};
}
catch(e)
{
window.console && console.log(e);
}
};
jserrorlog.php (Server Side)
<?php
// log error on server
$Msg = (isset($_POST['Msg'])) ? $_POST['Msg'] : null;
$Url = (isset($_POST['Url'])) ? $_POST['Url'] : null;
$Line = (isset($_POST['Line'])) ? $_POST['Line'] : null;
echo ( error_log('Javascript Error:'.$Msg.'; Url:'.$Url.'; Line:'.$Line) ) ? 1 : 0;

From: http://msdn.microsoft.com/en-us/library/ms976144.aspx
Handling Errors via the window.onerror DHTML Event
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)
Disable script debugging to invoke your own onerror handler
It should be clear from this discussion that you can catch both syntax
and run-time errors using a window.onerror handler. However, I only
told you this so that you would understand how it works, not so that
you would intentionally allow syntax errors in your production Web
pages. All syntax errors can, and should, be eliminated during the
development phase. Besides, onerror handling doesn't even work for
VBScript syntax errors (as noted below), and there is no way to catch
server-side syntax errors in any language.
Disable script debugging on IE
In Internet Explorer, choose Internet Options from the Tools menu.
In the Internet Options dialog box, click the Advanced tab.
On the Advanced tab, under Browsing, clear Disable Script Debugging.
Click OK.

Related

"You are not currently attached to a supported page or app." error while executing JQuery code in Internet Explorer 11 console

I am trying to execute following code in IE 11 Console:
var alinks = $('a');
for (var i = 0; i < alinks.length; i++) {
if ($(alinks[i]).text().trim() == "Contact Management") {
alinks[i].click();
break;
}
}
But I am getting following error:
You are not currently attached to a supported page or app.
I researched on Google and SO but didn't find any solutions or reasons for this error.
I also tried running this code in Chrome and Firefox and it's working fine there.
UPDATE
I also tried simple console.log('s') but it's showing undefined without display s. Also, no alert when alert('s') is executed.
Go to Tools> Internet Options > Security > Tap on Custom Level button > Under Scripting, Enable Active Scripting > Ok
Restart internet Explorer
Hoe it works :)

How do I determine what exception was thrown?

I work on a script that is added to hundreds of different websites in ways that I can't always predict, particularly when code is loaded in an iframe. In my code I've got a try/catch block setup to handle the exceptions. It's something like this:
var vals = {};
try {
vals.hostname = window.top.location.hostname; // will throw DOMException if loaded in iframe
< more code which might throw other exceptions >
} catch (e) {
if (e instanceof DOMException) {
vals.hostname = window.location.hostname;
} else {
<do something different>
}
}
e instanceof DOMException works awesome on Chrome, but it turns out that on Firefox and Safari, e instanceof DOMException is false on those browsers. I've done a lot of searching and for some reason can't seem to find anybody who explains how to check the exception type in a browser agnostic way.
Edit: Okay, Chrome is throwing a DOMException, but Firefox (and presumably Safari) are just throwing a generic "Error":
Error: Permission denied to access property "hostname"
I think that means I can't do anything with the specific error on other browsers.

chrome.extension undefined, Javascript doesn't work in Chrome

I have a Javascript code which checks which browser the user has, the code:
var xmlHR = new XMLHttpRequest();
if (navigator.userAgent.indexOf('Chrome') > -1) { // Chrome
alert(chrome); // alerts "[object Object]"
alert(chrome.extension); // alerts "undefined"
xmlHR.open("GET", chrome.extension.getURL(path), true);
} else {
// do stuff
}
chrome.extension is undefined.
I didn't include any Chrome related scripts to the .js , what's needed to be done to have 'extension' defined ?
The chrome.extension API (and most other chrome.* APIs relating to extensions) is only defined a chrome extensions, not for the open web. If you want to write a chrome extension, then there are a few good tutorials around https://developer.chrome.com/extensions/getstarted.
The method you mention (chrome.extension.getURL()) is used to reference an extension's resources - if you are trying to do that for a normal website, then it will depend on your configuration, but likely it would be easiest to query the server for the resource at the path.
Hope that helps. :)

JQuery security error in Opera and Internet Explorer

I am developing an app for social network which works in IFrame. The app works just fine in Google Chrome and Microsoft Firefox browsers, but in Opera 12.15 JQuery library v1.10.1 fails to load with security error Unhandled error: Security error: attempted to read protected variable on line 1513.
The screenshot is here:
It looks like the same bug exists in Internet Explorer 10.
How to deal with it?
UPDATE:
I have made dirty hack by commenting the lines 1513-1517 in the code of jquery:
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
/*if ( parent && parent.frameElement ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}*/
The functionality of my app seems to work now, maybe it is necessary to create issue in JQuery repo...
Bug report was created - http://bugs.jquery.com/ticket/13980.
Bug is now fixed.
Add this before you include JQuery:
var isIE11 = !!(navigator.userAgent.match(/Trident/) && !navigator.userAgent.match(/MSIE/));
if (isIE11) {
if (typeof window.attachEvent == "undefined" || !window.attachEvent) {
window.attachEvent = window.addEventListener;
}
}
Hope it helps, It worked for me.

XDomainRequest - not calling...not doing anything

I've a problem...I use jQuery ajax to call a web service that returns XML. The jQuery ajax stuff works awesome for every browser except for ie.
So for ie browsers, I am using XDomainRequest. Here is the code:
if ($.browser.msie && window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", theUserUrl);
xdr.timeout = 95000;
xdr.onerror = function () {
console.log('we have an error!');
}
xdr.onprogress = function () {
console.log('this sucks!');
};
xdr.ontimeout = function () {
console.log('it timed out!');
};
xdr.onopen = function () {
console.log('we open the xdomainrequest');
};
xdr.onload = function () {
// XDomainRequest doesn't provide responseXml, so if you need it:
var xml2 = new ActiveXObject("Microsoft.XMLDOM");
xml2.async = false;
xml2.loadXML(xdr.responseText);
console.log('do we get any response text at all?: ' + xdr.responseText);
ParseOwnershipObjects(xml2);
//AddServiceRequestsToMap(xml2, map, spinner);
};
xdr.send();
}
This exact code works fine elsewhere in the application with a
different url.
The url is fine, it returns exactly what it should in the browser
(and hence why the jquery ajax call works). Couple of things to
note:
I am integrating my own html/javascript with another guy's asp.net
project.
In the global.asax.cs file, I have:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,OPTIONS");
}
so I don't think that it's a header problem.
None of my handlers fire. Not the onprogress, ontimeout, onerror...nothing!
I don't have time to convert the web service to JSON.
Any thoughts?
Thanks!
Disclaimer - I actually haven't used 'XDomainRequest' - when using jQ I set data to jsonp for xdomain requests...
When debugging - are you using IE Dev tools (F12)? If not, the error is likely console.log
EDIT:
mea culpa, disregard the jsonp stuff - missed the part you mentioned XML
Update:
Out of curiosity I'm trying XDomainRequest. I copied your code and just added a value for theUserUrl.
as above/expected, unless I have Internet Explorer Developer tools running, console is undefined - and may give the impression that "none of your handlers are firing".
Once I have the IE dev tools enabled (docked or otherwise) xdr.onerror fires. we have an error is logged in the IE console. So while there is an error, the handler does fire.
A quick read on XDomainRequest requires the responding server to have the Access-Control-Allow-Origin header. I'm calling my own server and I know I don't have this header set, so without further debugging, it would be a good guess that's why xdr.onerror is being fired.
As it turns out, there were special characters in the url parameters that were not being correctly dealt with by the XDomainRequest object. Instead of the GET request, I am going to use the POST request on internet explorer-only queries.
EDIT - I ended up switching the web service over to return output in JSON format, thus negating the need for the XDomainRequest. Using JSON speeds things up a bit too, I recommend it!

Categories

Resources