我正在尝试在内容脚本和扩展名之间传递消息
这是我的内容脚本
chrome.runtime.sendMessage({type: "getUrls"}, function(response) {
console.log(response)
});
在后台脚本中
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "getUrls"){
getUrls(request, sender, sendResponse)
}
});
function getUrls(request, sender, sendResponse){
var resp = sendResponse;
$.ajax({
url: "http://localhost:3000/urls",
method: 'GET',
success: function(d){
resp({urls: d})
}
});
}
现在,如果我在getUrls
函数中的ajax调用之前发送响应,则响应已成功发送,但是在ajax调用的成功方法中,当我发送响应时它不会发送响应,当我进入调试程序时,我可以看到该sendResponse
函数代码中的端口为null 。
从文档中chrome.runtime.onMessage.addListener
:
当事件侦听器返回时,此函数将变为无效,除非您从事件侦听器返回true表示您希望异步发送响应(这将使消息通道向另一端开放,直到调用sendResponse为止)。
因此,您只需要return true;
在调用后添加getUrls
即可指示将异步调用响应函数。
可接受的答案是正确的,我只想添加示例代码以简化此过程。问题在于(我认为)API的设计不当,因为它迫使我们开发人员知道是否将异步处理特定消息。如果您处理许多不同的消息,这将成为不可能完成的任务,因为您永远不知道是否深入了解某些函数的传入sendResponse是否称为异步。考虑一下:
chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
if (request.method == "method1") {
handleMethod1(sendResponse);
}
我怎么知道handleMethod1
电话的深处是否是异步的?进行修改的人如何handleMethod1
知道会通过引入异步内容来中断呼叫者?
我的解决方案是这样的:
chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
var responseStatus = { bCalled: false };
function sendResponse(obj) { //dummy wrapper to deal with exceptions and detect async
try {
sendResponseParam(obj);
} catch (e) {
//error handling
}
responseStatus.bCalled= true;
}
if (request.method == "method1") {
handleMethod1(sendResponse);
}
else if (request.method == "method2") {
handleMethod2(sendResponse);
}
...
if (!responseStatus.bCalled) { //if its set, the call wasn't async, else it is.
return true;
}
});
无论您选择如何处理消息,这都会自动处理返回值。请注意,这假设您永远不会忘记调用响应函数。还请注意,铬可能为我们实现了自动化,我不明白为什么他们没有这样做。
您可以使用我的库https://github.com/lawlietmester/webextension使Chrome和FF结合使用Firefox和Firefox,而无需回调。
您的代码如下所示:
Browser.runtime.onMessage.addListener( request => new Promise( resolve => {
if( !request || typeof request !== 'object' || request.type !== "getUrls" ) return;
$.ajax({
'url': "http://localhost:3000/urls",
'method': 'GET'
}).then( urls => { resolve({ urls }); });
}) );
本文地址:http://javascript.askforanswer.com/chromekuozhanchengxuxiaoxichuandiweifasongxiangying.html
文章标签:google-chrome , google-chrome-app , google-chrome-extension , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
文章标签:google-chrome , google-chrome-app , google-chrome-extension , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!