進行 A/B 測試

使用 Shared Storage 小程式執行 A/B 測試。

Shared Storage API 是 Privacy Sandbox 提案,提供一般用途的跨網站儲存空間,支援多種可能用途。例如 A/B 測試,您可以在 Chrome 104.0.5086.0 以上版本中測試這項功能。

您可以將使用者指派給實驗群組,然後將該群組儲存在共用儲存空間中,以便在跨網站環境中存取。

試試 A/B 測試

如要使用 Shared Storage 進行 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.

參與討論及分享意見

請注意,「選取網址」API 提案目前仍在積極討論和開發中,隨時可能變更。

我們很期待聽到您對 Select URL API 的想法。