如何解决Chrome 扩展异步消息传递
我目前正在开发 Chrome 扩展程序,我想执行以下操作。
content.js:
chrome.runtime.sendMessage({message: "Teszt",licenseKey: "XXXX-XXXX-XXXX-XXXX",data: "bolond"},(response) => {
alert(response.data);
});
background.js:
chrome.runtime.onMessage.addListener((request,sender,sendResponse) => {
if(request) {
const xhr = new XMLHttpRequest();
xhr.open("GET",`https://api.hyper.co/v4/licenses/${request.licenseKey}`);
xhr.setRequestHeader("Authorization",`Bearer publickey`)
xhr.onload = () => {
sendResponse({ sender: "background.js",data: (request.data+" response") })
}
xhr.send();
}
});
它不返回任何东西,显然是因为请求需要时间来完成。 我怎样才能使它异步?或者至少如何让 content.js 等到后台真正返回一些东西?
先谢谢你!
解决方法
请查看以下文档中的 simple one-time requests
部分
https://developer.chrome.com/docs/extensions/mv3/messaging/
如果要异步使用sendResponse,添加return true;到 onMessage 事件处理程序。
请尝试以下代码。它应该工作
chrome.runtime.onMessage.addListener((request,sender,sendResponse) => {
if(request) {
const xhr = new XMLHttpRequest();
xhr.open("GET",`https://api.hyper.co/v4/licenses/${request.licenseKey}`);
xhr.setRequestHeader("Authorization",`Bearer publickey`)
xhr.onload = () => {
sendResponse({ sender: "background.js",data: (request.data+" response") })
}
xhr.send();
return true;
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。