我正在编写一个 Chrome 扩展程序,它将每分钟获取 JSON 数据并根据结果更新弹出窗口的 html 正文(单击图标后可访问)。
这是我的背景.js:
var lastResponse = ""; //Here I save the JSON I receive
function generateTable() { //This function generates the html body table
console.log('Generating table');
var resp = JSON.parse(lastResponse);
var headers=new Array("", "last", "buy", "sell", "15m", "24h");
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
var row = document.createElement("tr");
for (var i=0;i<6;i++)
{
var cell = document.createElement("td");
var cellText = document.createTextNode(headers[i]);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
for(var key in resp){ {
// creates a table row
row = document.createElement("tr");
for (var i = 0; i < 6; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (i==0) {
var cellText = document.createTextNode("");
} else {
var cellText = document.createTextNode(key);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
document.body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
function readBlock() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://blockchain.info/ticker");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
lastResponse = xhr.responseText;
}
}
}
xhr.send();
}
function onAlarm(alarm) {
if (alarm && alarm.name == 'refresh') {
readBlock();
}
}
document.addEventListener('DOMContentLoaded', function () {
generateTable();
});
chrome.alarms.create('refresh', {periodInMinutes: 1.0});
chrome.alarms.onAlarm.addListener(onAlarm);
readBlock();
当我尝试运行它时,我收到一个错误
未捕获的 SyntaxError:输入 background.js:82 的意外结束
第 82 行是 .js 的最后一行。我猜我遇到了问题,因为我尝试在 JSON 可用之前访问它。我应该如何让这个程序正常工作?