政策規定網頁會導入政策。當容器在網頁上執行時,系統會將政策套用至代碼管理工具的自訂範本定義,以控制特定功能的使用方法。政策是透過 gtag('policy', ...)
API 實作。
使用 gtag('policy', ...)
API 時,必須有 dataLayer 和 gtag()
的定義。請確定您的程式碼中已定義 dataLayer
和 gtag()
,然後再透過指令碼呼叫 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
或擲回例外狀況時拒絕權限要求。啟用預覽模式後,偵錯窗格的「錯誤」部分將會顯示任何類型為 string
或 Error
的例外狀況。註冊多個政策檢查時,系統會逐一檢查每項檢查,而且每項檢查都可以拒絕政策要求。
此範例建立的政策將用於檢查 '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;
}
});