Javascript-浏览器扩展:在浏览器操作弹出窗口和背景脚本之间发送消息(带有响应)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Javascript-浏览器扩展:在浏览器操作弹出窗口和背景脚本之间发送消息(带有响应),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2616字,纯文字阅读大概需要4分钟。
内容图文
![Javascript-浏览器扩展:在浏览器操作弹出窗口和背景脚本之间发送消息(带有响应)](/upload/InfoBanner/zyjiaocheng/667/834e7cbc35a54c558f5e096f15694f1b.jpg)
首先,我不需要长期连接.我正在特别寻找一种发送消息并发送对这些消息的直接响应的方法.
当您在内容脚本和背景脚本之间发送消息时,这很简单,因为您使用chrome.tabs API从内容脚本发送消息/从内容脚本接收消息.并使用chrome.runtime API从/向后台脚本发送/接收消息.
但是对于浏览器操作弹出窗口,则有所不同,因为两者都在后台运行.因此,我想他们俩都必须使用chrome.runtime API.
但这意味着我必须在我的浏览器操作弹出窗口和背景脚本中都收听chrome.runtime.onMessage.因此,基本上,我会在后台脚本中以及在弹出窗口本身中接收从弹出窗口发送的消息.而另一种解决方法是相同的.
是的,这实际上是行不通的:
/////////////background-script//////////////
//Send message from background-script to browser-action-popup
chrome.runtime.sendMessage({msg:"This is a message sent from the background-script to the browser-action-popup"})
.then(response => { //Receive response from the browser-action-popup
console.log(response.msg)
})
//Receive messages from browser-action-popup
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse) {
sendResponse({msg:"This is a response message sent from the background-script"})
return true
})
…
///////////browser-action-popup/////////////
//Send message from browser-action-popup to background-script
chrome.runtime.sendMessage({msg:"This is a message sent from the browser-action-popup to the background-script"})
.then(response => { //Receive response from the background-script
console.log(response.msg)
})
//Receive message from background-script
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse) {
sendResponse({msg:"This is a response message sent from the browser-action-popup"})
return true
})
但是,由于它们都在后台运行,所以我还想知道,有没有比发送消息更简单的方法:是否可以在两者之间共享变量,或者它们完全孤立地运行?
解决方法:
从the docs开始:
If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender’s frame)
因此,您不必担心弹出窗口中的消息会触发弹出窗口中的onMessage事件.
您还可以通过共享变量来寻求另一种交流方式.从弹出窗口中,您可以调用chrome.runtime.getBackgroundPage,以获取背景页面的JavaScript窗口对象.从后台页面,您可以使用{type:’popup’}调用chrome.extension.getViews,以访问弹出窗口的窗口对象(如果已打开).
getBackgroundPage的Firefox documentation状态:
This provides a convenient way for other privileged add-on scripts to get direct access to the background script’s scope. This enables them to access variables or call functions defined in that scope. “Privileged script” here includes scripts running in options pages, or scripts running in browser action or page action popups, but does not include content scripts.
内容总结
以上是互联网集市为您收集整理的Javascript-浏览器扩展:在浏览器操作弹出窗口和背景脚本之间发送消息(带有响应)全部内容,希望文章能够帮你解决Javascript-浏览器扩展:在浏览器操作弹出窗口和背景脚本之间发送消息(带有响应)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。