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 登陆页。

规范

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

浏览器兼容性

另见