summaryrefslogtreecommitdiff
path: root/src/content/sanitizePaste.js
blob: 703f5b36c620fc6a08653e17db424fcd48f5b278 (plain)
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
'use strict';

window.addEventListener("paste", e => {
  let data = e.clipboardData;
  let html =  data.getData("text/html");
  let t = e.target;
  if (t.nodeType !== 1) t = t.parentElement;

  try {
    let node = t.cloneNode();

    node.innerHTML = html;

    if (sanitizeExtras(node)) {
      let sanitized = node.innerHTML;
      setTimeout(function() { try {
        if (sanitizeExtras(t)) {
          console.log(`[NoScript] Sanitized\n<PASTE>\n${html}\n</PASTE>to\n<PASTE>\n${t.innerHTML}\n</PASTE>`, t);
        }
      } catch(ex) {
       console.log(ex);
     }}, 0);
    }
  } catch(ex) {
    console.log(ex);
  }

  function removeAttribute(node, name, value = node.getAttribute(name)) {
    node.setAttribute(`data-noscript-removed-${name}`, value);
    node.removeAttribute(name);
  }

  function sanitizeExtras(el) {
    let ret = false;

    // remove attributes from forms
    for (let f of el.getElementsByTagName("form")) {
      for (let a of f.attributes) {
        f.removeAttribute(a.name);
        ret = true;
      }
    }

    let urlAttributes = ['href', 'to', 'from', 'by', 'values'];
    let selector = urlAttributes.map(a => `[${a}]`).join(',');
    for (let node of el.querySelectorAll(selector)) {
      for (let name of urlAttributes) {
        let value = node.getAttribute(name);
        if (/^\W*(?:(?:javascript|data):|https?:[\s\S]+[[(<])/i.test(unescape(value))) {
          node.setAttribute(`data-noscript-removed-${name}`, value);
          node.removeAttribute(name);
          ret = true;
        }
      }
    }
    return ret;
  }
}, true);