generated from shgysk8zer0/npm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault-policy.js
More file actions
48 lines (46 loc) · 1.46 KB
/
default-policy.js
File metadata and controls
48 lines (46 loc) · 1.46 KB
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
if (! ('trustedTypes' in globalThis && trustedTypes.createPolicy instanceof Function)) {
console.warn('Trusted Types is not supported.');
} else if (trustedTypes.defaultPolicy !== null) {
console.warn('Default policy already created.');
} else if (! (HTMLElement.prototype.setHTML instanceof Function)) {
console.warn('The Sanitizer API is not supported.');
} else {
try {
trustedTypes.createPolicy('default', {
createHTML(input, {
elements,
attributes,
comments = false,
dataAttributes = true,
...rest
} = {}) {
const el = document.createElement('div');
el.setHTML(input, { sanitizer: { elements, attributes, comments, dataAttributes, ...rest }});
return el.innerHTML;
},
createScriptURL(input, allowedSources = []) {
if (! Array.isArray(allowedSources)) {
throw new TypeError('`allowedSources` must be an array.');
} else if (allowedSources.length === 0) {
throw new TypeError('No `allowedSources` given to `createScriptURL`.');
} else {
const src = new URL(input, document.baseURI);
const mapped = allowedSources.map(src => src instanceof URL
? src
: new URL(src, document.baseURI)
);
if (mapped.some(({ origin, pathname }) => (
src.origin === origin
&& src.pathname.startsWith(pathname))
)) {
return src.href;
} else {
throw new TypeError(`${src.href} is not an allowed script URL.`);
}
}
}
});
} catch(err) {
console.error(err);
}
}