用信息重新加载弹出窗口

时间:2015-04-17 19:02:44

标签: javascript html google-chrome-extension popup

我的弹出窗口中有一个表格,我将用户输入的值保存到localStorage。这是片段。

popup.html

<table id="main_table">
</table>

<script src="popup.js"></script>

popup.js

function create_row() {
    localStorage["last_session"] = true;
    var table = document.getElementById("main_table");
    var n = table.rows.length;
    var m = table.rows[0].cells.length;
    var row = table.insertRow(n);
    if (!localStorage['use_storage']) {
        if (n === 1) {
            localStorage["cells"] = JSON.stringify([{}]);
        }
        else if (n > 1) {
            var cells = JSON.parse(localStorage["cells"]);
            cells.push({});
            localStorage["cells"] = JSON.stringify(cells);
        }
    }
    var cell = row.insertCell(0);
    cell.innerHTML = n;
    for (j=1; j<m; j++) {
        create_cell(n-1, j, row);
    }
    return row
}

function create_cell(i, j, row){
    var cell = row.insertCell(j);
    if (j == 1) {
        cell.innerHTML = "<input size=10>";
    }
    else {
        cell.innerHTML = "<input size=4>";
    }
    cell.addEventListener("change", function () {
        var cells = JSON.parse(localStorage["cells"]);
        cells[i.toString()][j.toString()] = cell.childNodes[0].value;
        localStorage["cells"] = JSON.stringify(cells);
    })
}

document.getElementById('create_row').onclick = create_row;

// restore a table
if (localStorage["last_session"]) {
    localStorage["use_storage"] = true;
    try {
        var cells = JSON.parse(localStorage["cells"]);
        var n = cells.length;
        var table = document.getElementById("main_table")
        for (i=0; i<n; i++) {
            var row = create_row(true);
            var cell = cells[i]
            for (var key in cell) {
                if (cell.hasOwnProperty(key)) {
                    var col = parseInt(key);
                    var val = cell[key];
                    row.cells[col].childNodes[0].value = val;
                }
            }
        }
    } catch (e) {
        console.log("Catched error");
        console.log(e);
    }
if (localStorage["results"]) {
        show_results();
    }
    localStorage['use_storage'] = false;
}

在我的浏览器中,它按照预期的方式工作,即在刷新页面popup.html之后,我有我离开的状态(保留行数和值)。但是,在我的chrome扩展中,点击任何区域然后重新加载扩展后,我有了初始的空表。

如何在这种特殊情况下保留表格?

0 个答案:

没有答案