Building Chrome extension using xpath and Cross-Origin XMLHttpRequest

会有一股神秘感。 提交于 2020-01-30 10:58:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!