如何在HTML日历中导入Google日历事件?

时间:2019-08-16 13:52:33

标签: javascript joomla calendar

我想将事件从Google日历添加到发布在网站上的html日历中。以下是我尝试使用的代码...

我尝试使用名为sourcerer的插件来实现一些Java代码。试图找到许多其他解决方案,但无法使其正常工作。

    {source}

<html>
    <head>
    </head>
<body bgcolor="black" text="white" link="#00ffff" vlink="green" alink="yellow">
<script>

var clientId = '9nu4mq883opnp9sdhl38uatqi0@group.calendar.google.com'; //choose web app client Id, redirect URI and Javascript origin set to http://localhost
var apiKey = 'AIzaSyBu0ntKF5OdCGr3pFlzaQvj3kp6nVi5ATA'; //choose public apiKey, any IP allowed (leave blank the allowed IP boxes in Google Dev Console)
var userEmail = "robertkruizinga@gmail.com"; //your calendar Id
var userTimeZone = "Amsterdam"; //example "Rome" "Los_Angeles" ecc...
var maxRows = 10; //events to shown
var calName = "Villa Valencia beschikbaarheid"; //name of calendar (write what you want, doesn't matter)

var scopes = 'https://www.googleapis.com/auth/calendar';

//--------------------- Add a 0 to numbers
function padNum(num) {
    if (num <= 9) {
        return "0" + num;
    }
    return num;
}
//--------------------- end    

//--------------------- From 24h to Am/Pm
function AmPm(num) {
    if (num <= 12) { return "am " + num; }
    return "pm " + padNum(num - 12);
}
//--------------------- end    

//--------------------- num Month to String
function monthString(num) {
         if (num === "01") { return "JAN"; } 
    else if (num === "02") { return "FEB"; } 
    else if (num === "03") { return "MAR"; } 
    else if (num === "04") { return "APR"; } 
    else if (num === "05") { return "MAJ"; } 
    else if (num === "06") { return "JUN"; } 
    else if (num === "07") { return "JUL"; } 
    else if (num === "08") { return "AUG"; } 
    else if (num === "09") { return "SEP"; } 
    else if (num === "10") { return "OCT"; } 
    else if (num === "11") { return "NOV"; } 
    else if (num === "12") { return "DEC"; }
}
//--------------------- end

//--------------------- from num to day of week
function dayString(num){
         if (num == "1") { return "mon" }
    else if (num == "2") { return "tue" }
    else if (num == "3") { return "wed" }
    else if (num == "4") { return "thu" }
    else if (num == "5") { return "fri" }
    else if (num == "6") { return "sat" }
    else if (num == "0") { return "sun" }
}
//--------------------- end

//--------------------- client CALL
function handleClientLoad() {
    gapi.client.setApiKey(apiKey);
    checkAuth();
}
//--------------------- end

