如何创建一个由单独Javascript生成的数据填充的弹出式html

How do you create a popup html populated with data generated from a separate Javascript

本文关键字:数据 填充 html 弹出式 Javascript 创建 何创建 一个 单独      更新时间:2023-09-26

我找到的所有关于弹出窗口的教程都与我需要的略有不同,我不知道如何根据我的需要修改它们。

我有一个browser_action图标集,当你点击它时,它会从HTML中创建一个弹出窗口,我在一个单独的文件中有一个javascript,它向API发送XMLHttpRequest。

这就是我想要完成的,但如果这是不可行的,我愿意用其他方法来完成类似的结果:

我希望弹出。html出现时,浏览器插件按钮按下;然后,pop .html应该运行脚本httpsdetect.js,它将从另一个站点接收数据;最后,httpdetect .js应该将接收到的数据显示回popup.html中。

这是我到目前为止写的。

一个清单。json:

  "manifest_version": 2,
  "name": "HTTPS Detect",
  "version": "1.0",
  "description": "Whatever",
  "icons": {
    "48": "icons/border-48.png"
},
"browser_action": {
  "default_icon": "icons/browser-32.png",
  "default_title": "Page Info",
  "default_popup": "popup/popup.html"
}
}

Popup.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="popup.css"/>
  </head>
  <body>
<script src="httpsdetect.js"></script> 
    
    
  </body>
</html>

CSS文件:

html, body {
  width: 100px;
}
.responseText {
  margin: 3% auto;
  padding: 4px;
  text-align: center;
  font-size: 1.5em;
  background-color: #E5F2F2;
  cursor: pointer;
}
.responseText:hover {
  background-color: #CFF2F2;
}

向另一个API发送GET请求的JavaScript。目前,它只是将接收到的数据发送到控制台,但我希望它填充popup.html:

console.log("Site hostname is: " + window.location.hostname);
var requestURL = "http://www.freegeoip.net/xml/" + window.location.hostname;
getRequest(requestURL, theCallback);
function getRequest(requestURL, theCallback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", requestURL, true);
xhr.onload = function (e) {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      theCallback(xhr.responseText);
    } else {
      console.error(xhr.statusText);
    }
  }
};
xhr.onerror = function (e) {
  console.error(xhr.statusText);
};
xhr.send(null);
}
function theCallback(theResponse) {
  console.log(theResponse);
}

这是一个简单的版本。更复杂的需要你自己完成:)

<body>
<span id="mySpan"></span>
</body>

JS:

function theCallback(theResponse) {
    var text = theResponse; // I don't know what you want... Just put the text of your response here.
    var mySpan = document.getElementById("mySpan");
    mySpan.textContent=text;
}

看一下:https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/Display_a_Popup

核心是:

var text_entry = require("sdk/panel").Panel({
  contentURL: data.url("text-entry.html"),
  contentScriptFile: data.url("get-text.js")
});