I have a script that detects Javascript errors on my website and sends them to my backend for reporting:
<script>
window.onerror = function(msg, url, line, col, error){
msg = msg || '';
url = url || '';
line = parseInt(line || 0);
// Note that col & error are new to the HTML 5 spec and may not be supported in every browser.
col = parseInt(col || 0);
error = error || '';
try
{
// Ajax Request for IE 5.5+, Firefox, Opera, Chrome, Safari XHR object
var x = new (this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
x.open('POST', '/log.php', 1);
x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
x.send('msg='+encodeURIComponent(msg)+'&url='+encodeURIComponent(url)+'&line='+line+'&col='+col+'&error='+encodeURIComponent(error));
x.onreadystatechange = function()
{
if( (x.readyState > 3) && (x.status > 0 && x.status < 400))
window.console && console.log(x.responseText);
};
}
catch(e)
{
window.console && console.log(e);
}
return true;
};
</script>
I have a server-side php script that will listen for Ajax request and writes a log file
<?php
if( $handle = fopen('log.txt', 'a') ) {
$log = date('d/m/Y H:i:s').PHP_EOL;
if( isset($_REQUEST['msg']) )
$log .= 'msg:'.$_REQUEST['msg'].PHP_EOL;
if( isset($_REQUEST['url']) )
$log .= 'url:'.$_REQUEST['url'].PHP_EOL;
if( isset($_REQUEST['line']) )
$log .= 'line:'.$_REQUEST['line'].PHP_EOL;
if( isset($_REQUEST['col']) )
$log .= 'col:'.$_REQUEST['col'].PHP_EOL;
if( isset($_REQUEST['error']) )
$log .= 'error:'.$_REQUEST['error'].PHP_EOL;
$log .= '---------------------------------------------'.PHP_EOL;
fwrite($handle, $log);
fclose($handle);
echo 1;
} else {
echo 0;
}
if in a page rise a javascript exception, eg:
<script> call_undefined_function(); </script>
write in the log file...
25/10/2014 11:31:08
msg:ReferenceError: call_undefined_function is not defined
url:http://www.test.it/
line:46
col:1
error:ReferenceError: call_undefined_function is not defined
---------------------------------------------
Everything works quite well!
But, i find a lot of logs raised by plug-ins, toolbars, worms or browser extensions used by the users...
eg
24/10/2014 10:20:32
msg:Unsafe JavaScript attempt to access frame
url: http://ads.XXXXXX.net/?XXXXXX
line:0
col:0
error:Unsafe JavaScript attempt to access frame
---------------------------------------------
Obviously this script is not my site and doing some research I found to be a worm of internet explorer
my questions is: How can I limit the logs to my own script?
You could always check against the URL:
// If the script is not being loaded from my domain
if(url.indexOf('http://mydomain') == -1)
{
// Allow the error to propagate normally
return false;
}
This may not be effective however if some third party is injecting inline scripts as opposed to externally loaded ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With