我正在开发一个 Chrome 扩展程序,需要打包 XML 文件(trie 数据结构)并能够从内容脚本读取该文件。因此,每次加载扩展时,内容脚本都会在从 XML 文件读取数据后实例化 trie。
如何通过内容脚本(或后台页面)读取这个XML文件?我需要使用本地存储吗?
对 XML 文件的简单 ajax 请求应该为您提供 XML DOM 节点:
function request(url) {
var xhr = new XMLHttpRequest();
try {
xhr.onreadystatechange = function(){
if (xhr.readyState != 4)
return;
if (xhr.responseXML) {
console.debug(xhr.responseXML);
}
}
xhr.onerror = function(error) {
console.debug(error);
}
xhr.open("GET", url, true);
xhr.send(null);
} catch(e) {
console.error(e);
}
}
function init() {
request("sample.xml");
}
您需要使用基于 js 的 xml 解析器或编写自己的解析器。将数据保存为 JSON 对象可能会更容易。