如何在 Chrome 扩展程序中使用 Google API?

2023-11-23

我现在正在花几个小时搜索如何在 Chrome 扩展中使用 Google API。我想做的就是解析网站的内容并将其作为新事件插入到 Google 日历中。我得到了解析和一切,但似乎不可能在 Chrome 扩展中使用 Google API。我只是想在单击 chrome 扩展中的按钮时编写一个示例事件,但它一直拒绝加载 Google API,并出现以下错误:

Refused to load the script 'https://apis.google.com/js/platform.js' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

我的清单.json:

{
    "manifest_version": 2,

    "name": "DVB2Calender",
    "description": "This extension will export the current viewed schedule to your Google Calender.",
    "version": "1.0",

    "content_security_policy": "script-src 'self' https://apis.google.com/; object-src 'self'",

    "browser_action": {
     "default_icon": "icon.png",
     "default_popup": "popup.html"
    },
    "permissions": [
     "activeTab"
     ]
}

我的 popup.html

<!doctype html>
<html>
  <head>
    <title>DVB2Calender</title>
    <meta http-equiv="Content-Security-Policy" content="default-src *;">
    <script src="popup.js"></script>
    <script src="https://apis.google.com/js/platform.js" async defer>
    </script>
  </head>
  <body>

    <h1>DVB to Calender</h1>
    <button id="exportToCalender">Export this calender to Google Calender!</button>

  </body>
</html>

我的 popup.js:

