javascript – 未调用chrome.tabs.sendMessage回调函数.为什么?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 未调用chrome.tabs.sendMessage回调函数.为什么?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2107字,纯文字阅读大概需要4分钟。
内容图文
我有从Chrome扩展程序的后台脚本调用的以下方法.目标是将消息发送到特定选项卡,然后使用结果调用提供的回调方法.重要的是,必须始终在某个时间点调用callbackDone.所以它是这样的:
function sendToTab(nTabID, callbackDone)
{
(function()
{
chrome.tabs.sendMessage(nTabID, {
action: "update01"
},
function(response)
{
if(chrome.runtime.lastError)
{
//Failed to send message to the page
if(callbackDone)
callbackDone(nTabID, null); //Page never received the message
}
else
{
//Sent message OK
if(response.result === true)
{
if(callbackDone)
callbackDone(nTabID, true); //Success!
}
else
{
if(callbackDone)
callbackDone(nTabID, false); //Page returns failure
}
}
});
}());
}
然后从处理消息的页面(可以是注入的内容脚本)中我处理它:
chrome.runtime.onMessage.addListener(onMessageProc);
function onMessageProc(request, sender, sendResponse)
{
if(request.action == "update01")
{
//Do processing .... that sets `bResult`
sendResponse({result: bResult});
}
}
上面的方法工作得很好,除了…说,有一个页面,如选项页面脚本,不处理我的update01消息,而是处理自己的消息:
chrome.runtime.onMessage.addListener(onMessageProc);
function onMessageProc(request, sender, sendResponse)
{
if(request.action == "update02") //Note different action ID
{
//Does some other actions...
}
}
在这种情况下,为此选项卡调用我的第一个sendToTab方法时,我的callbackDone永远不会被调用,即调用chrome.tabs.sendMessage并立即返回,但从不调用其回调函数.
那我在这里错过了什么?
解决方法:
你看到了预期的行为.
documentation状态,关于回调函数:
If you specify the responseCallback parameter, it should be a function that looks like this:
function(any response) {...};
any response
The JSON response object sent by the handler of the message. If an error occurs while connecting to the specified tab, the callback will be called with no arguments andruntime.lastError
will be set to the error message.
sendMessage执行有3种可能的结果.
>有一个监听器,它叫sendResponse.
然后,以响应作为参数调用回调.
>有一个监听器,它终止而不调用sendResponse(同步或异步).
然后,根本不调用回调.
>发送邮件时出现了某种错误.
然后,调用没有参数的回调并设置chrome.runtime.lastError.
如果你需要在任何情况下执行回调,你需要在监听器中调用sendResponse的“默认”情况.
内容总结
以上是互联网集市为您收集整理的javascript – 未调用chrome.tabs.sendMessage回调函数.为什么?全部内容,希望文章能够帮你解决javascript – 未调用chrome.tabs.sendMessage回调函数.为什么?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。