Skip to content

Instantly share code, notes, and snippets.

@flashlin
Last active June 16, 2021 00:09
Show Gist options
  • Save flashlin/c67216852ccac1e374447d2bb1f8d4ed to your computer and use it in GitHub Desktop.
Save flashlin/c67216852ccac1e374447d2bb1f8d4ed to your computer and use it in GitHub Desktop.
[Chrome Extension WebRequest Hook] #chrome-extension #typescript
(function () {
const tabStorage = {};
const networkFilters = {
urls: ["*://*/*"],
};
chrome.webRequest.onBeforeRequest.addListener((details) => {
const { tabId, requestId } = details;
if (!tabStorage.hasOwnProperty(tabId)) {
return;
}
tabStorage[tabId].requests[requestId] = {
requestId: requestId,
url: details.url,
startTime: details.timeStamp,
status: "pending",
};
console.log(tabStorage[tabId].requests[requestId]);
}, networkFilters);
chrome.webRequest.onCompleted.addListener((details) => {
const { tabId, requestId } = details;
if (
!tabStorage.hasOwnProperty(tabId) ||
!tabStorage[tabId].requests.hasOwnProperty(requestId)
) {
return;
}
const request = tabStorage[tabId].requests[requestId];
Object.assign(request, {
endTime: details.timeStamp,
requestDuration: details.timeStamp - request.startTime,
status: "complete",
});
console.log(tabStorage[tabId].requests[details.requestId]);
}, networkFilters);
chrome.webRequest.onErrorOccurred.addListener((details) => {
const { tabId, requestId } = details;
if (
!tabStorage.hasOwnProperty(tabId) ||
!tabStorage[tabId].requests.hasOwnProperty(requestId)
) {
return;
}
const request = tabStorage[tabId].requests[requestId];
Object.assign(request, {
endTime: details.timeStamp,
status: "error",
});
console.log(tabStorage[tabId].requests[requestId]);
}, networkFilters);
chrome.tabs.onActivated.addListener((tab) => {
const tabId = tab ? tab.tabId : chrome.tabs.TAB_ID_NONE;
if (!tabStorage.hasOwnProperty(tabId)) {
tabStorage[tabId] = {
id: tabId,
requests: {},
registerTime: new Date().getTime(),
};
}
});
chrome.tabs.onRemoved.addListener((tabId) => {
if (!tabStorage.hasOwnProperty(tabId)) {
return;
}
tabStorage[tabId] = null;
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment