Parse XML Output with Javascript for a Chrome Extension?
Wow, yeah crazy title.
But seriously, i have a little dilemma, i'开发者_JAVA技巧m trying to work on a chrome extension that very simply takes an XML output from a script on a server and displays it in a pleasing manner.
here's the XML result
<foo>
<level>3</level>
<message>
No Additional Information
</message>
</foo>
Basically all i need to do is put a conditional statement for each level and display the message. However i seem to be having problems just getting XHR to work at all.
My manifest file does have permissions for the XML file and the entire domain that it's hosted from (for debugging purposes at the moment).
It's been ages since i've worked with javascript and things have changed drastically. It also doesn't help that i'm cribbing off of an extension written for Firefox to get the job done.
Any thoughts?
Edit:
To clarify i'm fine with the if statements i need, and actually initiating the XHR should be fine, my issue is manipulating the data from the XML file.
When you fetch your XML file using XmlHttpRequest (XHR), you can specify what the response to the request would be from using responseXML
. The response will be parsed as if it were a text/xml stream.
The result to responseXML
would be a DOM Document object. You can use any JavaScript API under document.* such as document.getElementById
, document.querySelector
, etc. They are all defined in Document link above.
If your responseXML
returns null, that means the server is not throwing the correct mimetype. You can override the mimetype with overrideMimeType before calling
send()`.
For example
(Synchronous XHR, you can do Asynchronous too by specifying onreadystatechange):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/db.xml');
xhr.overrideMimeType('text/xml');
xhr.send(null)
var root = xhr.responseXML;
var someidDOM = root.getElementById('someid');
Remember, for this to work, you should place that code in the Background Page and give permission to access that resource. The match patterns that you can use could be the URL itself:
{
// Required
"name": "My Extension",
"version": "1.0",
"background_page": "background.html",
"permissions": [ "http://example.com/db.xml" ]
}
Hopefully that will help you get started!
精彩评论