Skip to content

Register inline query

Ariz Zubair edited this page Nov 6, 2022 · 12 revisions

What is inline query?

Inline query is a quick approach for you to query word without leaving current page, usually for word translation.

SurfingKeys will not provide default dictionary service from 0.9.33, though shanbay(which is only for English-Chinese translation) had been built in before.

You need register your own dictionary service for inline query by API Front.registerInlineQuery.

Front.registerInlineQuery(dictionary_service_definition)
parameter explanation
dictionary_service_definition.url string or function, the dictionary service url or a function to return the dictionary service url.
dictionary_service_definition.parseResult function, a function to parse result from dictionary service and return a HTML string to render explanation.
dictionary_service_definition.headers object[optional], in case your dictionary service needs authentication.

Example shanbay

    api.Front.registerInlineQuery({
        url: "https://api.shanbay.com/bdc/search/?word=",
        parseResult: function(res) {
            try {
                res = JSON.parse(res.text);
                var exp = res.msg;
                if (res.data.definition) {
                    var pronunciations = [];
                    for (var reg in res.data.pronunciations) {
                        pronunciations.push(`<div>[${reg}] ${res.data.pronunciations[reg]}</div>`);
                        // pronunciations.push(`<div><audio src="${res.data[reg+'_audio']}" controls></audio></div>`);
                    }
                    var definition = res.data.definition.split("\n").map(function(d) {
                        return `<li>${d}</li>`;
                    }).join("");
                    exp = `${pronunciations.join("")}<ul>${definition}</ul>`;
                }
                if (res.data.en_definitions) {
                    exp += "<hr/>";
                    for (var lex in res.data.en_definitions) {
                        var sense = res.data.en_definitions[lex].map(function(s) {
                            return `<li>${s}</li>`;
                        }).join("");
                        exp += `<div>${lex}</div><ul>${sense}</ul>`;
                    }
                }
                return exp;
            } catch (e) {
                return "";
            }
        }
    });

Example Youdao

api.Front.registerInlineQuery({
    url: function(q) {
        return `http://dict.youdao.com/w/eng/${q}/#keyfrom=dict2.index`;
    },
    parseResult: function(res) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(res.text, "text/html");
        var collinsResult = doc.querySelector("#collinsResult");
        var authTransToggle = doc.querySelector("#authTransToggle");
        var examplesToggle = doc.querySelector("#examplesToggle");
        if (collinsResult) {
            collinsResult.querySelectorAll("div>span.collinsOrder").forEach(function(span) {
                span.nextElementSibling.prepend(span);
            });
            collinsResult.querySelectorAll("div.examples").forEach(function(div) {
                div.innerHTML = div.innerHTML.replace(/<p/gi, "<span").replace(/<\/p>/gi, "</span>");
            });
            var exp = collinsResult.innerHTML;
            return exp;
        } else if (authTransToggle) {
            authTransToggle.querySelector("div.via.ar").remove();
            return authTransToggle.innerHTML;
        } else if (examplesToggle) {
            return examplesToggle.innerHTML;
        }
    }
});

Example Jisho

api.Front.registerInlineQuery({
    url: function(q) {
        return `https://jisho.org/search/${q}`;
    },
    parseResult: function(res) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(res.text, "text/html");
        var result = doc.querySelector("#primary>div.exact_block");
        if (result) {
            result.querySelectorAll('div>span.furigana').forEach(function(e){
                br = document.createElement("br");
                e.appendChild(br);
            });
            result.querySelectorAll('h4').forEach(function(e){
                e.remove();
            });
            result.querySelectorAll('div>div.concept_light-status').forEach(function(e){
                e.remove();
            });
            result.querySelectorAll('div>a.light-details_link').forEach(function(e){
                e.remove();
            });
            result.querySelectorAll('div>span.meaning-abstract').forEach(function(e){
                e.remove();
            });
            result.querySelectorAll('div>span.supplemental_info').forEach(function(e){
                e.outerHTML = "&nbsp;" + e.outerHTML;
            });
            var exp = result.innerHTML;
            return exp;
        }    }
});

Example Merriam-Webster dictionary

// Go to https://dictionaryapi.com/ and get an API key for Learners Dictionary.
const API_KEY = 'your_own_personal_token';
const API_URL = 'https://dictionaryapi.com/api/v3';

api.Front.registerInlineQuery({
    url: function(q) {
        const url = `${API_URL}/references/learners/json/${q}?key=${API_KEY}`;
        return url;
    },
    parseResult: function(res) {
        try {
            const [firstResult] = JSON.parse(res.text);
            if (firstResult) {
                let definitionsList = `<ul><li>No definitions found</li></ul>`;
                let pronunciationsList = `<ul><li>No pronunciations found</li></ul>`;
                if (firstResult.hasOwnProperty('shortdef')) {
                    const definitions = [];
                    for (let definition of firstResult.shortdef) {
                        definitions.push(`${definition}`);
                    }
                    const definitionListItems = definitions.map(function(definition) {
                        return `<li>${definition}</li>`;
                    });
                    definitionsList = `<ul>${definitionListItems.join('')}</ul>`;
                    //TODO: Separate this function if possible
                }
                if (firstResult.hasOwnProperty('hwi')) {
                   const pronunciations = [];
                   const resultPronunciationsArray = firstResult.hwi.prs;
                   if (resultPronunciationsArray && resultPronunciationsArray.length !== 0) {
                       for (let i=0; i < resultPronunciationsArray.length; i++) {
                          if (resultPronunciationsArray[i].l) {
                            pronunciations.push(`<li>${resultPronunciationsArray[i].l} -- ${resultPronunciationsArray[i].ipa}</li>`);
                          } else {
                              pronunciations.push(`<li>${resultPronunciationsArray[i].ipa}</li>`);
                          }
                       }
                       
                       pronunciationsList = `<ul>${pronunciations.join('')}</ul>`;
                   }
                }
                return `
                   <h3>Pronunciations</h3>
                   ${pronunciationsList}
                   <hr/>
                   <h3>Definitions</h3>
                   ${definitionsList}
                `;
            } else {
                return `
                  <h3>This is not the definition you were looking for...</h3>
                `;
            }
        } catch (e) {
            console.log(e.message);
            return 'Something bad happend... Look behind you, a three headed monkey!';
        }
    }
});

q to query word under cursor in visual mode

image

Q to open Omnibar to query word interactively

image