通过后台和内容脚本之间的承诺传递响应回调?

时间:2015-06-04 17:30:37

标签: javascript google-chrome-extension

我试图通过内容脚本将html模板注入网页的DOM中。我更喜欢将html文件保存在扩展中的自己的文件夹中,以便它们易于维护。这意味着,为了注入模板,内容脚本必须向后台发送消息,然后后台将向适当的文件夹发送get请求,并通过回调返回检索到的模板。但是,内容脚本没有从后台页面接收响应。

contentscript.js

chrome.runtime.sendMessage({action: "template request"}, function(response) {
    //this should be html
    console.log(response) //hi, <div>template!</div>
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, response) {

    //ignore all non-template requests
    if (request.action !== "template request") return;

    //start the ajax promise
    getTemplate('templates/foobar.html')
        .then(function(data) {
            //we're still in the scope of the onMessage callback
            response(data) //but this does nothing, content script logs no errors
            console.log(data) //<div>foobar</div>
        })
        .catch(function(err) {
            //...
        });

    //however...
    response('hi') //the content script successfully receives this response callback
    response('<div>template!</div>') //the content script can also successfully receive this and inject it with jquery.
});

function getTemplate(url) {
    return new Promise(function(resolve, reject) {
        $.ajax({ 
            type: "GET",
            url: url,
            success: resolve
        })
    });
}

即使我通过ajax承诺从runtime.sendMessage传递回调,也没有任何反应

getTemplate('templates/foobar.html', responseCallback)
    .then(function(obj) {
        obj.callback(obj.data) //does nothing
    });

function getTemplate(url, callback) {
    return new Promise(function(resolve, reject) {
        $.ajax({ 
            type: "GET", 
            url: url, 
            success: function(data) {
                resolve({data: data, callback: callback})
            } 
        })
    }
}

我已将web_accessible_resources中的模板文件夹包含在内,因此我认为这不是一个明显的问题。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

没关系......你甚至不需要调用后台脚本,因为内容脚本可以访问chrome.extension.getURL。所以你可以这样做:

<强> contentsript.js

getTemplate('templates/template.html')
    .then(function(html) {
        var el = $(html);
        $('body').append(el);
    });

function getTemplate(url) {
    return new Promise(function(resolve, reject) {
        $.ajax({
            type: "GET",
            url: chrome.extension.getURL(url),
            success: resolve
        });
    }
}