diff options
Diffstat (limited to 'ext/bg/js')
-rw-r--r-- | ext/bg/js/options-form.js | 4 | ||||
-rw-r--r-- | ext/bg/js/yomichan.js | 42 |
2 files changed, 35 insertions, 11 deletions
diff --git a/ext/bg/js/options-form.js b/ext/bg/js/options-form.js index 9799f664..1c50d7a7 100644 --- a/ext/bg/js/options-form.js +++ b/ext/bg/js/options-form.js @@ -18,7 +18,7 @@ function optionsToForm(opts) { - $('#enableAnkiConnect').prop('checked', opts.ankiConnect); + $('#enableAnkiConnect').prop('checked', opts.enableAnkiConnect); $('#selectMatchedText').prop('checked', opts.selectMatchedText); $('#loadOnStartup').prop('checked', opts.loadOnStartup); $('#scanLength').val(opts.scanLength); @@ -28,7 +28,7 @@ function formToOptions() { return sanitizeOptions({ loadOnStartup: $('#loadOnStartup').prop('checked'), selectMatchedText: $('#selectMatchedText').prop('checked'), - ankiConnect: $('#enableAnkiConnect').prop('checked'), + enableAnkiConnect: $('#enableAnkiConnect').prop('checked'), scanLength: $('#scanLength').val() }); } diff --git a/ext/bg/js/yomichan.js b/ext/bg/js/yomichan.js index ac02f882..a412eef7 100644 --- a/ext/bg/js/yomichan.js +++ b/ext/bg/js/yomichan.js @@ -50,17 +50,14 @@ class Yomichan { onMessage(request, sender, callback) { const {action, data} = request, handlers = { - findKanji: ({text}) => this.translator.findKanji(text), - findTerm: ({text}) => this.translator.findTerm(text), - getState: () => this.state, - getOptions: () => this.options, - renderText: ({data, template}) => Handlebars.templates[template](data) + findKanji: ({text}) => this.findKanji(text, callback), + findTerm: ({text}) => this.findTerm(text, callback), + getOptions: () => callback(this.options), + getState: () => callback(this.state), + renderText: ({data, template}) => callback(Handlebars.templates[template](data)) }; - const result = handlers[action].call(this, data); - if (callback !== null) { - callback(result); - } + handlers[action].call(this, data); } onBrowserAction(tab) { @@ -102,6 +99,33 @@ class Yomichan { Yomichan.notifyChange('options', this.options); } + findTerm(text, callback) { + const results = this.translator.findTerm(text); + this.callAnkiApi('canAddNotes', results, (resultsFull) => { + callback(resultsFull || results); + }); + } + + findKanji(text, callback) { + const results = this.translator.findKanji(text); + this.callAnkiApi('cannAddNotes', results, (resultsFull) => { + callback(resultsFull || results); + }); + } + + callAnkiApi(action, data, callback) { + if (this.options.enableAnkiConnect) { + const xhr = new XMLHttpRequest(); + xhr.addEventListener('load', () => callback(JSON.parse(xhr.responseText))); + xhr.open('POST', 'http://127.0.0.1:8888'); + xhr.withCredentials = true; + xhr.setRequestHeader('Content-Type', 'text/json'); + xhr.send(JSON.stringify(data)); + } else { + callback(null); + } + } + static notifyChange(name, value) { chrome.tabs.query({}, (tabs) => { for (const tab of tabs) { |