0

Why sendResponse({ helloWorld: sendto }) sending back empty string and not that this.responseText is assigned to sendto variable? How to manage my code properly to achieve sending back this.responseText and not the empty string?

chrome.runtime.onMessage.addListener(

        function (request, sender, sendResponse) {
            **var sendto = 'empty';**
            var ccc = new XMLHttpRequest();
            ccc.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    console.log(this.responseText)
                    **sendto = this.responseText;**




                }
            }
            ccc.open("GET", "http://127.0.0.1:3000/" + request.greeting)
            ccc.send();

            **sendResponse({ helloWorld: sendto });**

        });
user18984
  • 57
  • 1
  • 9

1 Answers1

-1

You need to add return true; to the listener function in order to use sendResponse asynchronously. For example:

chrome.runtime.onMessage.addListener(

    function (request, sender, sendResponse) {
        var ccc = new XMLHttpRequest();
        ccc.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText)
                sendResponse({helloWorld: this.responseText});
            }
        };

        ccc.open("GET", "http://127.0.0.1:3000/" + request.greeting)
        ccc.send();

        return true;  // in order to use sendResponse asynchronously

    });
Iván Nokonoko
  • 4,888
  • 2
  • 19
  • 27