Last active
November 20, 2024 22:41
-
-
Save ernstki/94aff475aaa4d477d98461a8be36b044 to your computer and use it in GitHub Desktop.
Boilerplat for a userscript that hooks into the XHR 'load' event, for handling lazy-loaded pages
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
// ==UserScript== | |
// @name XHR Hook Example | |
// @namespace http://tampermonkey.net/ | |
// @version 0.1 | |
// @description Hook into XHR requests | |
// @match *://*/* | |
// @grant none | |
// ==/UserScript== | |
// source: | |
// https://duckduckgo.com/?q=hook+into+xhr+loading+with+javascript+event+listener&ia=chat&bang=true | |
// | |
// with the additional prompt: | |
// > i don't have an xhr object; i'm writing a userscript, and I don't have | |
// > any of the other xmlhttpresponse instances in my function scope | |
// | |
// this actually worked! | |
(function() { | |
// Store the original XMLHttpRequest constructor | |
const OriginalXMLHttpRequest = window.XMLHttpRequest; | |
// Create a new constructor that wraps the original | |
function NewXMLHttpRequest() { | |
const xhr = new OriginalXMLHttpRequest(); | |
// Add event listeners to the new XHR instance | |
xhr.addEventListener('load', function() { | |
console.log('Request completed successfully:', xhr.responseText); | |
}); | |
xhr.addEventListener('error', function() { | |
console.error('Request failed'); | |
}); | |
xhr.addEventListener('progress', function(event) { | |
if (event.lengthComputable) { | |
const percentComplete = (event.loaded / event.total) * 100; | |
console.log('Loading progress: ' + percentComplete + '%'); | |
} | |
}); | |
// Return the new XHR instance | |
return xhr; | |
} | |
// Replace the global XMLHttpRequest with the new one | |
window.XMLHttpRequest = NewXMLHttpRequest; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment