Skip to content

Commit 10e1a8b

Browse files
committed
feat: chatgpt web mode improvement, now when official website is open requests will be sent in the foreground (#25, #53, #65, #112, #127, #161, #192, #204, #230, #248, #281)
1 parent 17778f5 commit 10e1a8b

File tree

8 files changed

+116
-30
lines changed

8 files changed

+116
-30
lines changed

src/_locales/en/main.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,5 +104,6 @@
104104
"Max Conversation Length": "Max Conversation Length",
105105
"Always pin the floating window": "Always pin the floating window",
106106
"Export": "Export",
107-
"Always Create New Conversation Window": "Always Create New Conversation Window"
107+
"Always Create New Conversation Window": "Always Create New Conversation Window",
108+
"Please keep this tab open. You can now use the web mode of ChatGPTBox": "Please keep this tab open. You can now use the web mode of ChatGPTBox"
108109
}

src/_locales/zh-hans/main.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,5 +104,6 @@
104104
"Max Conversation Length": "对话处理的最大长度",
105105
"Always pin the floating window": "总是固定浮动窗口",
106106
"Export": "导出",
107-
"Always Create New Conversation Window": "总是创建新的对话窗口"
107+
"Always Create New Conversation Window": "总是创建新的对话窗口",
108+
"Please keep this tab open. You can now use the web mode of ChatGPTBox": "请保持这个页面打开, 现在你可以使用ChatGPTBox的网页版模式"
108109
}

src/_locales/zh-hant/main.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,5 +104,6 @@
104104
"Max Conversation Length": "對話處理的最大長度",
105105
"Always pin the floating window": "總是固定浮動視窗",
106106
"Export": "匯出",
107-
"Always Create New Conversation Window": "總是建立新的對話視窗"
107+
"Always Create New Conversation Window": "總是建立新的對話視窗",
108+
"Please keep this tab open. You can now use the web mode of ChatGPTBox": "請保持這個頁面開啟, 現在妳可以使用ChatGPTBox的網頁版模式"
108109
}

src/background/index.mjs

