SharedStorageWorklet

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

SharedStorageWorklet 介面是 共享儲存 API 的一部分,代表當前來源的共享儲存工作執行緒。

SharedStorageWorklet 沒有自己的屬性或方法。相反,它繼承了 Worklet 介面的 addModule() 方法。此方法用於新增模組。

與常規 Worklet 不同

  • 如果呼叫方未將共享儲存 API 包含在 隱私沙盒註冊流程 中,則對 sharedStorageWorklet.addModule() 的呼叫將被拒絕。
  • 出於隱私原因,SharedStorageWorklet 僅允許新增一個模組。即使成功註冊,對同一共享儲存工作執行緒重複呼叫 addModule() 也會被拒絕。

透過 WindowSharedStorage.worklet 訪問 SharedStorageWorklet

Worklet SharedStorageWorklet

示例

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

async function injectContent() {
  // Add the module to 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();

有關此示例的詳細介紹以及其他示例的連結,請參閱 共享儲存 API 登入頁。

規範

規範
共享儲存 API
# sharedstorageworklet

瀏覽器相容性

另見