首页 > 解决方案 > 如何将变量添加到 xhr.open outta Chrome 扩展?

问题描述

我正在编写一个 Chrome 扩展程序,它应该在浏览器中加载每个新域时获得特殊的远程 url,将当前域添加到它(如 with window.location.hostname),从目标页面获取特殊指标,以这种方式生成,(with XMLHttpRequestand XPath),并将此度量显示为BadgeText

我几乎所有的工作,但只有静态网址。如果不是"+window.location.hostname+"我对任何域名进行硬编码,一切都会像预期的那样工作 - 我得到的数字是BadgeText. 但是,如何使用当前加载在浏览器中的域来完成这项工作?

这是我的background.js

chrome.tabs.onUpdated.addListener(function (tabid, changeInfo, tab) {
    chrome.tabs.query({ 'active': true, 'currentWindow': true }, function (tabs) {
        let newUrl = new URL(tabs[0].url);
        currentDomain = newUrl.hostname;
        console.log(currentDomain);
    });
});

var xhr = new XMLHttpRequest();

xhr.open("GET", "url part 1" + window.location.hostname + "url part 2", true);

xhr.responseType = 'document';

xhr.send();

xhr.onreadystatechange = function () {
    console.log("XHR callback readyState = " + this.readyState);
    if (this.readyState == 4) {

        function getElementByXpath(path) {
            return xhr.response.evaluate(path, xhr.response, null, XPathResult.STRING_TYPE, null).stringValue;
        }

        console.log(getElementByXpath("//div[@class='data-mini']/span/span[@class='value']/text()"));

        var badgeText = getElementByXpath("//div[@class='data-mini']/span/span[@class='value']/text()");
        console.log(badgeText);
        chrome.browserAction.setBadgeText({ text: String(badgeText) });

        console.log(String(badgeText));
    }
}

在第一部分中,我将当前加载的选项卡的干净域放入控制台。第二部分应该完成剩下的工作。

剩下的就是得到

currentDomain

进入

xhr.open("GET", "https://app.sistrix.com/app_visindex/__loadModule/lang/de/domain/"+currentDomain+"/source/de/ref/app_controller_efcdc3b3cab713326d8830ac95b499e454ae4e46053a5cc6/_action/_result/_cache//_loadbox/empty/_ajax/1/_module-expire/217287/_controller", true);

主要目标:

标签: javascriptgoogle-chrome-extension

解决方案


正确且有效的代码是:

chrome.tabs.onUpdated.addListener(function(tabid, changeInfo, tab){
    chrome.tabs.query({'active' : true, 'currentWindow': true}, function(tabs){
        let newUrl = new URL(tabs[0].url);
        var currentDomain = newUrl.hostname;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "url part 1"+currentDomain+"url part 2", true);
        xhr.responseType='document';
        xhr.send();
        xhr.onreadystatechange = function() {
          if (this.readyState == 4) {

        function getElementByXpath(path) {
          return xhr.response.evaluate(path, xhr.response, null, XPathResult.STRING_TYPE, null).stringValue;
        }
            var badgeText = getElementByXpath("//div[@class='data-mini']/span/span[@class='value']/text()");
          chrome.browserAction.setBadgeText({text: String(badgeText)});
          chrome.browserAction.setBadgeBackgroundColor({ color: '#1d2554' });
          }
        }
    });
});

推荐阅读