-
-
Save moriwaka/0627f178eb7e54b7ecaeb902bcd40311 to your computer and use it in GitHub Desktop.
Google ChromeのTranslate APIを使った英日翻訳bookmarklet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| javascript:(async()=>{ | |
| if(!('Translator' in window)){alert('Translator API not supported');return;} | |
| const translator=await Translator.create({ | |
| sourceLanguage:'en', | |
| targetLanguage:'ja' | |
| }); | |
| function visible(node){ | |
| if(!node.parentElement) return false; | |
| const tag=node.parentElement.tagName; | |
| if(['SCRIPT','STYLE','NOSCRIPT','CODE','PRE','TEXTAREA'].includes(tag)) return false; | |
| return node.nodeValue.trim().length>0; | |
| } | |
| async function translateNode(node){ | |
| try{ | |
| const t=await translator.translate(node.nodeValue); | |
| node.nodeValue=t; | |
| }catch(e){} | |
| } | |
| async function translatePage(){ | |
| const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT); | |
| const tasks=[]; | |
| let n; | |
| while(n=walker.nextNode()){ | |
| if(visible(n)) tasks.push(translateNode(n)); | |
| } | |
| for(const t of tasks) await t; | |
| } | |
| await translatePage(); | |
| const observer=new MutationObserver(m=>{ | |
| for(const rec of m){ | |
| for(const n of rec.addedNodes){ | |
| if(n.nodeType===3 && visible(n)) translateNode(n); | |
| } | |
| } | |
| }); | |
| observer.observe(document.body,{childList:true,subtree:true}); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment