forked from quoid/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserscriptsSafari.js
More file actions
78 lines (74 loc) · 2.92 KB
/
Copy pathUserscriptsSafari.js
File metadata and controls
78 lines (74 loc) · 2.92 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
// all code from all scripts saved to data var
let data;
// var that determines whether strict csp injection has already run (JS only)
let evalJS = 0;
// attempt to ensure script only runs on top-level pages
if (window.top === window) {
// request saved script code
safari.extension.dispatchMessage("REQ_USERSCRIPTS");
// event listener to detect strict CSPs
document.addEventListener("securitypolicyviolation", function(e) {
const src = e.sourceFile.toUpperCase();
const ext = safari.extension.baseURI.toUpperCase();
// ensure that violation came from the extension
if ((ext.startsWith(src) || src.startsWith(ext))) {
// determine what kind of violation
if (e.effectiveDirective === "script-src" && evalJS != 1) {
inject("eval");
// change var to ensure eval injection only happens once
evalJS = 1;
}
}
});
}
function inject(method) {
// iterate over data and extract css/js individually for injection
for (const type in data) {
const codeType = data[type];
for (const filename in codeType) {
let code = codeType[filename];
// css injection only happens with inline method
// if blocked by csp, no reliable way to inject style code yet
// future fix?: https://wicg.github.io/construct-stylesheets/
if (type === "css" && method == "inline") {
const tag = document.createElement("style");
tag.textContent = code;
document.head.appendChild(tag);
console.log(`Injecting ${filename}`);
} else if (type === "js") {
code = code + "\n//# sourceURL=" + filename.replace(/\s/g, "-");
if (method === "inline") {
const tag = document.createElement("script");
tag.textContent = code;
document.body.appendChild(tag);
console.log(`Injecting ${filename}`);
} else if (method === "eval"){
eval(code);
}
}
}
}
}
// respond to messages
function handleMessage(event) {
// the only message currently sent to the content script
if (event.name === "RESP_USERSCRIPTS") {
// if error returned, log and stop execution
if (event.message.error) {
console.error(event.message.error);
return;
}
// save data sent with message to var
data = event.message.data;
// attempt to inject all code inline after page has loaded
if (document.readyState !== "loading") {
inject("inline");
} else {
document.addEventListener("DOMContentLoaded", function() {
inject("inline");
});
}
}
}
// event listener to handle messages
safari.self.addEventListener("message", handleMessage);