Reputation: 45
I'm trying to retrieve a page with greasemonkey and then extract a link from it, inserting the link into the current page. I'm having some trouble with:
GM_xmlhttpRequest({
method: "GET",
url: "http://www.test.net/search.php?file=test",
onload: function(data)
{
if (!data.responseXML)
{
data.responseXML = new DOMParser().parseFromString(data.responseText, "text/xml");
}
alert("!");
var xmldata = data.response.xml;
var tests = xmldata.getElementsByTagName('test');
alert(tests[0].innerHTML);
}
});
The page is valid, and GM_xmlhttpRequest returned it correctly as a string when I tried previously, but I can't seem to figure out how to make it so I can use node operations on it.Thanks in advance.
Edit - a second, related question
How should I refer to the current page so that I could pass it a to function, just as I would pass my fetched page? Ex
function FindTests(currentpage)
{
currentpage.getElementById('blah');
}
where initially I pass it document, but later I use the fetched page. Sorry if the wording is confusing.
Upvotes: 3
Views: 2070
Reputation: 8773
if the requested page is a well-formatted xml, then you are in the correct way.
but you should change data.response.xml
to data.responseXML
and i THINK you can't do this with a XMLDocument
(result of the xml parser) because .getElementById
works in HTMLDocument
.
however, you could do the following to have a valid HTMLDocument:
if (/^Content-Type: text\/xml/m.test(data.responseHeaders)) {
data.responseXML = new DOMParser().parseFromString(data.responseText, "text/xml");
}
else if (/^Content-Type: text\/html/m.test(data.responseHeaders)) {
var dt = document.implementation.createDocumentType("html", "-//W3C//DTD HTML 4.01 Transitional//EN", "http://www.w3.org/TR/html4/loose.dtd");
var doc = document.implementation.createDocument(null, null, dt);
// I have to find a workaround because this technique makes the html*/head/body tags to disappear.
var html = document.createElement('html');
html.innerHTML = data.responseText;
doc.appendChild(html);
data.responseXML = doc;
}
source: http://userscripts.org/scripts/review/56489
Upvotes: 2