Chrome Extension Message passing: response not sent

前端 未结 3 1859
挽巷
挽巷 2020-11-21 06:14

I am trying to pass messages between content script and the extension

Here is what I have in content-script

chrome.runtime.sendMessage({type: \"getUr         


        
3条回答
  •  自闭症患者
    2020-11-21 06:53

    The accepted answer is correct, I just wanted to add sample code that simplifies this. The problem is that the API (in my view) is not well designed because it forces us developers to know if a particular message will be handled async or not. If you handle many different messages this becomes an impossible task because you never know if deep down some function a passed-in sendResponse will be called async or not. Consider this:

    chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
    if (request.method == "method1") {
        handleMethod1(sendResponse);
    }
    

    How can I know if deep down handleMethod1 the call will be async or not? How can someone that modifies handleMethod1 knows that it will break a caller by introducing something async?

    My solution is this:

    chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
    
        var responseStatus = { bCalled: false };
    
        function sendResponse(obj) {  //dummy wrapper to deal with exceptions and detect async
            try {
                sendResponseParam(obj);
            } catch (e) {
                //error handling
            }
            responseStatus.bCalled= true;
        }
    
        if (request.method == "method1") {
            handleMethod1(sendResponse);
        }
        else if (request.method == "method2") {
            handleMethod2(sendResponse);
        }
        ...
    
        if (!responseStatus.bCalled) { //if its set, the call wasn't async, else it is.
            return true;
        }
    
    });
    

    This automatically handles the return value, regardless of how you choose to handle the message. Note that this assumes that you never forget to call the response function. Also note that chromium could have automated this for us, I don't see why they didn't.

提交回复
热议问题