非同步傳送響應

為了嘗試從 chrome.runtime.onMessage 回撥非同步傳送響應,我們可能會嘗試這個錯誤的程式碼

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    $.ajax({
        url: 'https://www.google.com',
        method: 'GET',
        success: function(data) {
            // data won't be sent
            sendResponse(data);
        },
    });
});

但是,我們會發現 data 永遠不會傳送。發生這種情況是因為我們已將 sendResponse 置於非同步 ajax 呼叫中,當執行 success 方法時,訊息通道已關閉。

**解決方案很簡單,**只要我們在回撥結束時明確表示我們希望非同步傳送響應,這樣訊息通道將保持開啟到另一端(呼叫者)直到執行 sendResponse

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    $.ajax({
        url: 'https://www.google.com',
        method: 'GET',
        success: function(data) {
            // data would be sent successfully
            sendResponse(data);
        },
    });

    return true; // keeps the message channel open until `sendResponse` is executed
});

當然,它也適用於 onMessage 回撥中的顯式 return

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action == 'get') {
        $.ajax({
            url: 'https://www.google.com',
            method: 'GET',
            success: function(data) {
                // data would be sent successfully
                sendResponse(data);
            },
        });

        return true; // keeps the message channel open until `sendResponse` is executed
    }

    // do something synchronous, use sendResponse

    // normal exit closes the message channel
});