使用来自 chrome 扩展名的 POST 数据创建 link

Create a link with POST data from chrome extension

我创建了一个 chrome 扩展,它向某个服务器发送 POST 请求并获得其响应,然后根据数据显示一个数字标记。

现在我想根据用于将 POST 请求发送到服务器的数据在 popup.html 中创建一个 link,这样用户就可以在网站(数据来源)。

这是我在 popup.js 中用来发送 POST 请求

的代码
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://someserver/path', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    var regex = new RegExp(/ID:\d+/g);
    var testregex = regex.test(this.responseText);
    if (testregex == true) {
        var count = this.responseText.match(/ID:\d+/g).length;
        var countext = count.toString();
        chrome.browserAction.setBadgeText({text: countext});
    } else {
        chrome.browserAction.setBadgeText({text: "0"});
    }
};
getCurrentTabUrl(function(url) {
var cleanurl = url.match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i);
xhr.send('search=' + cleanurl[1] +'&submit=Search');
});

问题是如何使用我之前使用的相同 POST 数据创建 link?

感谢帮助

因此,您想要查询外部服务,然后在弹出窗口中显示一些信息,并带有 link 以获取更多信息。

让我们制作一个您将如何显示它的脚手架。在您的弹出窗口中,包括以下内容:

<div id="data-container">
  <div id="data-loading">
    <!-- Maybe add an animated spinner here, or something else -->
    Loading...
  </div>
  <div id="data-display">
    <!-- Currently empty, will add a link here -->
  </div>
</div>

随意设置样式。然后,从你的 XHR:

xhr.onload = function () {
  /* ... */

  // Hide the loading notice
  document.getElementById("data-loading").style.display = "none";

  // Create the element that will show more details;
  //  <a href="#"> works okay, but consider making a button
  var link = document.createElement("a");
      link.href = "#";
      link.text = "More details..." // Add data from xhr.responseText?
      link.addEventListener("click", clickHandler);

  var container = document.getElementById("data-display");

  // Make sure the container is empty (in case we're calling this again)
  while (container.lastChild) node.removeChild(container.lastChild);

  // Append more elements if you want to display some data
  container.appendChild(link);
};

现在是有趣的部分:clickHandler 点击处理程序。要从弹出窗口中打开一个新选项卡,您应该使用 chrome.tabs.create():

function clickHandler() {
  chrome.tabs.create({
    url: /* ??? */
  });
}

如果我们想打开一个普通的GET页面,那将是微不足道的。要打开 POST 页面,我们必须作弊。主要有两种可能:

  1. 打开执行 POST 的 javascript: URL。概念上更简单,但仅适用于短参数。

  2. 在您的扩展程序中打开一个将执行 POST 的帮助页面。这允许您在 POST 发生之前传递任意大的参数。

两者都包含在这个问题中:Chrome Extension Development - POST to new tab