在后台和内容脚本之间通过promise传递一个响应回调

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

本文关键字:回调 响应 一个 promise 后台 脚本 之间      更新时间:2023-09-26

我试图通过内容脚本注入一个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
        })
    });
}

即使我从runtime.sendMessage通过ajax承诺传递回调,什么也没有发生

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
        });
    }
}