简体   繁体   English

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

[英]How can I use the Google API in a chrome extension?

I'm now searching for hours how I can use the Google API in a chrome extension.我现在正在搜索如何在 chrome 扩展中使用 Google API。 All I want to do is to parse the contents of a website and insert it as a new event to Google Calender.我想要做的就是解析网站的内容并将其作为新事件插入到 Google 日历中。 I got the parsing and everything, but it seems to be impossible to use the Google API inside a Chrome extension.我得到了解析和一切,但似乎不可能在 Chrome 扩展程序中使用 Google API。 I'm just trying to write an example event when clicking the button in my chrome extension, but it keeps refusing to load the Google API with this error:我只是想在我的 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.

My manifest.json:我的 manifest.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"
     ]
}

My popup.html我的 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>

My popup.js:我的 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);
                    });
                }
            };
        }
    }
}

I have made a chrome extension using reactJS, making use of Google Calendar API for creating calendar events.我使用 reactJS 制作了一个 chrome 扩展,利用 Google Calendar API 创建日历事件。 I have pasted the link below, hope that it might help people to get an idea of how to implement the above use case properly.我已经粘贴了下面的链接,希望它可以帮助人们了解如何正确实现上述用例。

Project Link (Do star the repo, If this helps you)项目链接(请为 repo 加星标,如果这对您有帮助)

For using google calendars API, a pre requisite is to configure Oauth2 first because Google Calendar Api requires auth token.要使用谷歌日历 API,先决条件是先配置 Oauth2,因为谷歌日历 Api 需要 auth 令牌。 Your manifest file must contain changes to configure OAuth.您的清单文件必须包含配置 OAuth 的更改。

After configuring Oauth2 inside the manifest file of chrome extension, the following function will help you make a call to create an event.在chrome扩展的manifest文件里面配置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
      });
  });
}

Make sure your manifest file has the following entries:确保您的清单文件包含以下条目:

"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"
    ]

To breakdown:分解:

  1. For using Google API in chrome extension, first thing you need to do is to log-in.要在 chrome 扩展中使用 Google API,您需要做的第一件事就是登录。 As so many "security restriction" nowadays, you can't import the that API js like a website anymore.由于现在有这么多“安全限制”,您不能再像网站一样导入该 API js。 Instead, you need to use the browser api to grant the access, aka chrome.identity.getAuthToken ( https://developer.chrome.com/docs/extensions/reference/identity/#method-getAuthToken ).相反,您需要使用浏览器 api 来授予访问权限,即chrome.identity.getAuthToken ( https://developer.chrome.com/docs/extensions/reference/identity/#method-getAuthToken )。 But to get this browser api works, you still need to do bunch of other works, eg manifest, packing extension, etc. But you can learn those things and why those are related with Google by searching this browser api.但是要让这个浏览器 api 工作,你仍然需要做一堆其他的工作,例如清单、打包扩展等。但是你可以通过搜索这个浏览器 api 来了解这些东西以及为什么它们与谷歌相关。

  2. After STEP 1 success, you will get a token with chrome.identity.getAuthToken . STEP 1 成功后,您将获得一个带有chrome.identity.getAuthToken的令牌。 Now you need to know what to do to request Google APIs with this token.现在您需要知道如何使用此令牌请求 Google API。 Like the example in this page ( https://developers.google.com/streetview/publish/first-app ), we can see the token can be sent in header like this authorization: Bearer YOUR_ACCESS_TOKEN .就像这个页面中的例子( https://developers.google.com/streetview/publish/first-app ),我们可以看到令牌可以像这样的authorization: Bearer YOUR_ACCESS_TOKEN头发送authorization: Bearer YOUR_ACCESS_TOKEN So now we know we can use fetch / XMLHttpRequest with this header to get the Google API works for the user.所以现在我们知道我们可以使用带有这个标头的fetch / XMLHttpRequest来让 Google API 为用户工作。

It looks like you just forgot to reload extension package.看起来您只是忘记重新加载扩展包。 Note, that every time change is made to the extension code, reload which can be done here chrome://extensions/ is necessary to code changes take effect.请注意,每次更改扩展代码时,都需要重新加载chrome://extensions/才能使代码更改生效。

chrome 扩展包重新加载

To check if the client script is ready to be used, it is suggested to add onload callback like this:要检查客户端脚本是否可以使用,建议像这样添加 onload 回调:

window.callbackFunction = function(){
  alert('client.js ready')
  // here goes google client api calls
}

Name of the onload callback function is specified by onload parameter in script url. onload 回调函数的名称由脚本 url 中的onload参数指定。

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

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