SharedStorageSelectURLOperation

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

SharedStorageSelectURLOperation 接口是 Shared Storage API 的一部分,代表一个 URL 选择输出门操作。

实例方法

run() 实验性

定义了在 URL 选择输出门操作中定义的 run() 方法应遵循的结构。

示例

在此示例中,一个名为 SelectURLOperation 的类在 worklet 中定义,并使用 SharedStorageWorkletGlobalScope.register()ab-testing 的名称注册。SharedStorageSelectURLOperation 定义了这个类需要遵循的结构,本质上定义了 run() 方法所需的参数。除了这个要求之外,类的功能可以灵活定义。

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

    // Return the group number
    return experimentGroup;
  }
}

// Register the operation
register("ab-testing", SelectURLOperation);

注意: 可以在同一个共享存储工作线程模块脚本中定义和注册多个具有不同名称的操作;有关示例,请参阅SharedStorageOperation

在主浏览上下文中,ab-testing 操作通过 WindowSharedStorage.selectURL() 方法调用。

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();

有关此示例的更多详细信息以及其他示例链接,请参阅 Shared Storage API 入门页面。

规范

此特性似乎未在任何规范中定义。

浏览器兼容性

另见