Skip to content

Instantly share code, notes, and snippets.

@JoeyBurzynski
Created September 15, 2023 05:05
Show Gist options
  • Save JoeyBurzynski/56ac9a8ab18cfedae56fe3064fffea9d to your computer and use it in GitHub Desktop.
Save JoeyBurzynski/56ac9a8ab18cfedae56fe3064fffea9d to your computer and use it in GitHub Desktop.
JavaScript SEO: Debugging Googlebot Crawling & Rendering Issues | Global JavaScript Error Handler [onerror]
// Here's an example that shows how to log JavaScript errors that are logged in the global onerror handler.
// Note that some types of JavaScript errors, such as a parse error, cannot be logged with this method.
window.addEventListener('error', function(e) {
var errorText = [
e.message,
'URL: ' + e.filename,
'Line: ' + e.lineno + ', Column: ' + e.colno,
'Stack: ' + (e.error && e.error.stack || '(no stack trace)')
].join('\n');
// Example: log errors as visual output into the host page.
// Note: you probably don't want to show such errors to users, or
// have the errors get indexed by Googlebot; however, it may
// be a useful feature while actively debugging the page.
var DOM_ID = 'rendering-debug-pre';
if (!document.getElementById(DOM_ID)) {
var log = document.createElement('pre');
log.id = DOM_ID;
log.style.whiteSpace = 'pre-wrap';
log.textContent = errorText;
if (!document.body) document.body = document.createElement('body');
document.body.insertBefore(log, document.body.firstChild);
} else {
document.getElementById(DOM_ID).textContent += '\n\n' + errorText;
}
// Example: log the error to remote service.
// Note: you can log errors to a remote service, to understand
// and monitor the types of errors encountered by regular users,
// Googlebot, and other crawlers.
var client = new XMLHttpRequest();
client.open('POST', 'https://example.com/logError');
client.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
client.send(errorText);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment