所以我有一个 chrome 扩展,可以通过 xml 文档检查程序的更新。但是,当我打开一个新标签时出现此错误:
Error in event handler for 'tabs.onActivated': Cannot call method 'getElementsByTagName' of null TypeError: Cannot call method 'getElementsByTagName' of null
at isUpdateAvailable (chrome-extension://bdhjocmpiogdmlfpbpppiffcjbonbocg/background.js:16:17)
at chrome-extension://bdhjocmpiogdmlfpbpppiffcjbonbocg/background.js:84:5
at chrome.Event.dispatch (event_bindings:237:41)
at Object.chromeHidden.Event.dispatchJSON (event_bindings:151:5
代码:
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp;
}
function isUpdateAvailable(type, build) {
var buildNumber = localStorage["version" + build + type];
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + build + "/view/latest-" + type + "/");
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("title")[0];
var y = x.childNodes[0];
var txt = y.nodeValue;
if(txt == buildNumber) {
return true;
}
xml.close();
return false;
}
function notify(type, build) {
window.webkitNotifications.createNotification('icon.png', getTitle(type, build), getDescription(type, build));
}
function getTitle(type, build) {
var title;
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/");
var xmlDoc=xml.responseXML;
var name=xmlDoc.getElementsByTagName("name")[0];
var version=xmlDoc.getElementsByTagName("version")[0];
title+=name;
title+=" version ";
title+=version;
title+=" is out!";
xml.close();
return title;
}
function getDescription(type, build) {
var desc;
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/");
var xmlDoc=xml.responseXML;
var name=xmlDoc.getElementsByTagName("name")[0];
desc+="There is a new update for ";
desc+=name;
desc+=". You can download it here: ";
var downloadLink;
get_short_url(long_url, function(short_url) {downloadLink=short_url;});
desc+=downloadLink;
xml.close();
return desc;
}
function get_short_url(long_url, func) {
var login = "kezz101";
var api_key = "R_d68d87d13b42412a56be9bd9711c4dc4";
$.getJSON("http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url
},
function(response) {
func(response.data.url);
}
);
}
chrome.tabs.onActivated.addListener(function() {
var type = localStorage["type"];
var build = localStorage["build"];
if(!type) {
type = "rb";
}
if(!build) {
build = "craftbukkit";
}
if(isUpdateAvailable(type, build)) {
notify(type, build);
var xml = loadXMLDoc("http://dl.bukkit.org/api/1.0/downloads/projects/" + type + "/view/latest-" + build + "/");
var xmlDoc=xml.responseXML;
localStorage["version" + build + type] = xmlDoc.getElementsByTagName("build_number")[0];
xml.close();
}
});