進行 A/B 測試

使用「共用儲存空間」小程式執行 A/B 測試。

Shared Storage API 是一項「隱私權」 一般用途的沙箱提案,支援多種 可能的用途例如 A/B 測試 Chrome 104.0.5086.0 以上版本。

您可以為使用者指派實驗組,然後將該群組儲存至「共用」 要在跨網站環境中存取的儲存空間。

嘗試 A/B 測試

如要透過共用儲存空間執行 A/B 測試實驗,請確認您使用的是 Chrome 104.0.5086.0 以上版本。啟用 chrome://settings/adPrivacy 下的所有廣告隱私權 API。

您也可以在指令列中使用 --enable-features=PrivacySandboxAdsAPIsOverride,OverridePrivacySandboxSettingsLocalTesting,SharedStorageAPI,FencedFrames 旗標啟用共用儲存空間。

使用程式碼範例進行實驗

若想確認實驗能否帶來所需效果,您可以在多個網站中執行 A/B 測試。廣告客戶或內容製作者可以選擇根據使用者指定的群組顯示不同的內容或廣告。群組作業會儲存在共用儲存空間中,但無法洩露。

在這個例子中:

  • ab-testing.js」應嵌入頁框中,而頁框會對應一個控制組和兩項實驗內容。指令碼會呼叫實驗的共用儲存空間工作程式。
  • ab-testing-worklet.js 是共用儲存空間工作程式,會傳回使用者獲派的群組,以決定要顯示哪則廣告。

ab-testing.js

// Randomly assigns a user to a group 0 or 1
function getExperimentGroup() {
  return Math.round(Math.random());
}

async function injectContent() {
  // Register the Shared Storage worklet
  await window.sharedStorage.worklet.addModule('ab-testing-worklet.js');

  // Assign user to a random group (0 or 1) and store it in Shared Storage
  window.sharedStorage.set('ab-testing-group', getExperimentGroup(), {
    ignoreIfPresent: true,
  });

  // Run the URL selection operation
  const fencedFrameConfig = await window.sharedStorage.selectURL(
    'ab-testing',
    [
      { url: `https://your-server.example/content/default-content.html` },
      { url: `https://your-server.example/content/experiment-content-a.html` }
    ],
    {
      resolveToConfig: true
    }
  );

  // Render the chosen URL into a fenced frame
  document.getElementById('content-slot').config = fencedFrameConfig;
}

injectContent();

ab-testing-worklet.js

class SelectURLOperation {
  async run(urls, data) {
    // Read the user's experiment group from Shared Storage
    const experimentGroup = await sharedStorage.get('ab-testing-group');

    // Return the corresponding URL (first or second item in the array)
    return urls.indexOf(experimentGroup);
  }
}

register('ab-testing', 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.

Stay Informed

  • Mailing List: Subscribe to our mailing list for the latest updates and announcements related to the Select URL and Shared Storage APIs.

Need Help?