document.addEventListener('DOMContentLoaded', function() {
    var checkPageButton = document.getElementById('exportToCalender');
    checkPageButton.addEventListener('click', function() {

        chrome.tabs.getSelected(null, function(tab) {
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = "https://apis.google.com/js/client.js?onload=callbackFunction";
            head.appendChild(script);

            d = document;
            var download = d.getElementsByClassName('icon-link ico-calender')[6];
            var request = makeHttpObject();
            request.open("GET", download, true);
            request.send(null);
            request.onreadystatechange = function() {
                if (request.readyState === 4) {
                    var resultText = request.responseText;
                    array = CSVToArray(resultText, ":");
                    alert(resultText);

                    var resource = {
                        "summary": "Appointment",
                        "location": "Somewhere",
                        "start": {
                        "dateTime": "2011-12-16T10:00:00.000-07:00"
                        },
                        "end": {
                        "dateTime": "2011-12-16T10:25:00.000-07:00"
                        }
                    };
                    var request = gapi.client.calendar.events.insert({
                    'calendarId': 'primary',
                    'resource': resource
                    });
                    request.execute(function(resp) {
                    console.log(resp);
                    });
                }
            };
        }
    }
}

我使用reactJS制作了一个chrome扩展,利用Google Calendar API来创建日历事件。我粘贴了下面的链接,希望它可以帮助人们了解如何正确实现上述用例。

项目链接(如果这对您有帮助,请为回购加注星标)

要使用 Google Calendars API,先决条件是首先配置 Oauth2,因为 Google Calendar Api 需要身份验证令牌。您的清单文件必须包含配置 OAuth 的更改。

在 chrome 扩展的清单文件中配置 Oauth2 后,以下函数将帮助您调用创建事件。

function createMeeting() {
  chrome.identity.getAuthToken({ interactive: true }, function (token) {
    console.log(token);

    
    //details about the event
    let event = {
      summary: 'Google Api Implementation',
      description: 'Create an event using chrome Extension',
      start: {
        'dateTime': '2015-05-28T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles'
      },
      end: {
        'dateTime': '2015-05-28T09:00:00-07:00',
        'timeZone': 'America/Los_Angeles'
      }
    };

    let fetch_options = {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(event),
    };

    fetch(
      'https://www.googleapis.com/calendar/v3/calendars/primary/events',
      fetch_options
    )
      .then((response) => response.json()) // Transform the data into json
      .then(function (data) {
        console.log(data);//contains the response of the created event
      });
  });
}

确保您的清单文件包含以下条目:

"oauth2": {
    "client_id": "your id",
    "scopes": [
      "profile email",
      "https://www.googleapis.com/auth/calendar",
      "https://www.googleapis.com/auth/calendar.readonly"
    ]
  },
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "permissions": [
      "identity",
      "identity.email"
    ]

细分:

  1. 要在 Chrome 扩展中使用 Google API,您需要做的第一件事就是登录。由于现在这么多“安全限制”,你不能再像网站一样导入API js了。相反,您需要使用浏览器 api 来授予访问权限,即:chrome.identity.getAuthToken (https://developer.chrome.com/docs/extensions/reference/identity/#method-getAuthToken)。 但是为了让这个浏览器 api 工作,你仍然需要做很多其他工作,例如但是你可以通过搜索这个浏览器api来了解这些东西以及为什么它们与Google相关。

  2. 第 1 步成功后,您将获得一个令牌chrome.identity.getAuthToken。现在您需要知道如何使用此令牌请求 Google API。就像本页的例子一样 (https://developers.google.com/streetview/publish/first-app), 我们 可以看到令牌可以像这样在标头中发送authorization: Bearer YOUR_ACCESS_TOKEN。所以现在我们知道我们可以使用fetch / XMLHttpRequest使用此标头让 Google API 为用户工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Chrome 扩展程序中使用 Google API? 的相关文章

随机推荐

  • 检查 W10 上的 Windows 版本

    有谁知道 TOSVersion Name 是否仍然适用于 Windows 10 我有一个 vcl 应用程序 它有一个表单显示事件 该事件获取操作系统详细信息并使用 SysUtils 中的 TOSVersion 记录将它们显示在 TMemo
  • 为什么 Java 会产生这么多进程?

    我编写了一个 Java 服务器应用程序 在Debian 7 虚拟服务器 该应用程序本身工作得很好 但我注意到一些非常奇怪的事情 Issue 打电话后java Xmx200M jar CCU jar我希望看到一个 Java 进程运行我的CCU
  • richfaces suggestBox 将附加值传递给支持 bean

    使用 RichFaces 时suggestionBox如何从带有文本输入的页面传递多个 id 或值suggestionBox支持豆 即 显示所选州内的建议城市列表 这是我的autoComplete method public List lt
  • pandas groupby 计算列中零的数量

    我有一个数据框 例如 Date B C 20 07 2018 10 8 20 07 2018 1 0 21 07 2018 0 1 21 07 2018 1 0 如何计算每个日期每列的零值和非零值 使用 sum 对我没有帮助 因为它会将非零
  • 从Python中的基类继承namedtuple

    是否有可能生产一个namedtuple哪个继承自基类 我想要的是Circle and Rectangle are namedtuples 和 都是从公共基类 Shape 继承的 from collections import namedtu
  • 如何将实体框架添加到控制台应用程序(包含图像)

    I try to add entity framework to console application I press add new item and then then 然后我添加了代码 class Program static vo
  • Chrome 不支持 Service Worker (69.0.3497.81)

    我开始使用 PWA 渐进式网络应用程序 当我尝试检查 Chrome 浏览器是否支持 Service Worker 时 它总是返回 false 下面的代码我用于检查 Note 我使用的是 chrome 版本 69 0 3497 81 官方版本
  • 如何使用 python nltk 获取解析树?

    给出以下句子 The old oak tree from India fell down 如何使用 python NLTK 获得句子的以下解析树表示 ROOT S NP NP DT The JJ old NN oak NN tree PP
  • char four[4] = "四";该语句的正确语义是什么?

    int main void char four 4 four return 0 当编译为 C 程序时 G 会报告 xxx cpp 在函数 int main 中 xxx cpp 3 错误 字符数组的初始化字符串太长 编译 C 程序时 GCC
  • 如何在网页上制作pandas操作的进度条

    我已经在谷歌上搜索了一段时间 但无法找到一种方法来做到这一点 我有一个简单的 Flask 应用程序 它接受 CSV 文件 将其读入 Pandas 数据帧 将其转换并输出为新的 CSV 文件 我已经成功上传并使用 HTML 转换它 div c
  • 另一个围栏代码块内的围栏代码块

    我正在尝试写有关 Markdown 语法的文章 并且为了编写它 我使用 Markdown 所以 我的文档如下所示 Example of markdown code foo fenced code block fail bar lalala
  • AppFabric 缓存 - 我可以指定用于所有对象的序列化样式吗?

    实现某些自定义序列化的对象可以序列化和反序列化为不同的格式 例如 Xml 或 byte 我遇到了一个问题 当我放入缓存时 AppFabric 在类上运行 IXmlSerialized 实现 而我宁愿强制它使用二进制文件 AppFabric
  • 如何使用 adb 卸载所有 3rd 方用户应用程序?

    我正在尝试创建一个脚本 该脚本将通过以下方式在一次批量操作中检索和卸载所有用户应用程序adb 有谁知道我怎样才能做到这一点 我目前可以通过以下方式列出所有 3rd 方应用程序 adb shell pm list packages 3 我可以
  • 我如何知道图片何时加载到 Picturebox 中

    我有一些巨大的图像 7000 5000 要在我的程序中同时加载 我将它们一张一张地显示在图片框中 这些图像需要一些时间才能加载到图片框 首先 我将所有图像加载到Image数组为Bitmap 然后我只显示图片框中的第一张图像picturebo
  • Numpy:条件和

    我有以下 numpy 数组 import numpy as np arr np array 1 2 3 4 2000 5 6 7 8 2000 9 0 1 2 2001 3 4 5 6 2001 7 8 9 0 2002 1 2 3 4 2
  • 平方根函数是如何实现的? [关闭]

    Closed 这个问题需要多问focused 目前不接受答案 平方根函数是如何实现的 简单的实现使用二分查找用C double root double n Max and min are used to take into account
  • 如何在 selenium 自动化中更改 chrome 浏览器语言

    我想自动化 Web 应用程序的本地化功能 根据我的应用程序 当浏览器语言更改时 应用程序语言应该根据浏览器语言自动更改 怎么做 在启动驱动程序之前 在 chrome 选项中设置语言代码 如下所示 System setProperty web
  • Eclipse 无法编译,类文件错误,版本错误

    我正在尝试编译从另一个开发人员处签出的 SVN 代码 Eclipse 最近给我带来了很多麻烦 Here are my project specific settings 这是我的 ant 文件的编译部分
  • 哪个编译器(如果有)在参数包扩展中存在错误?

    在尝试以容器形式访问元组的便捷方法时 我编写了一个测试程序 在 clang 3 9 1 和 apple clang 上 它按预期进行编译 产生预期的输出 1 1 foo 2 在 gcc 5 4 6 3 上 无法编译
  • 如何在 Chrome 扩展程序中使用 Google API?

    我现在正在花几个小时搜索如何在 Chrome 扩展中使用 Google API 我想做的就是解析网站的内容并将其作为新事件插入到 Google 日历中 我得到了解析和一切 但似乎不可能在 Chrome 扩展中使用 Google API 我只