-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathdom-auto-events.js
More file actions
78 lines (67 loc) · 1.87 KB
/
dom-auto-events.js
File metadata and controls
78 lines (67 loc) · 1.87 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
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
const { JSDOM } = require("jsdom");
const { readFileSync } = require("fs");
const vm = require("vm");
const SCRIPT_PATH = "dist/latest/auto-events.js";
/**
* @typedef {"navigate" | "reload" | "back_forward" | "prerender"} NavigationType
*/
/** @type {Record<NavigationType, {name: NavigationType, code: number}>} */
const NAVIGATION_TYPES = {
navigate: { name: "navigate", code: 0 },
reload: { name: "reload", code: 1 },
back_forward: { name: "back_forward", code: 2 },
prerender: { name: "prerender", code: 255 },
};
function createDOM(options = {}) {
const {
url = "https://example.com/",
navigationType = "navigate",
settings,
beforeRun,
} = options;
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
url,
runScripts: "outside-only",
pretendToBeVisual: true,
});
if (settings) {
vm.runInContext(
`window.sa_settings = ${JSON.stringify(settings)}`,
dom.getInternalVMContext()
);
}
if (typeof beforeRun === "function") beforeRun(dom.getInternalVMContext());
const sent = [];
dom.window.Image = function () {
return {
set src(value) {
sent.push({ type: "image", url: value });
},
};
};
dom.window.navigator.sendBeacon = function (url, data) {
sent.push({ type: "beacon", url, data });
return true;
};
Object.defineProperty(dom.window, "performance", {
writable: true,
value: {
getEntriesByType: function (type) {
if (type === "navigation") {
return [{ type: NAVIGATION_TYPES[navigationType].name }];
}
return [];
},
navigation: { type: NAVIGATION_TYPES[navigationType].code },
},
});
const script = readFileSync(SCRIPT_PATH, "utf8");
vm.runInContext(script, dom.getInternalVMContext());
dom.sent = sent;
return dom;
}
module.exports = {
createDOM,
SCRIPT_PATH,
NAVIGATION_TYPES,
};