0
我試圖通過內容腳本將html模板注入到網頁的DOM中。我更喜歡將html文件保存在擴展名中的自己的文件夾中,以便易於維護。這意味着爲了注入一個模板,內容腳本將不得不向後臺發送消息,然後後臺會向適當的文件夾發送一個獲取請求,並通過回調返回檢索到的模板。但是,內容腳本未收到來自後臺頁面的響應。通過背景和內容腳本之間的承諾傳遞響應回調?
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
中包含了模板文件夾,所以我不認爲這是一個明顯的問題。有什麼建議麼?