gpt4 book ai didi

javascript - 如何在 Google Chrome 扩展程序中发送 ajax 请求?

转载 作者:行者123 更新时间:2023-12-02 22:15:20 25 4
gpt4 key购买 nike

我正在尝试在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com