简体   繁体   English

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

[英]How to read an online resource and update the popup in a Google Chrome extension

I'm trying to create my first Google Chrome Extension. 我正在尝试创建我的第一个Google Chrome扩展程序。

Any ideas why this is not copy pasting from the example.com website to my pop-up? 有什么想法为什么不将它从example.com网站复制粘贴到我的弹出窗口?

popup.js: 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: 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.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"
  ]
}

BTW, I'm not intending to inject captured content straight into my popup! 顺便说一句,我不打算将捕获的内容直接插入到我的弹出窗口中! (Script injecting etc.) At this stage, I'm just working out how everything works. (脚本注入等。)在这个阶段,我只是在研究一切工作原理。

There are a couple of issues 有几个问题

  1. You need to request permissions for any XMLHttp request you make, so that's clearly labeled in your extension. 您需要为您发出的任何XMLHttp请求请求权限,以便在扩展名中清楚地标记该标签。 The way to do this is to list the websites you're going to access in your manifest.son. 这样做的方法是在manifest.son中列出要访问的网站。 This is super simple and covered here: https://developer.chrome.com/extensions/xhr 这非常简单,在这里介绍: https : //developer.chrome.com/extensions/xhr

  2. The request itself, when you send it, it doesn't have an answer right away. 请求本身,当您发送时,它没有立即答复。 This is because it's going over the internet and making your request in the background. 这是因为它正在通过Internet传输并在后台发出您的请求。 So you can't ask for responseText straight after you call send - because it doesn't know the answer yet. 因此,您无法在致电send之后直接请求responseText,因为它尚不知道答案。 You have to tell it to call you back on a function after it's finished loading. 您必须告诉它在完成加载后再调用一个函数。 This is called a callback. 这称为回调。

  3. Debugging. 调试。 There is a tool you can install from Google to make “Inspect Element” work on your extension. 您可以从Google安装一种工具,以在扩展程序上使用“检查元素”。 This means that you can right click on your dropdown and choose inspect element from the context menu. 这意味着您可以右键单击下拉菜单,然后从上下文菜单中选择检查元素。 Then you can flip to the console tab and see all your javascript errors. 然后,您可以转到控制台标签,查看所有JavaScript错误。 https://chrome.google.com/webstore/detail/chrome-apps-extensions-de/ohmmkhmmmpcnpikjeljgnaoabkaalbgc?hl=en https://chrome.google.com/webstore/detail/chrome-apps-extensions-de/ohmmkhmmmpcnpikjeljgnaoabkaalbgc?hl=en

This also means you can sprinkle in console.log(“am here”) anywhere and you can see what's getting called and what's not... 这也意味着您可以将console.log(“ am here”)撒在任何地方,并且可以看到正在调用的内容和未调用的内容...

Here's what I got working combining yours with the google sample. 这是我将您的内容与Google示例结合在一起的结果。

Hope this helps! 希望这可以帮助! JFo JFO

manifest.json 的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 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 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM