WindowSharedStorage: selectURL() 方法

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

WindowSharedStorage 介面的 selectURL() 方法會執行一個 URL 選擇操作,該操作在當前源的 SharedStorageWorklet 中新增的模組中註冊。

注意: URL 選擇輸出門用於根據共享儲存資料,從提供的列表中選擇一個 URL 展示給使用者。

語法

js
selectURL(name, urls)
selectURL(name, urls, options)

引數

name

一個字串,表示在共享儲存 worklet 模組中註冊的操作名稱。它必須與使用 SharedStorageWorkletGlobalScope.register() 註冊操作時給定的名稱匹配。

URLs

一個物件陣列,表示 URL 選擇操作可在其中選擇的 URL。每個物件包含兩個屬性:

url

一個字串,表示 URL。

reportingMetadata 可選

一個物件,其中屬性名是事件型別,屬性值是指向報告目的地的 URL,例如 "click" : "my-reports/report1.html"。這些 URL 用作型別為 "shared-storage-select-url" 的報告的目的地,通常透過 Fence.reportEvent()Fence.setReportEventDataForAutomaticBeacons() 方法呼叫提交。

options 可選

一個選項物件,可以包含以下屬性:

data 可選

一個物件,表示執行操作所需的任何資料。

keepAlive 可選

一個布林值。如果設定為 true,則會保留關聯 worklet 的 SharedStorageWorkletGlobalScope,並且可以再次執行該操作。因此,您需要為每個非最後一次使用的操作設定 keepAlivetrue。預設值 false 表示在執行操作後 SharedStorageWorkletGlobalScope 將被終止,且無法再次執行。

resolveToConfig 可選

一個布林值。如果設定為 true,則 run() 返回的 Promise 的 fulfilled 值將是一個 FencedFrameConfig 物件,可用於透過其 config 屬性將內容載入到 <fencedframe> 中。預設值 false 表示 fulfilled 值將是一個可用於將內容載入到 <iframe> 中的 URL。

返回值

一個 Promise,根據 resolveToConfig 選項的值,它會以 FencedFrameConfig 物件或表示 URL 的字串進行 fulfilled。

異常

TypeError

在以下情況下丟擲

  • 尚未透過 addModule() 新增 worklet 模組。
  • urls 為空或超出了允許的最大長度(具體取決於瀏覽器)。
  • 某個物件的 url 屬性包含一個無效的 URL。
  • 共享儲存已被停用(例如,透過瀏覽器設定)。
  • 呼叫站點未在成功的 隱私沙盒註冊流程中包含共享儲存 API。

示例

基本 A/B 測試

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 登入頁。

規範

此特性似乎未在任何規範中定義。

瀏覽器相容性

另見