📋 A Custom Google Spreadsheet Function for Tracking Pageviews
1. Overview
\[ \begin{array}{l} \textbf{You can track website pageviews directly in Google Sheets --} \\ \text{using a custom function written with Google Apps Script.} \\ \textbf{By connecting to the Google Analytics API or a pageview source --} \\ \text{you can automate traffic tracking inside spreadsheets.} \end{array} \]
2. Use Cases
- Monitor website performance daily, weekly, or monthly
- Automate traffic reports for clients or teams
- Visualize traffic trends with native Google Sheets charts
- Combine pageviews with campaign, product, or SEO data
This technique is perfect for marketers, content creators, and analysts who want
fast access to real-time pageview data without leaving their spreadsheet.
3. Custom Function with Google Analytics Integration
/**
* Custom function to retrieve Google Analytics pageviews.
* @param {string} viewId - The GA View ID (e.g., ga:12345678)
* @param {string} startDate - e.g. '30daysAgo'
* @param {string} endDate - e.g. 'today'
* @param {string} pagePath - e.g. '/blog/post-1'
* @return {number} Pageviews
*/
function PAGEVIEWS(viewId, startDate, endDate, pagePath) {
var results = Analytics.Data.Ga.get(
viewId,
startDate,
endDate,
'ga:pageviews',
{
'filters': 'ga:pagePath==' + pagePath
}
);
if (results.rows) {
return parseInt(results.rows[0][0], 10);
} else {
return 0;
}
}
This function retrieves pageview data for a specific page and date range.
You must enable the **Google Analytics API** and **Analytics service** in the Apps Script project.
4. Steps to Set Up the Script
1. Open your Google Sheet → Extensions → Apps Script.
2. Paste the PAGEVIEWS() function into the script editor.
3. Go to Services (+ icon) → Add Google Analytics API.
4. Save and authorize the script.
5. Use in a cell: =PAGEVIEWS("ga:12345678", "30daysAgo", "today", "/blog/post-1")
The GA View ID can be found in your Google Analytics Admin settings under View Settings.
5. Example Usage
=PAGEVIEWS("ga:987654321", "2023-01-01", "2023-01-31", "/landing-page")
This will return the number of pageviews for the specified URL between Jan 1 and Jan 31, 2023.
6. Alternative: Using Google Tag Manager + Webhook Logging
- Instead of using GA, set up GTM to send data to a Web App Script
- Create a Web App (deployed script) to receive POST data
- Log pageview info (path, timestamp, IP, etc.) into your sheet
This is a no-GA method that gives you full control, especially useful
for cookieless analytics or GDPR-compliant setups.
7. Conclusion
Creating a custom Google Sheets function with Apps Script unlocks powerful
tracking capabilities right in your spreadsheets. Whether you use GA API or
webhook logging, the result is fast, flexible analytics you can customize.
You can combine it with charts, filters, and formulas to build powerful dashboards
without external BI tools.