2017-12-16 4 views
0

Chrome 확장 프로그램에 영구 또는 영구 저장소를 저장하려고합니다. 현재 내가하려고하는 작업은 Indexeddb 데이터베이스를 만들고 다른 페이지에서이를 쿼리하는 것입니다.Chrome 확장 프로그램의 영구 저장소

여기 내 콘텐츠 스크립트 중 하나에서 뭔가 : 호출

 chrome.extension.sendRequest({ 
      "type": "search", 
      "text": char 
     }, 

을이 : 간다

search: function(text) { 
    var entry = this.db_query(text); 
    if (entry != null) { 
     for (var i = 0; i < entry.data.length; i++) { 
      var word = entry.data[i][1]; 
     } 
    } 
    return entry; 
} 

: 그러나 빈 색인화를 제공

db_query: function(text) { 
    var background = chrome.extension.getBackgroundPage(); 
    console.log(background); 
    var open = indexedDB.open("CEDICT", 1); 
    var db = open.result; 
    var tx = db.transaction("CEDICT", "readwrite"); 
    var store = tx.objectStore("CEDICT"); 
    var index2 = store.index("simplified"); 

    var getData = index2.get(text); 

    getData.onsuccess = function() { 
     console.log(getData.result); 
     return getData.result; 
}; 


    tx.oncomplete = function() { 
    db.close(); 
}; 
}, 

을, 이 배경 스크립트에도 불구하고 :

var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB; 

var open = indexedDB.open("CEDICT", 1); 

open.onupgradeneeded = function() { 
    var db = open.result; 
    var store = db.createObjectStore("CEDICT", {autoIncrement:true}); 
    var index1 = store.createIndex("traditional", 'traditional'); 
    var index2 = store.createIndex("simplified", 'simplified'); 
}; 

open.onsuccess = function() { 
    var db = open.result; 
    var tx = db.transaction("CEDICT", "readwrite"); 
    var store = tx.objectStore("CEDICT"); 

store.put({"traditional": "三體綜合症", "simplified": "三体综合症", "tones": ["1", "3", "1", "2", "4"]}); 
store.put({"traditional": "□", "simplified": "□", "tones": ["1"]}); 
store.put({"traditional": "○", "simplified": "○", "tones": ["2"]}); 

등 ...

tx.oncomplete = function() { 
    db.close(); 
}; 

왜 색인화가 비어? 내가 뭔가 잘못하고 있는거야? 처음으로이 플러그인을 다시 추가 한 후 제대로 작동하여 원하는 값을 제공했지만 그 이후로는 작동하지 않고 빈 값을 반환했습니다. 여기

오류가 나는 얻을 것 :

_generated_background_page.html:1 Error in event handler for extension.onRequest: InvalidStateError: Failed to read the 'result' property from 'IDBRequest': The request has not finished. 

이합니까 그냥 내가 약속이나 뭔가가 필요 의미?

+0

'chrome.storage' API를 확인 했습니까? https://developer.chrome.com/extensions/storage – Siggy

+0

거대한 데이터베이스에서 작동하지 않습니다. –

+0

'db_query' 함수에서'var db = open.result;'할당이 문제가되는 것 같습니다. 데이터베이스가 열릴 때까지 기다려야합니다. 또 다른 것은 ...'return getData.result'는'db_query'의 호출자에게 리턴하지 않을 것입니다, 그것은 이벤트 이미 터로 되돌아 갈 것입니다. – Siggy

답변

0

코드에서 알 수 있듯이 return getData.result;의 값을 반환 할 수 없습니다. indexedDB를 사용하려면 async js에 익숙해 져야합니다.

간략한 예를 들어 보자.이 버튼에는 버튼과 이벤트 리스너가 있다고 가정합니다. 이벤트 리스너 함수에서 값을 반환 할 수 있습니까? 아닙니다. 마찬가지로 여기에서 값을 반환 할 수도 없습니다.

간단히 말해 콜백 함수에 결과를 전달할 수 있습니다. 또는 약속을 사용하십시오.

function db_query(..., callbackFunction) { 
    getData.onsuccess = function(){ 
    // Instead of returning, call the callback function 
    callbackFunction(getData.result); 
    }; 
} 

그런 다음 db_query 결과를 가져 오는 대신 callbackFunction 본문 내에서 계속 실행하십시오.

db_query(..., function myCallback(value) { 
    console.log(value); 
}); 
+0

Chrome 확장 프로그램의 전체적인 부분 (백그라운드 페이지 대 메인 페이지에서 실행되는 콘텐츠 스크립트)이 문제가 아니라고 생각 하긴했지만, 결국 문제가된다면 그 내용을 약속으로 옮길 예정이었습니다. . 내가 알아야 할 문제는 indexdb가 비어있는 이유입니다. –

+0

데이터베이스가 가득 차면 원하는 데이터를 반환한다는 것을 알고 있습니다. –

관련 문제