MediaWiki:Gadget-AudioText.js
外观
注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。
- Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
- Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
- Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
// MediaWiki:Gadget-AudioText.js (function() { // 预缓存音频URL(提升隐私模式下的成功率) let cachedAudioUrl = null; mw.hook('wikipage.content').add(function() { alert("🎉 JS脚本已加载!"); // 保留初始提示 document.querySelectorAll('.audio-trigger').forEach(element => { element.addEventListener('click', async function() { try { // 立即尝试播放缓存(减少API请求) if (cachedAudioUrl) { await playAudio(cachedAudioUrl); return showDebugInfo(element, "✅ 使用缓存播放成功"); // [!code focus] } // 首次加载流程 const audioFile = element.dataset.audioFile; const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' + encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json'; // 并行处理:立即播放 + 后台更新缓存 const audioUrl = await fetch(apiUrl) .then(response => response.json()) .then(data => { const pages = data.query.pages; const pageId = Object.keys(pages)[0]; return pages[pageId].imageinfo[0].url; }); cachedAudioUrl = audioUrl; // 更新缓存 // 立即播放不等待调试提示 await playAudio(audioUrl); // 播放成功后显示调试信息 showDebugInfo(element, `🎵 音频URL: ${audioUrl}\n✅ 实时播放成功`); // [!code focus] } catch (error) { showDebugInfo(element, `❌ 错误: ${error.message}\n⚠️ 请关闭防跟踪功能后重试`); } }); }); }); // 专用播放函数 async function playAudio(url) { const audio = new Audio(url); await audio.play().catch(e => { throw new Error(`播放被阻止 (${e.message})`); }); } // 延迟显示调试信息(不影响播放) function showDebugInfo(element, message) { // [!code focus] setTimeout(() => { // 延迟500ms确保播放已触发 alert(message); element.style.backgroundColor = "#f0f8ff"; // 可视化反馈 setTimeout(() => element.style.backgroundColor = "", 1000); }, 500); } })();