如何在Chrome扩展中使用Google API? [英] How can I use the Google API in a chrome extension?

查看:51
本文介绍了如何在Chrome扩展中使用Google API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在寻找如何在Chrome扩展中使用Google API。所有我想做的就是解析一个网站的内容,并将其作为一个新事件插入到Google Calender中。我得到了解析和所有的东西,但是似乎不可能在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创建日历事件。我已经粘贴了下面的链接,希望它可以帮助人们了解如何正确实现上述用例。

Project Link(如果这对您有帮助,请启动回购)

要使用Google Calendars API,前提条件是首先配置OAuth2,因为Google Calendar Api需要auth令牌。您的清单文件必须包含更改才能配置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了。相反,您需要使用浏览器API授予访问权限,也就是。 chrome.identity.getAuthToken (https://developer.chrome.com/docs/extensions/reference/identity/#method-getAuthToken)。 但是要让这个浏览器API正常工作,你还需要做很多其他的工作,比如清单、打包扩展等等。但是你可以通过搜索这个浏览器API来了解这些事情,以及为什么这些事情与Google相关。

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

这篇关于如何在Chrome扩展中使用Google API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