简体   繁体   English

如何在 chrome 扩展内容脚本中使用 google api?

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

I am trying to list labels using Gmail api.我正在尝试使用 Gmail api 列出标签。 I want to use Gmail api in content script.我想在内容脚本中使用 Gmail api。 Following is my manifest.json file and content script file:以下是我的 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
}

content-script.js:内容脚本.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);

after running this there should at least be a "hello" in the console proving that the handleClientLoad() function is working.运行此程序后,控制台中至少应该有一个“hello”,证明 handleClientLoad() function 正在工作。 But nothing shows in the console.但控制台中没有显示任何内容。

Technically, Chrome won't allow you to do that.从技术上讲,Chrome 不允许您这样做。 If you use content script to inject into a website then you can just send request only on that site, if you're trying to send a request into another site, Chrome will stop you due to CORS policy.如果您使用内容脚本注入网站,那么您只能在该网站上发送请求,如果您尝试将请求发送到另一个网站,Chrome 将根据 CORS 政策阻止您。

So to achieve it, you have to setup a background script which receive passed messages from your content script and then send request into Google API endpoint and then you can return the result into your content script via defined message channel.因此,要实现它,您必须设置一个后台脚本,该脚本从您的内容脚本接收传递的消息,然后将请求发送到 Google API 端点,然后您可以通过定义的消息通道将结果返回到您的内容脚本中。 Here is how you can setup message passing in Chrome Extension.这是在 Chrome 扩展程序中设置消息传递的方法。

暂无
暂无

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

相关问题 如何在 Chrome 扩展程序中使用 Google API? - How can I use the Google API in a chrome extension? 我可以在Chrome扩展程序内容脚本中使用和访问Chrome存储API吗? - Can I use and access the Chrome storage API within a chrome extension content script? 如何:将Google Ajax API动态加载到Chrome扩展内容脚本中 - how to: dynamically load google ajax api into chrome extension content script 如何在Chrome扩展程序的内容脚本中将事件监听器添加到Google表格链接? - How can I add event Listener to google sheets link in chrome extension's content script? 当页面上已有旧版本时,如何在chrome扩展内容脚本中使用jquery - How can I use jquery in a chrome extension content script when an older version is already on the page 如何在后台获取chrome扩展程序的内容脚本? - How can I get chrome extension's content script to in the background? 如何确定Chrome扩展程序是否位于内容脚本的弹出窗口中? - How can I determine if a Chrome extension is in a popup from the content script? "<i>How can I fetch data in my content script?<\/i>如何在我的内容脚本中获取数据?<\/b> <i>(chrome extension)<\/i> (镀铬扩展)<\/b>" - How can I fetch data in my content script? (chrome extension) 如何在内容脚本Chrome扩展程序中使用jquery - how to use jquery in content script chrome extension 如何在Chrome扩展程序中使用Google Classroom API? - How do I use the Google Classroom API in chrome extension?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM