- 确定 GA4 跟踪代码中已定义了自定义维度。
- 获取 Google 客户端库,并使用以下代码获取自定义维度的值:
// Replace with your own client ID and API key
const CLIENT_ID = 'YOUR_CLIENT_ID_HERE';
const API_KEY = 'YOUR_API_KEY_HERE';
// Replace with the actual property ID and custom dimension index
const PROPERTY_ID = 'YOUR_GA4_PROPERTY_ID_HERE';
const CUSTOM_DIMENSION_INDEX = 'YOUR_CUSTOM_DIMENSION_INDEX_HERE';
// The Google API endpoint to call
const API_ENDPOINT = 'https://analyticsdata.googleapis.com/v1alpha:runReport';
// Request body that defines the report query
const requestBody = {
"entity" : {
"property_id" : PROPERTY_ID
},
"dimensions" : [
{
"name" : "customEvent:custom_dimension_" + CUSTOM_DIMENSION_INDEX
}
],
"dateRanges" : [
{
"startDate" : "today",
"endDate" : "today"
}
],
"metrics" : [
{
"name" : "sessions"
}
]
};
// Make the API call using the Google APIs client library
gapi.client.request({
'path': API_ENDPOINT,
'method': 'POST',
'headers': {
'Authorization': 'Bearer ' + access_token
},
'body': requestBody
}).then(function(response) {
console.log(response.result.rows[0].dimensionValues[0].value);
}, function(reason) {
console.error('Error: ' + reason.result.error.message);
});
- 运行代码并查看控制台输出,以获取自定义维度的值。