SharedStorageOperation

实验性:这是一个实验性技术
在生产环境中使用此技术之前,请仔细查看浏览器兼容性表格

SharedStorageOperationShared Storage API中的一个接口,它代表所有输出网关操作类型的基类。

输出网关类型如下所示:

名称 描述 由谁定义 由谁调用
URL 选择 用于根据共享存储数据选择要显示给用户的 URL。 SharedStorageSelectURLOperation selectURL()
运行 一种处理共享存储数据的通用方法。例如,私有聚合 API会使用它来处理共享存储数据并生成聚合报告。 SharedStorageRunOperation run()

示例

定义单个操作

许多共享存储工作线程模块脚本只定义和注册单个操作;您可以在SharedStorageSelectURLOperationSharedStorageRunOperation页面上看到示例。

定义多个操作

在更复杂的情况下,可以在同一个共享存储工作线程模块脚本中使用不同的名称定义和注册多个操作。在以下工作线程模块脚本中,我们定义了一个名为SelectURLOperation的 URL 选择操作,用于为 A/B 测试选择 URL,以及一个名为ExperimentGroupReportingOperation的运行操作,该操作根据用户的 A/B 测试组运行直方图报告。

js
// ab-testing-worklet.js

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

    // Log to console for the demo
    console.log(`urls = ${JSON.stringify(urls)}`);
    console.log(`data = ${JSON.stringify(data)}`);
    console.log(`ab-testing-group in shared storage is ${experimentGroup}`);

    // Return the index of the group
    return data.indexOf(experimentGroup);
  }
}

function getBucketForTestingGroup(testingGroup) {
  switch (testingGroup) {
    case "control":
      return 0;
    case "experiment-a":
      return 1;
    case "experiment-b":
      return 2;
  }
}

class ExperimentGroupReportingOperation {
  async run() {
    const experimentGroup = await sharedStorage.get("ab-testing-group");

    const bucket = BigInt(getBucketForTestingGroup(experimentGroup));
    privateAggregation.contributeToHistogram({ bucket, value: 1 });
  }
}

// Register the operations
register("ab-testing", SelectURLOperation);
register("experiment-group-reporting", ExperimentGroupReportingOperation);

在主浏览上下文中,这些操作分别由selectURL()run()调用。通过这些方法调用的操作是使用其注册的名称选择的,并且还必须符合SharedStorageSelectURLOperationSharedStorageRunOperation类及其run()方法定义的结构。

js
// For demo purposes. The hostname is used to determine the usage of
// development localhost URL vs production URL
const contentProducerUrl = window.location.host;

// Map the experiment groups to the URLs
const EXPERIMENT_MAP = [
  {
    group: "control",
    url: `https://${contentProducerUrl}/ads/default-ad.html`,
  },
  {
    group: "experiment-a",
    url: `https://${contentProducerUrl}/ads/experiment-ad-a.html`,
  },
  {
    group: "experiment-b",
    url: `https://${contentProducerUrl}/ads/experiment-ad-b.html`,
  },
];

// Choose a random group for the initial experiment
function getRandomExperiment() {
  const randomIndex = Math.floor(Math.random() * EXPERIMENT_MAP.length);
  return EXPERIMENT_MAP[randomIndex].group;
}

async function injectAd() {
  // Load the worklet module
  await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");

  // Set the initial value in the storage to a random experiment group
  window.sharedStorage.set("ab-testing-group", getRandomExperiment(), {
    ignoreIfPresent: true,
  });

  const urls = EXPERIMENT_MAP.map(({ url }) => ({ url }));
  const groups = EXPERIMENT_MAP.map(({ group }) => group);

  // Resolve the selectURL call to a fenced frame config only when it exists on the page
  const resolveToConfig = typeof window.FencedFrameConfig !== "undefined";

  // Run the URL selection operation to select an ad based on the experiment group in shared storage
  const selectedUrl = await window.sharedStorage.selectURL("ab-testing", urls, {
    data: groups,
    resolveToConfig,
    keepAlive: true,
  });

  const adSlot = document.getElementById("ad-slot");

  if (resolveToConfig && selectedUrl instanceof FencedFrameConfig) {
    adSlot.config = selectedUrl;
  } else {
    adSlot.src = selectedUrl;
  }

  // Run the reporting operation
  await window.sharedStorage.run("experiment-group-reporting");
}

injectAd();

规范

规范
Shared Storage API
# sharedstorageoperation

浏览器兼容性

BCD 表格仅在启用 JavaScript 的浏览器中加载。

另请参阅