异步发送响应

为了尝试从 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
});