設定沙箱模式 JavaScript 政策

您可以設定政策指令碼,限制伺服器端容器的權限。本頁面說明如何設定容器的政策檔案。這些操作說明假設您已熟悉代碼管理工具的自訂範本政策

伺服器端政策檔案是一個 JavaScript 檔案,使用 gtag.js 語法來定義並註冊一或多項政策。

  1. 建立 JavaScript 檔案來建立並註冊一或多項政策。每項政策函式都會針對特定權限或所有權限註冊。政策函式傳回 false 或擲回例外狀況時,權限要求會遭到拒絕。例如:

    gtag('policy', 'all', function(container, policy, data) {
      // This function will run for every permission check. Return true to
      // allow the permission check. Return false or throw an exception to
      // deny the permission check.
    
      // container is the container id (e.g. GTM-ABC123)
      // policy is the permission type (e.g. get_cookies)
      // data is an object containing data about the permission request
    
      // This policy applies to only one container. This check allows the
      // same policy file to apply to more than one Tag Manager server
      // container.
      if (container !== 'GTM-ABC123') return true;
    
      // Since this code runs on all permission checks, conditionally check
      // the permission type and decide to permit or deny the permission.
      switch (policy) {
    
        // Container GTM-ABC123 can send HTTP requests. Everything else is
        // prohibited.
        case 'send_http':
          return true;
    
        // All other permission requests are denied.
        default:
          return false;
      }
    });
    
    gtag('policy', 'get_cookies', function(container, policy, data) {
      // This function will run for checks on the get_cookies permission.
    
      // Deny all permission checks to read cookies except for the 'user_id'
      // cookie. This check applies to all containers that load this policy
      // file.
      return data.name === 'user_id';
    });
    
  2. 使用可公開存取的 HTTPS 網址代管 JavaScript 檔案。這個檔案可代管於任何網路伺服器,但下列步驟說明如何將該檔案託管於 Google Cloud Storage 值區中。

    1. 前往 console.cloud.google.com,然後選取頁面頂端的專案。
    2. 依序選取左側導覽面板中的 [儲存空間] > [瀏覽器]
    3. 按一下「建立值區」
    4. 按照步驟建立值區。在「存取權控制」部分中選取 [精細]
    5. 按一下 [Upload files] (上傳檔案),然後上傳政策的 JavaScript 檔案。
    6. 檔案上傳完畢後,請按一下檔案名稱,然後選取 [編輯權限]。
    7. 按一下 [Add entry] 來執行下列操作:
      • 實體:公開
      • 名稱:allUsers
      • 存取權:Reader
    8. 按一下「儲存」
    9. 按一下 返回箭頭 即可返回上一頁。
    10. 在政策檔案的那一行,按一下 [複製網址]。
  3. 按照「建立或重新設定代碼伺服器」一文的步驟修改標記伺服器設定。當系統提示您提供政策網址時,請輸入步驟 2 的網址。