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

Passing a response callback via promise between background and content script?

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

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 中,所以我认为这不是一个明显的问题。有什么建议吗?

没关系...您甚至不需要调用后台脚本,因为内容脚本可以访问 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
        });
    }
}