gpt4 book ai didi

javascript - 后台脚本的 sendResponse 中数组数据丢失

转载 作者:行者123 更新时间:2023-11-28 03:26:31 25 4
gpt4 key购买 nike

我需要从内容脚本内部访问我的 API 中的数据,但是由于它们是 HTTP 请求(而不是 HTTPS),因此它们在内容脚本内部被阻止。

因此,我正在后台脚本内部执行所有请求,并尝试使用消息 API 在后台脚本和内容脚本之间进行通信。每当我准备好使用 contentscript 中的数据时,我都会向后台脚本发送一条消息,然后后台脚本将从 API 中获取数据并将其作为对 contentscript 的响应发送。从后台脚本中,如果我在发送数据之前 console.log 数据,那么一切都很好(一个包含 4 个位置的数组)。但是,内容脚本中接收到的数据是一个空数组,数组中存储的所有数据都会丢失。

这是发送消息的内容脚本代码片段:

if (typeof chrome.app.isInstalled !== 'undefined')
{
console.log("gbdScreen sending requests")
chrome.runtime.sendMessage({metric: "issues"}, function(response)
{
setTimeout(function(){
if (response !== undefined)
{
console.log(response)
console.log(response.data)
}
else{
console.log("gbdScreen-else")
document.getElementById('gbdButton').click()
}
}, 2000)
})
}

这是后台脚本,它在其中接收消息,继续获取数据,然后将其发回:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) 
{
let arr = []
chrome.storage.sync.get('oauth2_token', function(res)
{
if (res.oauth2_token != undefined)
{
chrome.tabs.query
({
'active': true, 'lastFocusedWindow': true
},
function (tabs)
{
let url = tabs[0].url.split("/")
let owner = url[3]
let repo = url[4].split("#")[0]
let url_aux = `?owner=${owner}&repository=${repo}&token=${res.oauth2_token}`

let url_fetch = url_base + '/commits' + url_aux

// async function to make requests
const asyncFetch = async () => await (await fetch(url_fetch))

// commits request
asyncFetch().then((resp) => resp.json()).then(function(data)
{
arr[0] = data
}).catch(function(err)
{
console.log("Error: URL = " + url_fetch + "err: " + err)
})

// issues request
url_fetch = url_base + '/issues' + url_aux
asyncFetch().then((resp) => resp.json()).then(function(data)
{
arr[1] = data
}).catch(function(err)
{
console.log("Error: URL = " + url_fetch + "err: " + err)
})

// branches request
url_fetch = url_base + '/branches' + url_aux
asyncFetch().then((resp) => resp.json()).then(function(data)
{
arr[2] = data
}).catch(function(err)
{
console.log("Error: URL = " + url_fetch + "err: " + err)
})

// prs
url_fetch = url_base + '/pullrequests' + url_aux
asyncFetch().then((resp) => resp.json()).then(function(data)
{
arr[3] = data
}).catch(function(err)
{
console.log("Error: URL = " + url_fetch + "err: " + err)
})
console.log(arr)
sendResponse({data: arr}) // sends back to screen.js the data fetched from API
})
}
})
return true
})

我在backgroundscript和contentscript中都使用console.log,在backgroundscript中一切都很好,但在contentscript中打印一个空数组。如果有人能解释一下,我知道现在的代码非常困惑。

最佳答案

这个问题基本上是Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference的重复。 .

在发送空的首字母 [] 之后,您将异步填充数组很长时间 。至于 console.log,您只能看到最终的数组,因为 devtools 按需读取变量 - when you expand the value, not when console.log runs .

解决方案是使用 Promise.all 等待所有提取完成,然后才发送响应。

让我们使用 Mozilla's WebExtension Polyfill 来简化您的代码这样就可以代替 return truesendResponse我们可以从 onMessage 监听器返回一个 Promise,或者更好地使用 async/await :

const FETCH_TYPES = [
'commits',
'issues',
'branches',
'pullrequests',
];

async function fetchJson(type, aux) {
const url = `${url_base}/${type}${aux}`;
try {
return (await fetch(url)).json();
} catch (err) {
console.log('Error: URL =', url, 'err:', err);
}
}

browser.runtime.onMessage.addListener(async (request, sender) => {
const {oauth2_token} = await browser.storage.sync.get('oauth2_token');
if (oauth2_token) {
const url = sender.tab.url.split('/');
const owner = url[3];
const repo = url[4].split('#')[0];
const aux = `?owner=${owner}&repository=${repo}&token=${oauth2_token}`;
const data = await Promise.all(FETCH_TYPES.map(type => fetchJson(type, aux)));
return { data };
}
});

附注请注意代码如何使用 sender.tab.url因为消息可能来自非事件选项卡。

关于javascript - 后台脚本的 sendResponse 中数组数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58601031/

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