Electron应用中Roblox接口获取的图片URL无法加载问题排查
Electron中Roblox游戏图标无法显示问题排查
问题背景
通过noblox.js从Roblox游戏的placeid获取图片URL,返回响应数据如下:
{ "data": [ { "targetId": 4111023553, "state": "Completed", "imageUrl": "https://tr.rbxcdn.com/6c6e12c567342835b16e787d9ea60467/50/50/Image/Png", "version": null } ] }
但在Electron应用中将img.src设置为该imageUrl时,图片仅显示占位图,无法正常加载。这段代码在项目其他部分运行正常,怀疑是获取过程存在问题,相关代码如下:
var imageUrl function GetGameIcon(placeid) { var gameInfo = `https://thumbnails.roblox.com/v1/places/gameicons?placeIds=${placeid}&returnPolicy=PlaceHolder&size=50x50&format=Png&isCircular=false` fetch(gameInfo).then(responce => responce.json()).then(data => { imageUrl = data.data[0].imageUrl imageUrl = imageUrl.replace("50/50", "20/20") const img = document.querySelector('img') img.src = imageUrl }) } function Run() { document.getElementById("gamename").innerHTML = game GetGameIcon(placeid) }
排查与解决思路
修正URL尺寸修改方式
手动替换URL中的50/50为20/20可能触发Roblox CDN的权限或缓存限制。建议直接通过API参数指定20x20尺寸,而非修改返回的URL:var gameInfo = `https://thumbnails.roblox.com/v1/places/gameicons?placeIds=${placeid}&returnPolicy=PlaceHolder&size=20x20&format=Png&isCircular=false`调整Electron安全策略
Electron默认的跨域安全策略可能阻止外部CDN资源加载。可在主进程中配置资源白名单(生产环境推荐):// 主进程代码 const { app, BrowserWindow } = require('electron') app.whenReady().then(() => { const mainWindow = new BrowserWindow({ webPreferences: { contentSecurityPolicy: `default-src 'self'; img-src 'self' https://tr.rbxcdn.com;` } }) // 其他窗口初始化逻辑 })测试阶段可临时关闭webSecurity(不建议生产环境使用):
webPreferences: { webSecurity: false, allowRunningInsecureContent: true }确保DOM元素存在并添加错误捕获
检查Run函数执行时<img>元素是否已渲染完成,同时添加错误捕获排查请求问题:function GetGameIcon(placeid) { var gameInfo = `https://thumbnails.roblox.com/v1/places/gameicons?placeIds=${placeid}&returnPolicy=PlaceHolder&size=50x50&format=Png&isCircular=false` fetch(gameInfo) .then(response => response.json()) .then(data => { if (!data.data || data.data.length === 0) return; const img = document.querySelector('img') if (img) { img.src = data.data[0].imageUrl.replace("50/50", "20/20") } }) .catch(err => console.error('获取游戏图标失败:', err)) } // 确保DOM加载完成后执行Run document.addEventListener('DOMContentLoaded', () => { Run() })绕过缓存测试
若存在缓存问题,可在URL后添加时间戳强制刷新:img.src = imageUrl + '?t=' + Date.now()
内容的提问来源于stack exchange,提问作者user23206822
相关产品推荐
相关产品推荐

