Hi Sebnem,
It is not possible to directly push data to a Google Data Studio data layer from an external script that is not executed on the webpage. The Google Data Studio data layer is a JavaScript object that is only accessible within the context of the webpage where it is loaded. However, there is a workaround that you can use to send data to Data Studio from an external script.
You can use a server-side script to collect data from your external script and then send it to Data Studio using the Data Studio API. Here’s an example of a server-side script in Node.js that collects data from an external script and sends it to a Data Studio report using the Data Studio API:
const {google} = require('googleapis');
const dataStudio = google.datastudio('v1');
const reportId = 'REPORT_ID';
const datasetId = 'DATASET_ID';
// Collect data from form submission
app.post('/form-submission', (req, res) => {
const data = {
category: req.body.category,
action: req.body.action,
label: req.body.label,
date: new Date().toISOString()
};
// Authenticate with the Google API
const auth = new google.auth.JWT(
'your-service-account-email',
'path/to/privatekey.pem',
'your-private-key',
['https://www.googleapis.com/auth/datastudio']
);
// Append data to the Data Studio dataset
dataStudio.data.append({
auth,
requestBody: {
data: [data],
datasetId,
reportId,
appendMode: 'APPEND'
}
});
});
In this example, the script is using the req.body object from an express.js application to collect data from the form submission. The script is collecting the category, action, label and date fields and the values are assigned to the corresponding keys in the data object. The date field is being set to the current date and time.
You will need to replace ‘your-service-account-email’, ‘path/to/privatekey.pem’, and ‘your-private-key’ with your own values. You also need to replace ‘REPORT_ID’ and ‘DATASET_ID’ with the IDs of the report and dataset you want to send data to.
It is important to note that in order to use this script, you will need to create a Service Account with appropriate permissions and also enable Data Studio API on your project. You may need to follow the instructions on the following link to set it up: https://developers.google.com/datastudio/api/guides/authentication
Also, the example script is based on Node.js and Google client library, but you can use any other language or library as long as it allows you to make authenticated requests to the Data Studio API.