为已知客户定制用户体验

使用共享存储空间 worklet 识别已知客户。

Shared Storage API 是一项 Privacy Sandbox 提案,旨在提供通用的跨网站存储空间,支持许多可能的用例。一个示例是识别已知客户,此功能可在 Chrome 104.0.5086.0 及更高版本中进行测试。

您可以将用户是否已在您的网站上注册的信息存储到 Shared Storage 中,然后根据用户存储的状态(用户是否为“已知”客户)呈现不同的元素。

设置已知客户

如需尝试在共享存储空间中识别已知客户,请确认您使用的是 Chrome 104.0.5086.0 或更高版本。启用 chrome://settings/adPrivacy 下的所有广告隐私权 API。

您还可以在命令行中使用 --enable-features=PrivacySandboxAdsAPIsOverride,OverridePrivacySandboxSettingsLocalTesting,SharedStorageAPI,FencedFrames 标志启用共享存储空间。

试用代码示例

您可能希望根据用户是否在其他网站上出现过来呈现不同的元素。例如,付款服务提供商可能希望根据用户是否已在自己的网站上注册来呈现“注册”或“立即购买”按钮。共享存储空间可用于设置用户的状态,并根据该状态自定义用户体验。

在此示例中:

  • known-customer.js 嵌入在框架中。此脚本用于设置应在网站上显示哪个按钮:“注册”或“立即购买”。
  • known-customer-worklet.js 是用于确定用户是否已知的共享存储区工作程序。如果用户已知,则返回相应信息。如果用户未知,系统会返回相应信息以显示“注册”按钮,并将该用户标记为已知用户,以供日后使用。

known-customer.js

// The first URL for the "register" button is rendered for unknown users.
const BUTTON_URLS = [
  { url: `https://${advertiserUrl}/ads/register-button.html` },
  { url: `https://${advertiserUrl}/ads/buy-now-button.html` },
];

async function injectButton() {
  // Load the worklet module
  await window.sharedStorage.worklet.addModule('known-customer-worklet.js');

  // Set the initial status to unknown ('0' is unknown and '1' is known)
  window.sharedStorage.set('known-customer', 0, {
    ignoreIfPresent: true,
  });

  // Run the URL selection operation to choose the button based on the user status
  const fencedFrameConfig = await window.sharedStorage.selectURL('known-customer', BUTTON_URLS, {
    resolveToConfig: true
  });

  // Render the opaque URL into a fenced frame
  document.getElementById('button-slot').src = fencedFrameConfig;
}

injectButton();

known-customer-worklet.js

class SelectURLOperation {
  async run(urls) {
    const knownCustomer = await sharedStorage.get('known-customer');

    // '0' is unknown and '1' is known
    return parseInt(knownCustomer);
  }
}

register('known-customer', SelectURLOperation);

Use cases

All available use cases for Select URL API can be found in this section. We'll continue to add examples as we receive feedback and discover new test cases.

互动并分享反馈

请注意,Select 网址 API 提案正在积极讨论和制作中,因此可能会发生变化。

我们非常期待您就 Select 网址 API 提供反馈。