Skip to content

Instantly share code, notes, and snippets.

@m7kvqbe1
Created March 13, 2024 19:40
Show Gist options
  • Select an option

  • Save m7kvqbe1/4674360c0fc44e88ef4beb36d1e2c068 to your computer and use it in GitHub Desktop.

Select an option

Save m7kvqbe1/4674360c0fc44e88ef4beb36d1e2c068 to your computer and use it in GitHub Desktop.
// requestInterceptor.js
const hostnameWhitelist = ['api.example.com', 'another.api.com'];
// Original functions
const originalFetch = window.fetch;
const originalXMLHttpRequest = window.XMLHttpRequest;
const originalSendBeacon = navigator.sendBeacon.bind(navigator);
const originalWebSocket = window.WebSocket;
function isUrlAllowed(url) {
const parsedUrl = new URL(url, window.location.href);
return hostnameWhitelist.includes(parsedUrl.hostname);
}
// Override fetch
window.fetch = async (...args) => {
if (isUrlAllowed(args[0])) {
return originalFetch(...args);
} else {
throw new Error("Fetch request blocked by interceptor.");
}
};
// Override XMLHttpRequest
window.XMLHttpRequest = function() {
const xhr = new originalXMLHttpRequest();
const originalOpen = xhr.open;
xhr.open = function(method, url, ...args) {
if (isUrlAllowed(url)) {
originalOpen.call(xhr, method, url, ...args);
} else {
console.error("XMLHttpRequest blocked by interceptor.");
// Throwing an error might be too disruptive; consider alternatives
}
};
return xhr;
};
// Override sendBeacon
navigator.sendBeacon = (url, data) => {
if (isUrlAllowed(url)) {
return originalSendBeacon(url, data);
} else {
console.error("sendBeacon request blocked by interceptor.");
return false; // sendBeacon returns a boolean indicating success/failure
}
};
// Override WebSocket
window.WebSocket = function(url, protocols) {
if (isUrlAllowed(url)) {
return new originalWebSocket(url, protocols);
} else {
console.error("WebSocket connection blocked by interceptor.");
// Consider throwing an error or returning a dummy object depending on how you want to handle blocked attempts
throw new Error("WebSocket connection blocked by interceptor.");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment