進行 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);

用途

請參閱本節,瞭解 Select URL API 的所有可用用途。我們會持續新增示例,以回應使用者意見並探索新的測試案例。

互動並分享意見回饋

請注意,Select URL API 提案仍在積極討論和開發中,可能會有所變動。

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

掌握最新消息

  • 電子報名單:訂閱我們的電子報名單,即可取得與 Select 網址和 Shared Storage API 相關的最新消息和公告。

需要協助嗎?