Skip to content

Instantly share code, notes, and snippets.

@tryforceful
Created August 10, 2019 15:00
Show Gist options
  • Save tryforceful/e7c44b2e715ae3e7679b7e108d84d2b0 to your computer and use it in GitHub Desktop.
Save tryforceful/e7c44b2e715ae3e7679b7e108d84d2b0 to your computer and use it in GitHub Desktop.
WaniKani: Audio for Japanese Example Sentences
// ==UserScript==
// @name WaniKani: Audio for Japanese Example Sentences
// @namespace http://tryforceful.com/
// @version 0.1
// @description x
// @author @tryforceful
// @match https://www.wanikani.com/lesson/session
// @match http://www.wanikani.com/lesson/session
// @match https://www.wanikani.com/review/session
// @match http://www.wanikani.com/review/session
// @require https://code.responsivevoice.org/responsivevoice.js
// @grant GM_addStyle
// ==/UserScript==
GM_addStyle(`
.context-sentence-group p[lang=ja] {
font-size: 20px;
color: #a0f;
cursor: pointer;
}
.context-sentence-group p[lang=ja]:hover {
color: #60f;
}
`);
//from https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom
var observeDOM = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
return function( obj, callback ){
if( !obj || !obj.nodeType === 1 ) return; // validation
if( MutationObserver ){
// define a new observer
var obs = new MutationObserver(function(mutations, observer){
callback(mutations);
})
// have the observer observe foo for changes in children
obs.observe( obj, { childList:true, subtree:true });
}
else if( window.addEventListener ){
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
})();
const speakWrapper = (function () {
let i = 0;
const prefs = [
{speaker: 'Japanese Female', pref: {rate: 0.8, pitch: 1, volume: 1}},
{speaker: 'Japanese Male', pref: {rate: 0.9, pitch: 1.15, volume: 1}},
];
return function (text, slowSpeed) {
let speakSettings = prefs[(i++)%prefs.length],
pref = Object.assign({}, speakSettings.pref);
if(slowSpeed) {
pref.rate *= 0.7;
}
responsiveVoice.speak(text, speakSettings.speaker, pref);
};
})();
const addAudioLinks = function () {
const jpSentenceList = document.querySelectorAll('.context-sentence-group p[lang=ja]');
jpSentenceList.forEach( function (sentence) {
sentence.addEventListener("click", function(mouseEvent){
speakWrapper(sentence.innerText, mouseEvent.shiftKey);
});
sentence.style.cursor = 'pointer';
});
}
observeDOM(document.querySelector("#supplement-voc-context-sentence"), addAudioLinks); //lessons
observeDOM(document.querySelector("#item-info"), addAudioLinks); //reviews
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment