问题
I'm currently trying to build my first Chrome extension but I'm having a slight issue with my code.
I want to use XMLHTTPRequest and xpath to display a specific number from an external website as a badge on my icon. The code I'm using in my background.js file is as follows:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// innerText does not let the attacker inject HTML elements.
document.getElementById("resp").innerText = xhr.responseText;
}
}
xhr.send();
var xmlDoc = xhr.responseXML;
xmlDoc.setProperty('SelectionLanguage', 'XPath');
var badgeText = xmldoc.documentElement.selectSingleNode("//[@id='main']/div/div/section/div[1]/div[2]");
chrome.browserAction.setBadgeText({text: badgeText});
chrome.browserAction.setBadgeBackgroundColor({color: "#1f729f"});
I know this code is probably pretty horrible but this is my first extension and I'd really appreciate any help.
Thanks in advance.
回答1:
It looks like you are expecting some immediate response after xhr.send();
Here the code snipet which is working in one of my extensions (notice this in the callback function):
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com", true);
xhr.onreadystatechange = function() {
console.log("XHR callback readyState = " + this.readyState);
if (this.readyState == 4) {
// innerText does not let the attacker inject HTML elements.
document.getElementById("resp").innerText = this.responseText;
var xmlDoc = this.responseXML;
xmlDoc.setProperty('SelectionLanguage', 'XPath');
var badgeText = xmldoc.documentElement.selectSingleNode("//[@id='main']/div/div/section/div[1]/div[2]");
chrome.browserAction.setBadgeText({text: badgeText});
chrome.browserAction.setBadgeBackgroundColor({color: "#1f729f"});
}
}
xhr.send();
This way the code would be executed only after the response is available.
Hope this helps ;-)
来源:https://stackoverflow.com/questions/22263391/building-chrome-extension-using-xpath-and-cross-origin-xmlhttprequest