//--------------------- check Auth
function checkAuth() {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
//--------------------- end

//--------------------- handle result and make CALL
function handleAuthResult(authResult) {
    if (authResult) {
        makeApiCall();
    }
}
//--------------------- end

//--------------------- API CALL itself
function makeApiCall() {
    var today = new Date(); //today date
    gapi.client.load('calendar', 'v3', function () {
        var request = gapi.client.calendar.events.list({
            'calendarId' : userEmail,
            'timeZone' : userTimeZone, 
            'singleEvents': true, 
            'timeMin': today.toISOString(), //gathers only events not happened yet
            'maxResults': maxRows, 
            'orderBy': 'startTime'});
    request.execute(function (resp) {
            for (var i = 0; i < resp.items.length; i++) {
                var li = document.createElement('li');
                var item = resp.items[i];
                var classes = [];
                var allDay = item.start.date? true : false;
                var startDT = allDay ? item.start.date : item.start.dateTime;
                var dateTime = startDT.split("T"); //split date from time
                var date = dateTime[0].split("-"); //split yyyy mm dd
                var startYear = date[0];
                var startMonth = monthString(date[1]);
                var startDay = date[2];
                var startDateISO = new Date(startMonth + " " + startDay + ", " + startYear + " 00:00:00");
                var startDayWeek = dayString(startDateISO.getDay());
                if( allDay == true){ //change this to match your needs
                    var str = [
                    '<font size="4" face="courier">',
                    startDayWeek, ' ',
                    startMonth, ' ',
                    startDay, ' ',
                    startYear, '</font><font size="5" face="courier"> @ ', item.summary , '</font><br><br>'
                    ];
                }
                else{
                    var time = dateTime[1].split(":"); //split hh ss etc...
                    var startHour = AmPm(time[0]);
                    var startMin = time[1];
                    var str = [ //change this to match your needs
                        '<font size="4" face="courier">',
                        startDayWeek, ' ',
                        startMonth, ' ',
                        startDay, ' ',
                        startYear, ' - ',
                        startHour, ':', startMin, '</font><font size="5" face="courier"> @ ', item.summary , '</font><br><br>'
                        ];
                }
                li.innerHTML = str.join('');
                li.setAttribute('class', classes.join(' '));
                document.getElementById('events').appendChild(li);
            }
        document.getElementById('updated').innerHTML = "updated " + today;
        document.getElementById('calendar').innerHTML = calName;
        });
    });
}
//--------------------- end
</script>
<script src='https://apis.google.com/js/client.js?onload=handleClientLoad'></script>
    <div id='content'>
    <h1 id='calendar' style="color:grey">LOADING . . . .</h1>
    <ul id='events'></ul>
    </div>
    <p id='updated' style="font-size:12; color:grey">updating . . . . .</p>
    </body>
</html>



<div class="calendar">
<div class="calendar__picture">
<h2>,11 Sunday</h2>
<h3>Augustus</h3>
</div>
<div class="calendar__date">
<div class="calendar__day">M</div>
<div class="calendar__day">T</div>
<div class="calendar__day">W</div>
<div class="calendar__day">T</div>
<div class="calendar__day">F</div>
<div class="calendar__day">S</div>
<div class="calendar__day">S</div>
<div class="calendar__number"></div>
<div class="calendar__number"></div>
<div class="calendar__number"></div>
<div class="calendar__number">1</div>
<div class="calendar__number">2</div>
<div class="calendar__number">3</div>
<div class="calendar__number">4</div>
<div class="calendar__number">5</div>
<div class="calendar__number">6</div>
<div class="calendar__number">7</div>
<div class="calendar__number">8</div>
<div class="calendar__number">9</div>
<div class="calendar__number">10</div>
<div class="calendar__number">11</div>
<div class="calendar__number">12</div>
<div class="calendar__number">13</div>
<div class="calendar__number">14</div>
<div class="calendar__number">15</div>
<div class="calendar__number">16</div>
<div class="calendar__number">17</div>
<div class="calendar__number calendar__number--current">18</div>
<div class="calendar__number">19</div>
<div class="calendar__number">20</div>
<div class="calendar__number">21</div>
<div class="calendar__number">22</div>
<div class="calendar__number">23</div>
<div class="calendar__number">24</div>
<div class="calendar__number">25</div>
<div class="calendar__number">26</div>
<div class="calendar__number">27</div>
<div class="calendar__number">28</div>
<div class="calendar__number">29</div>
<div class="calendar__number">30</div>
</div>
</div>{/source}

源代码来自一个名为sourcerer的插件,我将其用于Java代码。 我试图找到其他解决方案,例如更改导入的Google日历的CSS,但无法像我想要的那样更改布局。它只是一直重置为标准的Google布局。

所以这是另一个编辑,我试图在Dreamweaver中遵循Google的快速入门教程。我已将以下代码添加到新的index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Google Calendar API Quickstart</title>
    <meta charset="utf-8" />
  </head>
  <body>
    <p>Google Calendar API Quickstart</p>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize_button" style="display: none;">Authorize</button>
    <button id="signout_button" style="display: none;">Sign Out</button>

    <pre id="content" style="white-space: pre-wrap;"></pre>

    <script type="text/javascript">
      // Client ID and API key from the Developer Console
      var CLIENT_ID = '<111283467407-ia17tmh2tslj37be3r1ak8p2784ut37n.apps.googleusercontent.com>';
      var API_KEY = '<AIzaSyB_NUYfmr2FlZgC2oMYmWKk9lTQo0VnN_0>';

      // 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.readonly";

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

      /**
       *  On load, called to load the auth2 library and API client library.
       */
      function handleClientLoad() {
        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());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        }, function(error) {
          appendPre(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) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';
          listUpcomingEvents();
        } else {
          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

      /**
       *  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();
      }

      /**
       * Append a pre element to the body containing the given message
       * as its text node. Used to display the results of the API call.
       *
       * @param {string} message Text to be placed in pre element.
       */
      function appendPre(message) {
        var pre = document.getElementById('content');
        var textContent = document.createTextNode(message + '\n');
        pre.appendChild(textContent);
      }

      /**
       * Print the summary and start datetime/date of the next ten events in
       * the authorized user's calendar. If no events are found an
       * appropriate message is printed.
       */
      function listUpcomingEvents() {
        gapi.client.calendar.events.list({
          'calendarId': 'primary',
          'timeMin': (new Date()).toISOString(),
          'showDeleted': false,
          'singleEvents': true,
          'maxResults': 10,
          'orderBy': 'startTime'
        }).then(function(response) {
          var events = response.result.items;
          appendPre('Upcoming events:');

          if (events.length > 0) {
            for (i = 0; i < events.length; i++) {
              var event = events[i];
              var when = event.start.dateTime;
              if (!when) {
                when = event.start.date;
              }
              appendPre(event.summary + ' (' + when + ')')
            }
          } else {
            appendPre('No upcoming events found.');
          }
        });
      }

    </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>
</html>

执行此操作时,出现以下错误:

Google Calendar API快速入门

{
  "error": {
    "errors": [
      {
        "domain": "usageLimits",
        "reason": "keyInvalid",
        "message": "Bad Request"
      }
    ],
    "code": 400,
    "message": "Bad Request"
  }
}

有人可以帮助我解决这个问题吗?

0 个答案:

没有答案