-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
403 lines (324 loc) · 11 KB
/
Copy pathcontent.js
File metadata and controls
403 lines (324 loc) · 11 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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
(() => {
if (window.__rightClickGPTContentScriptLoaded) {
return;
}
window.__rightClickGPTContentScriptLoaded = true;
const CHATGPT_COMPOSER_SELECTORS = [
'#prompt-textarea[contenteditable="true"]',
'[role="textbox"][aria-label="Chat with ChatGPT"]',
'textarea[aria-label="Chat with ChatGPT"]',
'textarea',
];
const CHATGPT_SEND_BUTTON_SELECTORS = [
'button[data-testid="send-button"]',
'button[aria-label="Send prompt"]',
];
const T3_COMPOSER_SELECTORS = [
'[role="textbox"][aria-label="Message input"]',
'textarea[aria-label="Message input"]',
'[contenteditable="true"][aria-label="Message input"]',
];
const T3_SEND_BUTTON_SELECTORS = [
'button[aria-label="Send message"]',
];
const WAIT_TIMEOUT_MS = 15000;
const WAIT_INTERVAL_MS = 100;
const SUBMIT_TIMEOUT_MS = 5000;
function logToBackground(...args) {
chrome.runtime.sendMessage({
action: 'logToBackground',
data: args,
});
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
const supportedActions = [
'sendToChatGPT',
'ensureChatGPTPromptSubmitted',
'sendToChatProvider',
'ensureChatProviderPromptSubmitted',
];
if (!supportedActions.includes(request.action)) {
return false;
}
const provider = request.provider || 'chatgpt';
const task = request.action === 'sendToChatGPT' || request.action === 'sendToChatProvider'
? sendPromptToProvider(request.prompt, provider)
: ensurePromptSubmitted(request.prompt, provider);
task
.then(() => sendResponse({ ok: true }))
.catch((error) => {
const message = error && error.message ? error.message : String(error);
logToBackground('RightClickGPT failed:', message);
sendResponse({ ok: false, error: message });
});
return true;
});
const framedPrompt = window.top !== window && isSupportedProviderURL() ? getPromptParamFromCurrentURL() : '';
if (framedPrompt) {
ensurePromptSubmitted(framedPrompt, getCurrentProviderId()).catch((error) => {
const message = error && error.message ? error.message : String(error);
logToBackground('RightClickGPT sidechat failed:', message);
});
}
async function sendPromptToProvider(prompt, provider) {
const composer = await waitForElement(() => findComposer(provider), `${getProviderLabel(provider)} composer`);
await insertPrompt(composer, prompt);
await submitPrompt(composer, provider);
}
async function ensurePromptSubmitted(prompt, provider) {
if (await waitForPromptInConversation(prompt, 2500, provider)) {
return;
}
const composer = await waitForElement(() => findComposer(provider), `${getProviderLabel(provider)} composer`);
if (!getComposerText(composer) && !currentURLHasPromptParam()) {
return;
}
if (getComposerText(composer) !== prompt) {
insertPrompt(composer, prompt);
}
await submitPrompt(composer, provider);
}
function findComposer(provider) {
for (const selector of getComposerSelectors(provider)) {
const element = document.querySelector(selector);
if (element && isVisible(element)) {
return element;
}
}
return null;
}
function findEnabledSendButton(provider) {
for (const selector of getSendButtonSelectors(provider)) {
const button = document.querySelector(selector);
if (button && isVisible(button) && !button.disabled && button.getAttribute('aria-disabled') !== 'true') {
return button;
}
}
return null;
}
function findSendButton(provider) {
for (const selector of getSendButtonSelectors(provider)) {
const button = document.querySelector(selector);
if (button && isVisible(button)) {
return button;
}
}
return null;
}
function isVisible(element) {
const rect = element.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
function waitForElement(getElement, label) {
const startedAt = Date.now();
return new Promise((resolve, reject) => {
const check = () => {
const element = getElement();
if (element) {
resolve(element);
return;
}
if (Date.now() - startedAt >= WAIT_TIMEOUT_MS) {
reject(new Error(`Timed out waiting for ${label}.`));
return;
}
setTimeout(check, WAIT_INTERVAL_MS);
};
check();
});
}
async function submitPrompt(composer, provider) {
const beforeSubmitText = getComposerText(composer);
if (provider === 't3') {
pressEnterToSubmit(composer);
if (await waitForPromptToSubmit(composer, beforeSubmitText, 1200, provider)) {
return;
}
}
const sendButton = await waitForElement(() => findEnabledSendButton(provider), `enabled ${getProviderLabel(provider)} send button`);
clickButtonLikeAUser(sendButton);
if (await waitForPromptToSubmit(composer, beforeSubmitText, 1200, provider)) {
return;
}
requestFormSubmit(sendButton);
if (await waitForPromptToSubmit(composer, beforeSubmitText, 1200, provider)) {
return;
}
pressEnterToSubmit(composer);
if (await waitForPromptToSubmit(composer, beforeSubmitText, SUBMIT_TIMEOUT_MS, provider)) {
return;
}
const currentButton = findSendButton(provider);
if (currentButton && !currentButton.disabled && currentButton.getAttribute('aria-disabled') !== 'true') {
currentButton.click();
}
if (!(await waitForPromptToSubmit(composer, beforeSubmitText, 1500, provider))) {
throw new Error(`Prompt was inserted, but ${getProviderLabel(provider)} did not submit it.`);
}
}
function insertPrompt(composer, prompt) {
composer.focus();
if (composer.isContentEditable) {
insertIntoContentEditable(composer, prompt);
return;
}
insertIntoTextField(composer, prompt);
}
function insertIntoContentEditable(element, text) {
selectExistingComposerText(element);
if (document.queryCommandSupported && document.queryCommandSupported('insertText')) {
document.execCommand('insertText', false, text);
element.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: text }));
return;
}
element.textContent = text;
element.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: text }));
}
function insertIntoTextField(element, text) {
element.focus();
element.value = text;
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
}
function clickButtonLikeAUser(button) {
button.scrollIntoView({ block: 'center', inline: 'center' });
button.focus();
for (const type of ['pointerdown', 'pointerup']) {
const EventClass = window.PointerEvent || MouseEvent;
button.dispatchEvent(new EventClass(type, { bubbles: true, cancelable: true, view: window }));
}
for (const type of ['mousedown', 'mouseup', 'click']) {
button.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
function requestFormSubmit(button) {
const form = button.closest('form');
if (!form) {
return;
}
if (typeof form.requestSubmit === 'function') {
form.requestSubmit(button);
return;
}
form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
}
function pressEnterToSubmit(composer) {
composer.focus();
for (const type of ['keydown', 'keypress', 'keyup']) {
composer.dispatchEvent(new KeyboardEvent(type, {
bubbles: true,
cancelable: true,
key: 'Enter',
code: 'Enter',
which: 13,
keyCode: 13,
}));
}
}
function waitForPromptToSubmit(composer, submittedText, timeout, provider) {
const startedAt = Date.now();
return new Promise((resolve) => {
const check = () => {
const sendButton = findSendButton(provider);
const currentText = getComposerText(composer);
const submitButtonChanged = sendButton && sendButton.getAttribute('aria-label') !== 'Send prompt';
if (!currentText || currentText !== submittedText || submitButtonChanged) {
resolve(true);
return;
}
if (Date.now() - startedAt >= timeout) {
resolve(false);
return;
}
setTimeout(check, WAIT_INTERVAL_MS);
};
check();
});
}
function waitForPromptInConversation(prompt, timeout, provider) {
const startedAt = Date.now();
return new Promise((resolve) => {
const check = () => {
if (textAppearsOutsideComposer(prompt, provider)) {
resolve(true);
return;
}
if (Date.now() - startedAt >= timeout) {
resolve(false);
return;
}
setTimeout(check, WAIT_INTERVAL_MS);
};
check();
});
}
function textAppearsOutsideComposer(text, provider) {
const composer = findComposer(provider);
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
const node = walker.currentNode;
if (composer && composer.contains(node.parentElement)) {
continue;
}
if (node.textContent && node.textContent.includes(text)) {
return true;
}
}
return false;
}
function currentURLHasPromptParam() {
try {
return new URL(window.location.href).searchParams.has('q');
} catch (error) {
return false;
}
}
function getPromptParamFromCurrentURL() {
try {
return new URL(window.location.href).searchParams.get('q') || '';
} catch (error) {
return '';
}
}
function getCurrentProviderId() {
try {
const hostname = new URL(window.location.href).hostname;
if (hostname === 't3.chat') {
return 't3';
}
return 'chatgpt';
} catch (error) {
return 'chatgpt';
}
}
function isSupportedProviderURL() {
try {
const hostname = new URL(window.location.href).hostname;
return hostname === 'chatgpt.com' || hostname === 'chat.openai.com' || hostname === 't3.chat';
} catch (error) {
return false;
}
}
function getComposerSelectors(provider) {
return provider === 't3' ? T3_COMPOSER_SELECTORS : CHATGPT_COMPOSER_SELECTORS;
}
function getSendButtonSelectors(provider) {
return provider === 't3' ? T3_SEND_BUTTON_SELECTORS : CHATGPT_SEND_BUTTON_SELECTORS;
}
function getProviderLabel(provider) {
return provider === 't3' ? 't3.chat' : 'ChatGPT';
}
function getComposerText(element) {
if (!element) {
return '';
}
return (element.isContentEditable ? element.innerText : element.value || '').trim();
}
function selectExistingComposerText(element) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
})();