簡體   English   中英

如何在 chrome 擴展內容腳本中使用 google api?

[英]How can I use google api in chrome extension content script?

我正在嘗試使用 Gmail api 列出標簽。 我想在內容腳本中使用 Gmail api。 以下是我的 manifest.json 文件和內容腳本文件:

{
  "name": "Append Test Text",
  "description": "Add test123 to body",
  "version": "1.0",
  "permissions": ["activeTab"],
  "content_scripts": [
    {
      "matches": ["https://mail.google.com/*"],
      "js": ["jquery-3.4.1.min.js", "gmail.js", "content-script.js"],
      "all_frames": true
    }
  ],
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "browser_action": {
    "default_title": "Append Test Text"
  },
  "manifest_version": 2
}

內容腳本.js:

// Client ID and API key from the Developer Console
var CLIENT_ID = "<CLIENT_ID>";
var API_KEY = "<API_KEY>";

// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = [
  "https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"
];

// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/gmail.readonly";

/**
 *  On load, called to load the auth2 library and API client library.
 */
function handleClientLoad() {
  console.log("hello");
  gapi.load("client:auth2", initClient);
}

/**
 *  Initializes the API client library and sets up sign-in state
 *  listeners.
 */
function initClient() {
  gapi.client
    .init({
      apiKey: API_KEY,
      clientId: CLIENT_ID,
      discoveryDocs: DISCOVERY_DOCS,
      scope: SCOPES
    })
    .then(
      function() {
        // Listen for sign-in state changes.
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

        // Handle the initial sign-in state.
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      },
      function(error) {
        console.log(JSON.stringify(error, null, 2));
      }
    );
}

/**
 *  Called when the signed in status changes, to update the UI
 *  appropriately. After a sign-in, the API is called.
 */
function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    listLabels();
  } else {
    gapi.auth2.getAuthInstance().signIn();
  }
}

/**
 * Print all Labels in the authorized user's inbox. If no labels
 * are found an appropriate message is printed.
 */
function listLabels() {
  gapi.client.gmail.users.labels
    .list({
      userId: "me"
    })
    .then(function(response) {
      var labels = response.result.labels;
      console.log("Labels:");

      if (labels && labels.length > 0) {
        for (i = 0; i < labels.length; i++) {
          var label = labels[i];
          console.log(label.name);
        }
      } else {
        console.log("No Labels found.");
      }
    });
}
var script = $(
  '<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === "complete") this.onload()"></script>'
);
$("body").append(script);

運行此程序后,控制台中至少應該有一個“hello”,證明 handleClientLoad() function 正在工作。 但控制台中沒有顯示任何內容。

從技術上講,Chrome 不允許您這樣做。 如果您使用內容腳本注入網站,那么您只能在該網站上發送請求,如果您嘗試將請求發送到另一個網站,Chrome 將根據 CORS 政策阻止您。

因此,要實現它,您必須設置一個后台腳本,該腳本從您的內容腳本接收傳遞的消息,然后將請求發送到 Google API 端點,然后您可以通過定義的消息通道將結果返回到您的內容腳本中。 這是在 Chrome 擴展程序中設置消息傳遞的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM