javascript - 如何阅读在线资源并更新 Google Chrome 扩展程序中的弹出窗口

标签 javascript google-chrome

我正在尝试创建我的第一个 Google Chrome 扩展程序。

知道为什么这不是从 example.com 网站复制粘贴到我的弹出窗口吗?

popup.js:

document.addEventListener('DOMContentLoaded', function () {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", chrome.extension.getURL('http://example.com'), false);
  xhr.send();
  document.getElementById('response').innerHTML = xhr.responseText;
});

popup.html:

<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="popup.js"></script>
  </head>
  <body>
    <p id="response"></p>
  </body>
</html>

manifest.json:

{
  "manifest_version": 2,
  "name": "Getting started",
  "description": "Display test from Example.com",
  "version": "1.0",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
  },
  "permissions": [
    "http://example.com"
  ]
}

顺便说一句,我不打算将捕获的内容直接注入(inject)到我的弹出窗口中! (脚本注入(inject)等)在这个阶段,我只是弄清楚一切是如何工作的。

最佳答案

有几个问题

  1. 您需要为您发出的任何 XMLHttp 请求请求权限,以便在您的扩展中明确标记。方法是在您的manifest.son中列出您要访问的网站。这非常简单,如下所示:https://developer.chrome.com/extensions/xhr

  2. 请求本身,当您发送它时,它不会立即得到答复。这是因为它通过互联网并在后台提出您的请求。所以你不能在调用 send 之后直接请求responseText - 因为它还不知道答案。您必须告诉它在完成加载后回调您的函数。这称为回调。

  3. 调试。您可以从 Google 安装一个工具,使“Inspect Element”在您的扩展上运行。这意味着您可以右键单击下拉列表并从上下文菜单中选择检查元素。然后您可以翻转到控制台选项卡并查看所有 JavaScript 错误。 https://chrome.google.com/webstore/detail/chrome-apps-extensions-de/ohmmkhmmmpcnpikjeljgnaoabkaalbgc?hl=en

这也意味着你可以在任何地方添加 console.log(“am here”),你可以看到什么被调用了,什么没有......

这是我将您的示例与 Google 示例相结合得到的结果。

希望这有帮助! JFo

list .json

{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "http://www.example.com/"
  ]
}

Popup.js

// makeWebRequest
//
// ANY URLs you want to call with "makeWebRequest" need to be listed in your manifest.json
//    https://developer.chrome.com/extensions/xhr

//
// responseType 'json' 'document' 'text'
// callback is the function to call back on success. will be passed the XMLHttpRequest
// errorCallback is called when there's a problem

function makeWebRequest(urlToLoad, responseType, callback, errorCallback) {

  console.log("making web request for: "  + urlToLoad);

  var xmlReq = new XMLHttpRequest();
  xmlReq.open('GET', urlToLoad);
  // The Google image search API responds with JSON, so let Chrome parse it.
  xmlReq.responseType = responseType;
  xmlReq.onload = function() {
    // Parse and process the response from Google Image Search.
    var response = xmlReq.response;
   /// if (!response || !response.responseData || !response.responseData.results ||
    //    response.responseData.results.length === 0) {

    if (!xmlReq.response) {
       errorCallback('No response from the web request!');
       return;
    }


    callback(xmlReq);
  };
  xmlReq.onerror = function() {
    errorCallback('Network error.');
  };
  xmlReq.send();  // this goes away, makes the internet request, then calls back when it's finished.
}




// This is called when the extension loads.

document.addEventListener('DOMContentLoaded', function () {

  // Response type:
  // use json for json, document for html documents, text for raw text

  makeWebRequest("http://www.example.com/index.html", "document", 
    function (xmlReq) {
        // this is the function that is called back on when "Send" finishes

        // returns an HTMLDocument because we passed the "document" 
        // responseType into makeWebRequest.
        var doc = xmlReq.response;

        console.log("web request finished " + xmlReq.response);

        document.getElementById('response').innerHTML = doc.documentElement.innerHTML;
    }

  , function(errorMessage) {
        // this is the function that is called back on when there is an error 
        // requesting the file
        console.log("got error:" + errorMessage);

  });

});

弹出.html

<!doctype html>
<!--
 This page is shown when the extension button is clicked, because the
 "browser_action" field in manifest.json contains the "default_popup" key with
 value "popup.html".
 -->
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
        font-size: 100%;
      }
      #status {
        /* avoid an excessively wide status text */
        white-space: pre;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 400px;
      }
    </style>

    <!--
      - JavaScript and HTML must be in separate files: see our Content Security
      - Policy documentation[1] for details and explanation.
      -
      - [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
     -->
    <script src="popup.js"></script>
  </head>
  <body>
    Sample extension
    <div id="status"></div>
    <p id="response"></p>
    <img id="image-result" hidden>
  </body>
</html>

关于javascript - 如何阅读在线资源并更新 Google Chrome 扩展程序中的弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31611226/

相关文章:

javascript - 谷歌浏览器在加载期间错误地报告图像的宽度和高度

javascript - (打包的Chrome应用程序)chrome.identity.getAuthToken需要manifest.json中的 "key"

javascript - Codewars 挑战 - Hamelin 的聋鼠 - JavaScript - 如何通过特定字符集拆分字符串?

javascript - 如何使用 Javascript/jQuery 保存在浏览器(DOM)上修改过的 html

javascript - 如何在 AngularJS 中上传多个文件

javascript - 从 javascript 发送数据到 Laravel Controller

jQuery 的 'keypress' 不适用于 Chrome 中的某些键。如何解决?

html - Chrome下无法查看缓存文件

javascript - Chrome 应用程序文件系统。无法写入本地文件

javascript - D3 : Create a grouped bar chart from json objects