KevInSol KevInSol - 4 months ago 17x
jQuery Question

restrict javascript window.onerror to errors only in my script

I have added a means to log events that happen at the browser to my server side logs:

This sends a message to my server (used just as I would use console.log to log key events during normal operation)

function remoteConsoleLog(msgToLog, msgDesc) {
type: 'POST',
url: '/php/log_javascript_events.php',
data: JSON.stringify({UA: navigator.userAgent, MSG: msgToLog, MSGDESC: msgDesc}),
contentType: 'application/json; charset=utf-8'

And this is a wrapper for the above to capture other errors (based on this):

window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
remoteConsoleLog(errorMsg, 'window onerror');

This works well and I get all the events I expect in my server log file. However, the problem is that I'm getting some errors I don't expect from the window.onerror handler such as generic "Script error" (I have seen this may be a CORS issue) and other very specific errors e.g.

Uncaught ReferenceError: DealPly is not defined

(which appears to relate to a browser plugin unrelated to my site).

My site uses some external JS files such as JQuery and the like. Is there any way to only log errors generated by the javascript file that contains my logging, i.e. exclude third party errors - or is that even a good thing to try to do?


Well, i believe the URL shows the name of the script, so you could check that against your own script files

var mySripts = ["a.js", "b.js"];
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
    //or however the url is formatted
    if (myScripts.indexOf(url) > -1) {
         remoteConsoleLog(errorMsg, 'window onerror');