在后台和内容脚本之间通过promise传递一个响应回调
Passing a response callback via promise between background and content script?
我试图通过内容脚本注入一个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
});
}
}
相关文章:
- 如何收集所有发射回调的所有响应
- jQuery post,访问responseType或回调中的响应
- node.js+MySQL;JSON结果-回调问题&没有响应客户端
- 可以't从回调函数内部访问响应
- 回调返回响应,但当在API中发送时,响应在节点JS中显示为空白
- 挂起的回调:在每次回调返回之前返回响应
- Node.JS-如何识别哪个异步HTTPGET响应在回调中返回数据
- 具有一个响应的多个回调-Node JS
- React native:如何将参数传递给手势响应程序回调
- POST 响应未等待回调完成
- Facebook Javascript SDK 响应回调未触发
- GreaseMonkey 和 JQuery AJAX 响应不会以任何形式在回调中幸存下来
- 如何为每个 AJAX 请求/响应事件添加回调
- 节点.js如果我使用 process.send(),请等待回调/响应
- 如何在angularjs中使用factory在GPS检测器函数内部使用$http.post方法时获得回调响应
- 如何在ejb中处理回调响应
- 如何传递javascript回调响应到php
- 向数组添加多个回调响应
- Backbone.Wreqr 请求-响应处理程序的回调响应/状态(完成后)
- Strophejs获得花名册成功回调响应