WorkletSharedStorage: get() 方法

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

WorkletSharedStorage 介面的 get() 方法從共享儲存中檢索一個值。

語法

js
get(key)

引數

key

一個字串,代表您想要檢索的鍵值對的鍵。

返回值

一個 Promise,它會解析為一個字串(等於檢索到的鍵值對的值),或者如果指定的 key 在共享儲存中未找到,則解析為 undefined

異常

TypeError

在以下情況下丟擲

  • 尚未透過 addModule() 新增 worklet 模組。
  • key 超出了瀏覽器定義的長度限制。
  • 呼叫站點未在成功的 隱私沙盒註冊流程中包含共享儲存 API。

示例

衡量 K+ 頻率

以下示例衡量了內容檢視的 K+ 頻率。K 頻率有時被描述為“有效頻率”,它指的是使用者在能夠識別或回憶起特定內容(通常用於廣告檢視的語境)之前的最小觀看次數。

主頁面指令碼

js
// k-frequency-measurement.js

async function injectContent() {
  // Load the Shared Storage worklet
  await window.sharedStorage.worklet.addModule("k-freq-measurement-worklet.js");

  // Run the K-frequency measurement operation
  await window.sharedStorage.run("k-freq-measurement", {
    data: { kFreq: 3, contentId: 123 },
  });
}

injectContent();

下面顯示了 worklet 模組

js
// k-frequency-measurement-worklet.js

// Scale factor for handling noise added to data
const SCALE_FACTOR = 65536;

/**
 * The bucket key must be a number, and in this case, it is simply the content
 * ID itself. For more complex bucket key construction, see other use cases in
 * this demo.
 */
function convertContentIdToBucket(contentId) {
  return BigInt(contentId);
}

class KFreqMeasurementOperation {
  async run(data) {
    const { kFreq, contentId } = data;

    // Read from Shared Storage
    const hasReportedContentKey = "has-reported-content";
    const impressionCountKey = "impression-count";
    const hasReportedContent =
      (await this.sharedStorage.get(hasReportedContentKey)) === "true";
    const impressionCount = parseInt(
      (await this.sharedStorage.get(impressionCountKey)) || 0,
      10,
    );

    // Do not report if a report has been sent already
    if (hasReportedContent) {
      return;
    }

    // Check impression count against frequency limit
    if (impressionCount < kFreq) {
      await this.sharedStorage.set(impressionCountKey, impressionCount + 1);
      return;
    }

    // Generate the aggregation key and the aggregatable value
    const bucket = convertContentIdToBucket(contentId);
    const value = 1 * SCALE_FACTOR;

    // Send an aggregatable report via the Private Aggregation API
    privateAggregation.sendHistogramReport({ bucket, value });

    // Set the report submission status flag
    await this.sharedStorage.set(hasReportedContentKey, "true");
  }
}

// Register the operation
register("k-freq-measurement", KFreqMeasurementOperation);

有關此示例的更多詳細資訊,請參閱 K+ 頻率測量。有關其他示例的連結,請參閱 Shared Storage API 登陸頁。

規範

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

瀏覽器相容性

另見