Created
February 29, 2020 11:46
-
-
Save xtj7/71fb36a7740fbfcb143a7b2fe2b6932e to your computer and use it in GitHub Desktop.
Demo to create a custom console that intercepts all console.X methods and errors that would end up in the console.
This file contains hidden or 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
<!doctype html> | |
<html> | |
<head> | |
<title>Console Demo</title> | |
<script> | |
// Method that adds log entries to your custom console | |
const addEntryToMyConsole = (type, content) => { | |
if (typeof content === 'undefined') { | |
content = '[missing content]'; | |
} else if (typeof content !== 'string') { | |
content = content.join(' '); | |
} | |
document.querySelector('.myConsole').innerHTML += `<strong>${type.toUpperCase()}</strong> - ${content}<br />`; | |
}; | |
// Override all console.X methods | |
const methods = ['log', 'debug', 'warn', 'error', 'info']; | |
methods.forEach(method => { | |
const originalMethod = console[method].bind(console) | |
console[method] = (...args) => { | |
addEntryToMyConsole(method, args); | |
originalMethod(...args) | |
} | |
}); | |
// Intercept other errors that end up in console implicitly | |
window.onerror = (e, url, line) => { | |
addEntryToMyConsole('error', `${e} (${url}:${line})`); | |
return e; | |
}; | |
// Broken function to test the error intercept functionality | |
const brokenFunction = () => { | |
console.log('log message'); | |
console.error('error message'); | |
console.debug('debug message'); | |
console.warn('warn message'); | |
console.info('info message'); | |
document.querySelector('.doesNotExist').innerHTML = 'foo'; | |
}; | |
</script> | |
<style type="text/css"> | |
body { | |
font-family: Helvetica; | |
} | |
.myConsole { | |
background: #ddd; | |
padding: 15px; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="myConsole"></div> | |
<button onclick="brokenFunction()">Test methods</button> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment