0

I'm trying to inject an html template into the DOM of a webpage via a content script. I prefer to keep the html files in their own folder within the extension so that they are easy to maintain. This means that in order to inject a template, the content script will have to message the background, where the background will then send a get request to the appropriate folder and return the retrieved template via callback. However, the content script isn't receiving the response from the background page.

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

Even if I pass the callback from runtime.sendMessage through the ajax promise, nothing happens

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

I've included the template folder in web_accessible_resources, so I don't think it's a manifest problem. Any suggestions?

Daniel Lizik
  • 3,058
  • 2
  • 20
  • 42

1 Answers1

0

Nevermind...you don't even need to call a background script, since chrome.extension.getURL is accessible to the content script. So you can just do this:

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
        });
    }
}
Daniel Lizik
  • 3,058
  • 2
  • 20
  • 42