Saving Data Locally and Exporting for Analysis
This step builds on Step 3 by replacing temporary console logs with persistent data storage in your browser. You'll learn to save data locally using localStorage and export it for analysis.
Click a choice to log it. Your data is automatically saved to your browser's local storage.
This step uses the browser's built-in localStorage API. It's a simple key-value store that persists even when the user closes the tab.
Want to learn exactly how this demo saves data? Check out our detailed guide on this example's code β
localStorage as a JSON string.localStorage, parse it, and convert it into a downloadable file (JSON or CSV).Saving data is a two-step process: declare your array, add to it, then save the whole array.
// Declare your experiment data array at the top of your script
let experimentData = [];
// Add new trial data to our array
experimentData.push(trialData);
// Save the entire updated array to localStorage
localStorage.setItem('myExperimentData', JSON.stringify(experimentData));
To create a download button, you write a function that converts your data array into a file that the browser can download.
function downloadJSON() {
// Convert the array of data into a text format
const dataStr = JSON.stringify(experimentData, null, 2);
// Create a file-like object in the browser
const dataBlob = new Blob([dataStr], {type: "application/json"});
// Create a temporary, invisible link to trigger the download
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = "experiment-data.json"; // The filename
link.click(); // Click the link programmatically
}
The process is similar for a CSV file, but you have to manually create the headers and rows.
function downloadCSV() {
// Define the column headers for your file
const headers = "trial,timestamp,playerChoice,step,status";
// Convert each data object into a single, comma-separated line
const rows = experimentData.map(d =>
`${d.trial},${d.timestamp},${d.playerChoice},${d.step},${d.status}`
);
// Join the headers and all the rows into one big string
const csvContent = [headers, ...rows].join("\n");
// The rest is the same as the JSON download!
const dataBlob = new Blob([csvContent], {type: "text/csv"});
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = "experiment-data.csv";
link.click();
}
Use this prompt to add localStorage functionality to your own experiment from Step 3. Be sure to include your existing experiment.js file as context.
I want to add local data collection to my experiment using localStorage.
I need help with:
The goal is to collect data that persists between page loads, all locally in the browser.
localStorage or JSON.stringify.