Производители контента часто хотят понять демографию своей аудитории. Вы можете использовать Shared Storage для записи демографических данных пользователей в контексте, где они у вас есть, например, на вашем сайте первой стороны, а затем использовать агрегированную отчетность для включения этих данных в отчеты с других сайтов, например, во встроенный контент.
Shared Storage API — это предложение Privacy Sandbox для общего назначения, межсайтового хранения, которое поддерживает множество возможных вариантов использования. Private Aggregation API — это вывод, доступный в Shared Storage, который позволяет вам агрегировать межсайтовые данные.
Попробуйте демографические измерения пользователей
Чтобы поэкспериментировать с измерением демографических данных пользователей с помощью Shared Storage и Private Aggregation, убедитесь, что вы используете Chrome Canary и Dev M107 или более позднюю версию. Включите все API конфиденциальности рекламы в chrome://settings/adPrivacy .
Вы также можете включить общее хранилище с помощью флага --enable-features=PrivacySandboxAdsAPIsOverride,OverridePrivacySandboxSettingsLocalTesting,SharedStorageAPI,FencedFrames в командной строке.
Экспериментируйте с примерами кода
Вы можете захотеть измерить определенные демографические данные пользователей, которые видели ваш контент на разных сайтах, например, возрастной диапазон или географическое местоположение. В этом примере идентификатор контента, идентификатор возрастной группы и измерения географического идентификатора кодируются в ключе агрегации (корзине), а количество используется как агрегируемое значение. Сгенерированный сводный отчет будет содержать такую информацию, как «Примерно 391 пользователь, которые видели контент с идентификатором 123, находятся в возрасте от 18 до 39 лет и находятся в Европе».
В этом примере:
-
demographic-measurement.jsзагружается с помощью фрейма и отвечает за загрузку рабочего проекта общего хранилища. -
demographic-measurement-worklet.js— это ворклет общего хранилища, который считывает демографические данные из общего хранилища и отправляет отчет с помощью API частного агрегирования.
(Запускается в определенный момент времени до проведения измерения для помещения демографических данных в общее хранилище)
function getDemogrationsData() {
// Collect age group and continent data
return {
ageGroup,
continent
}
}
async function storeDemographics() {
const { ageGroup, continent } = getDemographicsData();
await window.sharedStorage.set('age-group', ageGroup);
await window.sharedStorage.set('continent', continent);
}
storeDemographics();
async function measureDemographics() {
// Load the Shared Storage worklet
await window.sharedStorage.worklet.addModule('demographics-measurement-worklet.js');
// Run the demographics measurement operation
await window.sharedStorage.run('demographics-measurement', { data: { contentId: '123' } });
}
measureDemographics();
demographic-measurement-worklet.js
// Learn more about noise and scaling from the Private Aggregation fundamentals
// documentation on Chrome blog
const SCALE_FACTOR = 65536;
/**
* The bucket key must be a number, and in this case, it is just the ad campaign
* ID itself. For more complex bucket key construction, see other use cases in
* this demo.
*/
const AGGREGATION_KEY_MAP = {
ageGroupId: {
'18-39': '1',
'40-64': '2',
'65+': '3',
},
continentId: {
africa: '1',
antarctica: '2',
asia: '3',
australia: '4',
europe: '5',
'north-america': '6',
'south-america': '7',
},
};
/**
* The aggregation key will be in the format of:
* contentId | ageGroupId | continentId
*
* For example, a user from Australia between the age of 40-64, who has
* seen the Content ID 321 will be represented by the key:
* 321 | 2 | 4 or 32124
*/
function generateAggregationKey(contentId, ageGroup, continent) {
const ageGroupId = AGGREGATION_KEY_MAP.ageGroupId[ageGroup];
const continentId = AGGREGATION_KEY_MAP.continentId[continent];
const aggregationKey = BigInt(`${contentId}${ageGroupId}${continentId}`);
return aggregationKey;
}
class DemographicsMeasurementOperation {
async run(data) {
const { contentId } = data;
// Read from Shared Storage
const key = 'has-reported-content';
const hasReportedContent = (await sharedStorage.get(key)) === 'true';
const ageGroup = await sharedStorage.get('age-group');
const continent = await sharedStorage.get('continent');
// Don't report if a report has been sent already
if (hasReportedContent) {
return;
}
// Generate the aggregation key and the aggregatable value
const bucket = generateAggregationKey(contentId, ageGroup, continent);
const value = 1 * SCALE_FACTOR;
// Send an aggregatable report using the Private Aggregation API
privateAggregation.contributeToHistogram({ bucket, value });
// Set the report submission status flag
await sharedStorage.set(key, true);
}
}
// Register the operation
register('demographics-measurement', DemographicsMeasurementOperation); \
Engage and share feedback
Note that the Shared Storage API proposal is under active discussion and development and therefore subject to change.
We're eager to hear your thoughts on the Shared Storage API.
- Proposal: Review the detailed proposal.
- Discussion: Join the ongoing discussion to ask questions and share your insights.