This repository has been archived by the owner on Jun 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpt_utils.js
124 lines (108 loc) · 2.91 KB
/
gpt_utils.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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// all methods to be injected go here
var gpt = {
ask,
submitConversation,
waitForReady,
getResult,
onReady,
onResult,
onSubmit,
};
var gpt_inject = inject;
async function submitConversation(text) {
await waitForReady();
const textarea = document.querySelector("textarea[tabindex='0']");
const enterKeyEvent = new KeyboardEvent("keydown", {
bubbles: true,
cancelable: true,
keyCode: 13,
});
textarea.value = text;
textarea.dispatchEvent(enterKeyEvent);
}
async function waitForReady() {
let chatgptReady = false;
while (!chatgptReady) {
await new Promise((resolve) => setTimeout(resolve, 500));
chatgptReady = !document.querySelector(
".text-2xl > span:not(.invisible)"
);
}
}
async function getResult() {
await waitForReady();
var children = document.querySelectorAll(
"#__next > div.overflow-hidden.w-full.h-full.relative.flex.z-0 > div.relative.flex.h-full.max-w-full.flex-1.overflow-hidden > div > main > div.flex-1.overflow-hidden > div > div > div > div"
);
var resp = children[children.length - 2].querySelector(
"div > div:nth-child(2) > div > div"
);
if (children.length === 3) {
return resp.parentElement.querySelector("div:nth-child(2) > div")
.textContent;
}
return resp.textContent;
}
async function ask(prompt) {
await submitConversation(prompt);
var res;
await getResult().then((result) => {
res = result;
});
return res;
}
function onSubmit(callback) {
document.addEventListener("keyup", handleKeyPress);
var value = "";
function handleKeyPress(event) {
const textarea = event.target;
if (
textarea.tagName === "TEXTAREA" &&
textarea.matches("[tabindex='0']")
) {
if (event.keyCode === 13 && textarea.value === "") {
callback(value);
} else {
value = textarea.value;
}
}
}
}
function onResult(callback) {
return new Promise((resolve) => {
const processNextResult = async () => {
const message = await new Promise((innerResolve) => {
onSubmit(innerResolve);
});
const result = await getResult();
callback(result);
resolve(result);
processNextResult();
};
processNextResult();
});
}
function onReady(callback) {
const checkReadyState = () => {
const isReady = !document.querySelector(
".text-2xl > span:not(.invisible)"
);
if (isReady) {
callback();
} else {
setTimeout(checkReadyState, 500);
}
};
checkReadyState();
}
function g(str) {
console.log(str);
}
function hi() {
g("Hello");
}
// private/local
// Injects ChatGPT Utils
function inject() {
window.gpt = gpt;
}