SharedStorageOperation
Экспериментальный: Это экспериментальная технология
Перед использованием в рабочей среде тщательно проверьте таблицу совместимости с браузерами.
Интерфейс SharedStorageOperation API общего хранилища представляет базовый класс для всех типов операций шлюза вывода.
Типы шлюзов вывода подробно описаны ниже:
| Название | Описание | Определено в | Вызывается из |
|---|---|---|---|
| Выбор URL-адреса | Используется для выбора URL-адреса для отображения пользователю на основе данных общего хранилища. | SharedStorageSelectURLOperation | selectURL() |
| Выполнение | Общий способ обработки данных общего хранилища. Используется, например, API частного агрегирования для обработки данных общего хранилища и генерации сводных отчетов. | SharedStorageRunOperation | run() |
Примеры
Определение отдельных операций
Многие скрипты модулей работы с общим хранилищем определяют и регистрируют только одну операцию; примеры можно найти на страницах SharedStorageSelectURLOperation и SharedStorageRunOperation.
Определение нескольких операций
В более сложных случаях можно определить и зарегистрировать несколько операций в одном скрипте модуля работы с общим хранилищем с различными именами. В следующем скрипте модуля работы с общим хранилищем мы определяем операцию выбора URL-адреса под названием SelectURLOperation для выбора URL-адреса для A/B-тестирования и операцию выполнения под названием ExperimentGroupReportingOperation, которая выполняет отчет гистограммы на основе группы A/B-тестирования пользователя:
// ab-testing-worklet.js
class SelectURLOperation {
async run(urls, data) {
// Read the user's group from shared storage
const experimentGroup = await sharedStorage.get("ab-testing-group");
// Log to console for the demo
console.log(`urls = ${JSON.stringify(urls)}`);
console.log(`data = ${JSON.stringify(data)}`);
console.log(`ab-testing-group in shared storage is ${experimentGroup}`);
// Return the index of the group
return data.indexOf(experimentGroup);
}
}
function getBucketForTestingGroup(testingGroup) {
switch (testingGroup) {
case "control":
return 0;
case "experiment-a":
return 1;
case "experiment-b":
return 2;
}
}
class ExperimentGroupReportingOperation {
async run() {
const experimentGroup = await sharedStorage.get("ab-testing-group");
const bucket = BigInt(getBucketForTestingGroup(experimentGroup));
privateAggregation.contributeToHistogram({ bucket, value: 1 });
}
}
// Register the operations
register("ab-testing", SelectURLOperation);
register("experiment-group-reporting", ExperimentGroupReportingOperation);
В основном контексте просмотра эти операции вызываются selectURL() и run() соответственно. Операции для вызова с помощью этих методов выбираются по именам, с которыми они были зарегистрированы, и они также должны соответствовать структурам, определённым классами SharedStorageSelectURLOperation и SharedStorageRunOperation и их методами run().
// For demo purposes. The hostname is used to determine the usage of
// development localhost URL vs production URL
const contentProducerUrl = window.location.host;
// Map the experiment groups to the URLs
const EXPERIMENT_MAP = [
{
group: "control",
url: `https://${contentProducerUrl}/ads/default-ad.html`,
},
{
group: "experiment-a",
url: `https://${contentProducerUrl}/ads/experiment-ad-a.html`,
},
{
group: "experiment-b",
url: `https://${contentProducerUrl}/ads/experiment-ad-b.html`,
},
];
// Choose a random group for the initial experiment
function getRandomExperiment() {
const randomIndex = Math.floor(Math.random() * EXPERIMENT_MAP.length);
return EXPERIMENT_MAP[randomIndex].group;
}
async function injectAd() {
// Load the worklet module
await window.sharedStorage.worklet.addModule("ab-testing-worklet.js");
// Set the initial value in the storage to a random experiment group
window.sharedStorage.set("ab-testing-group", getRandomExperiment(), {
ignoreIfPresent: true,
});
const urls = EXPERIMENT_MAP.map(({ url }) => ({ url }));
const groups = EXPERIMENT_MAP.map(({ group }) => group);
// Resolve the selectURL call to a fenced frame config only when it exists on the page
const resolveToConfig = typeof window.FencedFrameConfig !== "undefined";
// Run the URL selection operation to select an ad based on the experiment group in shared storage
const selectedUrl = await window.sharedStorage.selectURL("ab-testing", urls, {
data: groups,
resolveToConfig,
keepAlive: true,
});
const adSlot = document.getElementById("ad-slot");
if (resolveToConfig && selectedUrl instanceof FencedFrameConfig) {
adSlot.config = selectedUrl;
} else {
adSlot.src = selectedUrl;
}
// Run the reporting operation
await window.sharedStorage.run("experiment-group-reporting");
}
injectAd();
Спецификации
Данные спецификаций не найдены для api.SharedStorageOperation.
Проверьте наличие проблем с этой страницей или внесите недостающие spec_url в mdn/browser-compat-data. Также убедитесь, что спецификация включена в w3c/browser-specs.
Совместимость с браузерами
См. также
© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/SharedStorageOperation