Building a Chrome Extension to Track App View Counts with HTML
Creating a lightweight Chrome extension that counts how many times a web‑based app is viewed is a practical way to learn about Chrome APIs, manifest files, content scripts, and background services. In this guide we’ll walk through every step—from setting up the project structure to publishing the extension—while keeping the code clean, well‑commented, and ready for real‑world use.
Introduction
Modern web apps often need analytics to understand user engagement. While third‑party services exist, a custom Chrome extension offers a privacy‑friendly, offline‑ready solution that runs directly in the browser. In this tutorial we’ll build an extension called ViewCounter that:
- Detects when the target app (named “bpmcpldpdmajfigpchkicefoigmkfalc”) loads.
- Increments a view counter stored in
chrome.storage. - Displays the current count in the browser toolbar.
The extension uses pure HTML, JavaScript, and the Chrome Extensions API—no external libraries required.
Project Structure
view-counter/
├─ manifest.json
├─ icons/
│ ├─ icon16.png
│ ├─ icon48.png
│ └─ icon128.png
├─ background.js
├─ content.js
├─ popup.html
├─ popup.js
└─ styles.css
- manifest.json – declares metadata, permissions, and entry points.
- background.js – handles persistent logic and storage.
- content.js – injected into the target app’s page to detect view events.
- popup.html / popup.js – the toolbar UI that shows the count.
- styles.css – minimal styling for the popup.
1. Crafting the Manifest
{
"manifest_version": 3,
"name": "ViewCounter",
"description": "Counts how many times bpmcpldpdmajfigpchkicefoigmkfalc is viewed.",
"version": "1.0",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"permissions": ["storage", "tabs"],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://*.bpmcpldpdmajfigpchkicefoigmkfalc.com/*"],
"js": ["content.js"],
"run_at": "document_end"
}
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
}
Key points
manifest_version3 is the latest standard.content_scriptsmatch the target domain; adjust the URL pattern as needed.storagepermission allows persistent data storage;tabslets us query the active tab if required.- The
actionfield defines the toolbar button and its popup.
2. Background Service Worker
background.js handles data persistence and inter‑script messaging But it adds up..
// background.js
// Initialize counter if not present
chrome.storage.get(['viewCount'], (data) => {
if (typeof data.viewCount === 'undefined') {
chrome.local.runtime.On top of that, onInstalled. Which means addListener(() => {
chrome. On top of that, storage. local.
// Listen for messages from content script
chrome.storage.set({ viewCount: newCount }, () => {
// Notify popup to update display
chrome.On top of that, runtime. type === 'increment') {
chrome.Day to day, local. local.Think about it: addListener((request, sender, sendResponse) => {
if (request. get(['viewCount'], (data) => {
const newCount = (data.onMessage.viewCount || 0) + 1;
chrome.storage.runtime.
**What it does**
- Sets an initial `viewCount` of 0 on first install.
- Listens for an `increment` message from the content script.
- Updates the stored count and broadcasts the new value to any listening popup.
---
### 3. Content Script – Detecting a View
`content.js` runs inside the target app’s page. It sends a message to the background whenever the page fully loads.
```js
// content.js
// Helper to send increment request
function notifyView() {
chrome.Now, runtime. sendMessage({ type: 'increment' }, (response) => {
console.log('View counted:', response.
// Trigger on page load
window.addEventListener('load', () => {
notifyView();
});
Why load?
The load event fires after the entire page, including images and sub‑resources, has finished loading—ensuring we count a genuine view rather than a partial refresh.
4. Popup UI – Showing the Count
popup.html is a small, self‑contained HTML file.
View Counter
App Views
0
styles.css keeps the popup tidy:
body { font-family: Arial, sans-serif; text-align: center; padding: 10px; }
h1 { font-size: 1.2em; margin: 0 0 10px; }
#count { font-size: 2em; font-weight: bold; }
popup.js fetches the current count and updates when the value changes That's the part that actually makes a difference..
// popup.js
function updateDisplay(count) {
document.getElementById('count').textContent = count;
}
// Fetch initial count
chrome.storage.local.get(['viewCount'], (data) => {
updateDisplay(data.
// Listen for updates from background
chrome.runtime.onMessage.On the flip side, addListener((request) => {
if (request. type === 'updated') {
updateDisplay(request.
---
### 5. Packaging and Testing
1. **Load the extension**
- Open Chrome → `chrome://extensions/`
- Enable “Developer mode”
- Click “Load unpacked” and select the `view-counter` folder
2. **Test the counter**
- manage to `https://www.bpmcpldpdmajfigpchkicefoigmkfalc.com` (replace with the actual domain).
- Reload the page several times.
- Click the extension icon; the popup should show the incrementing view count.
3. **Debug if needed**
- Open the popup’s console (`Right‑click > Inspect`) to see logs.
- Verify `content.js` is injected by looking at the page’s console.
---
### 6. Advanced Features (Optional)
| Feature | How to Implement |
|---------|------------------|
| **Reset Button** | Add a button in `popup.So naturally, html` that sends a `reset` message to `background. And js`. |
| **Export Data** | Use `chrome.storage.Which means local. In real terms, get` and prompt the user to download a JSON file. |
| **Multiple Apps** | Store an object `{ appName: count }` in storage and detect the app via URL. |
| **Badge Count** | Update the toolbar badge with `chrome.action.setBadgeText`.
You'll probably want to bookmark this section.
These extensions keep the core structure intact while adding valuable functionality.
---
### FAQ
**Q1: Why use a background service worker instead of a persistent background page?**
*A1:* Manifest V3 promotes event‑based workers to reduce memory usage. Service workers automatically shut down when idle, improving performance.
**Q2: Can the counter be synced across devices?**
*A2:* Yes. Replace `chrome.storage.local` with `chrome.storage.sync` to sync data across the user’s Chrome profiles (subject to quota limits).
**Q3: Will the extension affect page performance?**
*A3:* Minimal. The content script runs once on `load`, and only a small message is sent to the background. No heavy computation or network calls are involved.
**Q4: How to make the counter visible on the toolbar itself?**
*A4:* Use `chrome.action.setBadgeText({text: count.toString()})` in the background after each increment.
---
### Conclusion
By combining a simple **content script** that detects page loads, a **background service worker** that manages state, and a lightweight **popup UI**, we’ve built a fully functional Chrome extension that counts views for any web app—here exemplified with “bpmcpldpdmajfigpchkicefoigmkfalc.That said, ” The same pattern scales to more complex analytics: you can track clicks, form submissions, or even integrate with external analytics APIs. Happy coding, and may your view counts keep climbing!
### 7. Next Steps and Enhancements
To take your extension further, consider these enhancements:
1. **User Preferences**
Add a settings page where users can customize the tracked domain, choose a color scheme for the popup, or set a daily limit for notifications.
2. **Analytics Integration**
Send view counts to a backend API or Google Analytics using `fetch` in the background script. This allows centralized tracking across multiple users or apps.
3. **Permissions Management**
Request permissions dynamically (e.g., `chrome.permissions.request`) only when the user enables export or sync features, improving initial trust and UX.
4. **Error Handling**
Wrap storage operations in `try/catch` blocks and display user-friendly error messages if something goes wrong (e.g., storage quota exceeded).
5. **Localization**
Support multiple languages by loading locale-specific strings from a JSON file and using `chrome.i18n` for dynamic text replacement.
---
### Conclusion
Building a Chrome extension to count views is a straightforward yet powerful way to deepen your understanding of browser APIs and client-side state management. By leveraging Manifest V3’s event-driven architecture, you create an efficient, lightweight tool that respects user privacy and system resources.