Skip to content

Instantly share code, notes, and snippets.

@alwinchan
Last active March 23, 2024 10:26
Show Gist options
  • Save alwinchan/d68c537447afd3c8de9a27b68b96bb47 to your computer and use it in GitHub Desktop.
Save alwinchan/d68c537447afd3c8de9a27b68b96bb47 to your computer and use it in GitHub Desktop.
Use html2canvas to capture a screenshot of the page upon any errors in the console via window.onerror event and send it to Slack as alert/notification. Image are stored with imgbb.com
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//html2canvas.hertzen.com/dist/html2canvas.min.js';
document.head.appendChild(script);
window.onerror = async function () {
const { 0: errorMessage, 1: fileName, 2: lineNumber, 3: columnNumber, 4: errorObj } = arguments;
if (typeof html2canvas === 'function') {
html2canvas(document.body, { scale: 1.0 }).then(async (canvas) => {
const base64image = canvas.toDataURL('image/png');
let imageData = base64image.split('base64,');
imageData = imageData[1];
const formData = new FormData();
formData.append('image', imageData);
await fetch('https://api.imgbb.com/1/upload?&key=<YOUR_API_KEY>', {
method: 'POST',
cache: 'no-cache',
body: formData,
}).then(async (response) => {
const data = await response.json();
const screenshot = data.data.image.url || '';
const message = {
attachments: [
{
image_url: screenshot,
mrkdwn: true,
fallback: `${errorMessage}`,
text: `${errorMessage}`,
author_name: fileName,
author_link: fileName,
footer: 'window.onerror Notification',
ts: new Date().getTime() / 1000,
fields: [
{
title: 'FileName',
value: fileName,
short: true,
},
{
title: 'Error Message',
value: errorMessage,
short: true,
},
{
title: 'Line Number',
value: lineNumber,
short: true,
},
{
title: 'Column Number',
value: columnNumber,
short: true,
},
],
color: '#ff0000',
},
],
};
await fetch('https://hooks.slack.com/services/<YOUR_API_KEY>', {
method: 'POST',
cache: 'no-cache',
body: JSON.stringify(message),
});
});
});
}
};
window.onerror = function () {
const { 0: errorMessage, 1: fileName, 2: lineNumber, 3: columnNumber, 4: errorObj } = arguments;
const message = {
attachments: [
{
mrkdwn: true,
fallback: `${errorMessage}`,
text: `${errorMessage}`,
author_name: fileName,
author_link: fileName,
footer: 'window.onerror Notification',
ts: new Date().getTime() / 1000,
fields: [
{
title: 'FileName',
value: fileName,
short: true,
},
{
title: 'Error Message',
value: errorMessage,
short: true,
},
{
title: 'Line Number',
value: lineNumber,
short: true,
},
{
title: 'Column Number',
value: columnNumber,
short: true,
},
{
title: 'Error Object',
value: JSON.stringify(errorObj),
},
],
color: '#ff0000',
},
],
};
fetch('https://hooks.slack.com/services/<YOUR-HOOKS-SECRET>', {
method: 'POST',
cache: 'no-cache',
body: JSON.stringify(message),
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment