JavaScript 快速入門導覽課程

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

快速入門導覽課程會說明如何設定並執行會呼叫 Google Workspace API 的應用程式。

Google Workspace 快速入門導覽課程會使用 API 用戶端程式庫處理驗證和授權流程的部分細節。建議您在自己的應用程式中使用用戶端程式庫。每個快速入門導覽課程都必須啟用驗證和授權,才能執行範例應用程式。如果您不熟悉 Google Workspace API 的驗證和授權,請參閱驗證和授權總覽

建立向 Google Drive API 發出要求的 JavaScript 網路應用程式。

目標

  • 設定環境。
  • 設定範例。
  • 執行範例。

必要條件

  • 已啟用 Google 雲端硬碟的 Google 帳戶。

設定環境

如要完成本快速入門導覽課程,請設定您的環境。

啟用 API

您必須先在 Google Cloud 專案中啟用 Google API,才能使用 Google API。您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台啟用 Google Drive API。

    啟用 API

為網頁應用程式授權

如要以使用者的身分進行驗證,並存取應用程式中的使用者資料,您必須建立一或多個 OAuth 2.0 用戶端 ID。用戶端 ID 可讓 Google 的 OAuth 伺服器識別單一應用程式。如果您的應用程式是在多個平台中運作,您必須為每個平台分別建立用戶端 ID。
  1. 在 Google Cloud 控制台中,依序點選「選單」圖示 > [API 和服務] > [憑證]

    前往「憑證」

  2. 依序按一下 [建立憑證] > [OAuth 用戶端 ID]
  3. 依序按一下 [Application type] > [Web Application]
  4. 在 [名稱] 欄位中輸入憑證的名稱。這個名稱只會出現在 Google Cloud 控制台中。
  5. 新增與您應用程式相關的授權 URI:
    • 用戶端應用程式 (JavaScript):在「已獲授權的 JavaScript 來源」下方,按一下 [新增 URI]。然後輸入要用於瀏覽器要求的 URI。這個屬性可識別應用程式可向 API 2.0 伺服器傳送 API 要求的網域。
    • 伺服器端應用程式 (Java、Python 等):按一下「授權的重新導向 URI」下方的 [新增 URI]。然後輸入端點 URI,可供 OAuth 2.0 伺服器傳送回應。
  6. 按一下「建立」,畫面上會顯示 OAuth 用戶端建立的畫面,其中顯示新的用戶端 ID 和用戶端密鑰。

    記下用戶端 ID。網頁應用程式未用於用戶端密鑰。

  7. 按一下「OK」。新建立的憑證會顯示在「OAuth 2.0 用戶端 ID」之下。
  8. 選擇性:如果您要建立憑證做為 JavaScript 快速入門導覽課程的先決條件,就必須產生 API 金鑰

請記下這些憑證,您稍後將在本快速入門導覽課程中需要用到。

設定範例

  1. 在工作目錄中建立名為 index.html 的檔案。
  2. index.html 檔案中,貼上下列程式碼範例:

    drive/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Drive API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Drive API Quickstart</p>
    
        <!--Add buttons to initiate auth sequence and sign out-->
        <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
        <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
    
        <pre id="content" style="white-space: pre-wrap;"></pre>
    
        <script type="text/javascript">
          /* exported gapiLoaded */
          /* exported gisLoaded */
          /* exported handleAuthClick */
          /* exported handleSignoutClick */
    
          // TODO(developer): Set to client ID and API key from the Developer Console
          const CLIENT_ID = '<YOUR_CLIENT_ID>';
          const API_KEY = '<YOUR_API_KEY>';
    
          // Discovery doc URL for APIs used by the quickstart
          const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly';
    
          let tokenClient;
          let gapiInited = false;
          let gisInited = false;
    
          document.getElementById('authorize_button').style.visibility = 'hidden';
          document.getElementById('signout_button').style.visibility = 'hidden';
    
          /**
           * Callback after api.js is loaded.
           */
          function gapiLoaded() {
            gapi.load('client', initializeGapiClient);
          }
    
          /**
           * Callback after the API client is loaded. Loads the
           * discovery doc to initialize the API.
           */
          async function initializeGapiClient() {
            await gapi.client.init({
              apiKey: API_KEY,
              discoveryDocs: [DISCOVERY_DOC],
            });
            gapiInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Callback after Google Identity Services are loaded.
           */
          function gisLoaded() {
            tokenClient = google.accounts.oauth2.initTokenClient({
              client_id: CLIENT_ID,
              scope: SCOPES,
              callback: '', // defined later
            });
            gisInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Enables user interaction after all libraries are loaded.
           */
          function maybeEnableButtons() {
            if (gapiInited && gisInited) {
              document.getElementById('authorize_button').style.visibility = 'visible';
            }
          }
    
          /**
           *  Sign in the user upon button click.
           */
          function handleAuthClick() {
            tokenClient.callback = async (resp) => {
              if (resp.error !== undefined) {
                throw (resp);
              }
              document.getElementById('signout_button').style.visibility = 'visible';
              document.getElementById('authorize_button').innerText = 'Refresh';
              await listFiles();
            };
    
            if (gapi.client.getToken() === null) {
              // Prompt the user to select a Google Account and ask for consent to share their data
              // when establishing a new session.
              tokenClient.requestAccessToken({prompt: 'consent'});
            } else {
              // Skip display of account chooser and consent dialog for an existing session.
              tokenClient.requestAccessToken({prompt: ''});
            }
          }
    
          /**
           *  Sign out the user upon button click.
           */
          function handleSignoutClick() {
            const token = gapi.client.getToken();
            if (token !== null) {
              google.accounts.oauth2.revoke(token.access_token);
              gapi.client.setToken('');
              document.getElementById('content').innerText = '';
              document.getElementById('authorize_button').innerText = 'Authorize';
              document.getElementById('signout_button').style.visibility = 'hidden';
            }
          }
    
          /**
           * Print metadata for first 10 files.
           */
          async function listFiles() {
            let response;
            try {
              response = await gapi.client.drive.files.list({
                'pageSize': 10,
                'fields': 'files(id, name)',
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
            const files = response.result.files;
            if (!files || files.length == 0) {
              document.getElementById('content').innerText = 'No files found.';
              return;
            }
            // Flatten to string to display
            const output = files.reduce(
                (str, file) => `${str}${file.name} (${file.id})\n`,
                'Files:\n');
            document.getElementById('content').innerText = output;
          }
        </script>
        <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
        <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
      </body>
    </html>

    更改下列內容:

執行範例

  1. 在工作目錄中啟動網路伺服器:

    Python 2.x

    python -m SimpleHTTPServer 8000
    

    Python 3.x

    python3 -m http.server 8000
    
  2. 透過瀏覽器前往 http://localhost:8000

  3. 首次執行範例時,系統會提示您授予存取權:

    1. 如果您尚未登入 Google 帳戶,系統會提示您登入帳戶。如果您登入多個帳戶,請選取一個要授權的帳戶。
    2. 然後點選 [Accept]
    3. 從瀏覽器複製程式碼,然後貼到指令列提示中,然後按下 Enter

    授權資訊會儲存在檔案系統中,因此當您下次執行程式碼範例時,系統不會提示您授權。

您已成功建立第一個 JavaScript 應用程式,向 Google Drive API 發出要求。

後續步驟