跳转到内容

MediaWiki:Gadget-AudioText.js:修订间差异

来自电棍ottowiki
第1行: 第1行:
// MediaWiki:Gadget-AudioText.js
// MediaWiki:Gadget-AudioText.js
(function() {
(function() {
    // 预缓存音频URL(提升隐私模式下的成功率)
    let cachedAudioUrl = null;
     mw.hook('wikipage.content').add(function() {
     mw.hook('wikipage.content').add(function() {
         alert("🎉 JS脚本已加载!"); // 1. 脚本加载确认
         alert("🎉 JS脚本已加载!"); // 保留初始提示
 
       
         document.querySelectorAll('.audio-trigger').forEach(element => {
         document.querySelectorAll('.audio-trigger').forEach(element => {
             element.addEventListener('click', function() {
             element.addEventListener('click', async function() {
                 alert("🖱️ 点击事件已触发!"); // 2. 点击事件确认
                 try {
               
                    // 立即尝试播放缓存(减少API请求)
                const audioFile = element.dataset.audioFile;
                    if (cachedAudioUrl) {
                alert("📁 音频文件名: " + audioFile); // 3. 显示模板参数
                        await playAudio(cachedAudioUrl);
 
                        return showDebugInfo(element, "✅ 使用缓存播放成功"); // [!code focus]
                // 构造API请求URL
                    }
                const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' +
                    encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';
                alert("🔗 即将请求API: \n" + apiUrl); // 4. 显示API地址


                // 发送API请求
                    // 首次加载流程
                fetch(apiUrl)
                     const audioFile = element.dataset.audioFile;
                     .then(response => {
                     const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' +
                        alert("📡 API响应状态: " + response.status); // 5. HTTP状态码
                         encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json';
                        return response.json();
                     })
                    .then(data => {
                        alert("📦 API返回原始数据: \n" + JSON.stringify(data)); // 6. 原始API数据
                       
                        const pages = data.query.pages;
                         const pageId = Object.keys(pages)[0];
                        const audioUrl = pages[pageId].imageinfo[0].url;
                        alert("🎵 解析出的音频URL: \n" + audioUrl); // 7. 最终音频地址


                        // 尝试播放
                    // 并行处理:立即播放 + 后台更新缓存
                        const audio = new Audio(audioUrl);
                    const audioUrl = await fetch(apiUrl)
                         audio.play()
                         .then(response => response.json())
                            .then(() => alert("✅ 播放成功!"))
                        .then(data => {
                             .catch(e => alert("❌ 播放失败: " + e.message)); // 8. 播放结果
                            const pages = data.query.pages;
                     })
                            const pageId = Object.keys(pages)[0];
                     .catch(error => {
                             return pages[pageId].imageinfo[0].url;
                        alert("💥 发生严重错误: " + error.message); // 9. 全局错误捕获
                        });
                    });
                   
                    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);
    }
})();
})();

2025年5月24日 (六) 22:37的版本

// 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);
    }
})();