iT邦幫忙

0

Chrome extention 頁面間的溝通問題

  • 分享至 

  • xImage

新手上路請各路大神多指教
目前初學 react 想做做看自己的 google extention
以下是其中一個片段
想在 Override Page 中儲存 to do list 並且在設定的提醒時間發出提醒訊息
但為了避免像目前 background.ts 中那種不斷向 api 要資料的情形,想將兩個頁面之間的溝通改成類似 socket 的方式,在資料被更動的時候像其他頁面發送更新資料的指示即可。目前在文件中找到的方式應該是 Chrome.runtime 中的方法最接近我想要做的事,但是無論怎麼做都無法順利溝通,附上兩邊的程式碼跟功能相關的部分

background.ts

const todoListPort = chrome.runtime.connect({ name: "todo" });
console.log(todoListPort);
todoListPort.onMessage.addListener((res)=>{
  console.log(res);
})
...
chrome.alarms.onAlarm.addListener((alarm)=>{
  const now = Date.now();
  if(alarm.name="TodoListReminder"){
    chrome.storage.sync.get(['todoList'], function (result) {
      if(result.todoList){
        let tempList = [];
        result.todoList.forEach((todo: todo)=>{
          if(todo.isSetAlert && !todo.alertSend && (Date.parse(`${todo.alertDate} ${todo.alertTime}`)<now)){
            this.registration.showNotification("To do list reminder",{
              body: `The set time of work item "${todo.workContent}" has passed`,
              icon: "logo.png"
            })
            const tempTodo = {...todo}
            tempTodo.alertSend = true;
            tempList.push(tempTodo)
            todoListPort.postMessage({msg: "update"})
          } else {
            tempList.push(todo);
          }        
        })
        chrome.storage.sync.set({ todoList: tempList }, function () {
          console.log("set");
        });
      }
      
    });
  }  
})

toDoListPanel.tsx
uesEffect 內是兩種目前試的方式,但直覺就覺得不對,可是也不知道怎麼寫,有請大神指教

export const ToDoListPanel: React.FC<{ tebInfo: { id: number; }; }> = (props) => {
const toDoListPort = useRef(null);

function delTodo(id: number) {
    const tempWorkList = workList.filter((todo) => todo.id !== id);
    chrome.storage.sync.set({ todoList: tempWorkList }, function () {
      setWorkList(tempWorkList);
    });
    toDoListPort.current.postMessage({ msg: "update" });
  }

useEffect(() => {
    chrome.storage.sync.get(['todoList'], function (result) {
      setWorkList(result.todoList);
    });
    const queryOptions = { active: true, lastFocusedWindow: true };
    chrome.tabs.query(queryOptions).then((res) => {
      toDoListPort.current = chrome.tabs.connect(res[0].id, { name: "todo" });
      toDoListPort.current.onMessage.addListener(function (res: { msg: string; }) {
        console.log(res);
        if (res.msg === "update") {
          console.log("todolist panel update");
        }
      });
    });
    // toDoListPort.current = chrome.runtime.connect({ name: "todo" });
    // toDoListPort.current.onMessage.addListener(function (res: { msg: string; }) {
    //   console.log(res);
    //   if (res.msg === "update") {
    //     console.log("todolist panel update");
    //   }
    // });
  }, []);
  
  return(
  <WorksPanel>
      To do list
      {workList && workList.map((item: todo) => {
        return <ToDoItem key={item.id} changeIsDone={changeIsDone} delTodo={delTodo} setTempTodo={setTempTodo} item={item as todo} setIsEditOn={setIsEditOn}></ToDoItem>;
      })

      });
      </WorksPanel >

manifest.json

"permissions":["storage", "alarms", "notifications", "identity", "identity.email", "contextMenus", "bookmarks", "search", "tabs", "nativeMessaging","tts"],

不確定這樣的描述夠不夠詳細,第一次發文,再請幫忙了!

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答