From 4ba3a9028b20b1ebaf0f1710d2f5d4e26de2e251 Mon Sep 17 00:00:00 2001 From: Jin Date: Sun, 14 Jul 2024 22:50:53 +0700 Subject: [PATCH] We won't share messages between tabs; each tab will be a separate chat. --- background.js | 187 ++++++++++++++++++++++++++++++++++++++++++-------- content.js | 118 +++++++------------------------ manifest.json | 3 +- 3 files changed, 184 insertions(+), 124 deletions(-) diff --git a/background.js b/background.js index 71190aa..218b434 100644 --- a/background.js +++ b/background.js @@ -1,13 +1,82 @@ -chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { - //console.log('Request received in background.js:', request); +function clearTabStorage(tabId){ + let tabIdKey = `store_tab_${tabId}`; + var obj = {}; + obj[tabIdKey] = []; + chrome.storage.local.set(obj); +} + + +function setTabItems(tabId, items, cb){ + let tabIdKey = `store_tab_${tabId}`; + + chrome.storage.local.get([tabIdKey]).then(result => { + const tabObject = result[tabIdKey] || {}; + Object.keys(items).forEach(itemName => { + tabObject[itemName] = items[itemName]; + }); - // if (request.type === 'getSelectedText') { - // const selectedText = window.getSelection().toString(); - // sendResponse({ selectedText: selectedText }); - // } + let setObj = {}; + setObj[tabIdKey] = tabObject; - if (request.type === 'summarize' || request.type === 'translate'|| request.type === 'correct-english' || request.type === 'teach-me' || request.type === 'simple-chat') { + chrome.storage.local.set(setObj).then(() =>{ + cb && cb(); + }); + }); +} +chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { + + if (request.type === 'getTabItems') { + let tabIdKey = `store_tab_${sender.tab.id}`; + + chrome.storage.local.get([tabIdKey]).then(result => { + const items = {}; + (request.itemNames || []).forEach(itemName => { + items[itemName] = result[tabIdKey] && result[tabIdKey][itemName]; + }); + sendResponse(items); + }) + + return true; + } else if (request.type === 'setTabItems') { + + let tabIdKey = `store_tab_${sender.tab.id}`; + chrome.storage.local.get(tabIdKey).then(result => { + const tabObject = result[tabIdKey] || {}; + Object.keys(request.itemNames).forEach(itemName => { + tabObject[itemName] = request.itemNames[itemName]; + }); + + let setObj = {}; + setObj[tabIdKey] = tabObject; + chrome.storage.local.set(setObj).then(()=>{ + sendResponse({ result: 'success' }); + }); + }); + + return true; + } else if (request.type === 'removeTabItems') { + + let tabIdKey = `store_tab_${sender.tab.id}`; + chrome.storage.local.get(tabIdKey).then(result => { + const tabObject = result[tabIdKey]; + if (tabObject) { + request.itemNames.forEach(itemName => { + delete tabObject[itemName]; + }); + + let setObj = {}; + setObj[tabIdKey] = tabObject; + chrome.storage.local.set(setObj).then(()=>{ + sendResponse({ result: 'success' }); + }); + } + }); + + return true; + } + else if (request.type === 'summarize' || request.type === 'translate'|| request.type === 'correct-english' || request.type === 'teach-me' || request.type === 'simple-chat') + { /* request: { type: command type, e.g summarize, translate, correct-english @@ -298,13 +367,25 @@ ${request.selectionText}` content: msg }); - chrome.storage.local.set({ - defaultMessages: defaultMessages, - lastSelectedCommand: request.type, - chatMessages: requestObj.messages - }, () => { - sendResponse({ result: msg }); + setTabItems(sender.tab.id, { + defaultMessages: defaultMessages, + lastSelectedCommand: request.type, + chatMessages: requestObj.messages + }, ()=>{ + sendResponse({ result: msg }); }); + // chrome.tabs.sendMessage(sender.tab.id, { + // type: 'setTabItems', + // itemNames: { + // defaultMessages: defaultMessages, + // lastSelectedCommand: request.type, + // chatMessages: requestObj.messages + // } + // }, res => { + // sendResponse({ result: msg }); + // }); + // return true; + } else { let msg = data.error.message; requestObj.messages.push({ @@ -312,14 +393,26 @@ ${request.selectionText}` content: msg }); - chrome.storage.local.set({ - defaultMessages: defaultMessages, - lastSelectedCommand: request.type, - chatMessages: requestObj.messages - }, () => { - sendResponse({ error: msg }); + setTabItems(sender.tab.id, { + defaultMessages: defaultMessages, + lastSelectedCommand: request.type, + chatMessages: requestObj.messages + }, ()=>{ + sendResponse({ error: msg }); }); - + + // chrome.tabs.sendMessage(sender.tab.id, { + // type: 'setTabItems', + // itemNames: { + // defaultMessages: defaultMessages, + // lastSelectedCommand: request.type, + // chatMessages: requestObj.messages + // } + // }, res => { + // sendResponse({ error: msg }); + // }); + + return true; } }) .catch(error => { @@ -332,13 +425,26 @@ ${request.selectionText}` content: msg }); - chrome.storage.local.set({ - defaultMessages: defaultMessages, - lastSelectedCommand: request.type, - chatMessages: requestObj.messages - }, () => { - sendResponse({ error: msg }); + setTabItems(sender.tab.id, { + defaultMessages: defaultMessages, + lastSelectedCommand: request.type, + chatMessages: requestObj.messages + }, ()=>{ + sendResponse({ error: msg }); }); + + // chrome.tabs.sendMessage(sender.tab.id, { + // type: 'setTabItems', + // itemNames: { + // defaultMessages: defaultMessages, + // lastSelectedCommand: request.type, + // chatMessages: requestObj.messages + // } + // }, res => { + // sendResponse({ error: msg }); + // }); + + return true; }); return true; @@ -399,10 +505,11 @@ chrome.contextMenus.onClicked.addListener((info, tab) => { info.menuItemId === 'simple-chat' ) { - // reset chat message - chrome.storage.local.set({ - chatMessages: [] - }, () => { + //reset chat message + setTabItems(tab.id, { + chatMessages: [] + }, ()=>{ + }); // Send the message to the content script @@ -419,6 +526,26 @@ chrome.contextMenus.onClicked.addListener((info, tab) => { // alert(response.result); // } }); + + // clearTabStorage(tab.id); + + // chrome.tabs.sendMessage(tab.id, { + // type: 'setTabItems', + // itemNames: {chatMessages: []} + // }, res => {}); + + } +}); + +// Listen for tab updates +chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { + // Set a default value for the tab + //setTabItemValue(tabId, 'foo', 'bar'); +}); + +// Listen for tab removals +chrome.tabs.onRemoved.addListener(function(tabId) { + clearTabStorage(tabId); }); \ No newline at end of file diff --git a/content.js b/content.js index d5c9e30..8a98454 100644 --- a/content.js +++ b/content.js @@ -48,7 +48,7 @@ const playAudio = (audioUrl) => { audioElement.play(); }; -chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { + chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { // if (request.type === 'getSelectedText') { // const selectedText = window.getSelection().toString(); @@ -90,7 +90,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { } // Listen for messages from the context menu - if (request.type === 'simple-chat') { + if (request.type === 'simple-chat') { let modal = document.querySelector('.my-extension-modal'); // Create modal if it doesn't exist @@ -135,8 +135,10 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { clearAllMessagesHtml(); } - chrome.storage.local.get(['defaultMessages'], (items) => { - const defaultMessages = items.defaultMessages; + chrome.runtime.sendMessage({ type: 'getTabItems', itemNames: ['defaultMessages'] }, storageResponse => { + //console.log(storageResponse.value); // outputs "bar" + + const defaultMessages = storageResponse.defaultMessages; if (response.error) { //console.error(response.error); @@ -404,9 +406,9 @@ function addMessageIntoModal(request, role, rawMessage, hideDefaultMessage, isEr } } - chrome.storage.local.get(['lastSelectedCommand', 'chatMessages'], (items) => { - const memoryMessages = items.chatMessages; - const lastSelectedCommand = items.lastSelectedCommand; + chrome.runtime.sendMessage({ type: 'getTabItems', itemNames: ['lastSelectedCommand', 'chatMessages'] }, (storageResponse) => { + const memoryMessages = storageResponse.chatMessages; + const lastSelectedCommand = storageResponse.lastSelectedCommand; if (messagesArray.length > 0){ memoryMessages.splice(newestUserMessageIndex + 1, memoryMessages.length - (newestUserMessageIndex + 1)); @@ -440,10 +442,8 @@ function addMessageIntoModal(request, role, rawMessage, hideDefaultMessage, isEr if (response.error) { // update message list - chrome.storage.local.set({ - chatMessages: memoryMessages - }, () => { - }); + + chrome.runtime.sendMessage({ type: 'setTabItems', itemNames: {chatMessages: memoryMessages} }, (res) => {}); //console.error(response.error); addMessageIntoModal(request, 'assistant', response.error, false, true); @@ -459,16 +459,12 @@ function addMessageIntoModal(request, role, rawMessage, hideDefaultMessage, isEr //console.log(memoryMessages); // update message list - chrome.storage.local.set({ - chatMessages: memoryMessages - }, () => { - }); - + chrome.runtime.sendMessage({ type: 'setTabItems', itemNames: {chatMessages: memoryMessages} }, (res) => {}); // Display the result on the webpage addMessageIntoModal(request, 'assistant', response.result, false, false); } }); - }) + }); }); // const actionDeleteButton = document.createElement('button'); @@ -540,9 +536,10 @@ function addMessageIntoModal(request, role, rawMessage, hideDefaultMessage, isEr } // trigger send button - chrome.storage.local.get(['lastSelectedCommand', 'chatMessages'], (items) => { - let lastSelectedCommand = items.lastSelectedCommand; - let memoryMessages = items.chatMessages; + + chrome.runtime.sendMessage({ type: 'getTabItems', itemNames: ['lastSelectedCommand', 'chatMessages'] }, (storageResponse) => { + let lastSelectedCommand = storageResponse.lastSelectedCommand; + let memoryMessages = storageResponse.chatMessages; let role = "user"; @@ -564,63 +561,9 @@ function addMessageIntoModal(request, role, rawMessage, hideDefaultMessage, isEr }); // save new list messages into memory - chrome.storage.local.set({ - chatMessages: memoryMessages - }, () => { - }); - - // if (role == "assistant"){ - - // } - // else { - // showLoadingIndicator(); - - // if (request.type === 'simple-chat'){ - // lastSelectedCommand = 'simple-chat'; - // } - - // chrome.runtime.sendMessage({ - // type: lastSelectedCommand, - // messages: memoryMessages - // }, (response) => { - - // // Hide loading indicator when response is received - // hideLoadingIndicator(); - - // if (response.error) { - // // update message list - // chrome.storage.local.set({ - // chatMessages: memoryMessages - // }, () => { - // }); - - // //console.error(response.error); - // addMessageIntoModal(request, 'assistant', response.error, false, true); - // // Handle error, maybe show an error message on the page - // } else { - // memoryMessages.push({ - // role: "assistant", - // content: response.result - // }); - - // // update message list - // chrome.storage.local.set({ - // chatMessages: memoryMessages - // }, () => { - // }); - - // //console.log(memoryMessages); - - // //addMessageIntoModal(request, 'user', nextMessage, false); - - // // Display the result on the webpage - // addMessageIntoModal(request, 'assistant', response.result, false, false); - // } - // }); - // } + chrome.runtime.sendMessage({ type: 'setTabItems', itemNames: {chatMessages: memoryMessages} }, (res) => {}); }); } - }); const actionCopyButton = document.createElement('button'); @@ -1221,12 +1164,7 @@ function createModal(request) { const container = modal.shadowRoot.querySelector('.chat-messages') container.innerHTML = ''; - chrome.storage.local.set({ - lastSelectedCommand: undefined, - chatMessages: [] - }, () => { - }); - + chrome.runtime.sendMessage({ type: 'setTabItems', itemNames: {lastSelectedCommand: undefined,chatMessages: []} }, (res) => {}); }); const maximizeButton = shadow.querySelector('.maximize-dialog-button'); @@ -1262,9 +1200,9 @@ function createModal(request) { }); shadow.querySelector('.send-button').addEventListener('click', () => { - chrome.storage.local.get(['lastSelectedCommand', 'chatMessages'], (items) => { - let lastSelectedCommand = items.lastSelectedCommand; - let memoryMessages = items.chatMessages; + chrome.runtime.sendMessage({ type: 'getTabItems', itemNames: ['lastSelectedCommand', 'chatMessages'] }, (storageResponse) => { + let lastSelectedCommand = storageResponse.lastSelectedCommand; + let memoryMessages = storageResponse.chatMessages; const chatInput = shadow.querySelector('.chat-input'); @@ -1304,10 +1242,7 @@ function createModal(request) { if (response.error) { // update message list - chrome.storage.local.set({ - chatMessages: memoryMessages - }, () => { - }); + chrome.runtime.sendMessage({ type: 'setTabItems', itemNames: {chatMessages: memoryMessages} }, (res) => {}); //console.error(response.error); addMessageIntoModal(request, 'assistant', response.error, false, true); @@ -1319,11 +1254,8 @@ function createModal(request) { }); // update message list - chrome.storage.local.set({ - chatMessages: memoryMessages - }, () => { - }); - + chrome.runtime.sendMessage({ type: 'setTabItems', itemNames: {chatMessages: memoryMessages} }, (res) => {}); + //console.log(memoryMessages); //addMessageIntoModal(request, 'user', nextMessage, false); diff --git a/manifest.json b/manifest.json index b7cddef..b92a9f3 100644 --- a/manifest.json +++ b/manifest.json @@ -5,7 +5,8 @@ "description": "Summarize and translate web pages and selected text.", "permissions": [ "storage", - "contextMenus" + "contextMenus", + "activeTab" ], "background": { "service_worker": "background.js"