' sendResponse'使用来自background.js函数的数据到外部页面

时间:2016-06-29 13:59:08

标签: jquery google-chrome-extension

我有一个外部页面,可以向我的Chrome扩展程序发送消息,后台脚本会获取并响应它。但是,我想首先处理function getID(),然后才将响应(带有ID)发送回外部页面。 我已经尝试:设置$.when()setTimeout等待getID。但没有任何作用,而且响应总是"未定义" ...

有没有等待函数执行,然后才将ID发送回外部页面?!

外部页面(发送消息)

var extID = "pncieomfimcmcbnbnogelnipdnkejmdf";

chrome.runtime.sendMessage(laserExtensionId, {getTargetData: true}, function(response) {
        console.log(response);
});

后台脚本

var id;

function getID(){
    $.get("url1", function( data1 ) {
        //process data1 and use part of data1 on next get       
        $.get("url2", function( data2 ) {
            //process data2 and use part of data2 on next get
            $.get("url3", function( data3 ) {
                //process data3 and return
                return id;
            });
        });
    });
}

chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        getID();
        sendResponse({user: id});       
});

1 个答案:

答案 0 :(得分:2)

cannot return something from asynchronous functions。请在继续之前阅读该问题。

您需要在最后一次回调中调用sendResponse(id)。此外,您通过从处理程序返回trueneed to inform Chrome that you will be doing that asynchronously

function getID(callback){
    $.get("url1", function( data1 ) {
        //process data1 and use part of data1 on next get       
        $.get("url2", function( data2 ) {
            //process data2 and use part of data2 on next get
            $.get("url3", function( data3 ) {
                //process data3 and pass the result to callback
                callback(id);
            });
        });
    });
}

chrome.runtime.onMessageExternal.addListener(function(request, sender, sendResponse) {
    getID(function(id) {
        // Will be called asynchronously from getID()
        sendResponse({user: id});
    });
    return true; // Tell Chrome we need sendResponse asynchronously
});