将功能传递给onreadystatechange

时间:2019-07-13 17:57:47

标签: javascript function xmlhttprequest browser-extension

开发一个浏览器扩展,我需要从popup.js中查询content.js以获取当前窗口/标签中的数字(变量计数)。以下是我的代码,content.js用于使用传递的函数sendresponse将计数返回到popup.js,但是,sendresponseonreadystatechange内部不起作用(请参见下面的评论)-其中我应该正确放置sendresponse来等待onreadystatechange完成吗?

popup.js

browser.tabs.query({active: true, currentWindow: true}, function(tabs)
{
    browser.tabs.sendMessage(tabs[0].id, {type: "getcount"}, function(count)
    {
        console.log("popup.js says count is: " + count);
    });
});

content.js

browser.runtime.onMessage.addListener(

    function(message, sender, sendresponse)
    {
        switch(message.type)
        {
            case "getcount":

                var xmlhttp = new XMLHttpRequest();
                xmlhttp.responseType = 'document';
                xmlhttp.open("GET", window.location.href, true);

                //1. Everything works until here.
                //if for example I call sendresponse(5) here, 5 is 
                //sent back to popup.js 

                //3. However, if I set sendresponse as a function here
                //like this it will work inside the onreadystatechange
                //var sendresponse = function(count) { alert(count); };

                xmlhttp.onreadystatechange = function()
                {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                    {
                      var count = Math.random() * 100;

                      //2. if I call sendresponse(count) here it does not work
                      sendresponse(count);      
                    }
                };

                //send the request
                xmlhttp.send();
            break;

            default:
                console.error("Unrecognised message: ", message);
        }
    }
);

0 个答案:

没有答案