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

时间:2015-07-24 13:01:38

标签: 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"
  ]
}
顺便说一句,我并不打算将捕获的内容直接注入弹出窗口! (脚本注入等)在这个阶段,我只是弄清楚一切是如何运作的。

1 个答案:

答案 0 :(得分:1)

有几个问题

  1. 您需要为您所做的任何XMLHttp请求请求权限,以便在您的扩展程序中明确标记。这样做的方法是在manifest.son中列出您要访问的网站。这非常简单,并在此处介绍:https://developer.chrome.com/extensions/xhr

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

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

  4. 这也意味着你可以在任何地方撒上console.log(“在这里”),你可以看到被调用的内容和什么不是......

    这就是我将你的工作与谷歌样本结合起来的工作。

    希望这有帮助! JFO

    的manifest.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);
    
      });
    
    });
    

    Popup.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>