[英]How do I send an ajax request in a Google Chrome Extension?
我正在尝试在 chrome 扩展中发送一个 ajax 请求。 我的清单:
{
"name": "example",
"version": "0.0.1",
"description": "Chrome Extension's message passing example",
"browser_action": {
"default_icon": "images/get_started32.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts":[{
"matches":["http://*/*", "https://*/*"],
"js":["popup.js"]
}],
"permissions": [
"background","webRequest","webRequestBlocking","webNavigation","tabs","notifications","https://example.com/*"
],
"manifest_version": 2
}
背景.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.foo === 'bar') {
var url = "https://example.com/path";
fetch(url)
.then(response => sendResponse(response.text()))
.catch(error => handleError(error))
return true; // Will respond asynchronously.
}
});
function handleError(error){
console.log(error);
}
弹出窗口.js
chrome.runtime.sendMessage({foo: 'bar'}, response => {
alert(JSON.stringify(response));
});
即使有来自该 url 的数据,弹出数据也会返回为“{}”。 我究竟做错了什么?
由于response.text()
返回一个 Promise ,您需要添加另一个then
以在发送之前解析 Promise :
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) =>
{
if (msg.foo === 'bar')
{
var url = "https://example.com/path";
fetch(url)
.then(response => response.text()
.then(t => sendResponse(t))
.catch(error => handleError(error))
return true; // Will respond asynchronously.
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.