自定义模板政策

政策的实现是在网页上进行的。当容器在网页上运行时,系统会在跟踪代码管理器的自定义模板定义中应用政策,以控制某些功能的使用方式。政策是通过 gtag('policy', ...) API 实现的。

gtag('policy', ...) API 需要使用 dataLayer 和 gtag() 的定义。因此,请确保先在代码中定义 dataLayergtag(),然后在脚本中调用 gtag('policy', ...)

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

使用网页上的 gtag('policy', ...) API 为自定义模板权限设置政策:

gtag('policy', <permissionId>, <function>)

<permissionId> 参数可以是任何一种受支持的权限类型,例如 inject_script。每当容器希望检查是否允许该权限,系统就会调用该政策。

gtag('policy', 'inject_script', function(containerId, permissionId, data) {
  // Specific inject_script check goes here.
});

指定为 'all' 时,会响应所有的政策检查。

gtag('policy', 'all', function(containerId, permissionId, data) {
  // System-wide check goes here.
});

第三个参数 (<function>) 是一个函数,它会使用如下签名实现所示的政策:

function(containerId, permissionId, data) {...}
  • containerId 是跟踪代码管理器容器 ID,例如 'GTM-1234'
  • permissionId 字符串用于指定要检查的政策的类型。
  • data 对象包含指定权限类型的所有相关信息,例如 'send_pixel' 权限的 'url'

政策函数在返回 false 或抛出异常时会拒绝权限请求。启用预览模式后,系统会在调试窗格的错误部分中显示任何 stringError 类型的异常。如果注册了多个政策检查,系统会调用每个检查,而每个检查均可拒绝政策请求。

以下示例创建了一个检查 'inject_script' 权限的政策:

gtag('policy', 'inject_script', function(containerId, permissionId, data) {

  // reference the url of the script to be injected
  let url = data.url || '';

  // if the url of the injected script exactly matches, allow it.
  // otherwise throw an error
  if (url === 'https://scripts.example.com/analytics.js') {
    return true;
  } else {
    throw 'Only permitted to inject https://scripts.example.com/analytics.js';
  }
});

以下示例使用 'all' 关键字检查多个政策场景:

gtag('policy', 'all', function(containerId, permissionId, data) {

  // Only set policy for 1 specific container.
  // This enables other containers loaded on the page to
  // operate without restrictions on permissions.
  if (container != 'GTM-4321') return true;

  // Since the policy is 'all', adjust permissions conditionally.
  switch (permissionId) {

    case 'send_pixel':
      return true;

    case 'write_globals':
      return data.key && data.key == '_gaq';

    case 'inject_script':
      let url = data.url || '';
      if (url.indexOf('https://example.com') != 0)
        throw 'Only example.com scripts are permitted';

    default:
      // IT staff decides that all unknown permissions
      // are rejected.
      return false;
  }
});