-
Notifications
You must be signed in to change notification settings - Fork 7
/
browserUtility.js
61 lines (51 loc) · 1.38 KB
/
browserUtility.js
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
export {
downloadBlob,
evalGlobal,
};
const downloadBlob = function (blob, name = `download_file`) {
const url = URL.createObjectURL(blob);
const anchor = document.createElement(`a`);
anchor.href = url;
anchor.download = name;
// required
document.body.appendChild(anchor);
// will prompt file location
anchor.click();
// clean up
URL.revokeObjectURL(url);
document.body.removeChild(anchor);
};
let evalGlobalId = 0;
const evalGlobalResolves = new Map();
/**
*
* @param {String} code
* @param {String<'script' | 'module'>} as
*/
const evalGlobal = (code, as = `script`) => {
evalGlobalId += 1;
const thisId = evalGlobalId;
const script = document.createElement(`script`);
let innerHTML = `
${code}
window.evalGlobalReady(${thisId})`;
if (as === `script`) {
innerHTML = `"use strict";${innerHTML}`;
} else if (as === `module`) {
script.type = `module`;
}
script.innerHTML = innerHTML;
if (!window.evalGlobalReady) {
window.evalGlobalReady = (id) => {
const resolve = evalGlobalResolves.get(id);
if (resolve) {
evalGlobalResolves.delete(id);
resolve();
}
};
}
return new Promise((resolve) => {
evalGlobalResolves.set(thisId, resolve);
document.body.appendChild(script);
});
};