Lines changed: 54 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import Browser from 'webextension-polyfill'
2-
import { v4 as uuidv4 } from 'uuid'
32
import {
43
deleteConversation,
54
generateAnswersWithChatgptWebApi,
@@ -20,10 +19,12 @@ import {
2019
chatgptApiModelKeys,
2120
chatgptWebModelKeys,
2221
customApiModelKeys,
22+
defaultConfig,
2323
githubThirdPartyApiModelKeys,
2424
gptApiModelKeys,
2525
Models,
2626
poeWebModelKeys,
27+
setUserConfig,
2728
} from '../config/index.mjs'
2829
import '../_locales/i18n'
2930
import { openUrl } from '../utils/open-url'
@@ -37,12 +38,27 @@ import { registerCommands } from './commands.mjs'
3738

3839
async function executeApi(session, port, config) {
3940
if (chatgptWebModelKeys.includes(session.modelName)) {
40-
const accessToken = await getChatGptAccessToken()
41-
session.messageId = uuidv4()
42-
if (session.parentMessageId == null) {
43-
session.parentMessageId = uuidv4()
41+
let tabId
42+
if (
43+
config.chatgptTabId &&
44+
config.customChatGptWebApiUrl === defaultConfig.customChatGptWebApiUrl
45+
) {
46+
const tab = await Browser.tabs.get(config.chatgptTabId).catch(() => {})
47+
if (tab) tabId = tab.id
48+
}
49+
if (tabId) {
50+
const proxyPort = Browser.tabs.connect(tabId)
51+
proxyPort.onMessage.addListener((msg) => {
52+
port.postMessage(msg)
53+
})
54+
port.onMessage.addListener((msg) => {
55+
proxyPort.postMessage(msg)
56+
})
57+
proxyPort.postMessage({ session })
58+
} else {
59+
const accessToken = await getChatGptAccessToken()
60+
await generateAnswersWithChatgptWebApi(port, session.question, session, accessToken)
4461
}
45-
await generateAnswersWithChatgptWebApi(port, session.question, session, accessToken)
4662
} else if (bingWebModelKeys.includes(session.modelName)) {
4763
const accessToken = await getBingAccessToken()
4864
if (session.modelName === 'bingFreeSydney')
@@ -84,18 +100,38 @@ async function executeApi(session, port, config) {
84100
}
85101

86102
Browser.runtime.onMessage.addListener(async (message) => {
87-
if (message.type === 'FEEDBACK') {
88-
const token = await getChatGptAccessToken()
89-
await sendMessageFeedback(token, message.data)
90-
} else if (message.type === 'DELETE_CONVERSATION') {
91-
const token = await getChatGptAccessToken()
92-
const data = message.data
93-
await deleteConversation(token, data.conversationId)
94-
} else if (message.type === 'OPEN_URL') {
95-
const data = message.data
96-
openUrl(data.url)
97-
} else if (message.type === 'REFRESH_MENU') {
98-
refreshMenu()
103+
let token
104+
switch (message.type) {
105+
case 'FEEDBACK':
106+
token = await getChatGptAccessToken()
107+
await sendMessageFeedback(token, message.data)
108+
break
109+
case 'DELETE_CONVERSATION':
110+
token = await getChatGptAccessToken()
111+
await deleteConversation(token, message.data.conversationId)
112+
break
113+
case 'OPEN_URL':
114+
openUrl(message.data.url)
115+
break
116+
case 'REFRESH_MENU':
117+
refreshMenu()
118+
break
119+
case 'PIN_TAB':
120+
let tabId
121+
if (message.data.tabId) tabId = message.data.tabId
122+
else {
123+
const currentTab = (await Browser.tabs.query({ active: true, currentWindow: true }))[0]
124+
if (message.data.saveAsChatgptConfig) {
125+
if (currentTab.url.includes('chat.openai.com')) tabId = currentTab.id
126+
} else {
127+
tabId = currentTab.id
128+
}
129+
}
130+
if (tabId) {
131+
await Browser.tabs.update(tabId, { pinned: true })
132+
if (message.data.saveAsChatgptConfig) await setUserConfig({ chatgptTabId: tabId })
133+
}
134+
break
99135
}
100136
})
101137

src/config/index.mjs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ export const defaultConfig = {
132132
],
133133
accessToken: '',
134134
tokenSavedOn: 0,
135+
chatgptTabId: 0,
135136

136137
// unchangeable
137138

src/content-script/index.jsx

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@ import DecisionCard from '../components/DecisionCard'
55
import { config as siteConfig } from './site-adapters'
66
import { config as toolsConfig } from './selection-tools'
77
import { config as menuConfig } from './menu-tools'
8-
import { getPreferredLanguageKey, getUserConfig, setAccessToken } from '../config/index.mjs'
8+
import {
9+
chatgptWebModelKeys,
10+
getPreferredLanguageKey,
11+
getUserConfig,
12+
setAccessToken,
13+
} from '../config/index.mjs'
914
import {
1015
createElementAtPosition,
1116
cropText,
@@ -16,8 +21,10 @@ import FloatingToolbar from '../components/FloatingToolbar'
1621
import Browser from 'webextension-polyfill'
1722
import { getPreferredLanguage } from '../config/language.mjs'
1823
import '../_locales/i18n-react'
19-
import { changeLanguage } from 'i18next'
24+
import { changeLanguage, t } from 'i18next'
2025
import { initSession } from '../services/init-session.mjs'
26+
import { getChatGptAccessToken, registerPortListener } from '../services/wrappers.mjs'
27+
import { generateAnswersWithChatgptWebApi } from '../services/apis/chatgpt-web.mjs'
2128

2229
/**
2330
* @param {SiteConfig} siteConfig
@@ -293,6 +300,35 @@ async function overwriteAccessToken() {
293300
}
294301
}
295302

303+
async function prepareForForegroundRequests() {
304+
if (location.hostname !== 'chat.openai.com') return
305+
306+
const div = document.createElement('div')
307+
div.innerText = t('Please keep this tab open. You can now use the web mode of ChatGPTBox')
308+
div.style.position = 'fixed'
309+
div.style.top = '25px'
310+
div.style.right = '25px'
311+
div.style.zIndex = '2147483647'
312+
div.style.padding = '4px 10px'
313+
div.style.border = '1px solid'
314+
div.style.borderRadius = '4px'
315+
document.body.append(div)
316+
317+
await Browser.runtime.sendMessage({
318+
type: 'PIN_TAB',
319+
data: {
320+
saveAsChatgptConfig: true,
321+
},
322+
})
323+
324+
registerPortListener(async (session, port) => {
325+
if (chatgptWebModelKeys.includes(session.modelName)) {
326+
const accessToken = await getChatGptAccessToken()
327+
await generateAnswersWithChatgptWebApi(port, session.question, session, accessToken)
328+
}
329+
})
330+
}
331+
296332
async function run() {
297333
await getPreferredLanguageKey().then((lang) => {
298334
changeLanguage(lang)
@@ -305,6 +341,7 @@ async function run() {
305341
})
306342

307343
await overwriteAccessToken()
344+
await prepareForForegroundRequests()
308345

309346
prepareForSelectionTools()
310347
prepareForSelectionToolsTouch()

src/popup/Popup.jsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ function GeneralPart({ config, updateConfig }) {
271271
lang,
272272
},
273273
})
274-
.catch(() => ({}))
274+
.catch(() => {})
275275
})
276276
})
277277
}}

src/services/apis/chatgpt-web.mjs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { isEmpty } from 'lodash-es'
55
import { chatgptWebModelKeys, getUserConfig, Models } from '../../config/index.mjs'
66
import { pushRecord, setAbortController } from './shared.mjs'
77
import Browser from 'webextension-polyfill'
8+
import { v4 as uuidv4 } from 'uuid'
89

910
async function request(token, method, path, data) {
1011
const apiUrl = (await getUserConfig()).customChatGptWebApiUrl
@@ -54,6 +55,11 @@ export async function getModels(token) {
5455
* @param {string} accessToken
5556
*/
5657
export async function generateAnswersWithChatgptWebApi(port, question, session, accessToken) {
58+
session.messageId = uuidv4()
59+
if (session.parentMessageId == null) {
60+
session.parentMessageId = uuidv4()
61+
}
62+
5763
const { controller, messageListener } = setAbortController(port, null, () => {
5864
if (session.autoClean) deleteConversation(accessToken, session.conversationId)
5965
})
@@ -68,20 +74,23 @@ export async function generateAnswersWithChatgptWebApi(port, question, session,
6874
models && models.includes(selectedModel) ? selectedModel : Models[chatgptWebModelKeys[0]].value
6975
console.debug('usedModel', usedModel)
7076

71-
const cookie = (await Browser.cookies.getAll({ url: 'https://chat.openai.com/' }))
72-
.map((cookie) => {
73-
return `${cookie.name}=${cookie.value}`
74-
})
75-
.join('; ')
77+
let cookie
78+
if (Browser.cookies && Browser.cookies.getAll)
79+
cookie = (await Browser.cookies.getAll({ url: 'https://chat.openai.com/' }))
80+
.map((cookie) => {
81+
return `${cookie.name}=${cookie.value}`
82+
})
83+
.join('; ')
7684

7785
let answer = ''
7886
await fetchSSE(`${config.customChatGptWebApiUrl}${config.customChatGptWebApiPath}`, {
7987
method: 'POST',
8088
signal: controller.signal,
89+
credentials: 'include',
8190
headers: {
8291
'Content-Type': 'application/json',
8392
Authorization: `Bearer ${accessToken}`,
84-
Cookie: cookie,
93+
...(cookie && { Cookie: cookie }),
8594
},
8695
body: JSON.stringify({
8796
action: 'next',

0 commit comments

Comments
 (0)