Consent API 允许你以编程方式控制 Consent Management 计划的各个方面。这包括管理模态框、同意状态,以及获取有关已配置用途 (purposes) 的信息。
使用 Consent API,你可以将 Zaraz Consent 偏好与外部 Consent Management Platform 集成,自定义同意模态框,或将同意管理限制为特定地区的用户。
了解 Consent API 何时在页面上完全加载会很有用,这样与其方法和属性交互的代码就不会被过早调用。
document.addEventListener("zarazConsentAPIReady", () => {
// do things with the Consent API
});每当用户更改其同意偏好时,都会触发此事件。它可用于根据同意变更采取行动,例如在使用新的同意偏好更新工具时。
document.addEventListener("zarazConsentChoicesUpdated", () => {
// read the new consent preferences using `zaraz.consent.getAll();` and do things with it
});以下是 zaraz.consent 对象的属性。
-
modalboolean- 获取或设置同意模态对话框的当前可见性状态。
-
purposesobject read-only- 包含所有已配置用途的对象,包括其 ID、名称、描述和顺序。
-
APIReadyboolean read-only- 指示 Consent API 当前是否在页面上可用。
zaraz.consent.get(purposeId);get(purposeId):boolean | undefined
使用用途 ID 获取某用途的当前同意状态。
true:已授予同意。false:未授予同意。undefined:该用途不存在。
-
purposeIdstring- 表示该 Purpose 的 ID。
zaraz.consent.set(consentPreferences);set(consentPreferences):undefined
使用用途 ID 为某些用途设置同意状态。
-
consentPreferencesobject- 一个
{ purposeId: boolean }对象,描述你要设置的用途及其各自的同意状态。
- 一个
zaraz.consent.getAll();getAll():{ purposeId: boolean }
返回一个包含所有用途同意状态的对象。
zaraz.consent.setAll(consentStatus);setAll(consentStatus):undefined
一次性为所有用途设置同意状态。
-
consentStatusboolean- 指示是否已授予同意。
zaraz.consent.getAllCheckboxes();getAllCheckboxes():{ purposeId: boolean }
返回一个包含所有用途复选框状态的对象。
zaraz.consent.setCheckboxes(checkboxesStatus);setCheckboxes(checkboxesStatus):undefined
使用用途 ID 为某些用途设置同意状态。
-
checkboxesStatusobject- 一个
{ purposeId: boolean }对象,描述你要设置的复选框及其各自的选中状态。
- 一个
zaraz.consent.setAllCheckboxes(checkboxStatus);setAllCheckboxes(checkboxStatus):undefined
一次性在同意模态框中为所有用途设置 checkboxStatus 状态。
-
checkboxStatusboolean- 指示用途是否应标记为已选中。
zaraz.consent.sendQueuedEvents();sendQueuedEvents():undefined
如果某些基于 Pageview 的事件因缺乏同意而未发送,则可在授予同意后使用此方法发送它们。
你可以将 Zaraz 的多项功能组合起来,有效地为某些访问者禁用 Consent Management。例如,如果你只想对来自欧盟的访问者使用它,可以禁用同意模态框的自动显示,并添加一个包含以下脚本的 Custom HTML 工具:
<script>
function getCookie(name) {
const value = `; ${document.cookie}`
return value?.split(`; ${name}=`)[1]?.split(";")[0]
}
function handleZarazConsentAPIReady() {
const consent_cookie = getCookie("cf_consent")
const isEUCountry = "{{system.device.location.isEUCountry}}" === "1"
if (!consent_cookie) {
if (isEUCountry) {
zaraz.consent.modal = true
} else {
zaraz.consent.setAll(true)
zaraz.consent.sendQueuedEvents()
}
}
}
if (zaraz.consent?.APIReady) {
handleZarazConsentAPIReady()
} else {
document.addEventListener("zarazConsentAPIReady", handleZarazConsentAPIReady)
}
</script>注意:如果你已为 Consent Manager 自定义了 cookie 名称,请在上面的代码片段中使用该自定义名称,而不是 "cf_consent"。
通过让此 Custom HTML 工具在无同意要求的情况下运行,模态框将向所有欧盟访问者显示,而对其他访问者将自动授予同意。如果访问者来自欧盟国家,{{ system.device.location.isEUCountry }} 属性将为 1,否则为 0。你可以使用任何其他属性或变量以类似方式自定义 Consent Management 行为,例如使用 {{ system.device.location.country }} 根据国家/地区代码限制同意检查。