為已知客戶自訂使用者體驗

使用 Shared Storage 小程式識別已知顧客。

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.

Engage and share feedback

Note that the Select URL API proposal is under active discussion and development and subject to change.

We're eager to hear your thoughts on the Select URL API.