Chrome 扩展异步消息传递
Chrome extension asynchronous messaging
我目前正在开发 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();
}
});
它没有 return 任何东西,显然是因为请求需要时间才能完成。
我怎样才能让它异步?或者至少如何让 content.js 等到背景实际上 return 是什么?
提前致谢!
请检查以下文档中的 simple one-time requests
部分
https://developer.chrome.com/docs/extensions/mv3/messaging/
If you want to asynchronously use sendResponse, add return true; to
the onMessage event handler.
请尝试以下代码。它应该工作
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;
}
});
我目前正在开发 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();
}
});
它没有 return 任何东西,显然是因为请求需要时间才能完成。 我怎样才能让它异步?或者至少如何让 content.js 等到背景实际上 return 是什么?
提前致谢!
请检查以下文档中的 simple one-time requests
部分
https://developer.chrome.com/docs/extensions/mv3/messaging/
If you want to asynchronously use sendResponse, add return true; to the onMessage event handler.
请尝试以下代码。它应该工作
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;
}
});