Skip to content

Instantly share code, notes, and snippets.

@pl12133
Last active June 1, 2017 17:47
Show Gist options
  • Save pl12133/bebe3ec3f0c2eed080b1b7589df809d5 to your computer and use it in GitHub Desktop.
Save pl12133/bebe3ec3f0c2eed080b1b7589df809d5 to your computer and use it in GitHub Desktop.
/* Call a function when a fetch is made to a URL containing `str`
* @param {String} str if a URL being fetched contains this string, call {@param callback}
* @param {Function} callback a function to call when a fetch is made to the given {@param str}
* @example <caption>Call debugger on fetches to `example.com`</caption>
*
* breakOnUrlMatch('example.com', () => { debugger; });
*/
function breakOnURLMatch(str, callback) {
let nextOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function monkeypatchedOpen(...args) {
let url = args[1];
if (url && url.indexOf(str) >= 0) { callback(); }
console.log('XHR for ', url);
return nextOpen(...args);
}
let nextFetch = window.fetch;
window.fetch = function monkeypatchedFetch(...args) {
let url = args[0];
if (url && url.indexOf(str) >= 0) { callback(); }
console.log('Fetch for ', url);
return nextFetch(...args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment