Skip to content

Commit

Permalink
Add remove-cache-storage-item scriptlet
Browse files Browse the repository at this point in the history
Usage:

...##+js(remove-cache-storage-item, cacheNamePattern[, urlPattern])

`cacheNamePattern`: the name of the cache to target. Plain string
  or regex.

`urlPattern`: the URL of the resource to remove. Plain string
  or regex. If no pattern is provided, the whole cache is removed.

Reference:
https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
  • Loading branch information
gorhill committed Jan 27, 2024
1 parent fa162e2 commit 6c54731
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion assets/resources/scriptlets.js
Original file line number Diff line number Diff line change
Expand Up @@ -1678,7 +1678,7 @@ function jsonPrune(
if ( objAfter === undefined ) { return objBefore; }
safe.uboLog(logPrefix, 'Pruned');
if ( safe.logLevel > 1 ) {
safe.uboLog(logPrefix, JSON.stringify(objAfter, null, 1));
safe.uboLog(logPrefix, `After pruning:\n${JSON.stringify(objAfter, null, 1)}`);
}
return objAfter;
},
Expand Down Expand Up @@ -3941,6 +3941,58 @@ function multiup() {
document.addEventListener('click', handler, { capture: true });
}

/******************************************************************************/

builtinScriptlets.push({
name: 'remove-cache-storage-item.js',
fn: removeCacheStorageItem,
world: 'ISOLATED',
dependencies: [
'safe-self.fn',
],
});
function removeCacheStorageItem(
cacheNamePattern = '',
requestPattern = ''
) {
if ( cacheNamePattern === '' ) { return; }
const safe = safeSelf();
const logPrefix = safe.makeLogPrefix('remove-cache-storage-item', cacheNamePattern, requestPattern);
const cacheStorage = self.caches;
if ( cacheStorage instanceof Object === false ) { return; }
const reCache = safe.patternToRegex(cacheNamePattern, undefined, true);
const reRequest = safe.patternToRegex(requestPattern, undefined, true);
cacheStorage.keys().then(cacheNames => {
for ( const cacheName of cacheNames ) {
if ( reCache.test(cacheName) === false ) { continue; }
if ( requestPattern === '' ) {
cacheStorage.delete(cacheName).then(result => {
if ( safe.logLevel > 1 ) {
safe.uboLog(logPrefix, `Deleting ${cacheName}`);
}
if ( result !== true ) { return; }
safe.uboLog(logPrefix, `Deleted ${cacheName}: ${result}`);
});
continue;
}
cacheStorage.open(cacheName).then(cache => {
cache.keys().then(requests => {
for ( const request of requests ) {
if ( reRequest.test(request.url) === false ) { continue; }
if ( safe.logLevel > 1 ) {
safe.uboLog(logPrefix, `Deleting ${cacheName}/${request.url}`);
}
cache.delete(request).then(result => {
if ( result !== true ) { return; }
safe.uboLog(logPrefix, `Deleted ${cacheName}/${request.url}: ${result}`);
});
}
});
});
}
});
}


/*******************************************************************************
*
Expand Down

0 comments on commit 6c54731

Please sign in to comment.