WorkletSharedStorage:get() 方法
get()
是 WorkletSharedStorage
接口的方法,用于从共享存储中检索值。
语法
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,
);
// 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);
规范
规范 |
---|
共享存储 API # dom-workletsharedstorage-get |
浏览器兼容性
BCD 表格仅在启用 JavaScript 的浏览器中加载。