chrome瀏覽器外掛/擴充套件開發之popup與background通訊

FacingScreen發表於2024-07-15

chrome瀏覽器外掛/擴充套件開發之popup與background的雙向通訊,這塊東西太雜,看文件折騰了一天。。。做個記錄吧。

popup.js

const sendMessage = ({ type, data, callback }) => {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            const tabId = tabs[0].id;            
            const port = chrome.tabs.connect(tabId, { name: 'NetWatchConn' });
            // 這裡順帶監聽了訊息並執行回撥
            port.onMessage.addListener((evt) => {
                // console.log('[NetWatch]: popup.js onMessage', evt.type, evt);
                if (callback && evt.type == type) {
                    callback(evt.data);
                }
            });
            port.postMessage({ type, data, callback });
        });
    }

    // 從content_scripts獲取狀態
    sendMessage({
        type: 'getStatus',
        data: {},
        callback: (data) => {
            // console.log('[NetWatch]: getStatus ', data);
            const { running } = data;
            setRuningMsg(running);
        }
    });

background.js

let running = false;
chrome.runtime.onConnect.addListener((port) => {
    console.log('[NetWatch]: connect to content_scripts', port);

    // const sendMessage = port.postMessage;
    port.onMessage.addListener((evt, sender) => {
        const {type, data, callback} = evt;
        // const sendMessage = sender.postMessage;
        console.log("In background script, received message", type, data);

        switch (type) {
            case 'getStatus':
                port.postMessage({type, data: {running}});
                break;
            case 'start':
                running = true;
                port.postMessage({type, data: {running}});
                break;
            case 'stop':
                running = false;
                port.postMessage({type, data: {running}});
                break;
        }
    });
});

相關文章