Search code examples
google-chromegoogle-chrome-extensionmessage-passing

chrome extensions: extension.sendRequest (message passing) to same page?


is it possible to send a request using message passing api to the same page that will be listening to it? it dosen't seem to work!

One solution is to setup a listener on some other page and then redirect the request back to the parent page. But it is a hack and i really dont want to do that :(

EDIT (updated)

background.html (0)

chrome.extension.sendRequest({action:'foo'}, function(response) {
    //do stuff
});

index.html (1)

chrome.extension.sendRequest({action:'foo'}, function(response) {
    //do stuff
});

background.html (2)

chrome.extension.onRequest.addListener(function(request,sender,sendResponse) {
    if(request.action=='foo') //do stuff
});
...
...
//the code form (0)

from above (1) works but (0) does not :(

EDIT 2

from (2)

chrome.extension.onRequest.addListener(function(request,sender,sendResponse) {
    switch(request.action) {
        case 'foo': //do some stuff here
        break;
    }
});

The above switch has grown rather long.. some 30 entries i guess.. plus there is no way to call the switch other than poking the eventlistener. (or am i missing something?)

i want to execute the case 'foo':'s code somewhere below it in the same file hence i tried calling it in (0).


Solution

  • As you found out already you can't really send a request to the same page, so as a workaround I would do the following:

    function requestHandler(request, sendResponse) {
        switch(request.action) {
            case 'foo':
                sendResponse(true);
                break;
            }
    }
    
    chrome.extension.onRequest.addListener(function(request,sender,sendResponse) {
        requestHandler(request, sendResponse);
    });
    
    //calling handler directly
    requestHandler({action:"foo"}, function(result) {
        //response
    });