diff --git a/public/manifest.json b/public/manifest.json index d63fe3a..49e3e0b 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -4,7 +4,7 @@ "name": "__MSG_appName__", "description": "__MSG_appDesc__", "default_locale": "zh_CN", - "version": "0.9.1", + "version": "0.9.3", "icons": { "48": "assets/result48.png", "128": "assets/icon_128.png" diff --git a/src/background.js b/src/background.js index 673c26d..19c964c 100644 --- a/src/background.js +++ b/src/background.js @@ -8,9 +8,61 @@ const options = { } } -const cache = new LRUCache(options) const cacheAudio = new LRUCache(options) +let db + +function initDatabase() { + const request = indexedDB.open('WordDiscovererDB', 1) + + request.onerror = function(event) { + console.error('Database error:', event.target.errorCode) + } + + request.onsuccess = function(event) { + db = event.target.result + console.log('Database initialized.') + } + + request.onupgradeneeded = function(event) { + db = event.target.result + const objectStore = db.createObjectStore('dictionary', { keyPath: 'q' }) + objectStore.createIndex('q', 'q', { unique: true }) + } +} + +function saveToIndexedDB(q, data) { + const transaction = db.transaction(['dictionary'], 'readwrite') + const objectStore = transaction.objectStore('dictionary') + console.log('save to db', data) + const request = objectStore.add({ q: q.toLowerCase(), data: data }) + + request.onsuccess = function(event) { + console.log('Data saved to IndexedDB:', q) + } + + request.onerror = function(event) { + console.error('Error saving data to IndexedDB:', event.target.errorCode) + } +} + +function getFromIndexedDB(q) { + return new Promise((resolve, reject) => { + const transaction = db.transaction(['dictionary'], 'readonly') + const objectStore = transaction.objectStore('dictionary') + const request = objectStore.get(q.toLowerCase()) + + request.onsuccess = function(event) { + resolve(event.target.result ? event.target.result.data : null) + } + + request.onerror = function(event) { + reject(event.target.errorCode) + } + }) +} + + function do_load_dictionary(file_text) { const lines = file_text.split(/[\r\n]+/) const rare_words = {} @@ -84,85 +136,96 @@ function load_idioms() { } function initialize_extension() { - chrome.runtime.onMessage.addListener( - function(request, sender, sendResponse) { - if (request.type === 'fetch') { - let cacheHtml = cache.get(request.q.toLowerCase()) + initDatabase() + chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { + if (request.type === 'fetch') { + getFromIndexedDB(request.q) + .then(cachedData => { + if (cachedData) { + console.info(`\t==>db cache : ${request.q}`) + sendResponse(cachedData) + } else { + console.log('fetch bing: ', request.q) + return fetch( + `https://cn.bing.com/dict/clientsearch?mkt=zh-CN&setLang=zh&form=BDVEHC&ClientVer=BDDTV3.5.1.4320&q=${encodeURIComponent(request.q)}` + ).then(response => response.text()) + .then(html => { + const minimizeHtml = html + .replace(/