首页 > 解决方案 > 如何使用 chrome 扩展通过谷歌日历 API 创建事件?

问题描述

目标:使用 chrome 扩展创建一个谷歌日历事件。

我被困了好几个小时才能找到从我的弹出脚本中调用谷歌日历 api 的解决方案。但是,我不断收到以下错误:

拒绝加载脚本“https://apis.google.com/js/client.js”,因为它违反了以下内容安全策略指令:“script-src 'self' https://apis.google.com/js /api.js”。请注意,'script-src-elem' 没有明确设置,因此 'script-src' 用作后备。

如果我使用官方文档 ( https://developers.google.com/calendar/api/quickstart/js ) 中给出的示例,日历 api 就可以工作。但是,在此示例中,api 脚本是使用 html 文件中的 script 标签加载的,由于我不完全理解的原因,它没有遇到上述问题。

我的清单.json

{
    "manifest_version": 2,
  
    "name": "",
    "description": "",
    "version": "1.0",
    "permissions": [
        "identity","*://apis.google.com/*"
      ],
    "content_scripts":[
        {   "matches": ["<all_urls>"]
        }
      ],
    "browser_action":{
      "default_icon":"icon.png",
      "default_popup":"popup.html",
      "default_title":"A popup will come here"
    },
    "content_security_policy": "script-src 'self' https://apis.google.com/js/api.js; object-src 'self'"
    

    
  }

我的 popup.html

<!doctype html>
<html>

<head>
  <title>GTmetrix Analyzer</title>
  <script src="popup.js"></script>
</head>

<body>
  <button id="authorize_button" style="display: none;">Authorize</button>
  <button id="signout_button" style="display: none;">Sign Out</button>

</body>

</html>

我的 popup.js

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

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

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

var authorizeButton = document.getElementById("authorize_button");
var signoutButton = document.getElementById("signout_button");

function handleClientLoad() {
  gapi.load("client:auth2", initClient);
}

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());
        authorizeButton.onclick = handleAuthClick;
        signoutButton.onclick = handleSignoutClick;
      },
      function (error) {
        appendPre(JSON.stringify(error, null, 2));
      }
    );
}
/**
 *  Sign in the user upon button click.
 */
function handleAuthClick(event) {
  gapi.auth2.getAuthInstance().signIn();
}

/**
 *  Sign out the user upon button click.
 */
function handleSignoutClick(event) {
  gapi.auth2.getAuthInstance().signOut();
}

function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    authorizeButton.style.display = "none";
    signoutButton.style.display = "block";
    createEvent();
  } else {
    authorizeButton.style.display = "block";
    signoutButton.style.display = "none";
  }
}

function createEvent() {
  var event = {
    summary: "Google I/O 2015",
    location: "800 Howard St., San Francisco, CA 94103",
    description: "A chance to hear more about Google's developer products.",
    start: {
      dateTime: "2021-08-22T09:00:00-07:00",
      timeZone: "America/Los_Angeles",
    },
    end: {
      dateTime: "2021-08-22T17:00:00-07:00",
      timeZone: "America/Los_Angeles",
    },
  };

  gapi.client.calendar.events
    .insert({
      calendarId: "primary",
      resource: event,
    })
    .then(function (response) {
      appendPre("Event created: " + response.result.htmlLink);
      console.log(response);
    });
}


let script = document.createElement('script');
chrome.tabs.getSelected(null,function(tab){
    script.src = "https://apis.google.com/js/api.js";
    document.body.append(script);

})

script.addEventListener('load',function(){
  handleClientLoad();
})

注意:我也很想知道是否有比我目前正在做的更好的方法来制作这种类型的 chrome 扩展。谢谢!

标签: javascriptgoogle-chrome-extensiongoogle-oauthgoogle-calendar-apigoogle-api-js-client

解决方案


推荐阅读