document.getElementById("startBtn").onclick = async () => { chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { chrome.scripting.executeScript({ target: {tabId: tabs[0].id}, function: startTranslation }); }); }; document.getElementById("stopBtn").onclick = async () => { chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { chrome.scripting.executeScript({ target: {tabId: tabs[0].id}, function: stopTranslation }); }); }; function startTranslation() { if (window.translating) return; window.translating = true; const jpEl = document.getElementById("jp"); const enEl = document.getElementById("en"); const recognition = new webkitSpeechRecognition(); recognition.continuous = true; recognition.lang = "ja-JP"; recognition.onresult = async (event) => { const jp = event.results[event.resultIndex][0].transcript; jpEl.innerText = "Japanese: " + jp; const res = await fetch("https://api.mymemory.translated.net/get?q=" + encodeURIComponent(jp) + "&langpair=ja|en"); const data = await res.json(); const en = data.responseData.translatedText; enEl.innerText = "English: " + en; const utter = new SpeechSynthesisUtterance(en); utter.lang = "en-US"; speechSynthesis.speak(utter); }; recognition.start(); } function stopTranslation() { window.translating = false; speechSynthesis.cancel(); }