Project

General

Profile

Download (1.68 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / content / freezer.js @ 83a8d263

1
/**
2
 * Helper functions for blocking scripts in pages, based off NoScript's lib/DocumentFreezer.js
3
 *
4
 * Copyright (C) 2005-2021 Giorgio Maone - https://maone.net
5
 * Copyright (C) 2021 jahoti
6
 * Redistribution terms are gathered in the `copyright' file.
7
 */
8

    
9
"use strict";
10

    
11
(() => {
12
    const loaderAttributes = ["href", "src", "data"];
13
    const jsOrDataUrlRx = /^(?:data:(?:[^,;]*ml|unknown-content-type)|javascript:)/i;
14

    
15
    function sanitizeAttributes(element) {
16
	if (element._frozen)
17
	    return;
18
	let fa = [];
19
	let loaders = [];
20
	for (let a of element.attributes) {
21
	    let name = a.localName.toLowerCase();
22
	    if (loaderAttributes.includes(name))
23
		if (jsOrDataUrlRx.test(a.value))
24
		    loaders.push(a);
25

    
26
	    else if (name.startsWith("on")) {
27
		console.debug("Removing", a, element.outerHTML);
28
		fa.push(a.cloneNode());
29
		a.value = "";
30
		element[name] = null;
31
	    }
32
	}
33
	if (loaders.length) {
34
	    for (let a of loaders) {
35
		fa.push(a.cloneNode());
36
		a.value = "javascript://frozen";
37
	    }
38
	    if ("contentWindow" in element)
39
		element.replaceWith(element = element.cloneNode(true));
40

    
41
	}
42
	if (fa.length)
43
	    element._frozenAttributes = fa;
44
	element._frozen = true;
45
    }
46
    
47
    function scriptSuppressor(nonce) {
48
	const blockExecute = e => {
49
	    if (document.readyState === 'complete') {
50
		removeEventListener('beforescriptexecute', blockExecute, true);
51
		return;
52
	    }
53
	    else if (e.isTrusted && e.target.getAttribute('nonce') !== nonce) { // Prevent blocking of injected scripts
54
		e.preventDefault();
55
		console.log('Suppressed script', e.target);
56
	    }
57
	};
58
	return blockExecute;
59
    };
60
    
61
    window.scriptSuppressor = scriptSuppressor;
62
    window.sanitize_attributes = sanitizeAttributes;
63
})();
(1-1/3)