Vikesh
Vikesh

Reputation: 2028

Read file packaged with Chrome extension in content script

I am developing a Chrome extension that needs to package an XML file (a trie data structure) and be able to read that file from the content script. So the content script will instantiate the trie after reading the data from the XML file every time the extension is loaded.

How to read this XML file through content script (or background page)? Do I need to use localStorage?

Upvotes: 10

Views: 3358

Answers (1)

Shrey
Shrey

Reputation: 882

A simple ajax request to the XML file should give you the XML DOM nodes:

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");
}

You would need to use a js-based xml parser or write your own. It might be easier to save your data as a JSON object.

Upvotes: 6

Related Questions