-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathcall-nothrow.js
104 lines (96 loc) · 2.66 KB
/
call-nothrow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import {
hit,
getPropertyInChain,
logMessage,
isEmptyObject,
} from '../helpers';
/* eslint-disable max-len */
/**
* @scriptlet call-nothrow
*
* @description
* Prevents an exception from being thrown and returns undefined when a specific function is called.
*
* Related UBO scriptlet:
* https://github.com/gorhill/uBlock/wiki/Resources-Library#call-nothrowjs-
*
* ### Syntax
*
* ```text
* example.org#%#//scriptlet('call-nothrow', functionName)
* ```
*
* - `functionName` — required, the name of the function to trap
*
* ### Examples
*
* 1. Prevents an exception from being thrown when `Object.defineProperty` is called:
*
* ```adblock
* example.org#%#//scriptlet('call-nothrow', 'Object.defineProperty')
* ```
*
* For instance, the following call normally throws an error, but the scriptlet catches it and returns undefined:
*
* ```javascript
* Object.defineProperty(window, 'foo', { value: true });
* Object.defineProperty(window, 'foo', { value: false });
* ```
*
* 2. Prevents an exception from being thrown when `JSON.parse` is called:
*
* ```adblock
* example.org#%#//scriptlet('call-nothrow', 'JSON.parse')
* ```
*
* For instance, the following call normally throws an error, but the scriptlet catches it and returns undefined:
*
* ```javascript
* JSON.parse('foo');
* ```
*
* @added v1.10.1.
*/
/* eslint-enable max-len */
export function callNoThrow(source, functionName) {
if (!functionName) {
return;
}
const { base, prop } = getPropertyInChain(window, functionName);
if (!base || !prop || typeof base[prop] !== 'function') {
const message = `${functionName} is not a function`;
logMessage(source, message);
return;
}
const objectWrapper = (...args) => {
let result;
try {
result = Reflect.apply(...args);
} catch (e) {
const message = `Error calling ${functionName}: ${e.message}`;
logMessage(source, message);
}
hit(source);
return result;
};
const objectHandler = {
apply: objectWrapper,
};
base[prop] = new Proxy(base[prop], objectHandler);
}
export const callNoThrowNames = [
'call-nothrow',
// aliases are needed for matching the related scriptlet converted into our syntax
'call-nothrow.js',
'ubo-call-nothrow.js',
'ubo-call-nothrow',
];
// eslint-disable-next-line prefer-destructuring
callNoThrow.primaryName = callNoThrowNames[0];
callNoThrow.injections = [
hit,
getPropertyInChain,
logMessage,
// following helpers are needed for helpers above
isEmptyObject,
];