Cloudflare-Blocker/background.js
2025-09-28 06:09:19 +00:00

69 lines
2.2 KiB
JavaScript

let blockingEnabled = true;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'toggleBlocking') {
blockingEnabled = message.enabled;
}
if (message.action === 'getBlockingState') {
sendResponse({ action: 'setBlockingState', enabled: blockingEnabled });
}
});
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
if (!blockingEnabled) {
return { cancel: false };
}
// These are Cloudflare's headers, taken from here:
// https://developers.cloudflare.com/fundamentals/reference/http-headers/
const cloudflare_headers = [
'cf-connecting-ip',
'cf-connecting-ipv6',
'cf-ew-via',
'cf-Pseudo-ipv4',
'cf-ray',
'cf-ipcountry',
'cf-visitor',
'cf-worker'
];
// You might want capture all headers prefixed with "cf-":
// const cf_header = details.responseHeaders.find(header =>
// header.name.toLowerCase().startsWith('cf-')
// );
const cf_header = details.responseHeaders.find(header =>
cloudflare_headers.includes(header.name.toLowerCase())
);
if (cf_header) {
console.log('Cloudflare header found:', cf_header);
const query_params = new URLSearchParams({
name: cf_header.name,
value: cf_header.value,
url: details.url
}).toString();
/*
* It would be cool to pass the tab URL in the query params, but how?
* When accessing chrome.tabs here, the active tab URL is "about:newtab".
* Because we block the request immediately and the tab URL state doesn't
* never update to the URL we tried to access. I'd like to pass the URL
* to the web.archive.org/tab_url_here in blocked.html.
* Email contact@libroot.org if you know a solution!
*/
// Redirect to our custom blocked.html page
const url = chrome.runtime.getURL('blocked.html') + '?' + query_params;
console.log('Redirecting to blocked page:', url);
chrome.tabs.update(details.tabId, { url: url });
// Block the request, reject Cloudflare!
return { cancel: true };
}
},
{ urls: ['<all_urls>'] },
['blocking', 'responseHeaders']
);