forked from hoppscotch/hoppscotch-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontentScript.ts
95 lines (81 loc) · 2.24 KB
/
contentScript.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const fs = require("fs")
const hookContent = fs.readFileSync(__dirname + "/hookContent.js", {
encoding: "utf-8",
})
const hookContentInvalidOrigin = fs.readFileSync(
__dirname + "/hookContentInvalidOrigin.js",
{
encoding: "utf-8",
}
)
type HookType = "valid_origin" | "unknown-origin"
function getOriginList(): Promise<string[]> {
return new Promise((resolve, reject) => {
chrome.storage.sync.get((items) => {
let originList: string[] = JSON.parse(items["originList"])
resolve(originList)
})
})
}
/**
* when an origin is added or removed,reevaluate the hook
*/
chrome.storage.onChanged.addListener((changes, _areaName) => {
if (changes.originList && changes.originList.newValue) {
injectHoppExtensionHook()
}
})
async function injectHoppExtensionHook() {
let originList = await getOriginList()
let url = new URL(window.location.href)
const script = document.createElement("script")
script.textContent = originList.includes(url.origin)
? hookContent
: hookContentInvalidOrigin
document.documentElement.appendChild(script)
script.parentNode.removeChild(script)
}
window.addEventListener("message", (ev) => {
if (ev.source !== window || !ev.data) {
return
}
if (ev.data.type === "__POSTWOMAN_EXTENSION_REQUEST__") {
chrome.runtime.sendMessage(
{
messageType: "send-req",
data: ev.data.config,
},
(message) => {
if (message.data.error) {
window.postMessage(
{
type: "__POSTWOMAN_EXTENSION_ERROR__",
error: message.data.error,
},
"*"
)
} else {
window.postMessage(
{
type: "__POSTWOMAN_EXTENSION_RESPONSE__",
response: message.data.response,
isBinary: message.data.isBinary,
},
"*"
)
}
}
)
} else if (ev.data.type === "__POSTWOMAN_EXTENSION_CANCEL__") {
chrome.runtime.sendMessage({
messageType: "cancel-req",
})
}
})
const VERSION = { major: 0, minor: 25 }
injectHoppExtensionHook()
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg.action === "__POSTWOMAN_EXTENSION_PING__") {
sendResponse(true)
}
})