MediaWiki:Gadget-AudioText.js:修订间差异
外观
![]() OctoberSama(留言 | 贡献) 小 |
![]() OctoberSama(留言 | 贡献) 小 |
||
第2行: | 第2行: | ||
(function() { | (function() { | ||
mw.hook('wikipage.content').add(function() { | mw.hook('wikipage.content').add(function() { | ||
document.querySelectorAll('.audio-trigger').forEach(element => { | document.querySelectorAll('.audio-trigger').forEach(element => { | ||
element.addEventListener('click', function() { | element.addEventListener('click', async function(event) { | ||
event.preventDefault(); | |||
// 1. 立即创建音频对象并触发播放请求(占位) | |||
const audio = new Audio(); | |||
audio.autoplay = true; // 关键:声明自动播放意图 | |||
audio.play().catch(() => {}); // 静默忽略首次错误 | |||
// 2. 异步获取真实URL | |||
const audioFile = element.dataset.audioFile; | const audioFile = element.dataset.audioFile; | ||
const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' + | const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' + | ||
encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json'; | encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json'; | ||
try { | |||
const response = await fetch(apiUrl); | |||
const data = await response.json(); | |||
const pages = data.query.pages; | |||
const pageId = Object.keys(pages)[0]; | |||
const audioUrl = pages[pageId].imageinfo[0].url; | |||
// 3. 替换音频源并重新播放 | |||
audio.src = audioUrl; | |||
await audio.play(); | |||
} catch (error) { | |||
alert("❌ 终极错误: " + error.message); | |||
} | |||
}); | }); | ||
}); | }); | ||
}); | }); | ||
})(); | })(); |
2025年5月24日 (六) 22:15的版本
// MediaWiki:Gadget-AudioText.js (function() { mw.hook('wikipage.content').add(function() { document.querySelectorAll('.audio-trigger').forEach(element => { element.addEventListener('click', async function(event) { event.preventDefault(); // 1. 立即创建音频对象并触发播放请求(占位) const audio = new Audio(); audio.autoplay = true; // 关键:声明自动播放意图 audio.play().catch(() => {}); // 静默忽略首次错误 // 2. 异步获取真实URL const audioFile = element.dataset.audioFile; const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' + encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json'; try { const response = await fetch(apiUrl); const data = await response.json(); const pages = data.query.pages; const pageId = Object.keys(pages)[0]; const audioUrl = pages[pageId].imageinfo[0].url; // 3. 替换音频源并重新播放 audio.src = audioUrl; await audio.play(); } catch (error) { alert("❌ 终极错误: " + error.message); } }); }); }); })();