作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 chrome 扩展中发送 ajax 请求。我的 list :
{
"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);
}
popup.js
chrome.runtime.sendMessage({foo: 'bar'}, response => {
alert(JSON.stringify(response));
});
即使该网址有数据,弹出数据也会以“{}”形式返回。我做错了什么?
最佳答案
自response.text()
returns a 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.
}
});
关于javascript - 如何在 Google Chrome 扩展程序中发送 ajax 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401933/
我是一名优秀的程序员,十分优秀!