javascript - Passing a response callback via promise between background and content script? -
this question has answer here:
i'm trying inject html template dom of webpage via content script. prefer keep html files in own folder within extension easy maintain. means in order inject template, content script have message background, background send request appropriate folder , return retrieved template via callback. however, content script isn't receiving response background page.
contentscript.js
chrome.runtime.sendmessage({action: "template request"}, function(response) { //this should html console.log(response) //hi, <div>template!</div> });
background.js
chrome.runtime.onmessage.addlistener(function(request, sender, response) { //ignore non-template requests if (request.action !== "template request") return; //start ajax promise gettemplate('templates/foobar.html') .then(function(data) { //we're still in scope of onmessage callback response(data) //but nothing, content script logs no errors console.log(data) //<div>foobar</div> }) .catch(function(err) { //... }); //however... response('hi') //the content script receives response callback response('<div>template!</div>') //the content script can receive , inject jquery. }); function gettemplate(url) { return new promise(function(resolve, reject) { $.ajax({ type: "get", url: url, success: resolve }) }); }
even if pass callback runtime.sendmessage
through 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 template folder in web_accessible_resources
, don't think it's manifest problem. suggestions?
nevermind...you don't need call background script, since chrome.extension.geturl
accessible content script. can 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 }); } }
Comments
Post a Comment