[Userscript] Simple Show Context Sentence

Just made your script a bit more difficult by changing the context sentence to a random one of the three available.

sentence = item.data.context_sentences[Math.floor(Math.random() * 3)]?.ja || '';

haha maybe I should just go back to choosing from the first 2

not sure why this mod is not showing up even after having tamper money and open framework, any idea why? tried to activate only this and open framework on the dashboard but the example sentences still is not there.

This would be better done via

const context_sentences = item.data.context_sentences || [];
sentence = context_sentences[Math.floor(Math.random()*context_sentences.length)]?.ja || '';

Because with the way that you have it, the item could have one or two context sentences available but none ends up being shown because the nonexistent third ends up getting picked by random and then it tries to access that element outside of the array.
Alternatively, to keep the upper limit to 3 (i.e., to keep the functionality the same as what it appears you desire), put a Math.min(3,context_sentences.length) in there as well.

Hello! your script is just what I’d been looking for, but is there any way to add an audio button, like in the advanced context sentence 2 script?

this uses automated voice synthesis. I’ve been using it heavily during lessons, it allows me to read along with the voice ; it makes reading context sentences faster, and helps print the pronunciation and pitch accent in my memory.

For now, as an equivalent function, I’m using the “google translate” chrome extension ; when I select any text, it opens a little google translate box, which has a text to speech option.

But this process is slower than just clicking on a “audio” button like with the “advanced context sentence 2” script.

I don’t know how to code, or I’d do it myself. It might be possible to use relevantlines from “advanced context sentence 2” and insert them in this script?

Also this script is super useful but I had trouble initially finding it, because it’s not in the main list of API and 3rd party apps. Lots of people would benefit from finding it there!

Script worked for me about a week ago and then suddenly died. Anyone else?

version 1.1.2 looks to have a typo on line 92.
"parent = "

Deleting this line fixed the script for me.

I don’t know if this script is still being maintained, or if there is already another script that does this, but I edited the code a little bit to show the translation of the sentence when hovering with the mouse. Also, instead of always showing the first sentence, it shows one at random from the ones available for that subject.

Code Update
// ==UserScript==
// @name        WaniKani Show Context Sentence
// @namespace   skatefriday
// @match       https://www.wanikani.com/subjects/review
// @match       https://www.wanikani.com/subjects/extra_study*
// @require     https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
// @grant       none
// @version     1.1.2
// @license     Apache, https://www.apache.org/licenses/LICENSE-2.0
// @author      skatefriday
// @description Show context sentence on review page.
// @downloadURL https://update.greasyfork.org/scripts/421496/WaniKani%20Show%20Context%20Sentence.user.js
// @updateURL https://update.greasyfork.org/scripts/421496/WaniKani%20Show%20Context%20Sentence.meta.js
// ==/UserScript==

(function() {
  
if (!window.wkof) {
    alert('The show context sentence script requires Wanikani Open Framework.\nYou will now be forwarded to installation instructions.');
    window.location.href = 'https://community.wanikani.com/t/instructions-installing-wanikani-open-framework/28549';
    return;
}

var currSubject = null;
var sentence = "";
var translation = "";
var sentenceNode = null;
var wk_items = null;

function format_sentence(sentence, characters) {
    if (!characters)
        return sentence;

    const highlightElement = '<span style="font-weight: bold;">$1</span>';

    // highlight characters in the sentence
    const regex = new RegExp(`(${characters})`, 'g');
    let formattedSentence = sentence.replace(regex, highlightElement);

    // if not change
    if (formattedSentence === sentence) {
        // remove all kana characters and only keep kanji from characters
        const kanaRegex = /[ぁ-ゖ]/g;
        const kanjiOnly = characters.replace(kanaRegex, '');
        formattedSentence = sentence.replaceAll(new RegExp(`(${kanjiOnly})`, 'g'), highlightElement);
    }

    return formattedSentence;
}

function get_random_sentence_index(sentences) {
    const max = sentences.length;
    return Math.floor(Math.random() * max);
}

function get_new_sentence()
{
    if (wk_items == null) {
      return;
    }

    if (currSubject.type === "Vocabulary") {
      sentenceNode.style.display = 'flex';

      let id_index = wkof.ItemData.get_index(wk_items, 'subject_id');
      let item = id_index[currSubject.id]
      let random_index = get_random_sentence_index(item.data.context_sentences);

      sentence = item.data.context_sentences[random_index]?.ja || '';
      translation = item.data.context_sentences[random_index]?.en || '';
      
      if (sentence)
        sentence = format_sentence(sentence, item.data.characters);
      
    } else {
      sentence = ""
      translation = "";
      sentenceNode.style.display = 'none';
    }
  
    sentenceNode.querySelector('span').innerHTML = sentence;
    sentenceNode.querySelector('span + span').innerHTML = translation;
}

window.addEventListener(`willShowNextQuestion`, e => {
	console.log(e.detail);
  currSubject = e.detail.subject;
  get_new_sentence();
});

var config = {
    wk_items: {
        options: {
            study_materials: true
        }
    }
};

//
// Note that this async operation is slower than the willShowNextQuestion above.
// Which is why we cache the current subject as a global in the event handler.  
// Otherwise the first item, if vocabulary, will have no sentence.
//
function fetch_items()
{
    wkof.ItemData.get_items(config)
        .then((items) => { wk_items = items; })
        .then(get_new_sentence);
    
    console.log("Fetched the items")
}

function startup_wkof()
{
    wkof.include('ItemData');
    wkof.ready('ItemData')
      .then(fetch_items);
}

function install_context_sentence_css()
{
    var better_font = "<link href=\"https://fonts.googleapis.com/css?family=Sawarabi+Mincho\" rel=\"stylesheet\">";
    var context_sentence_css = ".wf-sawarabimincho { font-family: \"Sawarabi Mincho\"; font-size:1.5em; background-color:#a100f1; color:#ffffff}"

    $('head').append(better_font);
    $('head').append('<style>'+ context_sentence_css +'</style>');
}

$(document).ready(function()
{
const quizInput = document.querySelector('.quiz-input');
  if (quizInput) {
    quizInput.insertAdjacentHTML('beforebegin', `
      <div class="wf-sawarabimincho" style="
        text-align:center;
        padding: 10px;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        row-gap: 12px;
        display: none;
      ">
        <span>${sentence}</span>
        <span style="background-color: white">${translation}</span>
      </div>
    `);
  }

  sentenceNode = document.querySelector('.wf-sawarabimincho');
  sentenceNode.querySelector('span:last-child').addEventListener('mouseover', e => e.target.style.backgroundColor = '#a100f1');
  sentenceNode.querySelector('span:last-child').addEventListener('mouseout', e => e.target.style.backgroundColor = 'white');

  startup_wkof();
  install_context_sentence_css();
  console.log( "ready!" );
});
          
})();

Thanks, It’s very helpful!

Feel free to submit a PR here: GitHub

This script doesn’t work for me, is it a global issue or something on my side? I tried also code from @digas99 and doesn’t work.

Yeah, I’m the original author, but WK likes to update their website, and that breaks scripts. I can’t really complain too much as nothing is guaranteed when you are essentially trying to rewrite their web pages. Maybe I’ll be inclined sometime in the future to figure out what they changed, and hence why it broke, but until then, it was good while it lasted.

It seems that there was something on my side. Some script doesn’t load for me until I reload page.

I just change “match” value to have it in all study types (review, extra study etc.).

// @match       https://www.wanikani.com/*