使用 xpath 和 Cross-Origin XMLHttpRequest 构建 Chrome 扩展 [英] Building Chrome extension using xpath and Cross-Origin XMLHttpRequest

查看:43
本文介绍了使用 xpath 和 Cross-Origin XMLHttpRequest 构建 Chrome 扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试构建我的第一个 Chrome 扩展程序,但我的代码有一个小问题.

I'm currently trying to build my first Chrome extension but I'm having a slight issue with my code.

我想使用 XMLHTTPRequest 和 xpath 将来自外部网站的特定数字显示为我图标上的徽章.我在 background.js 文件中使用的代码如下:

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.

提前致谢.

推荐答案

看起来您希望在 xhr.send();

这是在我的一个扩展中工作的代码片段(注意回调函数中的this):

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.

希望这有帮助;-)

这篇关于使用 xpath 和 Cross-Origin XMLHttpRequest 构建 Chrome 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