Skip to content
Permalink
Browse files
Add json-prune.js scriptlet
The scriptlet will trap calls to JSON.parse, and
if the result of the parsing is an Object, it
will remove specified properties from the result
before returning to the caller.

Usage:

    ##+js(json-prune, arg1, [arg2])

Where:

- arg1: a list of space-separated properties to remove

- arg2: optional, a list of space-separated properties
        which must be all present for the pruning to
        occur

Example:

    ##+js(json-prune, enabled, adpath config)

A property in a list of properties can be a chain
of properties, example: adpath.url.first
  • Loading branch information
gorhill committed Sep 9, 2019
1 parent 4792e0e commit 2fd86a66fcc2665e5672cc5862e24b3782ee7504
Showing 1 changed file with 55 additions and 0 deletions.
@@ -236,6 +236,61 @@
})();


/// json-prune.js
(function() {
const log = console.log.bind(console);
const rawPrunePaths = '{{1}}';
const rawNeedlePaths = '{{2}}';
const prunePaths = rawPrunePaths !== '{{1}}' && rawPrunePaths !== ''
? rawPrunePaths.split(/ +/)
: [];
const needlePaths = rawNeedlePaths !== '{{2}}' && rawNeedlePaths !== ''
? rawNeedlePaths.split(/ +/)
: [];
const findOwner = function(root, path) {
let owner = root;
let chain = path;
for (;;) {
if ( owner instanceof Object === false ) { return; }
const pos = chain.indexOf('.');
if ( pos === -1 ) {
return owner.hasOwnProperty(chain)
? [ owner, chain ]
: undefined;
}
const prop = chain.slice(0, pos);
if ( owner.hasOwnProperty(prop) === false ) { return; }
owner = owner[prop];
chain = chain.slice(pos + 1);
}
};
const mustProcess = function(root) {
for ( const needlePath of needlePaths ) {
const details = findOwner(root, needlePath);
if ( details === undefined ) { return false; }
}
return true;
};
JSON.parse = new Proxy(JSON.parse, {
apply: function() {
const r = Reflect.apply(...arguments);
if ( prunePaths.length === 0 ) {
log(location.hostname, r);
return r;
}
if ( mustProcess(r) === false ) { return r; }
for ( const path of prunePaths ) {
const details = findOwner(r, path);
if ( details !== undefined ) {
delete details[0][details[1]];
}
}
return r;
},
});
})();


// Imported from:
// https://github.com/NanoAdblocker/NanoFilters/blob/1f3be7211bb0809c5106996f52564bf10c4525f7/NanoFiltersSource/NanoResources.txt#L126
//

1 comment on commit 2fd86a6

@gorhill
Copy link
Owner Author

@gorhill gorhill commented on 2fd86a6 Sep 9, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to mention that +js(json-prune) (no arguments) will log the current hostname + json payload at the console.

Please sign in to comment.