Debian Codegraph @

src/js/firstparties/lib/utils.js

raw
1 window.isURL = function (url) {
2 // ensure the URL starts with HTTP or HTTPS; otherwise we might be vulnerable
3 // to XSS attacks
4 return (url && (url.startsWith("https://") || url.startsWith("http://")));
5 };
6
7 /**
8 * Search a window and all IFrames within it for a query selector, then return a
9 * list of all the elements in any frame that match.
10 */
11 window.findInAllFrames = function (query) {
12 let out = [];
13 document.querySelectorAll(query).forEach((node) => {
14 out.push(node);
15 });
16 Array.from(document.getElementsByTagName('iframe')).forEach((iframe) => {
17 try {
18 iframe.contentDocument.querySelectorAll(query).forEach((node) => {
19 out.push(node);
20 });
21 } catch (e) {
22 // pass on cross origin iframe errors
23 }
24 });
25 return out;
26 };
27
28 /**
29 * Listen for mutations on a page. If any nodes that match `selector` are added
30 * to the page, execute the function `callback` on them.
31 * Used by first-party scripts to listen for new links being added to the page
32 * and strip them of tracking code immediately.
33 */
34 window.observeMutations = function (selector, callback) {
35 // Check all new nodes added by a mutation for tracking links and unwrap them
36 function onMutation(mutation) {
37 if (mutation.type == "attributes" && mutation.target) {
38 callback(mutation.target);
39 return;
40 }
41
42 for (let node of mutation.addedNodes) {
43 // Only act on element nodes, otherwise querySelectorAll won't work
44 if (node.nodeType != Node.ELEMENT_NODE) {
45 continue;
46 }
47
48 // check all child nodes against the selector first
49 node.querySelectorAll(selector).forEach((element) => {
50 callback(element);
51 });
52
53 // then check the node itself
54 if (node.matches(selector)) {
55 callback(node);
56 }
57 }
58 }
59
60 // Set up a mutation observer with the constructed callback
61 new MutationObserver(function (mutations) {
62 mutations.forEach(onMutation);
63 }).observe(document.body, {
64 childList: true,
65 subtree: true,
66 attributes: true,
67 attributeFilter: ["href"],
68 characterData: false,
69 });
70 };