Created
May 3, 2020 11:03
-
-
Save ToX82/20134e5006823360f87ee2b54b95b681 to your computer and use it in GitHub Desktop.
A simple script that captures the browser's JavaScript errors and send them to a server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Pt. 1) This is the server side part. We read the error (see pt. 2) and write it down using error_log | |
if (!empty($_POST)) { | |
$errorData = $_POST; | |
$error = " Error: " . $errorData['url']; | |
if ($errorData['error'] !== '') { | |
$error .= "<br><br>" . $errorData['error']; | |
} | |
if ($errorData['msg'] !== '') { | |
$error .= "<br><br>" . $errorData['msg']; | |
} | |
$error .= "<br><br>Browser info: " . $_SERVER['HTTP_USER_AGENT']; | |
error_log($error); | |
echo "Error detected!<br>"; | |
echo $error; | |
} | |
?> | |
<?php | |
// Pt. 2) The following is the client side part. | |
// It is triggered by the window.onerror function, and makes an ajax request to the server side part. | |
?> | |
<html> | |
<head> | |
<title>Javascript Error Logger</title> | |
</head> | |
<body> | |
Hi! I am a simple button that creates Javascript errors!! | |
<button onclick="undefinedFunction('Something broke!');">Click me!</button> | |
<script> | |
// Tracking the error and sending it as an AJAX request to a php logger | |
window.onerror = function(msg, url, line, col, error) { | |
var data = new FormData(); | |
data.append('msg', msg); | |
data.append('url', url + ' (at line ' + line + ', column ' + col + ')'); | |
data.append('error', error.stack); | |
let xhr = new XMLHttpRequest(); | |
xhr.open('POST', window.location.href); | |
xhr.send(data); | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment