无法将eventurl变量传入fetchData函数,请求技术排查协助
问题分析与解决方案
你的代码存在两个关键问题:
- 异步执行顺序问题:
chrome.tabs.query是异步API,它的回调函数会在后续事件循环中执行,但你在全局作用域直接同步调用了fetchData(),此时eventurl还未生成。 - 变量作用域问题:
eventurl是在chrome.tabs.query的回调函数内部定义的,外部作用域无法访问这个变量。
修正步骤
- 将
fetchData()的调用移到chrome.tabs.query的回调函数内部,确保在eventurl生成后再执行,同时传入该变量。 - 给
stock变量添加const声明,避免全局变量污染。 - 增加错误处理逻辑,防止
fetch请求失败或JSON解析出错导致页面崩溃。
修正后的代码
async function fetchData(eventurl) { try { const res = await fetch(eventurl); if (!res.ok) { throw new Error(`请求失败:${res.status}`); } const record = await res.json(); const stock = record.groups[0].sections; document.getElementById("stock").innerHTML = JSON.stringify(stock); } catch (err) { console.error('数据获取失败:', err); document.getElementById("stock").innerHTML = '数据加载失败,请重试'; } } chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function(tabs) { const url = tabs[0].url; const pid = url.split("/"); const eventpid = pid[5]; const eventurl = `https://availability.ticketmaster.eu/api/v2/TM_CH/availability/${eventpid}?subChannelId=1`; document.getElementById("link").innerHTML = eventurl; document.getElementById("event").innerHTML = eventpid; // 在这里调用fetchData并传入eventurl fetchData(eventurl); });
内容的提问来源于stack exchange,提问作者eightmax
相关产品推荐
相关产品推荐

