Javascript提取和Chrome扩展程序本地存储出现问题

时间:2019-03-05 13:42:34

标签: javascript google-chrome fetch-api google-chrome-storage

我想我已经包含了所有相关代码。我要做的就是等待checkForWord返回其结果,然后再移至getWordDefinition函数的下一部分,因为结果对于下一部分至关重要。到目前为止,我没有尝试过任何方法。我了解chrome的存储是异步的,checkForWord中已经包含了一个回调,但是只要存储数据完成获取数据,该回调就会运行。不知道我在想什么。感谢任何帮助!

chrome.runtime.onInstalled.addListener(function() {
    let thisMenu = chrome.contextMenus.create({
        "id": "Save",
        "title": "Save word",
        "contexts": ["selection"]
    });

})

let dictionary = [];

chrome.contextMenus.onClicked.addListener(function(clickData) {
    getWordDefinition(clickData.selectionText);
})

function getWordDefinition(search) {
    var searchQuery = "https://googledictionaryapi.eu-gb.mybluemix.net/?define=" + search.toLowerCase();

    fetch(searchQuery) // 
        .then((response) => response.json()) // 
        .then((data) => {
            let checker = formatWord(data);
            console.log(checker);
            return checker;
        })
        .then((data) => {
            let a = checkForWord(data); // this is async.
            return a;
        })
        .then(function(data) {
            if (!data[0]) {
                addWordToDictAndSave(data[1]);
            }
        })
}

function formatWord(word) {
    let arr = [];
    for (let letter of word.word) {
        if (isLetter(letter)) {
            arr.push(letter);
        }
    }
    // console.log(arr);
    word.word = arr.join("");
    // console.log(word.word);
    return word;
}

function isLetter(s) {
    return s.match("^[a-zA-Z\(\)]+$");
}

function checkForWord(word) {
    chrome.storage.local.get({
        dictionary: []
    }, (data) => {

        let arr = [];

        dictionary = data.dictionary;
        for (var key of dictionary) {
            if (word == key.word) {
                arr.push(true, word);
                return arr;
            }
        }
    })
}

function addWordToDictAndSave(newWord) {
    dictionary.unshift(newWord);
    saveDict();
}

function saveDict() {
    chrome.storage.local.set({
        dictionary
    });
}

// function fixedEncodeURIComponent(str) {
//     return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
//         return '%' + c.charCodeAt(0).toString(16);
//     });
// }

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Word Saver</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="popup.css">    
        <script type="text/javascript" src="popup.js"></script>
    </head>
    <body>
        <button id="clearAll">Clear All</button>
        <div id="container">
            <div id="dictionary"></div>

        </div>

    </body> 

</html>

0 个答案:

没有答案